diff --git a/CHANGELOG.md b/CHANGELOG.md index fbe3530..77479a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,66 @@ ## Unreleased +- The bot form shows the portrait with a pencil, and the avatar editor opens in a dialog instead of filling the form, as on the web. +- Pin the bot's `6.0.0` contract as a local export and bump the generator to `1.1.0`, adding closed objects with declared properties, nullable named schemas and `allOf` parts, and `*/*` binary responses. +- Sign in with account email and password. The server token is gone; the app stores the returned session. +- Send provider keys as `value` and MCP tokens as `{ value }`, and show learned changes in the activity feed. +- Approve or decline held actions, answer coding job questions, and approve or decline bot requests from the chat. Pending cards refresh every five seconds. +- Fix the "List is empty." error when opening a chat with no messages. +- Draw bots with Open Bot Avatar, using the avatar stored on the server, and edit avatars in the bot editor: colors, gallery, JSON import, and a generation prompt. +- Fix saving a bot from the app removing its web, coding, desktop, and create-bots tools. +- Fix saving a bot from the app replacing its skills and shared skills. The editor no longer submits either list. +- Require the password when the server URL changes, so a saved session is never sent to another server. +- Add Sign out to Settings. It unregisters notifications, ends the session on the server, and removes the session, email, and cached chats from the device. +- Keep a draft, its attachments, and its reply target per bot across navigation. Only signing out or changing server clears them. +- Sending a draft restored after a failed send retries with the same request ID, so a message the server already received never goes out twice. A row whose send fails after you navigate now shows Failed. +- Load pages during unrelated saves: a read keeps only the records being changed and fetches again when a change finished while it ran. +- Keep a form open when its record is still saving, and say so, instead of closing it and losing the edit. +- Failed bot deletes restore unsaved profile edits, failed task and MCP saves keep the record in place, and failed bot saves keep changes confirmed in the meantime. +- Drop late bot approvals and attachment images from a previous session. +- Offer `@` mentions to every enabled bot when the bot can message others, like the website. +- Add Web search, Coding, Bot desktop, and Create bots toggles for new and existing bots, a per-bot web search provider, and a desktop job provider and model. Coding and desktop show only when the server offers them or the bot already has them. +- Draw `show` cards in bot chats: stats, tables, and charts with tap-to-read values. Show desktop screenshots and emoji reactions there too. +- Tapping the bot's name in the chat opens its details: profile, desktop preview, and automations with on/off switches. Edit bot moved there. +- Show "Working…" and the working avatar for every bot in the list, not only the open one. The list checks each bot's status every five seconds while it is open. +- Attach images from a panel that opens under the composer, as in Google Messages. Other file types can't be picked for now. +- Start new bots with memory, web search, and messaging, like the website, and remove the Schedule tasks and Code mode toggles, which every bot has anyway. +- Build bot avatars from the `open-bot-avatar-kt` `0.1.0` tag with a Gradle source dependency instead of a submodule. +- Follow Google Messages and Android Settings: Home is a conversation list with search and an account button at the top right, the Account page leads to Memory, Automations, Activity, and Settings, and chats have Back, a details menu, and a pill composer. Settings lists every section in grouped rows, General replaces the settings dialog, and pages use the system's card colors, tracking, and rounded fields. +- Replace New bot on Home with New chat, which starts a chat with a bot, creates a bot, or picks bots for a group chat. Home lists group chats after the bots, with no section of their own. +- Use the Crumble icon for the app, with a themed icon, instead of the default Android one. +- Carry the grouped look to every page: Memory, Skills, Automations, Activity, Integrations, Credentials, Logins, the connection pages, Avatars, jobs, change history, the bot editor, bot details, the group form, and the command palette. - Replace the local glossary with a link to the canonical glossary in the spec repository. - Preserve admitted task execution fields for navigation and reject non-admitted or incomplete starts instead of reporting success. +- Edit a bot proposal before approving it. The sheet stays open with your edits until the server confirms, and fields the editor doesn't show are kept. +- Show coding and desktop jobs in the chat, with a job list and a job panel: live status, model and cost, step history with results, earlier activity, job questions, and a transcript download. +- Show the pages a reply cites as source chips after it. +- Fix the Activity row that read "Change Change"; changes now say who did what, such as "Kev's review changed a skill · Triage". +- Add group chats: list, create, edit, and delete them from the sidebar, and chat with up to six bots at once. Includes live member status, stop, earlier messages, attachments, replies, `@` mentions, reactions, and sources. Sends and record changes apply at once and recover on failure. +- Title group replies "Bot in Group", keep them quiet only while that group is on screen, and open the group from the notification. +- Rework the Skills page: per-bot skills through the skill endpoints, search, owner filters, pinning, confirmed deletes, and a used-by picker in the skill form. +- Install shared skills from GitHub, view them read-only, make editable copies, check for updates, and review an update's diff before applying it. These stay pending until the server confirms. +- Select skills to update, delete, assign to bots, or remove from bots in bulk. Failures stay selected and each one is reported. +- Show where each memory came from and how old it is, mark search matches, default new memories to the filtered owner, and report a failed owner's memories in its own group. +- Add a change history to Memory and Skills, and diffs with revert to Activity. Reverts apply at once and roll back on failure. +- Add the Avatars page: idle, working, and sleeping previews, and saving a definition to a chosen bot. +- Add script tasks to the task form, with a command, timeout, and result notifications, for bots with coding jobs on a server with workspaces. +- Run tasks on events: add and delete event sources in the new Event sources tab, shown once with their webhook address, and pick one in the task form. Source changes stay pending until the relay confirms. +- Add a Runs tab that merges prompt and script runs, with script output, exit code, and duration. +- Show task status and next run, pause and resume tasks, sort tasks by status, and hide prompt tasks that already ran. Running a script task now opens its bot's chat. +- Add the Credentials and Logins pages: per-bot lists with search, waiting requests, edit, delete, and a 90-day use history. Plain values apply at once and roll back on failure; password manager references and 1Password items stay pending until Crumble has read them. +- Answer `request_credential` and `request_login` in the chat with request cards that settle as saved or declined. +- Add the Password managers page: connect 1Password or Bitwarden with a token, replace it, and disconnect. Secrets can be read from a connected manager instead of being stored in Crumble. +- Add the Providers page: search, status, API keys from a value or a password manager, sign out, copyable commands for externally signed-in providers, and account sign-in with auth links, device codes, and prompts. Sign-in keeps running on the server when hidden. "Provider Settings…" in a failed chat now opens this page, and the bot editor links to its credentials. +- Keep typed secrets in memory only, redacted from `toString`, and drop them after saving or when leaving the screen. +- Add the Coding page: GitHub Apps (create, install, check, sign in as you, client secret, bots, remove), machine accounts (add, token, bots, signing key, remove), and workspace settings for admins. GitHub's pages open inside the app, and nothing reads as done until the server confirms. +- Add the Message gateways pages: status, token, default bot, aliases, owner, direct messages, and channels. Save and Reset work on a draft that survives refreshes and failed saves. +- Add the Event relay page: relay address, status, token, and event sources. +- Add the Web search, Judge model, and Vision model pages, with plugin keys on the pages that need them. Choices apply at once and roll back on failure. +- Add search, delete confirmation, connection errors, password manager tokens, and an OAuth app to Integrations. +- Create an account from Settings, with an optional invite link or code. It reads as done only once the server confirms; if connecting fails after that, the form switches to sign-in. +- Add the Users page for admins: change roles, remove accounts after a confirmation, create and revoke one-time invite links, and open or close sign-up. Changes apply at once and roll back on failure. +- List workspaces still on an older image on the Coding page. - Pin the bot's `1.0.0` contract as a checksum-verified local export with committed source provenance. - Generate Kotlin HTTP operations and serializable wire types with repository-owned generator `1.0.0` and a pinned transport template. @@ -14,3 +72,39 @@ - Verify committed generated output byte-for-byte in public CI. Add explicit local/release update commands and a scheduled, self-checking update PR workflow. The bootstrap pin must switch to the immutable `contract-v1.0.0` release after bot publishes it, before merging the consumer update. +- Add the bot desktop: a live preview with machine status and wake in Jobs, a full viewer from there or from a desktop job, and Take control and Hand back with live updates from the server. Control reads as yours only once the server confirms, and leaving hands it back. Touch gestures click and scroll, and a key row and text field type on the desktop. Rotating no longer restarts the app. +- Remove the provider key form from Settings; the Providers page replaces it. Also remove the unused compact chat action. +- Clear the typed password and invite code when Settings closes, and drop typed credentials when a notification leaves their page for the selected bot's chat. +- Stop waiting for an MCP sign-in when you come back from the browser without finishing it, so the row and the other Sign In buttons work again. Finishing in the browser later still signs in. +- Warn in Settings when the server URL is http and the host isn't local or private. +- Exclude stored credentials from device backups and transfers. +- Remove a deleted bot's cached chat from the device, and clear GitHub's web sign-in when the session changes. GitHub's pages have no file access. +- Keep the password field out of the keyboard's suggestions, and mark copied invite links as sensitive. +- Open on Home: a greeting, today's date, and every bot with its live status. Home is in the drawer, and a chat no longer opens by itself at launch. +- Search chats, pages, settings, and themes from the drawer or Home. +- Add Notifications to Settings: turn bot replies and their sound on or off for this device, with a link to Android's settings when notifications are blocked. +- Pick a System, Light, or Dark theme in Settings. It applies at once, saves to your account like the website, and goes back if the save fails. +- Show the connected server's address in Settings, with a copy button. +- Activity filters by kind and bot, loads older pages with "Show older activity", groups rows by day, and shows readable sentences and previews instead of raw JSON. +- Pick when a task runs with a friendly recurrence picker, date, time, and time zone pickers, and a next-run preview. Cron schedules read as worded text, and a custom cron stays available. +- Ask before deleting a task. +- Fix the previous server's activity staying on the page after signing out. +- Keep drafts, open forms, the current page, and running saves when Android recreates the screen, such as on a dark mode or font size change. +- New bots start on the first set-up provider. The editor lists only set-up providers plus the bot's current one, and needs a provider and model before saving, like the website. +- Remove the per-bot permitted list and the Use shared memory switch, which the server ignores, and stop sending those fields. +- Label event, script, credential, and bot request messages as the website does instead of "You", and hide job messages from the chat. +- Only open an MCP sign-in page that is a web address. +- Refuse an oversized attachment without reading it all, and read picked files off the main thread. Images over 32 MB are refused rather than re-encoded. +- Show GitHub-managed credentials without Edit or Delete. +- Send the device's time zone with bot chat messages, so bots know the owner's local time. +- End the previous session on the server when connecting replaces it. +- Mark the copied event source webhook address as sensitive, and keep the invite code out of keyboard suggestions. +- Say so when a sign-in comes back after its request was lost, instead of doing nothing. +- Stay on the open page after reconnecting from Settings instead of jumping to a chat. +- Drop job lists that arrive after a job question's session has changed. +- Links in bot replies open in the browser: Markdown links, bare URLs, and `` autolinks. Only web links can be tapped. +- Show Markdown tables and strikethrough in bot replies. +- Keep bot and group text drafts across an app restart, encrypted and scoped to the server and account. Signing out or changing server deletes them. Attachments and reply targets are not saved. +- The chat's credential request opens the same sheet as the Credentials page, where you can edit the hosts the bot proposed, read the value from a password manager, and see the warning to check them. +- Add a Reasoning field to the bot editor. It follows the chosen model: a level the model doesn't take saves as the nearest one it does, and the field hides for models that don't reason. +- Collapse automation, event, script, credential, bot request, and other bots' messages into notice rows, like the website. Tap one to read it. diff --git a/GLOSSARY.md b/GLOSSARY.md index b58a3e4..f2bc95f 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -1,3 +1,3 @@ # Crumble -Crumble's domain language is defined once, in the [canonical glossary](https://github.com/crumble-project/spec/blob/main/GLOSSARY.md). In a local checkout of the project, it is `../spec/GLOSSARY.md`. Add and change terms there, not here. +Crumble's domain language is defined once, in the [canonical glossary](https://github.com/crumble-project/bot/blob/main/GLOSSARY.md). In a local checkout of the project, it is `../bot/GLOSSARY.md`. Add and change terms there, not here. diff --git a/README.md b/README.md index 3cda460..10a4d81 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,8 @@ Native Kotlin and Jetpack Compose client for a Crumble server. ## Build and test +Gradle builds bot avatars from the [open-bot-avatar-kt](https://github.com/cheetahbyte/open-bot-avatar-kt) `0.1.0` tag on GitHub. Set `ANDROID_HOME` in your environment before building, because `local.properties` does not reach that source build. + ```bash ./gradlew assembleDebug python3 -m unittest discover -s scripts -p 'test_*.py' @@ -18,11 +20,11 @@ python3 scripts/contract.py check ## Connect to a server -Open the navigation drawer › **Settings**, enter the server URL (`http://10.0.2.2:7337` on the Android Emulator for a host server on `127.0.0.1:7337`, or a LAN/HTTPS address on a physical device) and `server-token`, and tap **Save Connection**. Credentials are stored encrypted in the Android Keystore. Debug builds install as **Crumble Dev** (`ng.crumbli.android.dev`) beside the release app (`ng.crumbli.android`), so each keeps its own connection; the sign-in callback scheme is the application ID, for example `ng.crumbli.android:/oauth/callback`. +Open the navigation drawer › **Settings**, enter the server URL (`http://10.0.2.2:7337` on the Android Emulator for a host server on `127.0.0.1:7337`, or a LAN/HTTPS address on a physical device), your account email and password, and tap **Save Connection**. The app stores the account session encrypted in the Android Keystore; it does not store the password. Debug builds install as **Crumble Dev** (`ng.crumbli.android.dev`) beside the release app (`ng.crumbli.android`), so each keeps its own connection; the sign-in callback scheme is the application ID, for example `ng.crumbli.android:/oauth/callback`. ## Shared API contract -`contract/pin.json` and `contract/assets/` pin the verified `bot` contract release (`contract-vX.Y.Z`). `scripts/generate-contract.py` generates Kotlin wire models and operations without external build-time dependencies. +`contract/pin.json` and `contract/assets/` pin a verified `bot` contract: a local export of a `bot` commit, or a release (`contract-vX.Y.Z`). `bot` no longer publishes contract releases, so current updates use `--local`. `scripts/generate-contract.py` generates Kotlin wire models and operations without external build-time dependencies. ```bash python3 scripts/contract.py generate # Regenerate from current pin diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 8c4a7ce..9d3b112 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -1,13 +1,14 @@ # Third-party notices -## Bot avatars +## Open Bot Avatar for Kotlin -Bot avatars (`app/src/main/java/dev/crumble/android/ui/BotAvatar.kt`) are adapted from Hermex's drawn bot faces: their shapes, palette, eye geometry, blink schedule, and working pose. Hermex is available under the MIT License, Copyright (c) 2026 Uzair Ansar. The eye expressions follow Bloub's measured catalogue (jeremy-prt/bloub), also under the MIT License. +Bot avatars are drawn by [open-bot-avatar-kt](https://github.com/cheetahbyte/open-bot-avatar-kt), a port of Open Bot Avatar. `app/src/main/res/raw/generate_avatar_prompt.txt` comes from the `bot` web app. ```text MIT License -Copyright (c) 2026 Uzair Ansar +Copyright (c) 2026 Dominik Scholz +Copyright (c) 2026 Leonhard Breuer Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/app/build.gradle.kts b/app/build.gradle.kts index c9566fd..a2ef9a3 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -54,6 +54,7 @@ kotlin { } dependencies { + implementation(libs.open.bot.avatar.compose) implementation(platform(libs.firebase.bom)) implementation(libs.firebase.messaging) implementation(libs.androidx.work.runtime.ktx) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 0634ceb..8b735f0 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -6,6 +6,8 @@ diff --git a/app/src/main/java/dev/crumble/android/AppViewModel.kt b/app/src/main/java/dev/crumble/android/AppViewModel.kt new file mode 100644 index 0000000..5cecd06 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/AppViewModel.kt @@ -0,0 +1,26 @@ +package dev.crumble.android + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dev.crumble.android.model.AppModel +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob + +/** Keeps the model through activity recreation, so drafts, open forms, and running saves survive a theme or locale change. */ +class AppViewModel(build: (CoroutineScope, () -> Unit) -> AppModel) : ViewModel() { + /** The current activity's handler; the model itself must never hold an activity. */ + var onNotificationsChanged: () -> Unit = {} + + val model: AppModel = build(viewModelScope) { onNotificationsChanged() } + + private var started = false + + /** True once per model: a recreated activity must not reload it or replay the intent that opened the app. */ + fun start(): Boolean = !started.also { started = true } + + override fun onCleared() { + // viewModelScope has ended by now; handing back must not end with it. + model.closeBotDesktop(CoroutineScope(SupervisorJob() + Dispatchers.IO)) + } +} diff --git a/app/src/main/java/dev/crumble/android/MainActivity.kt b/app/src/main/java/dev/crumble/android/MainActivity.kt index 9c44e9d..0164ec9 100644 --- a/app/src/main/java/dev/crumble/android/MainActivity.kt +++ b/app/src/main/java/dev/crumble/android/MainActivity.kt @@ -3,12 +3,18 @@ package dev.crumble.android import android.Manifest import android.content.Intent import android.content.pm.PackageManager +import android.graphics.Color import android.os.Build import android.os.Bundle +import android.webkit.CookieManager +import android.webkit.WebStorage import androidx.activity.ComponentActivity +import androidx.activity.SystemBarStyle import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.result.contract.ActivityResultContracts +import androidx.activity.viewModels +import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface @@ -19,7 +25,10 @@ import androidx.core.content.ContextCompat import androidx.lifecycle.lifecycleScope import androidx.lifecycle.Lifecycle import androidx.lifecycle.repeatOnLifecycle +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory import dev.crumble.android.model.AppModel +import dev.crumble.android.model.ThemeChoice import dev.crumble.android.storage.AndroidKeyStoreCredentials import dev.crumble.android.theme.CrumbleTheme import dev.crumble.android.ui.CrumbleAppScreen @@ -28,29 +37,62 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch +private val LIGHT_BAR_SCRIM = Color.argb(0xe6, 0xff, 0xff, 0xff) +private val DARK_BAR_SCRIM = Color.argb(0x80, 0x1b, 0x1b, 0x1b) + +/** GitHub's pages keep their own sign-in, which must not carry over to the next account. */ +private fun forgetWebSessions() { + runCatching { + CookieManager.getInstance().removeAllCookies(null) + WebStorage.getInstance().deleteAllData() + } +} + class MainActivity : ComponentActivity() { - private lateinit var model: AppModel private val push by lazy { PushRuntime.get(applicationContext) } + private val owner: AppViewModel by viewModels { + // The model outlives this activity, so nothing it keeps may reach back here. + val context = applicationContext + val runtime = push + viewModelFactory { + initializer { + AppViewModel { scope, notificationsChanged -> + AppModel( + credentials = AndroidKeyStoreCredentials(context), + notifier = runtime, + scope = scope, + environment = System.getenv(), + onSignOut = { runtime.signedOut(it) }, + onSessionReset = ::forgetWebSessions, + onNotificationsChanged = notificationsChanged, + ) + } + } + } + } + private val model: AppModel + get() = owner.model private val notificationPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission(), - ) { if (::model.isInitialized) model.client?.let { push.configure(it) } } + ) { + model.notificationsAllowed = push.notificationsAllowed() + model.client?.let { push.configure(it) } + } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - requestNotificationPermissionIfNeeded() + if (push.repliesWanted) requestNotificationPermissionIfNeeded() - model = AppModel( - credentials = AndroidKeyStoreCredentials(applicationContext), - notifier = push, - scope = lifecycleScope, - environment = System.getenv(), - ) + owner.onNotificationsChanged = ::notificationsChanged + model.notificationsAllowed = push.notificationsAllowed() model.client?.let { push.configure(it) } - model.refresh() - model.followActivity() - handleIncomingIntent(intent) + if (owner.start()) { + model.refresh() + model.followActivity() + handleIncomingIntent(intent) + } lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.RESUMED) { while (isActive) { @@ -70,7 +112,13 @@ class MainActivity : ComponentActivity() { push.updatePresence(active, route) } } - CrumbleTheme { + val dark = when (model.theme) { + ThemeChoice.System -> isSystemInDarkTheme() + ThemeChoice.Light -> false + ThemeChoice.Dark -> true + } + LaunchedEffect(dark) { matchSystemBars(dark) } + CrumbleTheme(darkTheme = dark) { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background, @@ -88,25 +136,45 @@ class MainActivity : ComponentActivity() { override fun onResume() { super.onResume() - if (::model.isInitialized) { - model.appActive = true - model.client?.let { push.configure(it) } - push.updatePresence(true, model.route) - } + model.appActive = true + model.browserReturned() + model.notificationsAllowed = push.notificationsAllowed() + model.client?.let { push.configure(it) } + push.updatePresence(true, model.route) } override fun onPause() { super.onPause() - if (::model.isInitialized) { - model.appActive = false - push.updatePresence(false, model.route) - } + model.appActive = false + model.saveDrafts() + push.updatePresence(false, model.route) + } + + override fun onDestroy() { + owner.onNotificationsChanged = {} + super.onDestroy() + } + + /** Android's default follows the system, which leaves dark icons on a dark app after a theme pick. */ + private fun matchSystemBars(dark: Boolean) { + enableEdgeToEdge( + statusBarStyle = SystemBarStyle.auto(Color.TRANSPARENT, Color.TRANSPARENT) { dark }, + navigationBarStyle = SystemBarStyle.auto(LIGHT_BAR_SCRIM, DARK_BAR_SCRIM) { dark }, + ) + } + + private fun notificationsChanged() { + if (model.replyNotifications) requestNotificationPermissionIfNeeded() + model.client?.let { push.configure(it) } } private fun handleIncomingIntent(intent: Intent?) { - if (intent == null || !::model.isInitialized) return + if (intent == null) return + val groupId = push.groupFromIntent(intent) val agentId = push.agentFromIntent(intent) - if (!agentId.isNullOrEmpty()) { + if (!groupId.isNullOrEmpty()) { + model.openGroupChat(groupId) + } else if (!agentId.isNullOrEmpty()) { model.selectAgent(agentId) } val data = intent.data diff --git a/app/src/main/java/dev/crumble/android/generated/ContractBoundary.kt b/app/src/main/java/dev/crumble/android/generated/ContractBoundary.kt index 024c37a..65249ca 100644 --- a/app/src/main/java/dev/crumble/android/generated/ContractBoundary.kt +++ b/app/src/main/java/dev/crumble/android/generated/ContractBoundary.kt @@ -1,4 +1,4 @@ -// Generated by scripts/generate-contract.py 1.0.0. Do not edit. +// Generated by scripts/generate-contract.py 1.1.0. Do not edit. package dev.crumble.android.generated import dev.crumble.android.network.HttpRequestData diff --git a/app/src/main/java/dev/crumble/android/generated/ContractModels.kt b/app/src/main/java/dev/crumble/android/generated/ContractModels.kt index 603fedd..c23d6dc 100644 --- a/app/src/main/java/dev/crumble/android/generated/ContractModels.kt +++ b/app/src/main/java/dev/crumble/android/generated/ContractModels.kt @@ -1,5 +1,5 @@ @file:OptIn(kotlinx.serialization.ExperimentalSerializationApi::class) -// Generated by scripts/generate-contract.py 1.0.0. Do not edit. +// Generated by scripts/generate-contract.py 1.1.0. Do not edit. package dev.crumble.android.generated import kotlinx.serialization.* @@ -74,6 +74,10 @@ data class ActivityEventPayloadVariant1( val `preview`: String, val `createdAt`: String, val `executionId`: String? = null, + val `jobName`: String? = null, + val `groupId`: String? = null, + val `groupName`: String? = null, + val `waitingFor`: String? = null, ) @Serializable @@ -86,19 +90,69 @@ data class ActivityEventPayloadVariant2( @Serializable data class ActivityFeed( - val `activities`: List, + val `activities`: List, val `hasMore`: Boolean, + val `nextCursor`: String?, +) + +@Serializable(with = ActivityFeedActivitiesItemCodec::class) +sealed class ActivityFeedActivitiesItem { + data class Variant1(val value: OperationalActivity) : ActivityFeedActivitiesItem() + data class Variant2(val value: ChangeActivity) : ActivityFeedActivitiesItem() +} +object ActivityFeedActivitiesItemCodec : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ActivityFeedActivitiesItem") + override fun deserialize(decoder: Decoder): ActivityFeedActivitiesItem { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement() + return when { + (element is JsonObject && element["id"] != null && element["agentId"] != null && element["agentName"] != null && element["entryId"] != null && element["kind"] != null && (element["kind"] == Json.parseToJsonElement("\"tool-call\"") || element["kind"] == Json.parseToJsonElement("\"tool-result\"") || element["kind"] == Json.parseToJsonElement("\"mcp-call\"") || element["kind"] == Json.parseToJsonElement("\"bot-message\"")) && element["details"] != null) -> ActivityFeedActivitiesItem.Variant1(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["id"] != null && element["agentId"] != null && element["agentName"] != null && element["timestamp"] != null && element["kind"] != null && (element["kind"] == Json.parseToJsonElement("\"change\"")) && element["change"] != null) -> ActivityFeedActivitiesItem.Variant2(input.json.decodeFromJsonElement(element)) + else -> throw SerializationException("Unknown ActivityFeedActivitiesItem variant") + } + } + override fun serialize(encoder: Encoder, value: ActivityFeedActivitiesItem) { + val output = encoder as JsonEncoder + output.encodeJsonElement(when (value) { + is ActivityFeedActivitiesItem.Variant1 -> output.json.encodeToJsonElement(value.value) + is ActivityFeedActivitiesItem.Variant2 -> output.json.encodeToJsonElement(value.value) + }) + } +} + +@Serializable +data class AddGithubAccountRequest( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `value`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `reference`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class AddGithubAccountRequestReference( + val `passwordManager`: String, + val `reference`: String, +) + +@Serializable +data class AdminUser( + val `id`: String, + val `email`: String, + val `name`: String, + val `role`: String, + val `createdAt`: String, ) @Serializable data class Agent( val `id`: String, val `name`: String, - val `avatar`: String, + val `avatar`: BotAvatarDefinition, val `description`: String, val `instructions`: String, val `provider`: String, val `model`: String, + val `webSearchProvider`: String? = null, val `enabled`: Boolean, val `tools`: List, val `skills`: List, @@ -107,10 +161,19 @@ data class Agent( val `mcpServers`: List, val `delegates`: List, val `inference`: AgentInference? = null, + val `desktopModel`: AgentDesktopModel? = null, + val `review`: AgentReview? = null, + val `reviewModel`: AgentReviewModel? = null, val `createdAt`: String, val `updatedAt`: String, ) +@Serializable +data class AgentDesktopModel( + val `provider`: String, + val `model`: String, +) + @Serializable data class AgentInference( val `thinkingLevel`: String? = null, @@ -122,11 +185,12 @@ data class AgentInference( data class AgentPreview( val `id`: String, val `name`: String, - val `avatar`: String, + val `avatar`: BotAvatarDefinition, val `description`: String, val `instructions`: String, val `provider`: String, val `model`: String, + val `webSearchProvider`: String? = null, val `enabled`: Boolean, val `tools`: List, val `skills`: List, @@ -135,11 +199,20 @@ data class AgentPreview( val `mcpServers`: List, val `delegates`: List, val `inference`: AgentPreviewInference? = null, + val `desktopModel`: AgentPreviewDesktopModel? = null, + val `review`: AgentPreviewReview? = null, + val `reviewModel`: AgentPreviewReviewModel? = null, val `createdAt`: String, val `updatedAt`: String, val `lastMessage`: String? = null, ) +@Serializable +data class AgentPreviewDesktopModel( + val `provider`: String, + val `model`: String, +) + @Serializable data class AgentPreviewInference( val `thinkingLevel`: String? = null, @@ -148,101 +221,68 @@ data class AgentPreviewInference( ) @Serializable -data class AgentPreviewSkillsItem( - val `name`: String, - val `instructions`: String, +data class AgentPreviewReview( + val `enabled`: Boolean, + val `skillThreshold`: Long, + val `memoryThreshold`: Long, + val `maxInputTokens`: Long? = null, ) @Serializable -data class AgentSkillsItem( - val `name`: String, - val `instructions`: String, +data class AgentPreviewReviewModel( + val `provider`: String, + val `model`: String, ) @Serializable -data class AttachmentInfo( +data class AgentPreviewSkillsItem( val `name`: String, - val `mimeType`: String, - val `size`: Double, - val `kind`: String, -) - -@Serializable -data class BotCommunication( - val `executionId`: String, - val `fromAgentId`: String, - val `fromName`: String, - val `toAgentId`: String, - val `toName`: String, - val `status`: String, -) - -@Serializable -data class Capabilities( - val `coding`: Boolean, + val `instructions`: String, ) @Serializable -data class ChatPreviewEvent( - val `type`: String, - val `agentId`: String, - val `agentName`: String, - val `lastMessage`: String, +data class AgentReview( + val `enabled`: Boolean, + val `skillThreshold`: Long, + val `memoryThreshold`: Long, + val `maxInputTokens`: Long? = null, ) @Serializable -data class ChatSnapshot( - val `messages`: List, - val `hasMore`: Boolean, - val `oldestEntryId`: String?, - val `conversationId`: String, - val `agentId`: String, - val `conversation`: Conversation, - val `live`: JsonElement? = null, - val `partial`: String, - val `usage`: JsonElement? = null, - val `status`: String, - val `updatedAt`: Double, - val `error`: String?, +data class AgentReviewModel( + val `provider`: String, + val `model`: String, ) @Serializable -data class CodingJob( +data class AgentSkillsItem( val `name`: String, - val `conversationId`: String, - val `status`: String, -) - -@Serializable -data class CodingJobs( - val `jobs`: List, + val `instructions`: String, ) @Serializable -data class Compaction( - val `taskId`: String, +data class AnswerCodingJobRequest( + val `questionId`: String, + val `text`: String, ) @Serializable -data class Conversation( - val `id`: String, - val `agentId`: String, - val `title`: String, - val `createdAt`: String, - val `updatedAt`: String, - val `archived`: Boolean? = null, +data class AnswerProviderLoginRequest( + val `promptId`: String, + val `value`: String, ) @Serializable -data class CreateAgentMemoryRequest( - val `content`: String, +data class ApproveBotRequestRequest( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `proposal`: OptionalField = OptionalField.Absent, ) @Serializable -data class CreateAgentRequest( +data class ApproveBotRequestRequestProposal( val `name`: String, @EncodeDefault(EncodeDefault.Mode.NEVER) - val `avatar`: OptionalField = OptionalField.Absent, + val `avatar`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) val `description`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) @@ -252,11 +292,13 @@ data class CreateAgentRequest( @EncodeDefault(EncodeDefault.Mode.NEVER) val `model`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) + val `webSearchProvider`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) val `enabled`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) val `tools`: OptionalField> = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) - val `skills`: OptionalField> = OptionalField.Absent, + val `skills`: OptionalField> = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) val `sharedSkills`: OptionalField> = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) @@ -266,147 +308,1098 @@ data class CreateAgentRequest( @EncodeDefault(EncodeDefault.Mode.NEVER) val `delegates`: OptionalField> = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) - val `inference`: OptionalField = OptionalField.Absent, -) - -@Serializable -data class CreateAgentRequestInference( + val `inference`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) - val `thinkingLevel`: OptionalField = OptionalField.Absent, + val `review`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) - val `temperature`: OptionalField = OptionalField.Absent, + val `reviewModel`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) - val `maxOutputTokens`: OptionalField = OptionalField.Absent, + val `desktopModel`: OptionalField = OptionalField.Absent, ) @Serializable -data class CreateAgentRequestSkillsItem( - val `name`: String, - val `instructions`: String, +data class ApproveBotRequestRequestProposalAvatar( + val `definition`: ApproveBotRequestRequestProposalAvatarDefinition, + val `color`: String, + val `eyeColor`: String, ) @Serializable -data class CreateMcpServerRequest( +data class ApproveBotRequestRequestProposalAvatarDefinition( + val `version`: Double, + val `id`: String, val `name`: String, - val `url`: String, + val `body`: ApproveBotRequestRequestProposalAvatarDefinitionBody, + val `eyes`: ApproveBotRequestRequestProposalAvatarDefinitionEyes, +) + +@Serializable +data class ApproveBotRequestRequestProposalAvatarDefinitionBody( + val `path`: String, +) + +@Serializable +data class ApproveBotRequestRequestProposalAvatarDefinitionEyes( + val `x`: Double, + val `y`: Double, + val `spacing`: Double, + val `scale`: Double, +) + +@Serializable +data class ApproveBotRequestRequestProposalDesktopModel( + val `provider`: String, + val `model`: String, +) + +@Serializable +data class ApproveBotRequestRequestProposalInference( @EncodeDefault(EncodeDefault.Mode.NEVER) - val `enabled`: OptionalField = OptionalField.Absent, + val `thinkingLevel`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) - val `token`: OptionalField = OptionalField.Absent, + val `temperature`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) - val `agentId`: OptionalField = OptionalField.Absent, + val `maxOutputTokens`: OptionalField = OptionalField.Absent, ) @Serializable -data class CreateScheduleRequest( - val `agentId`: String, - val `name`: String, - val `prompt`: String, +data class ApproveBotRequestRequestProposalReview( @EncodeDefault(EncodeDefault.Mode.NEVER) - val `cron`: OptionalField = OptionalField.Absent, + val `enabled`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) - val `timezone`: OptionalField = OptionalField.Absent, + val `skillThreshold`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) - val `runAt`: OptionalField = OptionalField.Absent, + val `memoryThreshold`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) - val `enabled`: OptionalField = OptionalField.Absent, + val `maxInputTokens`: OptionalField = OptionalField.Absent, ) @Serializable -data class CreateSharedMemoryRequest( - val `content`: String, +data class ApproveBotRequestRequestProposalReviewModel( + val `provider`: String, + val `model`: String, ) @Serializable -data class CreateSkillRequest( +data class ApproveBotRequestRequestProposalSkillsItem( val `name`: String, val `instructions`: String, ) @Serializable -data class Error( - val `error`: String, - val `details`: List? = null, +data class ApproveBotRequestResponse( + val `request`: BotRequest, + val `agent`: Agent, ) @Serializable -data class ErrorDetailsItem( - val `code`: String, - val `path`: List, - val `message`: String, +data class AssignSkillBotRequest( + val `botId`: String, + val `assigned`: Boolean, ) -@Serializable(with = ErrorDetailsItemPathItemCodec::class) -sealed class ErrorDetailsItemPathItem { - data class Variant1(val value: String) : ErrorDetailsItemPathItem() - data class Variant2(val value: Double) : ErrorDetailsItemPathItem() -} -object ErrorDetailsItemPathItemCodec : KSerializer { - override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ErrorDetailsItemPathItem") - override fun deserialize(decoder: Decoder): ErrorDetailsItemPathItem { - val input = decoder as JsonDecoder - val element = input.decodeJsonElement() - return when { - (element is JsonPrimitive && element.isString) -> ErrorDetailsItemPathItem.Variant1(input.json.decodeFromJsonElement(element)) - (element is JsonPrimitive && !element.isString && element.doubleOrNull != null) -> ErrorDetailsItemPathItem.Variant2(input.json.decodeFromJsonElement(element)) - else -> throw SerializationException("Unknown ErrorDetailsItemPathItem variant") - } - } - override fun serialize(encoder: Encoder, value: ErrorDetailsItemPathItem) { - val output = encoder as JsonEncoder - output.encodeJsonElement(when (value) { - is ErrorDetailsItemPathItem.Variant1 -> output.json.encodeToJsonElement(value.value) - is ErrorDetailsItemPathItem.Variant2 -> output.json.encodeToJsonElement(value.value) - }) - } -} +@Serializable +data class AssignSkillBotResponse( + val `skipped`: Boolean, +) @Serializable -data class Execution( +data class AttachmentInfo( + val `name`: String, + val `mimeType`: String, + val `size`: Double, + val `kind`: String, +) + +@Serializable +data class BotAvatarDefinition( + val `definition`: BotAvatarDefinitionDefinition, + val `color`: String, + val `eyeColor`: String, +) + +@Serializable +data class BotAvatarDefinitionDefinition( + val `version`: Double, val `id`: String, - val `agentId`: String, - val `conversationId`: String, - val `scheduleId`: String?, - val `submissionId`: String?, - val `requestId`: String, - val `prompt`: String, - val `replyTo`: String? = null, - val `attachmentsDigest`: String? = null, - val `status`: String, - val `error`: String?, - val `createdAt`: String, - val `updatedAt`: String, + val `name`: String, + val `body`: BotAvatarDefinitionDefinitionBody, + val `eyes`: BotAvatarDefinitionDefinitionEyes, ) @Serializable -data class FinishMcpOAuthRequest( - val `code`: String, - val `state`: String, - @EncodeDefault(EncodeDefault.Mode.NEVER) - val `iss`: OptionalField = OptionalField.Absent, +data class BotAvatarDefinitionDefinitionBody( + val `path`: String, ) @Serializable -data class Health( +data class BotAvatarDefinitionDefinitionEyes( + val `x`: Double, + val `y`: Double, + val `spacing`: Double, + val `scale`: Double, +) + +@Serializable +data class BotCommunication( + val `executionId`: String, + val `fromAgentId`: String, + val `fromName`: String, + val `toAgentId`: String, + val `toName`: String, val `status`: String, - val `apiVersion`: Double, ) @Serializable -class HeartbeatEvent +data class BotRequest( + val `id`: String, + val `agentId`: String, + val `proposal`: BotRequestProposal, + val `reason`: String, + val `status`: String, + val `createdAgentId`: String?, + val `requestedAt`: String, + val `decidedAt`: String?, +) @Serializable -class HeartbeatEventPayload +data class BotRequestProposal( + val `name`: String, + val `avatar`: BotRequestProposalAvatar? = null, + val `description`: String? = null, + val `instructions`: String? = null, + val `provider`: String? = null, + val `model`: String? = null, + val `webSearchProvider`: String? = null, + val `enabled`: Boolean? = null, + val `tools`: List? = null, + val `skills`: List? = null, + val `sharedSkills`: List? = null, + val `sharedMemory`: Boolean? = null, + val `mcpServers`: List? = null, + val `delegates`: List? = null, + val `inference`: BotRequestProposalInference? = null, + val `review`: BotRequestProposalReview? = null, + val `reviewModel`: BotRequestProposalReviewModel? = null, + val `desktopModel`: BotRequestProposalDesktopModel? = null, +) -@Serializable(with = ListedSkillCodec::class) -sealed class ListedSkill { - data class Variant1(val value: ListedSkillVariant1) : ListedSkill() - data class Variant2(val value: ListedSkillVariant2) : ListedSkill() -} -object ListedSkillCodec : KSerializer { - override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ListedSkill") - override fun deserialize(decoder: Decoder): ListedSkill { - val input = decoder as JsonDecoder +@Serializable +data class BotRequestProposalAvatar( + val `definition`: BotRequestProposalAvatarDefinition, + val `color`: String, + val `eyeColor`: String, +) + +@Serializable +data class BotRequestProposalAvatarDefinition( + val `version`: Double, + val `id`: String, + val `name`: String, + val `body`: BotRequestProposalAvatarDefinitionBody, + val `eyes`: BotRequestProposalAvatarDefinitionEyes, +) + +@Serializable +data class BotRequestProposalAvatarDefinitionBody( + val `path`: String, +) + +@Serializable +data class BotRequestProposalAvatarDefinitionEyes( + val `x`: Double, + val `y`: Double, + val `spacing`: Double, + val `scale`: Double, +) + +@Serializable +data class BotRequestProposalDesktopModel( + val `provider`: String, + val `model`: String, +) + +@Serializable +data class BotRequestProposalInference( + val `thinkingLevel`: String? = null, + val `temperature`: Double? = null, + val `maxOutputTokens`: Long? = null, +) + +@Serializable +data class BotRequestProposalReview( + val `enabled`: Boolean? = null, + val `skillThreshold`: Long? = null, + val `memoryThreshold`: Long? = null, + val `maxInputTokens`: Long? = null, +) + +@Serializable +data class BotRequestProposalReviewModel( + val `provider`: String, + val `model`: String, +) + +@Serializable +data class BotRequestProposalSkillsItem( + val `name`: String, + val `instructions`: String, +) + +@Serializable +data class BrowseSkillRepositoryRequest( + val `location`: String, +) + +@Serializable +data class Capabilities( + val `coding`: Boolean, + val `desktop`: Boolean, + val `jobKinds`: List, +) + +@Serializable +data class ChangeActivity( + val `id`: String, + val `agentId`: String?, + val `agentName`: String?, + val `timestamp`: Double, + val `kind`: String, + val `change`: LearnedChange, +) + +@Serializable +data class ChangeSource( + val `executionId`: String? = null, + val `conversationId`: String? = null, + val `groupId`: String? = null, +) + +@Serializable +data class ChatPreviewEvent( + val `type`: String, + val `agentId`: String, + val `agentName`: String, + val `lastMessage`: String, +) + +@Serializable +data class ChatSnapshot( + val `messages`: List, + val `hasMore`: Boolean, + val `oldestEntryId`: String?, + val `conversationId`: String, + val `agentId`: String, + val `conversation`: Conversation, + val `live`: JsonElement? = null, + val `partial`: String, + val `usage`: JsonElement? = null, + val `status`: String, + val `updatedAt`: Double, + val `error`: String?, +) + +@Serializable +data class CodingJob( + val `name`: String, + val `conversationId`: String, + val `status`: String, + val `model`: CodingJobModel? = null, + val `usage`: JsonElement? = null, + val `question`: CodingJobQuestion? = null, +) + +@Serializable +data class CodingJobModel( + val `provider`: String, + val `model`: String, +) + +@Serializable +data class CodingJobQuestion( + val `id`: String, + val `text`: String, + val `askedAt`: Double, + val `options`: List? = null, + val `multiple`: Boolean? = null, +) + +@Serializable +data class CodingJobs( + val `jobs`: List, +) + +@Serializable +data class Compaction( + val `taskId`: String, +) + +@Serializable +data class CompleteGithubAppRequest( + val `code`: String, + val `state`: String, +) + +@Serializable +data class CompleteGithubAppSignInRequest( + val `code`: String, + val `state`: String, +) + +@Serializable +data class ConnectPasswordManagerRequest( + val `token`: String, +) + +@Serializable +data class Conversation( + val `id`: String, + val `agentId`: String, + val `title`: String, + val `createdAt`: String, + val `updatedAt`: String, + val `archived`: Boolean? = null, +) + +@Serializable +data class CreateAgentMemoryRequest( + val `content`: String, +) + +@Serializable +data class CreateAgentRequest( + val `name`: String, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `avatar`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `description`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `instructions`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `provider`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `model`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `webSearchProvider`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `enabled`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `tools`: OptionalField> = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `skills`: OptionalField> = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `sharedSkills`: OptionalField> = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `sharedMemory`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `mcpServers`: OptionalField> = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `delegates`: OptionalField> = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `inference`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `review`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `reviewModel`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `desktopModel`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class CreateAgentRequestAvatar( + val `definition`: CreateAgentRequestAvatarDefinition, + val `color`: String, + val `eyeColor`: String, +) + +@Serializable +data class CreateAgentRequestAvatarDefinition( + val `version`: Double, + val `id`: String, + val `name`: String, + val `body`: CreateAgentRequestAvatarDefinitionBody, + val `eyes`: CreateAgentRequestAvatarDefinitionEyes, +) + +@Serializable +data class CreateAgentRequestAvatarDefinitionBody( + val `path`: String, +) + +@Serializable +data class CreateAgentRequestAvatarDefinitionEyes( + val `x`: Double, + val `y`: Double, + val `spacing`: Double, + val `scale`: Double, +) + +@Serializable +data class CreateAgentRequestDesktopModel( + val `provider`: String, + val `model`: String, +) + +@Serializable +data class CreateAgentRequestInference( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `thinkingLevel`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `temperature`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `maxOutputTokens`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class CreateAgentRequestReview( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `enabled`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `skillThreshold`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `memoryThreshold`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `maxInputTokens`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class CreateAgentRequestReviewModel( + val `provider`: String, + val `model`: String, +) + +@Serializable +data class CreateAgentRequestSkillsItem( + val `name`: String, + val `instructions`: String, +) + +@Serializable +data class CreateAgentSkillRequest( + val `name`: String, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `description`: OptionalField = OptionalField.Absent, + val `instructions`: String, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `documents`: OptionalField> = OptionalField.Absent, +) + +@Serializable +data class CreateAgentSkillRequestDocumentsItem( + val `path`: String, + val `content`: String, +) + +@Serializable +data class CreateEventSourceRequest( + val `name`: String, +) + +@Serializable +data class CreateEventSourceResponse( + val `id`: String, + val `name`: String, + val `createdAt`: String, + val `usedBy`: Long, + val `address`: String, +) + +@Serializable +data class CreateGithubAppManifestRequest( + val `name`: String, + val `origin`: String, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `organization`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class CreateGithubAppManifestResponse( + val `url`: String, + val `manifest`: String, +) + +@Serializable +data class CreateGroupChatRequest( + val `name`: String, + val `memberIds`: List, +) + +@Serializable +data class CreateMcpServerRequest( + val `name`: String, + val `url`: String, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `enabled`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `token`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `oauthClientId`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `oauthClientSecret`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `agentId`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class CreateMcpServerRequestOauthClientSecret( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `value`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `reference`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class CreateMcpServerRequestOauthClientSecretReference( + val `passwordManager`: String, + val `reference`: String, +) + +@Serializable +data class CreateMcpServerRequestToken( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `value`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `reference`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class CreateMcpServerRequestTokenReference( + val `passwordManager`: String, + val `reference`: String, +) + +@Serializable +data class CreateScheduleRequest( + val `agentId`: String, + val `name`: String, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `kind`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `prompt`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `command`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `timeoutSeconds`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `notify`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `cron`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `timezone`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `runAt`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `eventSourceId`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `enabled`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class CreateSharedMemoryRequest( + val `content`: String, +) + +@Serializable +data class CreateSkillRequest( + val `name`: String, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `description`: OptionalField = OptionalField.Absent, + val `instructions`: String, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `documents`: OptionalField> = OptionalField.Absent, +) + +@Serializable +data class CreateSkillRequestDocumentsItem( + val `path`: String, + val `content`: String, +) + +@Serializable +data class CreatedInvite( + val `id`: String, + val `createdAt`: String, + val `url`: String, +) + +@Serializable +data class Credential( + val `name`: String, + val `hosts`: List, + val `secret`: CredentialSecret?, + val `createdAt`: String, + val `updatedAt`: String, + val `lastUsedAt`: String?, + val `lastError`: String?, + val `github`: Boolean, +) + +@Serializable +data class CredentialRequest( + val `name`: String, + val `hosts`: List, + val `reason`: String, + val `requestedAt`: String, +) + +@Serializable +data class CredentialSecret( + val `configured`: Boolean, + val `passwordManager`: String?, + val `reference`: String?, +) + +@Serializable +data class CredentialUse( + val `id`: String, + val `at`: String, + val `method`: String, + val `host`: String, + val `path`: String, + val `status`: Long?, + val `error`: String?, +) + +@Serializable +data class Credentials( + val `credentials`: List, + val `requests`: List, +) + +@Serializable +data class DeclineAgentHeldActionRequest( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `reason`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class DesktopControl( + val `holder`: String, + val `changes`: Long, + val `updatedAt`: String, +) + +@Serializable +data class DesktopJob( + val `name`: String, + val `conversationId`: String, + val `status`: String, + val `model`: DesktopJobModel? = null, + val `usage`: JsonElement? = null, + val `question`: DesktopJobQuestion? = null, +) + +@Serializable +data class DesktopJobModel( + val `provider`: String, + val `model`: String, +) + +@Serializable +data class DesktopJobQuestion( + val `id`: String, + val `text`: String, + val `askedAt`: Double, + val `options`: List? = null, + val `multiple`: Boolean? = null, +) + +@Serializable +data class DesktopJobs( + val `jobs`: List, +) + +@Serializable +data class DesktopStatus( + val `running`: Boolean, +) + +@Serializable +data class DesktopViewer( + val `path`: String, + val `expiresAt`: String, +) + +@Serializable +data class Error( + val `error`: String, + val `details`: List? = null, +) + +@Serializable +data class ErrorDetailsItem( + val `code`: String, + val `path`: List, + val `message`: String, +) + +@Serializable(with = ErrorDetailsItemPathItemCodec::class) +sealed class ErrorDetailsItemPathItem { + data class Variant1(val value: String) : ErrorDetailsItemPathItem() + data class Variant2(val value: Double) : ErrorDetailsItemPathItem() +} +object ErrorDetailsItemPathItemCodec : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ErrorDetailsItemPathItem") + override fun deserialize(decoder: Decoder): ErrorDetailsItemPathItem { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement() + return when { + (element is JsonPrimitive && element.isString) -> ErrorDetailsItemPathItem.Variant1(input.json.decodeFromJsonElement(element)) + (element is JsonPrimitive && !element.isString && element.doubleOrNull != null) -> ErrorDetailsItemPathItem.Variant2(input.json.decodeFromJsonElement(element)) + else -> throw SerializationException("Unknown ErrorDetailsItemPathItem variant") + } + } + override fun serialize(encoder: Encoder, value: ErrorDetailsItemPathItem) { + val output = encoder as JsonEncoder + output.encodeJsonElement(when (value) { + is ErrorDetailsItemPathItem.Variant1 -> output.json.encodeToJsonElement(value.value) + is ErrorDetailsItemPathItem.Variant2 -> output.json.encodeToJsonElement(value.value) + }) + } +} + +@Serializable +data class Execution( + val `id`: String, + val `agentId`: String, + val `conversationId`: String, + val `scheduleId`: String?, + val `submissionId`: String?, + val `requestId`: String, + val `prompt`: String, + val `replyTo`: String? = null, + val `attachmentsDigest`: String? = null, + val `status`: String, + val `error`: String?, + val `createdAt`: String, + val `updatedAt`: String, +) + +@Serializable +data class FinishMcpOAuthRequest( + val `code`: String, + val `state`: String, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `iss`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class GetEventRelayResponse( + val `url`: String?, + val `tokenConfigured`: Boolean, + val `status`: String, + val `error`: String?, +) + +@Serializable +data class GetWebSearchResponse( + val `defaultProvider`: String, + val `exaKeyConfigured`: Boolean, +) + +@Serializable +data class GitHubAccount( + val `id`: String, + val `login`: String, + val `htmlUrl`: String, + val `botIds`: List, + val `token`: SecretStatus, + val `signingKey`: String, + val `createdAt`: String, +) + +@Serializable +data class GitHubApp( + val `id`: String, + val `slug`: String, + val `name`: String, + val `login`: String, + val `htmlUrl`: String, + val `installUrl`: String, + val `account`: String?, + val `installed`: Boolean, + val `clientSecret`: SecretStatus, + val `user`: String?, + val `botIds`: List, + val `createdAt`: String, +) + +@Serializable +data class GroupActivity( + val `paused`: Boolean, + val `botTurns`: Double, + val `members`: List, +) + +@Serializable +data class GroupChat( + val `id`: String, + val `name`: String, + val `memberIds`: List, + val `createdAt`: String, + val `updatedAt`: String, +) + +@Serializable +data class GroupChatSnapshot( + val `messages`: List, + val `hasMore`: Boolean, + val `oldestEntryId`: String?, + val `groupChat`: GroupChat, + val `activity`: GroupActivity, + val `updatedAt`: Double, +) + +@Serializable +data class GroupMemberActivity( + val `agentId`: String, + val `status`: String, + val `error`: String?, +) + +@Serializable +data class GroupMessageReceipt( + val `requestId`: String, + val `entryId`: String, +) + +@Serializable +data class Health( + val `status`: String, + val `apiVersion`: Double, +) + +@Serializable +class HeartbeatEvent + +@Serializable +class HeartbeatEventPayload + +@Serializable +data class HeldAction( + val `id`: String, + val `job`: String, + val `action`: String, + val `page`: String?, + val `ownerMessages`: List, + val `reason`: String, + val `status`: String, + val `declineReason`: String?, + val `heldAt`: String, + val `decidedAt`: String?, +) + +@Serializable +data class HeldActionOwnerMessagesItem( + val `requestId`: String, + val `text`: String, + val `from`: String, +) + +@Serializable +data class InstallSkillsRequest( + val `repository`: String, + val `branch`: String, + val `commit`: String, + val `paths`: List, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `botIds`: OptionalField> = OptionalField.Absent, +) + +@Serializable +data class Invite( + val `id`: String, + val `createdAt`: String, +) + +@Serializable +data class JudgeChoice( + val `provider`: String, + val `model`: String, + val `name`: String, + val `kind`: String, +) + +@Serializable +data class JudgeModel( + val `judgeModel`: JudgeModelJudgeModel?, + val `effective`: JudgeChoice?, + val `choices`: List, +) + +@Serializable +data class JudgeModelJudgeModel( + val `provider`: String, + val `model`: String, +) + +@Serializable +data class LearnedChange( + val `id`: String, + val `agentId`: String?, + val `actor`: String, + val `target`: String, + val `targetId`: String, + val `action`: String, + val `before`: LearnedChangeBefore, + val `after`: LearnedChangeAfter, + val `source`: ChangeSource?, + val `revertsId`: String?, + val `createdAt`: String, +) + +@Serializable(with = LearnedChangeAfterCodec::class) +sealed class LearnedChangeAfter { + data class Variant1(val value: SkillPackage) : LearnedChangeAfter() + data class Variant2(val value: Memory) : LearnedChangeAfter() + data class Variant3(val value: JsonNull) : LearnedChangeAfter() +} +object LearnedChangeAfterCodec : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("LearnedChangeAfter") + override fun deserialize(decoder: Decoder): LearnedChangeAfter { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement() + return when { + (element is JsonObject && element["id"] != null && element["name"] != null && element["instructions"] != null && element["createdAt"] != null && element["updatedAt"] != null && element["agentId"] != null && element["description"] != null && element["documents"] != null && element["createdBy"] != null && (element["createdBy"] == Json.parseToJsonElement("\"owner\"") || element["createdBy"] == Json.parseToJsonElement("\"bot\"")) && element["sourceExecutionId"] != null && element["useCount"] != null && element["lastUsedAt"] != null && element["state"] != null && (element["state"] == Json.parseToJsonElement("\"active\"") || element["state"] == Json.parseToJsonElement("\"stale\"") || element["state"] == Json.parseToJsonElement("\"archived\"")) && element["pinned"] != null) -> LearnedChangeAfter.Variant1(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["id"] != null && element["agentId"] != null && element["content"] != null && element["source"] != null && element["createdAt"] != null && element["updatedAt"] != null) -> LearnedChangeAfter.Variant2(input.json.decodeFromJsonElement(element)) + element is JsonNull -> LearnedChangeAfter.Variant3(input.json.decodeFromJsonElement(element)) + else -> throw SerializationException("Unknown LearnedChangeAfter variant") + } + } + override fun serialize(encoder: Encoder, value: LearnedChangeAfter) { + val output = encoder as JsonEncoder + output.encodeJsonElement(when (value) { + is LearnedChangeAfter.Variant1 -> output.json.encodeToJsonElement(value.value) + is LearnedChangeAfter.Variant2 -> output.json.encodeToJsonElement(value.value) + is LearnedChangeAfter.Variant3 -> output.json.encodeToJsonElement(value.value) + }) + } +} + +@Serializable(with = LearnedChangeBeforeCodec::class) +sealed class LearnedChangeBefore { + data class Variant1(val value: SkillPackage) : LearnedChangeBefore() + data class Variant2(val value: Memory) : LearnedChangeBefore() + data class Variant3(val value: JsonNull) : LearnedChangeBefore() +} +object LearnedChangeBeforeCodec : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("LearnedChangeBefore") + override fun deserialize(decoder: Decoder): LearnedChangeBefore { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement() + return when { + (element is JsonObject && element["id"] != null && element["name"] != null && element["instructions"] != null && element["createdAt"] != null && element["updatedAt"] != null && element["agentId"] != null && element["description"] != null && element["documents"] != null && element["createdBy"] != null && (element["createdBy"] == Json.parseToJsonElement("\"owner\"") || element["createdBy"] == Json.parseToJsonElement("\"bot\"")) && element["sourceExecutionId"] != null && element["useCount"] != null && element["lastUsedAt"] != null && element["state"] != null && (element["state"] == Json.parseToJsonElement("\"active\"") || element["state"] == Json.parseToJsonElement("\"stale\"") || element["state"] == Json.parseToJsonElement("\"archived\"")) && element["pinned"] != null) -> LearnedChangeBefore.Variant1(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["id"] != null && element["agentId"] != null && element["content"] != null && element["source"] != null && element["createdAt"] != null && element["updatedAt"] != null) -> LearnedChangeBefore.Variant2(input.json.decodeFromJsonElement(element)) + element is JsonNull -> LearnedChangeBefore.Variant3(input.json.decodeFromJsonElement(element)) + else -> throw SerializationException("Unknown LearnedChangeBefore variant") + } + } + override fun serialize(encoder: Encoder, value: LearnedChangeBefore) { + val output = encoder as JsonEncoder + output.encodeJsonElement(when (value) { + is LearnedChangeBefore.Variant1 -> output.json.encodeToJsonElement(value.value) + is LearnedChangeBefore.Variant2 -> output.json.encodeToJsonElement(value.value) + is LearnedChangeBefore.Variant3 -> output.json.encodeToJsonElement(value.value) + }) + } +} + +@Serializable +data class LearnedEvent( + val `type`: String, + val `agentId`: String, + val `agentName`: String, + val `executionId`: String, + val `changes`: List, + val `createdAt`: String, +) + +@Serializable +data class LearnedEventChangesItem( + val `changeId`: String, + val `target`: String, + val `action`: String, + val `name`: String, +) + +@Serializable(with = ListChangesAgentIdCodec::class) +sealed class ListChangesAgentId { + data class Variant1(val value: String) : ListChangesAgentId() + data class Variant2(val value: String) : ListChangesAgentId() +} +object ListChangesAgentIdCodec : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ListChangesAgentId") + override fun deserialize(decoder: Decoder): ListChangesAgentId { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement() + return when { + (element is JsonPrimitive && element.isString) -> ListChangesAgentId.Variant1(input.json.decodeFromJsonElement(element)) + (element == Json.parseToJsonElement("\"shared\"")) -> ListChangesAgentId.Variant2(input.json.decodeFromJsonElement(element)) + else -> throw SerializationException("Unknown ListChangesAgentId variant") + } + } + override fun serialize(encoder: Encoder, value: ListChangesAgentId) { + val output = encoder as JsonEncoder + output.encodeJsonElement(when (value) { + is ListChangesAgentId.Variant1 -> output.json.encodeToJsonElement(value.value) + is ListChangesAgentId.Variant2 -> output.json.encodeToJsonElement(value.value) + }) + } +} + +@Serializable +data class ListEventSourcesResponse( + val `sources`: List, +) + +@Serializable +data class ListEventSourcesResponseSourcesItem( + val `id`: String, + val `name`: String, + val `createdAt`: String, + val `usedBy`: Long, +) + +@Serializable +data class ListGithubAccountsResponse( + val `accounts`: List, +) + +@Serializable +data class ListGithubAppsResponse( + val `apps`: List, +) + +@Serializable +data class ListInvitesResponse( + val `invites`: List, +) + +@Serializable +data class ListOutdatedWorkspacesResponse( + val `workspaces`: List, +) + +@Serializable +data class ListOutdatedWorkspacesResponseWorkspacesItem( + val `userId`: String, + val `agentId`: String, +) + +@Serializable +data class ListUsersResponse( + val `users`: List, +) + +@Serializable(with = ListedSkillCodec::class) +sealed class ListedSkill { + data class Variant1(val value: ListedSkillVariant1) : ListedSkill() + data class Variant2(val value: ListedSkillVariant2) : ListedSkill() +} +object ListedSkillCodec : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ListedSkill") + override fun deserialize(decoder: Decoder): ListedSkill { + val input = decoder as JsonDecoder val element = input.decodeJsonElement() val matches = listOf((element is JsonObject && element["id"] != null && element["name"] != null && element["instructions"] != null && element["createdAt"] != null && element["updatedAt"] != null && element["source"] != null && (element["source"] == Json.parseToJsonElement("\"shared\""))), (element is JsonObject && element["id"] != null && element["name"] != null && element["instructions"] != null && element["path"] != null && element["source"] != null && (element["source"] == Json.parseToJsonElement("\"bundled\"")))) require(matches.count { it } == 1) { "Expected exactly one ListedSkill variant" } @@ -433,6 +1426,9 @@ data class ListedSkillVariant1( val `createdAt`: String, val `updatedAt`: String, val `source`: String, + val `description`: String? = null, + val `origin`: SkillOrigin? = null, + val `update`: SkillUpdate? = null, ) @Serializable @@ -445,6 +1441,48 @@ data class ListedSkillVariant2( val `source`: String, ) +@Serializable +data class Login( + val `name`: String, + val `hosts`: List, + val `fields`: LoginFields, + val `createdAt`: String, + val `updatedAt`: String, + val `lastUsedAt`: String?, + val `lastError`: String?, +) + +@Serializable +data class LoginFields( + val `username`: SecretStatus? = null, + val `password`: SecretStatus? = null, + val `one_time_code`: SecretStatus? = null, +) + +@Serializable +data class LoginRequest( + val `name`: String, + val `hosts`: List, + val `reason`: String, + val `oneTimeCode`: Boolean, + val `requestedAt`: String, +) + +@Serializable +data class LoginUse( + val `id`: String, + val `at`: String, + val `host`: String, + val `field`: String, + val `error`: String?, +) + +@Serializable +data class Logins( + val `logins`: List, + val `requests`: List, +) + @Serializable(with = McpOAuthStartCodec::class) sealed class McpOAuthStart { data class Variant1(val value: McpOAuthStartVariant1) : McpOAuthStart() @@ -476,77 +1514,300 @@ data class McpOAuthStartVariant1( ) @Serializable -data class McpOAuthStartVariant2( - val `authorized`: Boolean, +data class McpOAuthStartVariant2( + val `authorized`: Boolean, +) + +@Serializable +data class McpServer( + val `id`: String, + val `name`: String, + val `url`: String, + val `enabled`: Boolean, + val `agentId`: String?, + val `oauthClientId`: String?, + val `token`: SecretStatus, + val `oauthClientSecret`: SecretStatus, +) + +@Serializable +data class McpServerStatus( + val `id`: String, + val `name`: String, + val `url`: String, + val `enabled`: Boolean, + val `agentId`: String?, + val `oauthClientId`: String?, + val `token`: SecretStatus, + val `oauthClientSecret`: SecretStatus, + val `auth`: String, + val `error`: String?, + val `authenticated`: Boolean, +) + +@Serializable +data class Memory( + val `id`: String, + val `agentId`: String?, + val `content`: String, + val `source`: MemorySource?, + val `createdAt`: String, + val `updatedAt`: String, +) + +@Serializable +data class MemorySource( + val `kind`: String, + val `name`: String? = null, + val `scheduleId`: String? = null, + val `agentId`: String? = null, + val `groupId`: String? = null, +) + +@Serializable +data class MessageGatewaysResponse( + val `gateways`: List, +) + +@Serializable +data class MessageGatewaysResponseGatewaysItem( + val `id`: String, + val `label`: String, + val `secretKey`: String, + val `tokenConfigured`: Boolean, + val `config`: MessageGatewaysResponseGatewaysItemConfig, + val `status`: String, + val `error`: String?, + val `pendingCount`: Long, + val `failedCount`: Long, +) + +@Serializable +data class MessageGatewaysResponseGatewaysItemConfig( + val `enabled`: Boolean, + val `defaultBotId`: String?, + val `ownerId`: String?, + val `allowedChannelIds`: List, + val `allowDirectMessages`: Boolean, + val `aliases`: List, +) + +@Serializable +data class MessageGatewaysResponseGatewaysItemConfigAliasesItem( + val `handle`: String, + val `botId`: String, +) + +@Serializable +data class MessageOrigin( + val `kind`: String, + val `name`: String? = null, + val `agentId`: String? = null, + val `via`: String? = null, + val `source`: String? = null, +) + +@Serializable +data class Model( + val `provider`: String, + val `id`: String, + val `name`: String, + val `contextWindow`: Double, + val `reasoning`: Boolean, + val `thinkingLevels`: List, +) + +@Serializable +data class OperationalActivity( + val `id`: String, + val `agentId`: String, + val `agentName`: String, + val `entryId`: String, + val `timestamp`: Double? = null, + val `kind`: String, + val `details`: Map, +) + +@Serializable +data class PasswordManager( + val `id`: String, + val `name`: String, + val `connected`: Boolean, + val `connectedAt`: String?, + val `usedBy`: List, +) + +@Serializable +data class PasswordManagers( + val `passwordManagers`: List, +) + +@Serializable +data class PendingSkillUpdate( + val `commit`: String, + val `name`: String, + val `description`: String, + val `instructions`: String, + val `documents`: List, + val `skipped`: List, +) + +@Serializable +data class PluginSetting( + val `key`: String, + val `kind`: String, + val `label`: String, + val `whenMissing`: String, + val `secret`: SecretStatus, +) + +@Serializable +data class PluginSettings( + val `plugins`: List, +) + +@Serializable +data class PluginSettingsPluginsItem( + val `id`: String, + val `contributes`: List, + val `settings`: List, +) + +@Serializable +data class Provider( + val `provider`: String, + val `name`: String, + val `configured`: Boolean, + val `authMethods`: List, + val `credentialType`: String?, + val `apiKey`: SecretStatus, + val `activeLoginId`: String?, + val `externalAuth`: ProviderExternalAuth?, +) + +@Serializable +data class ProviderConfigured( + val `provider`: String, + val `configured`: Boolean, +) + +@Serializable +data class ProviderExternalAuth( + val `status`: String, + val `cliVersion`: String?, + val `signInCommand`: String?, + val `signOutCommand`: String?, + val `message`: String?, +) + +@Serializable(with = ProviderLoginEventCodec::class) +sealed class ProviderLoginEvent { + data class Variant1(val value: ProviderLoginEventVariant1) : ProviderLoginEvent() + data class Variant2(val value: ProviderLoginEventVariant2) : ProviderLoginEvent() + data class Variant3(val value: ProviderLoginEventVariant3) : ProviderLoginEvent() + data class Variant4(val value: ProviderLoginEventVariant4) : ProviderLoginEvent() +} +object ProviderLoginEventCodec : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ProviderLoginEvent") + override fun deserialize(decoder: Decoder): ProviderLoginEvent { + val input = decoder as JsonDecoder + val element = input.decodeJsonElement() + val matches = listOf((element is JsonObject && element["type"] != null && (element["type"] == Json.parseToJsonElement("\"info\"")) && element["message"] != null), (element is JsonObject && element["type"] != null && (element["type"] == Json.parseToJsonElement("\"auth_url\"")) && element["url"] != null), (element is JsonObject && element["type"] != null && (element["type"] == Json.parseToJsonElement("\"device_code\"")) && element["userCode"] != null && element["verificationUri"] != null), (element is JsonObject && element["type"] != null && (element["type"] == Json.parseToJsonElement("\"progress\"")) && element["message"] != null)) + require(matches.count { it } == 1) { "Expected exactly one ProviderLoginEvent variant" } + return when { + (element is JsonObject && element["type"] != null && (element["type"] == Json.parseToJsonElement("\"info\"")) && element["message"] != null) -> ProviderLoginEvent.Variant1(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["type"] != null && (element["type"] == Json.parseToJsonElement("\"auth_url\"")) && element["url"] != null) -> ProviderLoginEvent.Variant2(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["type"] != null && (element["type"] == Json.parseToJsonElement("\"device_code\"")) && element["userCode"] != null && element["verificationUri"] != null) -> ProviderLoginEvent.Variant3(input.json.decodeFromJsonElement(element)) + (element is JsonObject && element["type"] != null && (element["type"] == Json.parseToJsonElement("\"progress\"")) && element["message"] != null) -> ProviderLoginEvent.Variant4(input.json.decodeFromJsonElement(element)) + else -> throw SerializationException("Unknown ProviderLoginEvent variant") + } + } + override fun serialize(encoder: Encoder, value: ProviderLoginEvent) { + val output = encoder as JsonEncoder + output.encodeJsonElement(when (value) { + is ProviderLoginEvent.Variant1 -> output.json.encodeToJsonElement(value.value) + is ProviderLoginEvent.Variant2 -> output.json.encodeToJsonElement(value.value) + is ProviderLoginEvent.Variant3 -> output.json.encodeToJsonElement(value.value) + is ProviderLoginEvent.Variant4 -> output.json.encodeToJsonElement(value.value) + }) + } +} + +@Serializable +data class ProviderLoginEventVariant1( + val `type`: String, + val `message`: String, + val `links`: List? = null, +) + +@Serializable +data class ProviderLoginEventVariant1LinksItem( + val `url`: String, + val `label`: String? = null, ) @Serializable -data class McpServer( - val `id`: String, - val `name`: String, +data class ProviderLoginEventVariant2( + val `type`: String, val `url`: String, - val `enabled`: Boolean, - val `agentId`: String?, + val `instructions`: String? = null, ) @Serializable -data class McpServerStatus( - val `id`: String, - val `name`: String, - val `url`: String, - val `enabled`: Boolean, - val `agentId`: String?, - val `auth`: String, - val `authenticated`: Boolean, +data class ProviderLoginEventVariant3( + val `type`: String, + val `userCode`: String, + val `verificationUri`: String, + val `intervalSeconds`: Double? = null, + val `expiresInSeconds`: Double? = null, ) @Serializable -data class Memory( - val `id`: String, - val `agentId`: String?, - val `content`: String, - val `createdAt`: String, - val `updatedAt`: String, +data class ProviderLoginEventVariant4( + val `type`: String, + val `message`: String, ) @Serializable -data class MessageOrigin( - val `kind`: String, - val `name`: String? = null, - val `agentId`: String? = null, +data class ProviderLoginMethod( + val `type`: String, + val `label`: String, + val `subscription`: Boolean, ) @Serializable -data class Model( - val `provider`: String, +data class ProviderLoginSession( val `id`: String, - val `name`: String, - val `contextWindow`: Double, - val `reasoning`: Boolean, + val `provider`: String, + val `method`: String, + val `status`: String, + val `createdAt`: Double, + val `expiresAt`: Double, + val `prompt`: ProviderLoginSessionPrompt?, + val `events`: List, + val `failure`: ProviderLoginSessionFailure?, ) @Serializable -data class OperationalActivity( - val `id`: String, - val `agentId`: String, - val `agentName`: String, - val `entryId`: String, - val `timestamp`: Double? = null, - val `kind`: String, - val `details`: Map, +data class ProviderLoginSessionFailure( + val `code`: String, + val `message`: String, ) @Serializable -data class Provider( - val `provider`: String, - val `name`: String, - val `configured`: Boolean, +data class ProviderLoginSessionPrompt( + val `id`: String, + val `type`: String, + val `message`: String, + val `placeholder`: String? = null, + val `options`: List? = null, ) @Serializable -data class ProviderConfigured( - val `provider`: String, - val `configured`: Boolean, +data class ProviderLoginSessionPromptOptionsItem( + val `id`: String, + val `label`: String, + val `description`: String? = null, ) @Serializable @@ -567,9 +1828,23 @@ data class PushStatusTransports( val `fcm`: Boolean, ) +@Serializable +data class PutDesktopControlRequest( + val `holder`: String, +) + @Serializable data class PutProviderKeyRequest( - val `apiKey`: String, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `value`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `reference`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class PutProviderKeyRequestReference( + val `passwordManager`: String, + val `reference`: String, ) @Serializable @@ -601,72 +1876,368 @@ data class ReplyEvent( val `preview`: String, val `createdAt`: String, val `executionId`: String? = null, + val `jobName`: String? = null, + val `groupId`: String? = null, + val `groupName`: String? = null, + val `waitingFor`: String? = null, +) + +@Serializable +data class ReviewResult( + val `executionId`: String, + val `agentId`: String, + val `createdAt`: String, + val `changes`: List, +) + +@Serializable +data class SaveAgentCredentialRequest( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `hosts`: OptionalField> = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `secret`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class SaveAgentCredentialRequestSecret( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `value`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `reference`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class SaveAgentCredentialRequestSecretReference( + val `passwordManager`: String, + val `reference`: String, +) + +@Serializable +data class SaveAgentLoginRequest( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `hosts`: OptionalField> = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `item`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `fields`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class SaveAgentLoginRequestFields( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `username`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `password`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `one_time_code`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class SaveAgentLoginRequestFieldsOneTimeCode( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `value`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `reference`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class SaveAgentLoginRequestFieldsOneTimeCodeReference( + val `passwordManager`: String, + val `reference`: String, +) + +@Serializable +data class SaveAgentLoginRequestFieldsPassword( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `value`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `reference`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class SaveAgentLoginRequestFieldsPasswordReference( + val `passwordManager`: String, + val `reference`: String, +) + +@Serializable +data class SaveAgentLoginRequestFieldsUsername( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `value`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `reference`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class SaveAgentLoginRequestFieldsUsernameReference( + val `passwordManager`: String, + val `reference`: String, +) + +@Serializable +data class SaveAgentLoginRequestItem( + val `passwordManager`: String, + val `reference`: String, +) + +@Serializable +data class Schedule( + val `id`: String, + val `agentId`: String, + val `name`: String, + val `prompt`: String, + val `kind`: String, + val `command`: String?, + val `timeoutSeconds`: Long, + val `notify`: Boolean, + val `cron`: String?, + val `timezone`: String, + val `runAt`: String?, + val `eventSourceId`: String?, + val `enabled`: Boolean, + val `nextRunAt`: String?, + val `createdAt`: String, + val `createdByAgentId`: String?, +) + +@Serializable +data class ScheduleRun( + val `admitted`: Boolean, + val `result`: ScheduleRunResult? = null, +) + +@Serializable +data class ScheduleRunResult( + val `id`: String? = null, + val `agentId`: String? = null, + val `conversationId`: String? = null, + val `scheduleId`: String? = null, + val `submissionId`: String? = null, + val `requestId`: String? = null, + val `prompt`: String? = null, + val `replyTo`: String? = null, + val `attachmentsDigest`: String? = null, + val `status`: String? = null, + val `error`: String? = null, + val `createdAt`: String? = null, + val `updatedAt`: String? = null, +) + +@Serializable +data class ScriptRun( + val `id`: String, + val `scheduleId`: String, + val `agentId`: String, + val `command`: String, + val `status`: String, + val `exitCode`: Long?, + val `output`: String, + val `droppedBytes`: Long, + val `error`: String?, + val `startedAt`: String, + val `finishedAt`: String?, +) + +@Serializable +data class SecretStatus( + val `configured`: Boolean, + val `passwordManager`: String?, + val `reference`: String?, +) + +@Serializable +data class SendGroupMessageRequest( + val `content`: String, + val `requestId`: String, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `replyTo`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `attachments`: OptionalField> = OptionalField.Absent, +) + +@Serializable +data class SendGroupMessageRequestAttachmentsItem( + val `name`: String, + val `mimeType`: String, + val `data`: String, +) + +@Serializable +data class SendMessageRequest( + val `content`: String, + val `requestId`: String, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `replyTo`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `attachments`: OptionalField> = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `timezone`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class SendMessageRequestAttachmentsItem( + val `name`: String, + val `mimeType`: String, + val `data`: String, +) + +@Serializable +data class ServerSettings( + val `signUpOpen`: Boolean, + val `workspaceCpus`: Long, + val `workspaceMemoryMib`: Long, + val `codingImage`: String?, + val `questionGraceMinutes`: Long, +) + +@Serializable +data class SetGithubAccountBotsRequest( + val `botIds`: List, +) + +@Serializable +data class SetGithubAccountTokenRequest( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `value`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `reference`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class SetGithubAccountTokenRequestReference( + val `passwordManager`: String, + val `reference`: String, +) + +@Serializable +data class SetGithubAppBotsRequest( + val `botIds`: List, +) + +@Serializable +data class SetGithubAppClientSecretRequest( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `value`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `reference`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class SetGithubAppClientSecretRequestReference( + val `passwordManager`: String, + val `reference`: String, +) + +@Serializable +data class SetPluginSettingRequest( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `value`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `reference`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class SetPluginSettingRequestReference( + val `passwordManager`: String, + val `reference`: String, +) + +@Serializable +data class SetUserRoleRequest( + val `role`: String, +) + +@Serializable +data class SignInGithubAppRequest( + val `origin`: String, +) + +@Serializable +data class SignInGithubAppResponse( + val `url`: String, ) @Serializable -data class Schedule( +data class Skill( val `id`: String, - val `agentId`: String, val `name`: String, - val `prompt`: String, - val `cron`: String?, - val `timezone`: String, - val `runAt`: String?, - val `enabled`: Boolean, - val `nextRunAt`: String?, + val `instructions`: String, val `createdAt`: String, - val `createdByAgentId`: String?, + val `updatedAt`: String, ) @Serializable -data class ScheduleRun( - val `admitted`: Boolean, - val `result`: ScheduleRunResult? = null, +data class SkillCandidate( + val `path`: String, + val `name`: String, + val `description`: String, + val `status`: String, + val `problem`: String?, + val `skipped`: List, + val `skillId`: String?, ) @Serializable -data class ScheduleRunResult( - val `id`: String? = null, - val `agentId`: String? = null, - val `conversationId`: String? = null, - val `scheduleId`: String? = null, - val `submissionId`: String? = null, - val `requestId`: String? = null, - val `prompt`: String? = null, - val `replyTo`: String? = null, - val `attachmentsDigest`: String? = null, - val `status`: String? = null, - val `error`: String? = null, - val `createdAt`: String? = null, - val `updatedAt`: String? = null, +data class SkillCheck( + val `failed`: List, ) @Serializable -data class SendMessageRequest( +data class SkillCheckFailedItem( + val `repository`: String, + val `branch`: String, + val `message`: String, +) + +@Serializable +data class SkillDocument( + val `path`: String, val `content`: String, - val `requestId`: String, - @EncodeDefault(EncodeDefault.Mode.NEVER) - val `replyTo`: OptionalField = OptionalField.Absent, - @EncodeDefault(EncodeDefault.Mode.NEVER) - val `attachments`: OptionalField> = OptionalField.Absent, - @EncodeDefault(EncodeDefault.Mode.NEVER) - val `timezone`: OptionalField = OptionalField.Absent, ) @Serializable -data class SendMessageRequestAttachmentsItem( - val `name`: String, - val `mimeType`: String, - val `data`: String, +data class SkillListing( + val `repository`: String, + val `branch`: String, + val `commit`: String, + val `path`: String, + val `skills`: List, + val `omitted`: Long, ) @Serializable -data class Skill( +data class SkillOrigin( + val `repository`: String, + val `branch`: String, + val `path`: String, + val `commit`: String, + val `digest`: String, +) + +@Serializable +data class SkillPackage( val `id`: String, val `name`: String, val `instructions`: String, val `createdAt`: String, val `updatedAt`: String, + val `agentId`: String?, + val `description`: String, + val `documents`: List, + val `createdBy`: String, + val `sourceExecutionId`: String?, + val `useCount`: Long, + val `lastUsedAt`: String?, + val `state`: String, + val `pinned`: Boolean, + val `copiedFromSkillId`: String? = null, + val `origin`: SkillOrigin? = null, +) + +@Serializable +data class SkillUpdate( + val `commit`: String, + val `removed`: Boolean, ) @Serializable @@ -710,11 +2281,14 @@ data class SnapshotEventPayloadMessagesItem( val `replyPreview`: String? = null, val `origin`: SnapshotEventPayloadMessagesItemOrigin? = null, val `communication`: SnapshotEventPayloadMessagesItemCommunication? = null, + val `jobQuestion`: SnapshotEventPayloadMessagesItemJobQuestion? = null, + val `heldAction`: SnapshotEventPayloadMessagesItemHeldAction? = null, val `attachments`: List? = null, val `toolCallId`: String? = null, val `toolName`: String? = null, val `isError`: Boolean? = null, val `toolDetails`: JsonElement? = null, + val `sources`: List? = null, ) @Serializable @@ -735,11 +2309,34 @@ data class SnapshotEventPayloadMessagesItemCommunication( val `status`: String, ) +@Serializable +data class SnapshotEventPayloadMessagesItemHeldAction( + val `id`: String, + val `job`: String, +) + +@Serializable +data class SnapshotEventPayloadMessagesItemJobQuestion( + val `id`: String, + val `kind`: String, + val `job`: String, + val `options`: List? = null, + val `multiple`: Boolean? = null, +) + @Serializable data class SnapshotEventPayloadMessagesItemOrigin( val `kind`: String, val `name`: String? = null, val `agentId`: String? = null, + val `via`: String? = null, + val `source`: String? = null, +) + +@Serializable +data class SnapshotEventPayloadMessagesItemSourcesItem( + val `url`: String, + val `title`: String, ) @Serializable @@ -747,6 +2344,11 @@ data class StartMcpOAuthRequest( val `redirectUri`: String, ) +@Serializable +data class StartProviderLoginRequest( + val `method`: String, +) + @Serializable data class TranscriptMessage( val `id`: String, @@ -762,11 +2364,35 @@ data class TranscriptMessage( val `replyPreview`: String? = null, val `origin`: MessageOrigin? = null, val `communication`: BotCommunication? = null, + val `jobQuestion`: TranscriptMessageJobQuestion? = null, + val `heldAction`: TranscriptMessageHeldAction? = null, val `attachments`: List? = null, val `toolCallId`: String? = null, val `toolName`: String? = null, val `isError`: Boolean? = null, val `toolDetails`: JsonElement? = null, + val `sources`: List? = null, +) + +@Serializable +data class TranscriptMessageHeldAction( + val `id`: String, + val `job`: String, +) + +@Serializable +data class TranscriptMessageJobQuestion( + val `id`: String, + val `kind`: String, + val `job`: String, + val `options`: List? = null, + val `multiple`: Boolean? = null, +) + +@Serializable +data class TranscriptMessageSourcesItem( + val `url`: String, + val `title`: String, ) @Serializable @@ -786,7 +2412,7 @@ data class UpdateAgentRequest( @EncodeDefault(EncodeDefault.Mode.NEVER) val `name`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) - val `avatar`: OptionalField = OptionalField.Absent, + val `avatar`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) val `description`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) @@ -796,6 +2422,8 @@ data class UpdateAgentRequest( @EncodeDefault(EncodeDefault.Mode.NEVER) val `model`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) + val `webSearchProvider`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) val `enabled`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) val `tools`: OptionalField> = OptionalField.Absent, @@ -811,6 +2439,47 @@ data class UpdateAgentRequest( val `delegates`: OptionalField> = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) val `inference`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `review`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `reviewModel`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `desktopModel`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class UpdateAgentRequestAvatar( + val `definition`: UpdateAgentRequestAvatarDefinition, + val `color`: String, + val `eyeColor`: String, +) + +@Serializable +data class UpdateAgentRequestAvatarDefinition( + val `version`: Double, + val `id`: String, + val `name`: String, + val `body`: UpdateAgentRequestAvatarDefinitionBody, + val `eyes`: UpdateAgentRequestAvatarDefinitionEyes, +) + +@Serializable +data class UpdateAgentRequestAvatarDefinitionBody( + val `path`: String, +) + +@Serializable +data class UpdateAgentRequestAvatarDefinitionEyes( + val `x`: Double, + val `y`: Double, + val `spacing`: Double, + val `scale`: Double, +) + +@Serializable +data class UpdateAgentRequestDesktopModel( + val `provider`: String, + val `model`: String, ) @Serializable @@ -823,12 +2492,84 @@ data class UpdateAgentRequestInference( val `maxOutputTokens`: OptionalField = OptionalField.Absent, ) +@Serializable +data class UpdateAgentRequestReview( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `enabled`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `skillThreshold`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `memoryThreshold`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `maxInputTokens`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class UpdateAgentRequestReviewModel( + val `provider`: String, + val `model`: String, +) + @Serializable data class UpdateAgentRequestSkillsItem( val `name`: String, val `instructions`: String, ) +@Serializable +data class UpdateAgentSkillRequest( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `name`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `description`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `instructions`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `documents`: OptionalField> = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `state`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `pinned`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class UpdateAgentSkillRequestDocumentsItem( + val `path`: String, + val `content`: String, +) + +@Serializable +data class UpdateEventRelayRequest( + val `url`: String?, +) + +@Serializable +data class UpdateEventRelayResponse( + val `url`: String?, + val `tokenConfigured`: Boolean, + val `status`: String, + val `error`: String?, +) + +@Serializable +data class UpdateGroupChatRequest( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `name`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `memberIds`: OptionalField> = OptionalField.Absent, +) + +@Serializable +data class UpdateJudgeModelRequest( + val `judgeModel`: UpdateJudgeModelRequestJudgeModel?, +) + +@Serializable +data class UpdateJudgeModelRequestJudgeModel( + val `provider`: String, + val `model`: String, +) + @Serializable data class UpdateMcpServerRequest( @EncodeDefault(EncodeDefault.Mode.NEVER) @@ -838,7 +2579,84 @@ data class UpdateMcpServerRequest( @EncodeDefault(EncodeDefault.Mode.NEVER) val `enabled`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) - val `token`: OptionalField = OptionalField.Absent, + val `token`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `oauthClientId`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `oauthClientSecret`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class UpdateMcpServerRequestOauthClientSecret( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `value`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `reference`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class UpdateMcpServerRequestOauthClientSecretReference( + val `passwordManager`: String, + val `reference`: String, +) + +@Serializable +data class UpdateMcpServerRequestToken( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `value`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `reference`: OptionalField = OptionalField.Absent, +) + +@Serializable +data class UpdateMcpServerRequestTokenReference( + val `passwordManager`: String, + val `reference`: String, +) + +@Serializable +data class UpdateMessageGatewayRequest( + val `enabled`: Boolean, + val `defaultBotId`: String?, + val `ownerId`: String?, + val `allowedChannelIds`: List, + val `allowDirectMessages`: Boolean, + val `aliases`: List, +) + +@Serializable +data class UpdateMessageGatewayRequestAliasesItem( + val `handle`: String, + val `botId`: String, +) + +@Serializable +data class UpdateMessageGatewayResponse( + val `id`: String, + val `label`: String, + val `secretKey`: String, + val `tokenConfigured`: Boolean, + val `config`: UpdateMessageGatewayResponseConfig, + val `status`: String, + val `error`: String?, + val `pendingCount`: Long, + val `failedCount`: Long, +) + +@Serializable +data class UpdateMessageGatewayResponseConfig( + val `enabled`: Boolean, + val `defaultBotId`: String?, + val `ownerId`: String?, + val `allowedChannelIds`: List, + val `allowDirectMessages`: Boolean, + val `aliases`: List, +) + +@Serializable +data class UpdateMessageGatewayResponseConfigAliasesItem( + val `handle`: String, + val `botId`: String, ) @Serializable @@ -848,17 +2666,41 @@ data class UpdateScheduleRequest( @EncodeDefault(EncodeDefault.Mode.NEVER) val `name`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) + val `kind`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) val `prompt`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) + val `command`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `timeoutSeconds`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `notify`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) val `cron`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) val `timezone`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) val `runAt`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) + val `eventSourceId`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) val `enabled`: OptionalField = OptionalField.Absent, ) +@Serializable +data class UpdateServerSettingsRequest( + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `signUpOpen`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `workspaceCpus`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `workspaceMemoryMib`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `codingImage`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `questionGraceMinutes`: OptionalField = OptionalField.Absent, +) + @Serializable data class UpdateSharedMemoryRequest( val `content`: String, @@ -869,5 +2711,56 @@ data class UpdateSkillRequest( @EncodeDefault(EncodeDefault.Mode.NEVER) val `name`: OptionalField = OptionalField.Absent, @EncodeDefault(EncodeDefault.Mode.NEVER) + val `description`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) val `instructions`: OptionalField = OptionalField.Absent, + @EncodeDefault(EncodeDefault.Mode.NEVER) + val `documents`: OptionalField> = OptionalField.Absent, +) + +@Serializable +data class UpdateSkillRequestDocumentsItem( + val `path`: String, + val `content`: String, +) + +@Serializable +data class UpdateVisionModelRequest( + val `visionModel`: UpdateVisionModelRequestVisionModel?, +) + +@Serializable +data class UpdateVisionModelRequestVisionModel( + val `provider`: String, + val `model`: String, +) + +@Serializable +data class UpdateWebSearchRequest( + val `defaultProvider`: String, +) + +@Serializable +data class UpdateWebSearchResponse( + val `defaultProvider`: String, + val `exaKeyConfigured`: Boolean, +) + +@Serializable +data class VisionChoice( + val `provider`: String, + val `model`: String, + val `name`: String, +) + +@Serializable +data class VisionModel( + val `visionModel`: VisionModelVisionModel?, + val `choices`: List, +) + +@Serializable +data class VisionModelVisionModel( + val `provider`: String, + val `model`: String, ) diff --git a/app/src/main/java/dev/crumble/android/generated/ContractOperations.kt b/app/src/main/java/dev/crumble/android/generated/ContractOperations.kt index e8cb850..4499a62 100644 --- a/app/src/main/java/dev/crumble/android/generated/ContractOperations.kt +++ b/app/src/main/java/dev/crumble/android/generated/ContractOperations.kt @@ -1,4 +1,4 @@ -// Generated by scripts/generate-contract.py 1.0.0. Do not edit. +// Generated by scripts/generate-contract.py 1.1.0. Do not edit. package dev.crumble.android.generated import kotlinx.serialization.* @@ -50,6 +50,260 @@ class ContractOperations(private val boundary: ContractBoundary) { boundary.send("PUT", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) } + suspend fun listUsers(timeoutMs: Int = 20_000): ListUsersResponse { + val query = mutableListOf() + val path = "/v1/admin/users" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun setUserRole(body: SetUserRoleRequest, `id`: String, timeoutMs: Int = 20_000): AdminUser { + val query = mutableListOf() + val path = "/v1/admin/users/${boundary.escape(`id`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PATCH", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun removeUser(`id`: String, timeoutMs: Int = 20_000): Unit { + val query = mutableListOf() + val path = "/v1/admin/users/${boundary.escape(`id`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + boundary.send("DELETE", path, null, timeoutMs) + } + + suspend fun listInvites(timeoutMs: Int = 20_000): ListInvitesResponse { + val query = mutableListOf() + val path = "/v1/admin/invites" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun createInvite(timeoutMs: Int = 20_000): CreatedInvite { + val query = mutableListOf() + val path = "/v1/admin/invites" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun revokeInvite(`id`: String, timeoutMs: Int = 20_000): Unit { + val query = mutableListOf() + val path = "/v1/admin/invites/${boundary.escape(`id`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + boundary.send("DELETE", path, null, timeoutMs) + } + + suspend fun listOutdatedWorkspaces(timeoutMs: Int = 20_000): ListOutdatedWorkspacesResponse { + val query = mutableListOf() + val path = "/v1/admin/workspaces/outdated" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun getServerSettings(timeoutMs: Int = 20_000): ServerSettings { + val query = mutableListOf() + val path = "/v1/admin/settings" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun updateServerSettings(body: UpdateServerSettingsRequest, timeoutMs: Int = 20_000): ServerSettings { + val query = mutableListOf() + val path = "/v1/admin/settings" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PATCH", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun messageGateways(timeoutMs: Int = 20_000): MessageGatewaysResponse { + val query = mutableListOf() + val path = "/v1/message-gateways" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun updateMessageGateway(body: UpdateMessageGatewayRequest, `id`: String, timeoutMs: Int = 20_000): UpdateMessageGatewayResponse { + val query = mutableListOf() + val path = "/v1/message-gateways/${boundary.escape(`id`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PUT", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun getEventRelay(timeoutMs: Int = 20_000): GetEventRelayResponse { + val query = mutableListOf() + val path = "/v1/event-relay" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun updateEventRelay(body: UpdateEventRelayRequest, timeoutMs: Int = 20_000): UpdateEventRelayResponse { + val query = mutableListOf() + val path = "/v1/event-relay" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PUT", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun listGithubApps(timeoutMs: Int = 20_000): ListGithubAppsResponse { + val query = mutableListOf() + val path = "/v1/github-apps" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun createGithubAppManifest(body: CreateGithubAppManifestRequest, timeoutMs: Int = 20_000): CreateGithubAppManifestResponse { + val query = mutableListOf() + val path = "/v1/github-apps/manifest" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun completeGithubApp(body: CompleteGithubAppRequest, timeoutMs: Int = 20_000): GitHubApp { + val query = mutableListOf() + val path = "/v1/github-apps/complete" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun connectGithubApp(`id`: String, timeoutMs: Int = 20_000): GitHubApp { + val query = mutableListOf() + val path = "/v1/github-apps/${boundary.escape(`id`)}/connect" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun setGithubAppBots(body: SetGithubAppBotsRequest, `id`: String, timeoutMs: Int = 20_000): GitHubApp { + val query = mutableListOf() + val path = "/v1/github-apps/${boundary.escape(`id`)}/bots" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PUT", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun deleteGithubApp(`id`: String, timeoutMs: Int = 20_000): Unit { + val query = mutableListOf() + val path = "/v1/github-apps/${boundary.escape(`id`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + boundary.send("DELETE", path, null, timeoutMs) + } + + suspend fun signInGithubApp(body: SignInGithubAppRequest, `id`: String, timeoutMs: Int = 20_000): SignInGithubAppResponse { + val query = mutableListOf() + val path = "/v1/github-apps/${boundary.escape(`id`)}/sign-in" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun completeGithubAppSignIn(body: CompleteGithubAppSignInRequest, timeoutMs: Int = 20_000): GitHubApp { + val query = mutableListOf() + val path = "/v1/github-apps/sign-in/complete" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun signOutGithubApp(`id`: String, timeoutMs: Int = 20_000): GitHubApp { + val query = mutableListOf() + val path = "/v1/github-apps/${boundary.escape(`id`)}/user" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("DELETE", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun setGithubAppClientSecret(body: SetGithubAppClientSecretRequest, `id`: String, timeoutMs: Int = 20_000): GitHubApp { + val query = mutableListOf() + val path = "/v1/github-apps/${boundary.escape(`id`)}/client-secret" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PUT", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun listGithubAccounts(timeoutMs: Int = 20_000): ListGithubAccountsResponse { + val query = mutableListOf() + val path = "/v1/github-accounts" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun addGithubAccount(body: AddGithubAccountRequest, timeoutMs: Int = 20_000): GitHubAccount { + val query = mutableListOf() + val path = "/v1/github-accounts" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun setGithubAccountToken(body: SetGithubAccountTokenRequest, `id`: String, timeoutMs: Int = 20_000): GitHubAccount { + val query = mutableListOf() + val path = "/v1/github-accounts/${boundary.escape(`id`)}/token" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PUT", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun setGithubAccountBots(body: SetGithubAccountBotsRequest, `id`: String, timeoutMs: Int = 20_000): GitHubAccount { + val query = mutableListOf() + val path = "/v1/github-accounts/${boundary.escape(`id`)}/bots" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PUT", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun deleteGithubAccount(`id`: String, timeoutMs: Int = 20_000): Unit { + val query = mutableListOf() + val path = "/v1/github-accounts/${boundary.escape(`id`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + boundary.send("DELETE", path, null, timeoutMs) + } + + suspend fun listEventSources(timeoutMs: Int = 20_000): ListEventSourcesResponse { + val query = mutableListOf() + val path = "/v1/event-sources" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun createEventSource(body: CreateEventSourceRequest, timeoutMs: Int = 20_000): CreateEventSourceResponse { + val query = mutableListOf() + val path = "/v1/event-sources" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun deleteEventSource(`id`: String, timeoutMs: Int = 20_000): Unit { + val query = mutableListOf() + val path = "/v1/event-sources/${boundary.escape(`id`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + boundary.send("DELETE", path, null, timeoutMs) + } + + suspend fun getWebSearch(timeoutMs: Int = 20_000): GetWebSearchResponse { + val query = mutableListOf() + val path = "/v1/web-search" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun updateWebSearch(body: UpdateWebSearchRequest, timeoutMs: Int = 20_000): UpdateWebSearchResponse { + val query = mutableListOf() + val path = "/v1/web-search" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PUT", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun getJudgeModel(timeoutMs: Int = 20_000): JudgeModel { + val query = mutableListOf() + val path = "/v1/judge-model" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun updateJudgeModel(body: UpdateJudgeModelRequest, timeoutMs: Int = 20_000): JudgeModel { + val query = mutableListOf() + val path = "/v1/judge-model" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PUT", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun getVisionModel(timeoutMs: Int = 20_000): VisionModel { + val query = mutableListOf() + val path = "/v1/vision-model" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun updateVisionModel(body: UpdateVisionModelRequest, timeoutMs: Int = 20_000): VisionModel { + val query = mutableListOf() + val path = "/v1/vision-model" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PUT", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + suspend fun listAgents(timeoutMs: Int = 20_000): List { val query = mutableListOf() val path = "/v1/agents" + if (query.isEmpty()) "" else "?" + query.joinToString("&") @@ -115,6 +369,12 @@ class ContractOperations(private val boundary: ContractBoundary) { return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) } + suspend fun answerCodingJob(body: AnswerCodingJobRequest, `id`: String, `name`: String, timeoutMs: Int = 20_000): Unit { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/coding-jobs/${boundary.escape(`name`)}/answer" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + } + suspend fun getCodingJobHistory(`id`: String, `name`: String, `limit`: Long? = null, `before`: String? = null, timeoutMs: Int = 20_000): TranscriptPage { val query = mutableListOf() `limit`?.let { query.add("limit=" + boundary.escape(it.toString())) } @@ -124,6 +384,57 @@ class ContractOperations(private val boundary: ContractBoundary) { return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) } + suspend fun listDesktopJobs(`id`: String, timeoutMs: Int = 20_000): DesktopJobs { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/desktop-jobs" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun getDesktopControl(`id`: String, timeoutMs: Int = 20_000): DesktopControl { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/desktop/control" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun putDesktopControl(body: PutDesktopControlRequest, `id`: String, timeoutMs: Int = 20_000): DesktopControl { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/desktop/control" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PUT", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun streamDesktopEvents(`id`: String, timeoutMs: Int = 20_000): HttpRequestData { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/desktop/events" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + return boundary.request("GET", path, null, timeoutMs) + } + + suspend fun getDesktopStatus(`id`: String, timeoutMs: Int = 20_000): DesktopStatus { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/desktop/status" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun createDesktopViewer(`id`: String, `passive`: String? = null, timeoutMs: Int = 20_000): DesktopViewer { + val query = mutableListOf() + `passive`?.let { query.add("passive=" + boundary.escape(it)) } + val path = "/v1/agents/${boundary.escape(`id`)}/desktop/viewer" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun getDesktopJobHistory(`id`: String, `name`: String, `limit`: Long? = null, `before`: String? = null, timeoutMs: Int = 20_000): TranscriptPage { + val query = mutableListOf() + `limit`?.let { query.add("limit=" + boundary.escape(it.toString())) } + `before`?.let { query.add("before=" + boundary.escape(it)) } + val path = "/v1/agents/${boundary.escape(`id`)}/desktop-jobs/${boundary.escape(`name`)}/history" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + suspend fun sendMessage(body: SendMessageRequest, `id`: String, timeoutMs: Int = 20_000): Execution { val query = mutableListOf() val path = "/v1/agents/${boundary.escape(`id`)}/messages" + if (query.isEmpty()) "" else "?" + query.joinToString("&") @@ -163,6 +474,195 @@ class ContractOperations(private val boundary: ContractBoundary) { return boundary.request("GET", path, null, timeoutMs) } + suspend fun listGroupChats(timeoutMs: Int = 20_000): List { + val query = mutableListOf() + val path = "/v1/group-chats" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString>(bytes.toString(Charsets.UTF_8)) + } + + suspend fun createGroupChat(body: CreateGroupChatRequest, timeoutMs: Int = 20_000): GroupChat { + val query = mutableListOf() + val path = "/v1/group-chats" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun getGroupChat(`id`: String, timeoutMs: Int = 20_000): GroupChat { + val query = mutableListOf() + val path = "/v1/group-chats/${boundary.escape(`id`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun updateGroupChat(body: UpdateGroupChatRequest, `id`: String, timeoutMs: Int = 20_000): GroupChat { + val query = mutableListOf() + val path = "/v1/group-chats/${boundary.escape(`id`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PATCH", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun deleteGroupChat(`id`: String, timeoutMs: Int = 20_000): Unit { + val query = mutableListOf() + val path = "/v1/group-chats/${boundary.escape(`id`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + boundary.send("DELETE", path, null, timeoutMs) + } + + suspend fun getGroupChatSnapshot(`id`: String, `limit`: Long? = null, timeoutMs: Int = 20_000): GroupChatSnapshot { + val query = mutableListOf() + `limit`?.let { query.add("limit=" + boundary.escape(it.toString())) } + val path = "/v1/group-chats/${boundary.escape(`id`)}/chat" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun getGroupChatHistory(`id`: String, `limit`: Long? = null, `before`: String? = null, timeoutMs: Int = 20_000): TranscriptPage { + val query = mutableListOf() + `limit`?.let { query.add("limit=" + boundary.escape(it.toString())) } + `before`?.let { query.add("before=" + boundary.escape(it)) } + val path = "/v1/group-chats/${boundary.escape(`id`)}/history" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun sendGroupMessage(body: SendGroupMessageRequest, `id`: String, timeoutMs: Int = 20_000): GroupMessageReceipt { + val query = mutableListOf() + val path = "/v1/group-chats/${boundary.escape(`id`)}/messages" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun getGroupAttachment(`id`: String, `entryId`: String, `index`: Long?, timeoutMs: Int = 20_000): ByteArray { + val query = mutableListOf() + val path = "/v1/group-chats/${boundary.escape(`id`)}/attachments/${boundary.escape(`entryId`)}/${boundary.escape(`index`.toString())}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + return boundary.send("GET", path, null, timeoutMs) + } + + suspend fun stopGroupChat(`id`: String, timeoutMs: Int = 20_000): Unit { + val query = mutableListOf() + val path = "/v1/group-chats/${boundary.escape(`id`)}/stop" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + boundary.send("POST", path, null, timeoutMs) + } + + suspend fun streamGroupChatEvents(`id`: String, `limit`: Long? = null, timeoutMs: Int = 20_000): HttpRequestData { + val query = mutableListOf() + `limit`?.let { query.add("limit=" + boundary.escape(it.toString())) } + val path = "/v1/group-chats/${boundary.escape(`id`)}/events" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + return boundary.request("GET", path, null, timeoutMs) + } + + suspend fun listAgentCredentials(`id`: String, timeoutMs: Int = 20_000): Credentials { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/credentials" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun listBotRequests(`id`: String, timeoutMs: Int = 20_000): List { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/bot-requests" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString>(bytes.toString(Charsets.UTF_8)) + } + + suspend fun approveBotRequest(body: ApproveBotRequestRequest, `id`: String, `requestId`: String, timeoutMs: Int = 20_000): ApproveBotRequestResponse { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/bot-requests/${boundary.escape(`requestId`)}/approve" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun declineBotRequest(`id`: String, `requestId`: String, timeoutMs: Int = 20_000): BotRequest { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/bot-requests/${boundary.escape(`requestId`)}/decline" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun saveAgentCredential(body: SaveAgentCredentialRequest, `id`: String, `name`: String, timeoutMs: Int = 20_000): Credential { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/credentials/${boundary.escape(`name`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PUT", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun deleteAgentCredential(`id`: String, `name`: String, timeoutMs: Int = 20_000): Unit { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/credentials/${boundary.escape(`name`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + boundary.send("DELETE", path, null, timeoutMs) + } + + suspend fun declineAgentCredential(`id`: String, `name`: String, timeoutMs: Int = 20_000): Unit { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/credentials/${boundary.escape(`name`)}/decline" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + boundary.send("POST", path, null, timeoutMs) + } + + suspend fun listAgentCredentialUses(`id`: String, `name`: String, `limit`: Long? = null, `before`: String? = null, timeoutMs: Int = 20_000): List { + val query = mutableListOf() + `limit`?.let { query.add("limit=" + boundary.escape(it.toString())) } + `before`?.let { query.add("before=" + boundary.escape(it)) } + val path = "/v1/agents/${boundary.escape(`id`)}/credentials/${boundary.escape(`name`)}/uses" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString>(bytes.toString(Charsets.UTF_8)) + } + + suspend fun listAgentLogins(`id`: String, timeoutMs: Int = 20_000): Logins { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/logins" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun saveAgentLogin(body: SaveAgentLoginRequest, `id`: String, `name`: String, timeoutMs: Int = 20_000): Login { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/logins/${boundary.escape(`name`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PUT", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun deleteAgentLogin(`id`: String, `name`: String, timeoutMs: Int = 20_000): Unit { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/logins/${boundary.escape(`name`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + boundary.send("DELETE", path, null, timeoutMs) + } + + suspend fun declineAgentLogin(`id`: String, `name`: String, timeoutMs: Int = 20_000): Unit { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/logins/${boundary.escape(`name`)}/decline" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + boundary.send("POST", path, null, timeoutMs) + } + + suspend fun listAgentLoginUses(`id`: String, `name`: String, `limit`: Long? = null, `before`: String? = null, timeoutMs: Int = 20_000): List { + val query = mutableListOf() + `limit`?.let { query.add("limit=" + boundary.escape(it.toString())) } + `before`?.let { query.add("before=" + boundary.escape(it)) } + val path = "/v1/agents/${boundary.escape(`id`)}/logins/${boundary.escape(`name`)}/uses" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString>(bytes.toString(Charsets.UTF_8)) + } + + suspend fun listAgentHeldActions(`id`: String, timeoutMs: Int = 20_000): List { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/held-actions" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString>(bytes.toString(Charsets.UTF_8)) + } + + suspend fun approveAgentHeldAction(`id`: String, `actionId`: String, timeoutMs: Int = 20_000): HeldAction { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/held-actions/${boundary.escape(`actionId`)}/approve" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun declineAgentHeldAction(body: DeclineAgentHeldActionRequest, `id`: String, `actionId`: String, timeoutMs: Int = 20_000): HeldAction { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/held-actions/${boundary.escape(`actionId`)}/decline" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + suspend fun listAgentMemories(`id`: String, timeoutMs: Int = 20_000): List { val query = mutableListOf() val path = "/v1/agents/${boundary.escape(`id`)}/memories" + if (query.isEmpty()) "" else "?" + query.joinToString("&") @@ -217,6 +717,65 @@ class ContractOperations(private val boundary: ContractBoundary) { boundary.send("DELETE", path, null, timeoutMs) } + suspend fun listAgentSkills(`id`: String, timeoutMs: Int = 20_000): List { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/skills" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString>(bytes.toString(Charsets.UTF_8)) + } + + suspend fun createAgentSkill(body: CreateAgentSkillRequest, `id`: String, timeoutMs: Int = 20_000): SkillPackage { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/skills" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun updateAgentSkill(body: UpdateAgentSkillRequest, `id`: String, `skillId`: String, timeoutMs: Int = 20_000): SkillPackage? { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/skills/${boundary.escape(`skillId`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PATCH", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun deleteAgentSkill(`id`: String, `skillId`: String, timeoutMs: Int = 20_000): Unit { + val query = mutableListOf() + val path = "/v1/agents/${boundary.escape(`id`)}/skills/${boundary.escape(`skillId`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + boundary.send("DELETE", path, null, timeoutMs) + } + + suspend fun assignSkillBot(body: AssignSkillBotRequest, `id`: String, timeoutMs: Int = 20_000): AssignSkillBotResponse { + val query = mutableListOf() + val path = "/v1/skills/${boundary.escape(`id`)}/assignment" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun listAgentReviews(`id`: String, `limit`: Long? = null, timeoutMs: Int = 20_000): List { + val query = mutableListOf() + `limit`?.let { query.add("limit=" + boundary.escape(it.toString())) } + val path = "/v1/agents/${boundary.escape(`id`)}/reviews" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString>(bytes.toString(Charsets.UTF_8)) + } + + suspend fun listChanges(`limit`: Long? = null, `before`: String? = null, `agentId`: ListChangesAgentId? = null, timeoutMs: Int = 20_000): List { + val query = mutableListOf() + `limit`?.let { query.add("limit=" + boundary.escape(it.toString())) } + `before`?.let { query.add("before=" + boundary.escape(it)) } + `agentId`?.let { query.add("agentId=" + boundary.escape(it.toString())) } + val path = "/v1/changes" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString>(bytes.toString(Charsets.UTF_8)) + } + + suspend fun revertChange(`id`: String, timeoutMs: Int = 20_000): LearnedChange { + val query = mutableListOf() + val path = "/v1/changes/${boundary.escape(`id`)}/revert" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + suspend fun listSkills(timeoutMs: Int = 20_000): List { val query = mutableListOf() val path = "/v1/skills" + if (query.isEmpty()) "" else "?" + query.joinToString("&") @@ -231,6 +790,13 @@ class ContractOperations(private val boundary: ContractBoundary) { return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) } + suspend fun getSkill(`id`: String, timeoutMs: Int = 20_000): SkillPackage { + val query = mutableListOf() + val path = "/v1/skills/${boundary.escape(`id`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + suspend fun updateSkill(body: UpdateSkillRequest, `id`: String, timeoutMs: Int = 20_000): Skill? { val query = mutableListOf() val path = "/v1/skills/${boundary.escape(`id`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") @@ -244,6 +810,41 @@ class ContractOperations(private val boundary: ContractBoundary) { boundary.send("DELETE", path, null, timeoutMs) } + suspend fun browseSkillRepository(body: BrowseSkillRepositoryRequest, timeoutMs: Int = 20_000): SkillListing { + val query = mutableListOf() + val path = "/v1/skills/github/browse" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun installSkills(body: InstallSkillsRequest, timeoutMs: Int = 20_000): List { + val query = mutableListOf() + val path = "/v1/skills/github/install" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString>(bytes.toString(Charsets.UTF_8)) + } + + suspend fun checkSkillUpdates(timeoutMs: Int = 20_000): SkillCheck { + val query = mutableListOf() + val path = "/v1/skills/updates/check" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun getPendingSkillUpdate(`id`: String, timeoutMs: Int = 20_000): PendingSkillUpdate { + val query = mutableListOf() + val path = "/v1/skills/${boundary.escape(`id`)}/update" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun applySkillUpdate(`id`: String, timeoutMs: Int = 20_000): SkillPackage { + val query = mutableListOf() + val path = "/v1/skills/${boundary.escape(`id`)}/update" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + suspend fun listSchedules(`agentId`: String? = null, timeoutMs: Int = 20_000): List { val query = mutableListOf() `agentId`?.let { query.add("agentId=" + boundary.escape(it)) } @@ -279,6 +880,15 @@ class ContractOperations(private val boundary: ContractBoundary) { return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) } + suspend fun listScriptRuns(`id`: String, `limit`: Long? = null, `before`: String? = null, timeoutMs: Int = 20_000): List { + val query = mutableListOf() + `limit`?.let { query.add("limit=" + boundary.escape(it.toString())) } + `before`?.let { query.add("before=" + boundary.escape(it)) } + val path = "/v1/schedules/${boundary.escape(`id`)}/runs" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString>(bytes.toString(Charsets.UTF_8)) + } + suspend fun listExecutions(`agentId`: String? = null, timeoutMs: Int = 20_000): List { val query = mutableListOf() `agentId`?.let { query.add("agentId=" + boundary.escape(it)) } @@ -287,10 +897,12 @@ class ContractOperations(private val boundary: ContractBoundary) { return boundary.json.decodeFromString>(bytes.toString(Charsets.UTF_8)) } - suspend fun getActivityFeed(`agentId`: String? = null, `limit`: Long? = null, timeoutMs: Int = 20_000): ActivityFeed { + suspend fun getActivityFeed(`agentId`: String? = null, `limit`: Long? = null, `kind`: String? = null, `cursor`: String? = null, timeoutMs: Int = 20_000): ActivityFeed { val query = mutableListOf() `agentId`?.let { query.add("agentId=" + boundary.escape(it)) } `limit`?.let { query.add("limit=" + boundary.escape(it.toString())) } + `kind`?.let { query.add("kind=" + boundary.escape(it)) } + `cursor`?.let { query.add("cursor=" + boundary.escape(it)) } val path = "/v1/activity/feed" + if (query.isEmpty()) "" else "?" + query.joinToString("&") val bytes = boundary.send("GET", path, null, timeoutMs) return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) @@ -324,6 +936,75 @@ class ContractOperations(private val boundary: ContractBoundary) { boundary.send("DELETE", path, null, timeoutMs) } + suspend fun startProviderLogin(body: StartProviderLoginRequest, `provider`: String, timeoutMs: Int = 20_000): ProviderLoginSession { + val query = mutableListOf() + val path = "/v1/providers/${boundary.escape(`provider`)}/login" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun getProviderLogin(`id`: String, timeoutMs: Int = 20_000): ProviderLoginSession { + val query = mutableListOf() + val path = "/v1/provider-logins/${boundary.escape(`id`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun cancelProviderLogin(`id`: String, timeoutMs: Int = 20_000): ProviderLoginSession { + val query = mutableListOf() + val path = "/v1/provider-logins/${boundary.escape(`id`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("DELETE", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun answerProviderLogin(body: AnswerProviderLoginRequest, `id`: String, timeoutMs: Int = 20_000): ProviderLoginSession { + val query = mutableListOf() + val path = "/v1/provider-logins/${boundary.escape(`id`)}/responses" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("POST", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun listPasswordManagers(timeoutMs: Int = 20_000): PasswordManagers { + val query = mutableListOf() + val path = "/v1/password-managers" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun connectPasswordManager(body: ConnectPasswordManagerRequest, `id`: String, timeoutMs: Int = 20_000): PasswordManager { + val query = mutableListOf() + val path = "/v1/password-managers/${boundary.escape(`id`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PUT", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun disconnectPasswordManager(`id`: String, timeoutMs: Int = 20_000): Unit { + val query = mutableListOf() + val path = "/v1/password-managers/${boundary.escape(`id`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + boundary.send("DELETE", path, null, timeoutMs) + } + + suspend fun listPluginSettings(timeoutMs: Int = 20_000): PluginSettings { + val query = mutableListOf() + val path = "/v1/plugin-settings" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("GET", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun setPluginSetting(body: SetPluginSettingRequest, `pluginId`: String, `key`: String, timeoutMs: Int = 20_000): PluginSetting { + val query = mutableListOf() + val path = "/v1/plugin-settings/${boundary.escape(`pluginId`)}/${boundary.escape(`key`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("PUT", path, boundary.json.encodeToString(body).toByteArray(Charsets.UTF_8), timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + + suspend fun deletePluginSetting(`pluginId`: String, `key`: String, timeoutMs: Int = 20_000): PluginSetting { + val query = mutableListOf() + val path = "/v1/plugin-settings/${boundary.escape(`pluginId`)}/${boundary.escape(`key`)}" + if (query.isEmpty()) "" else "?" + query.joinToString("&") + val bytes = boundary.send("DELETE", path, null, timeoutMs) + return boundary.json.decodeFromString(bytes.toString(Charsets.UTF_8)) + } + suspend fun listMcpServers(timeoutMs: Int = 20_000): List { val query = mutableListOf() val path = "/v1/mcp-servers" + if (query.isEmpty()) "" else "?" + query.joinToString("&") diff --git a/app/src/main/java/dev/crumble/android/generated/event-projection.json b/app/src/main/java/dev/crumble/android/generated/event-projection.json index df67ed6..bd56149 100644 --- a/app/src/main/java/dev/crumble/android/generated/event-projection.json +++ b/app/src/main/java/dev/crumble/android/generated/event-projection.json @@ -2,7 +2,7 @@ "openapi": "3.1.0", "info": { "title": "Crumble SSE payloads", - "version": "1.0.0" + "version": "6.0.0" }, "components": { "schemas": { @@ -57,6 +57,12 @@ }, "agentId": { "type": "string" + }, + "via": { + "type": "string" + }, + "source": { + "type": "string" } }, "required": [ @@ -102,6 +108,51 @@ ], "additionalProperties": true }, + "jobQuestion": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "job": { + "type": "string" + }, + "options": { + "type": "array", + "items": { + "type": "string" + } + }, + "multiple": { + "type": "boolean" + } + }, + "required": [ + "id", + "kind", + "job" + ], + "additionalProperties": true + }, + "heldAction": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "job": { + "type": "string" + } + }, + "required": [ + "id", + "job" + ], + "additionalProperties": true + }, "attachments": { "type": "array", "items": { @@ -142,7 +193,26 @@ "isError": { "type": "boolean" }, - "toolDetails": {} + "toolDetails": {}, + "sources": { + "type": "array", + "items": { + "type": "object", + "properties": { + "url": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": [ + "url", + "title" + ], + "additionalProperties": true + } + } }, "required": [ "id", @@ -275,6 +345,23 @@ }, "executionId": { "type": "string" + }, + "jobName": { + "type": "string" + }, + "groupId": { + "type": "string" + }, + "groupName": { + "type": "string" + }, + "waitingFor": { + "type": "string", + "enum": [ + "approval", + "credential", + "login" + ] } }, "required": [ diff --git a/app/src/main/java/dev/crumble/android/model/ActivityFeed.kt b/app/src/main/java/dev/crumble/android/model/ActivityFeed.kt new file mode 100644 index 0000000..6ee1817 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/ActivityFeed.kt @@ -0,0 +1,134 @@ +package dev.crumble.android.model + +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle +import java.time.temporal.ChronoUnit +import java.util.Locale +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.contentOrNull + +const val ACTIVITY_PAGE_SIZE = 50L +private const val PREVIEW_CHARS = 240 +private val SPACES = Regex("[\\s\\p{Z}]+") + +@OptIn(ExperimentalSerializationApi::class) +private val PrettyJson = Json { + prettyPrint = true + prettyPrintIndent = " " +} + +enum class ActivityKind(val value: String, val label: String) { + ToolCall("tool-call", "Tool calls"), + ToolResult("tool-result", "Tool results"), + McpCall("mcp-call", "MCP calls"), + BotMessage("bot-message", "Bot messages"), + Change("change", "Changes"), +} + +/** The Activity page: its filters, the pages loaded so far, and the read in flight. */ +data class ActivityFeedState( + val kind: String? = null, + val botID: String? = null, + val items: List = emptyList(), + val nextCursor: String? = null, + val loading: Boolean = false, + val loadingOlder: Boolean = false, + val error: String = "", + val olderError: String = "", +) + +/** The first page; `keepOlder` keeps older pages already loaded when the page still joins up with them. */ +fun ActivityFeedState.withFirstPage(page: ActivityFeedResponse, keepOlder: Boolean): ActivityFeedState { + val joint = if (keepOlder) items.indexOfFirst { it.id == page.activities.lastOrNull()?.id } else -1 + val merged = if (joint >= 0) page.activities + items.drop(joint + 1) else page.activities + return copy( + items = merged.distinctBy { it.id }, + nextCursor = if (joint >= 0) nextCursor else page.nextCursor, + loading = false, + error = "", + ) +} + +fun ActivityFeedState.withOlderPage(page: ActivityFeedResponse): ActivityFeedState = + copy(items = (items + page.activities).distinctBy { it.id }, nextCursor = page.nextCursor, loadingOlder = false, olderError = "") + +private fun JsonObject.string(key: String) = (get(key) as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull + +private fun JsonObject.text(key: String): String? = get(key)?.let { value: JsonElement -> + if (value is JsonPrimitive && value.isString) value.content else value.toString() +} + +private val ActivityRecord.fields: JsonObject + get() = details as? JsonObject ?: JsonObject(emptyMap()) + +private fun previewOf(text: String?) = text.orEmpty().replace(SPACES, " ").take(PREVIEW_CHARS) + +/** What a row says: `lead verb target`, with tool names set as code. */ +data class ActivityHeadline(val lead: String, val verb: String, val target: String, val code: Boolean = false, val muted: Boolean = false) + +fun ActivityRecord.headline(): ActivityHeadline { + if (kind == "change") { + val change = fields + return ActivityHeadline(changeSummary(change, agentName.nilIfEmpty), "·", changeTitle(change), muted = true) + } + val tool = fields.string("toolName") ?: fields.string("name") ?: "a tool" + val communication = fields["communication"] as? JsonObject + return when (kind) { + "tool-call" -> ActivityHeadline(agentName, "used", tool, code = true) + "tool-result" -> ActivityHeadline(agentName, if (fields.isError()) "got an error from" else "got a result from", tool, code = true) + "mcp-call" -> ActivityHeadline(agentName, "called", fields.string("name") ?: "an MCP tool", code = true) + "bot-message" -> ActivityHeadline(communication?.string("fromName") ?: agentName, "messaged", communication?.string("toName") ?: "a bot") + else -> ActivityHeadline(agentName, "", kind.replace('-', ' ')) + } +} + +private fun JsonObject.isError() = (get("isError") as? JsonPrimitive)?.booleanOrNull == true + +fun ActivityRecord.preview(): String = when (kind) { + "change" -> "" + "tool-result", "bot-message" -> previewOf(fields.text("content")) + else -> previewOf(fields.string("error") ?: fields.string("args") ?: fields.text("arguments")) +} + +fun ActivityRecord.detailText(): String { + val content = fields.text("content") + if (kind == "bot-message" && !content.isNullOrEmpty()) return content + return details?.let { PrettyJson.encodeToString(JsonElement.serializer(), it) } ?: "No details" +} + +val ActivityRecord.failed: Boolean + get() = kind != "change" && (fields.isError() || !fields.string("error").isNullOrEmpty()) + +data class ActivityDay(val key: String, val label: String, val items: List) + +private fun activityDayLabel(date: LocalDate?, today: LocalDate, locale: Locale): String { + if (date == null) return "Earlier" + return when (ChronoUnit.DAYS.between(date, today)) { + 0L -> "Today" + 1L -> "Yesterday" + else -> date.format(DateTimeFormatter.ofPattern(if (date.year == today.year) "EEEE, MMMM d" else "EEEE, MMMM d, yyyy", locale)) + } +} + +/** Groups records by the viewer's local day, oldest day last, keeping feed order inside a day. */ +fun activityDays( + records: List, + today: LocalDate = LocalDate.now(), + zone: ZoneId = ZoneId.systemDefault(), + locale: Locale = Locale.getDefault(), +): List = records + .groupBy { record -> record.timestamp?.let { Instant.ofEpochMilli(it).atZone(zone).toLocalDate() } } + .map { (date, items) -> ActivityDay(date?.toString() ?: "undated", activityDayLabel(date, today, locale), items) } + +fun ActivityRecord.clock(zone: ZoneId = ZoneId.systemDefault(), locale: Locale = Locale.getDefault()): String { + val stamp = timestamp?.takeIf { it != 0L } ?: return "" + return DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(locale).format(Instant.ofEpochMilli(stamp).atZone(zone)) +} diff --git a/app/src/main/java/dev/crumble/android/model/Admin.kt b/app/src/main/java/dev/crumble/android/model/Admin.kt new file mode 100644 index 0000000..6ae6974 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/Admin.kt @@ -0,0 +1,49 @@ +package dev.crumble.android.model + +import dev.crumble.android.generated.AdminUser +import dev.crumble.android.generated.ListOutdatedWorkspacesResponseWorkspacesItem +import java.net.URI +import java.net.URLDecoder +import java.nio.charset.StandardCharsets +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle + +enum class AccountMode { SignIn, SignUp } + +/** The new invite's link, shown once, or why minting it failed. Neither means it's still on its way. */ +data class InviteSheet(val url: String? = null, val error: String = "") + +data class OutdatedWorkspaceRow(val bot: String, val owner: String) + +fun canCreateAccount(name: String, email: String, password: String) = + name.isNotBlank() && email.isNotBlank() && password.isNotEmpty() + +/** The token in a pasted invite link, or the text itself when it's the bare code. */ +fun inviteToken(text: String): String { + val trimmed = text.trim() + val query = runCatching { URI(trimmed).rawQuery }.getOrNull().orEmpty() + val token = query.split("&").firstOrNull { it.startsWith("invite=") }?.removePrefix("invite=") + return token?.let { URLDecoder.decode(it, StandardCharsets.UTF_8.name()) } ?: trimmed +} + +fun userRowTitle(user: AdminUser): String = + user.name.ifEmpty { user.email } + if (user.role == "admin") " (admin)" else "" + +fun dateOnly(iso: String, zone: ZoneId = ZoneId.systemDefault()): String { + val instant = runCatching { Instant.parse(iso) }.getOrNull() ?: return iso + return DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).withZone(zone).format(instant) +} + +/** Other accounts' bots aren't listed for an admin, so those rows fall back to the bot's ID. */ +fun outdatedWorkspaceRows( + workspaces: List, + bots: List, + users: List, +): List = workspaces.map { workspace -> + OutdatedWorkspaceRow( + bot = bots.firstOrNull { it.id == workspace.agentId }?.name ?: workspace.agentId, + owner = users.firstOrNull { it.id == workspace.userId }?.let { it.name.ifEmpty { it.email } } ?: workspace.userId, + ) +} diff --git a/app/src/main/java/dev/crumble/android/model/AppModel.kt b/app/src/main/java/dev/crumble/android/model/AppModel.kt index 0e5f9b1..bb3b013 100644 --- a/app/src/main/java/dev/crumble/android/model/AppModel.kt +++ b/app/src/main/java/dev/crumble/android/model/AppModel.kt @@ -5,14 +5,53 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import dev.crumble.android.BuildConfig +import dev.crumble.android.generated.BotAvatarDefinition +import dev.crumble.android.generated.LearnedChange +import dev.crumble.android.generated.MemorySource +import dev.crumble.android.generated.ScriptRun +import dev.crumble.android.generated.SkillPackage +import dev.crumble.android.generated.BotRequest +import dev.crumble.android.generated.Credential +import dev.crumble.android.generated.CredentialRequest +import dev.crumble.android.generated.Credentials +import dev.crumble.android.generated.Login +import dev.crumble.android.generated.LoginRequest +import dev.crumble.android.generated.Logins +import dev.crumble.android.generated.PasswordManager +import dev.crumble.android.generated.Provider +import dev.crumble.android.generated.ProviderLoginSession +import dev.crumble.android.generated.Capabilities +import dev.crumble.android.generated.GitHubAccount +import dev.crumble.android.generated.GitHubApp +import dev.crumble.android.generated.JudgeModel +import dev.crumble.android.generated.JudgeModelJudgeModel +import dev.crumble.android.generated.PluginSetting +import dev.crumble.android.generated.PluginSettings +import dev.crumble.android.generated.SecretStatus +import dev.crumble.android.generated.AdminUser +import dev.crumble.android.generated.Invite +import dev.crumble.android.generated.ListOutdatedWorkspacesResponseWorkspacesItem +import dev.crumble.android.generated.OptionalField +import dev.crumble.android.generated.ServerSettings +import dev.crumble.android.generated.UpdateServerSettingsRequest +import dev.crumble.android.generated.VisionModel +import dev.crumble.android.generated.VisionModelVisionModel +import dev.crumble.android.generated.CodingJob +import dev.crumble.android.generated.GroupChat +import dev.crumble.android.generated.HeldAction import dev.crumble.android.network.APIClient import dev.crumble.android.network.APIError +import dev.crumble.android.network.CHANGES_PAGE +import dev.crumble.android.network.HttpTransport +import dev.crumble.android.network.UrlConnectionTransport +import dev.crumble.android.network.domain +import dev.crumble.android.network.edited import dev.crumble.android.network.friendlyError import dev.crumble.android.network.oauthResult import dev.crumble.android.storage.CredentialStore import dev.crumble.android.storage.InMemoryCredentialStore import dev.crumble.android.ui.BotState -import dev.crumble.android.ui.agentAvatarSeed +import dev.crumble.android.ui.placeholderAvatar import java.security.MessageDigest import java.time.Instant import java.time.ZoneId @@ -26,31 +65,96 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.encodeToJsonElement + +/** The website's sidebar pages, reached from the account menu. Everything else lives under Settings. */ +val WORKSPACE_PAGES: List get() = listOf(Route.Memory, Route.Tasks, Route.Activity) + +/** The website's settings sections, grouped the way Android's Settings groups its rows. */ +val SETTINGS_GROUPS: List> get() = listOf( + listOf(Route.General), + listOf(Route.Providers, Route.JudgeModel, Route.VisionModel, Route.WebSearch), + listOf(Route.Credentials, Route.Logins, Route.PasswordManagers), + listOf(Route.Integrations, Route.Coding, Route.MessageGateways, Route.EventRelay), + listOf(Route.Skills, Route.Avatars, Route.Users), +) + +val SETTINGS_PAGES: List get() = SETTINGS_GROUPS.flatten() sealed class Route { data class AgentChat(val id: String) : Route() + data class GroupChat(val id: String) : Route() data object Memory : Route() data object Skills : Route() data object Tasks : Route() data object Activity : Route() data object Integrations : Route() + data object Avatars : Route() + data object Providers : Route() + data object PasswordManagers : Route() + data object Credentials : Route() + data object Logins : Route() + data object WebSearch : Route() + data object JudgeModel : Route() + data object VisionModel : Route() + data object Coding : Route() + data object Users : Route() + data object MessageGateways : Route() + data class MessageGateway(val id: String) : Route() + data object EventRelay : Route() + data object Settings : Route() + data object General : Route() + data object Account : Route() + data object NewChat : Route() + data object NewGroup : Route() + + /** Where Back leads. Null is Home. */ + val parent: Route? + get() = when { + this in SETTINGS_PAGES -> Settings + this in WORKSPACE_PAGES || this == Settings -> Account + this is MessageGateway -> MessageGateways + this == NewGroup -> NewChat + else -> null + } val title: String get() = when (this) { is AgentChat -> "Chat" + is GroupChat -> "Group chat" Memory -> "Memory" Skills -> "Skills" - Tasks -> "Tasks" + Tasks -> "Automations" Activity -> "Activity" Integrations -> "Integrations" + Avatars -> "Avatars" + Providers -> "Providers" + PasswordManagers -> "Password managers" + Credentials -> "Credentials" + Logins -> "Logins" + WebSearch -> "Web search" + JudgeModel -> "Judge model" + VisionModel -> "Vision model" + Coding -> "Coding" + Users -> "Users" + MessageGateways -> "Message gateways" + is MessageGateway -> "Message gateway" + EventRelay -> "Event relay" + Settings -> "Settings" + General -> "General" + Account -> "Account" + NewChat -> "New chat" + NewGroup -> "New group chat" } } @@ -61,32 +165,32 @@ data class AgentDraft( var name: String = "", var description: String = "", var enabled: Boolean = true, - var provider: String = "melious", + var provider: String = "", var model: String = "", var instructions: String = "You are a thoughtful, capable personal assistant.", - var avatar: String = "bot:${newRequestID()}", - var avatarChoices: List = emptyList(), + var avatar: BotAvatarDefinition? = null, var thinking: String = "off", var temperature: String = "", var maxOutput: String = "", var toolsMemory: Boolean = true, var toolsDelegate: Boolean = false, - var toolsSchedule: Boolean = false, - var toolsCodemode: Boolean = false, - var sharedMemory: Boolean = false, - var delegates: Set = emptySet(), var mcpServers: Set = emptySet(), var skills: List = emptyList(), var sharedSkills: Set = emptySet(), + /** The bot request this draft edits; saving approves the request with the edits. */ + val botRequestID: String? = null, + /** Tools the proposal asks for beyond the toggles every draft has. */ + var otherTools: Set = emptySet(), + /** Null follows the account's default. */ + var webSearchProvider: String? = null, + /** Empty follows the bot's own provider and model. */ + var desktopProvider: String = "", + var desktopModel: String = "", + /** What the bot had when the editor opened; a granted tool stays visible when the server stops offering it. */ + val initialTools: Set = emptySet(), ) { - /** Offers new bots to pick from, keeping the current one first. */ - fun withShuffledAvatars(): AgentDraft { - val choices = mutableListOf(agentAvatarSeed(Agent(id = agentID, avatar = avatar))) - while (choices.size < 7) { - choices.add(newRequestID()) - } - return copy(avatarChoices = choices) - } + val chosenDesktopModel: ModelChoice? + get() = desktopModel.trim().nilIfEmpty?.takeIf { desktopProvider.isNotEmpty() }?.let { ModelChoice(desktopProvider, it) } } data class MemoryDraft( @@ -104,6 +208,16 @@ data class SkillDraft( var agentID: String? = null, var name: String = "", var instructions: String = "", + /** Bots that use a shared skill. */ + var usedBy: Set = emptySet(), +) + +/** The Avatars page: a definition being tried, and the bot it saves to, if any. */ +data class AvatarPage( + val botID: String = "", + val value: BotAvatarDefinition = placeholderAvatar("crumble"), + val saving: Boolean = false, + val saved: Boolean = false, ) data class TaskDraft( @@ -112,7 +226,15 @@ data class TaskDraft( var agentID: String, var name: String = "", var prompt: String = "", + var kind: String = "prompt", + var command: String = "", + var timeoutSeconds: String = "600", + var notify: Boolean = true, + var onEvent: Boolean = false, + var eventSourceID: String = "", var repeats: Boolean = false, + /** The owner chose Custom, so a cron that happens to fit a preset stays in the raw field. */ + var customCron: Boolean = false, var cron: String = "0 9 * * *", var runDate: Instant = Instant.now().plusSeconds(3600).truncatedTo(ChronoUnit.MINUTES), var timezone: String = ZoneId.systemDefault().id, @@ -126,8 +248,12 @@ data class MCPDraft( var agentID: String? = null, var name: String = "", var url: String = "", - var token: String = "", + var token: SecretDraft = SecretDraft(), var enabled: Boolean = true, + var clientID: String = "", + var clientSecret: SecretDraft = SecretDraft(), + /** A changed password manager reference is read before anything is saved, so the sheet waits for it. */ + var saving: Boolean = false, ) private fun defaultAppScope(): CoroutineScope { @@ -141,6 +267,30 @@ private fun defaultAppScope(): CoroutineScope { return CoroutineScope(SupervisorJob() + dispatcher) } +private const val DECISION_POLL_MS = 5_000L +private const val BOT_STATUS_POLL_MS = 5_000L +private const val PROVIDER_LOGIN_POLL_MS = 1_000L +private const val JOB_REFRESH_MS = 3_000L +private const val IDLE_JOB_REFRESH_MS = 15_000L +private const val DESKTOP_STATUS_MS = 10_000L +private const val DESKTOP_HAND_BACK_ATTEMPTS = 3 +private const val JOB_PAGE_SIZE = 100 +private const val JOB_TRANSCRIPT_PAGE_SIZE = 200 +private const val GROUP_PAGE_SIZE = 100 +private const val RECENT_CHAT_PREFIX = "recent-chat:" +private const val COMPOSER_DRAFT_PREFIX = "composer-draft:" +private const val DRAFT_SAVE_DELAY_MS = 500L +private const val THEME_KEY = "theme" +private val DRAFT_TOOLS = setOf("memory", "delegate") +private const val STILL_SAVING = "That change is still saving. Try again in a moment." +private const val BOT_RECORD = "agent:" +private const val GROUP_RECORD = "group:" +private const val MEMORY_RECORD = "memory:" +private const val SCHEDULE_RECORD = "schedule:" +private const val MCP_RECORD = "mcp:" +private const val SKILL_RECORD = "skill:" +private const val BOT_SKILL_RECORD = "agent-skill:" + /** * The app's state and the actions that change it. Network work runs in coroutines on the model's * scope; results from a replaced connection or a previous agent are dropped. @@ -153,14 +303,55 @@ class AppModel( private val scope: CoroutineScope = defaultAppScope(), environment: Map = emptyMap(), loadCredentials: Boolean = client == null, + private val transport: HttpTransport = UrlConnectionTransport, + private val onSignOut: suspend (APIClient) -> Unit = {}, + private val onSessionReset: () -> Unit = {}, + private val onNotificationsChanged: () -> Unit = {}, ) { var serverURL by mutableStateOf("http://127.0.0.1:7337") var token by mutableStateOf("") + var email by mutableStateOf("") + var heldActions by mutableStateOf>(emptyList()) + var codingJobs by mutableStateOf>(emptyList()) + var botRequests by mutableStateOf>(emptyList()) + var decisionsLoaded by mutableStateOf(false) + var decisionsFailed by mutableStateOf(false) + var decidingIDs by mutableStateOf>(emptySet()) + var decisionErrors by mutableStateOf>(emptyMap()) + private var decisionsJob: Job? = null + private var decisionsKey = "" + var jobs by mutableStateOf>(emptyList()) + var jobsLoaded by mutableStateOf(false) + var jobsFailed by mutableStateOf(false) + var showingJobs by mutableStateOf(false) + var showingBotDetails by mutableStateOf(false) + /** Bots the last status check found running; the selected bot's stream is fresher while it is open. */ + var workingBots by mutableStateOf>(emptySet()) + var jobPanel by mutableStateOf(null) + private var jobsFollow: Job? = null + private var chatJobsLoad: Job? = null + private var chatJobsKey = "" + private var jobPanelVersion = 0 + var botDesktop by mutableStateOf(null) + private set + var desktopPreview by mutableStateOf(null) + private set + private var desktopAPI: APIClient? = null + private var desktopFollow: Job? = null + private var desktopTake: Job? = null + private var desktopVersion = 0 + private var desktopPreviewPoll: Job? = null + private var desktopPreviewVersion = 0 + private var desktopPreviewLink = 0 + var password by mutableStateOf("") var client: APIClient? by mutableStateOf(client) private set private var generation = 0 + var signingOut by mutableStateOf(false) + private set var agents by mutableStateOf>(emptyList()) + /** Null is home, the bot overview. */ var route by mutableStateOf(null) var selectedAgentID by mutableStateOf("") private set @@ -168,14 +359,16 @@ class AppModel( private var awaitingInitialSnapshot = false private val recentChats = mutableMapOf() - private fun cacheKey(id: String): String { + /** Names the server and account, so what one session stored never reaches another. */ + private fun sessionDigest(): String { val api = client val identity = "${api?.baseURL}\n${api?.token}" - val digest = MessageDigest.getInstance("SHA-256") + return MessageDigest.getInstance("SHA-256") .digest(identity.toByteArray()).joinToString("") { "%02x".format(it) } - return "recent-chat:$digest:$id" } + private fun cacheKey(id: String) = "$RECENT_CHAT_PREFIX${sessionDigest()}:$id" + private fun cachedChat(id: String): ChatSnapshot? { val key = cacheKey(id) return recentChats[key] ?: runCatching { @@ -183,13 +376,19 @@ class AppModel( }.getOrNull()?.also { recentChats[key] = it } } + private fun forgetCachedChat(id: String) { + val key = cacheKey(id) + recentChats.remove(key) + credentials.delete(key) + } + /** Keep only recent confirmed rows; uploads and transient run state are never persisted here. */ private fun cacheRecentChat() { if (selectedAgentID.isEmpty()) return val confirmed = messages.filter { it.deliveryState == MessageDeliveryState.confirmed } val tail = confirmed.takeLast(5) // Keep an entry intact so the history cursor cannot skip another row from that entry. - val boundary = tail.first().entryId + val boundary = tail.firstOrNull()?.entryId val retained = if (boundary == null) tail else confirmed.dropWhile { it.entryId != boundary } val cached = ChatSnapshot( agentId = selectedAgentID, @@ -210,14 +409,62 @@ class AppModel( var loadingOlder by mutableStateOf(false) var expanded by mutableStateOf>(emptySet()) - var draft by mutableStateOf("") + private var composerText by mutableStateOf("") + + /** The selected bot's text. Assigning it saves it, so nothing that changes the selection may write it. */ + var draft: String + get() = composerText + set(value) { + if (value == composerText) return + composerText = value + saveDraft(botDraft(selectedAgentID), value) + } var attachments by mutableStateOf>(emptyList()) var replyTo by mutableStateOf(null) - var sending by mutableStateOf(false) - private var draftRequestID = "" - private var failedDraft = "" - private var failedReplyTo = "" - private var failedAttachments = emptyList() + + /** The other bots' composers; the selected bot's lives in `draft`, `attachments`, and `replyTo`. */ + private val parkedComposers = mutableMapOf() + + /** Text waiting to reach the store, by key; empty means delete. Attachments and reply targets are never stored. */ + private val unsavedDrafts = mutableMapOf() + private var draftSave: Job? = null + + private fun botDraft(id: String) = composerDraftKey("bot", id) + + private fun groupDraftKey(id: String) = composerDraftKey("group", id) + + private fun composerDraftKey(kind: String, id: String): String? = + if (id.isEmpty() || client?.token.isNullOrEmpty()) null else "$COMPOSER_DRAFT_PREFIX${sessionDigest()}:$kind:$id" + + // Encrypting on every keystroke would slow typing, so the store sees the text once it settles. + private fun saveDraft(key: String?, text: String) { + unsavedDrafts[key ?: return] = text + draftSave?.cancel() + draftSave = scope.launch { + delay(DRAFT_SAVE_DELAY_MS) + saveDrafts() + } + } + + /** Runs when the app leaves the screen too, because the system may end the process without warning. */ + fun saveDrafts() { + draftSave?.cancel() + for ((key, text) in unsavedDrafts) { + runCatching { if (text.isEmpty()) credentials.delete(key) else credentials.write(key, text) } + } + unsavedDrafts.clear() + } + + private fun savedDraft(key: String?): String { + if (key == null) return "" + return unsavedDrafts[key] ?: runCatching { credentials.read(key) }.getOrNull().orEmpty() + } + + private fun forgetDrafts() { + draftSave?.cancel() + unsavedDrafts.clear() + credentials.deletePrefixed(COMPOSER_DRAFT_PREFIX) + } private data class PendingSend( val content: String, @@ -235,6 +482,21 @@ class AppModel( private val pendingSends = mutableMapOf>() private val pendingPreviews = mutableMapOf() + var groupChats by mutableStateOf>(emptyList()) + var groupsFailed by mutableStateOf(false) + var groupConversation by mutableStateOf(null) + private set + var groupDraft by mutableStateOf(null) + + /** Drafts and unconfirmed messages stay with their group while the owner is elsewhere. */ + var groupComposers by mutableStateOf>(emptyMap()) + private set + var groupOutgoing by mutableStateOf>>(emptyMap()) + private set + private val groupSends = mutableMapOf() + private var groupStream: Job? = null + private var groupVersion = 0 + /** Sent image bytes, keyed by "entryId/index"; they never change once sent. */ var attachmentBytes by mutableStateOf>(emptyMap()) private set @@ -244,6 +506,12 @@ class AppModel( private set var mutationRevision = 0 private set + + /** What each pending mutation changes, as "kind:id"; a read keeps these records as they are here. */ + private val activeRecords = mutableMapOf>() + + /** The revision each record's last mutation settled at, so a read can tell it started too early. */ + private val settledRecords = mutableMapOf() var loading by mutableStateOf(false) var errorText by mutableStateOf("") var notice by mutableStateOf("") @@ -256,27 +524,144 @@ class AppModel( var agentMemories by mutableStateOf>>(emptyMap()) private var memoryLoadVersion = 0 var sharedMemories by mutableStateOf>(emptyList()) + /** Why an owner's memories didn't load, by bot ID, or SKILLS_SHARED for shared memory. */ + var memoryErrors by mutableStateOf>(emptyMap()) + /** Null shows every owner; otherwise SKILLS_SHARED or a bot's ID. */ + var memoryScope by mutableStateOf(null) var sharedSkills by mutableStateOf>(emptyList()) + var agentSkills by mutableStateOf>>(emptyMap()) + var agentSkillErrors by mutableStateOf>(emptyMap()) + var selectedSkills by mutableStateOf>(emptySet()) + var bulkReport by mutableStateOf>(emptyList()) + var checkingSkillUpdates by mutableStateOf(false) + private set + var skillCheckFailures by mutableStateOf>(emptyList()) + var skillInstall by mutableStateOf(null) + private var skillBrowseVersion = 0 + var installedSkill by mutableStateOf(null) + var skillUpdate by mutableStateOf(null) + var changes by mutableStateOf>(emptyList()) + var showingChanges by mutableStateOf(false) + var changesLoading by mutableStateOf(false) + private set + var changesHasMore by mutableStateOf(false) + private set + var changesError by mutableStateOf("") + private var changesVersion = 0 + var avatarPage by mutableStateOf(AvatarPage()) var schedules by mutableStateOf>(emptyList()) + var schedulesLoaded by mutableStateOf(false) + var schedulesError by mutableStateOf("") var executions by mutableStateOf>(emptyList()) - var activities by mutableStateOf>(emptyList()) + var scriptRuns by mutableStateOf>>(emptyMap()) + var taskRunsLoading by mutableStateOf(false) + var taskRunsError by mutableStateOf("") + private var taskRunsVersion = 0 + var taskTab by mutableStateOf(TaskTab.Tasks) + private set + var capabilities by mutableStateOf(null) + var eventSources by mutableStateOf>(emptyList()) + var eventSourcesLoaded by mutableStateOf(false) + var eventSourcesError by mutableStateOf("") + private var eventSourcesVersion = 0 + var deletingEventSources by mutableStateOf>(emptySet()) + var eventSourceErrors by mutableStateOf>(emptyMap()) + var activityFeed by mutableStateOf(ActivityFeedState()) + val activities: List + get() = activityFeed.items + private var activityLoadVersion = 0 var mcpServers by mutableStateOf>(emptyList()) var providers by mutableStateOf>(emptyList()) var models by mutableStateOf>(emptyList()) + var desktopModels by mutableStateOf>(emptyList()) var agentDraft by mutableStateOf(null) var memoryDraft by mutableStateOf(null) var taskDraft by mutableStateOf(null) + var eventSourceDraft by mutableStateOf(null) var mcpDraft by mutableStateOf(null) var skillDraft by mutableStateOf(null) - var showingSettings by mutableStateOf(false) + var showingPalette by mutableStateOf(false) + var theme by mutableStateOf(ThemeChoice.of(credentials.read(THEME_KEY)) ?: ThemeChoice.System) + private set + private var accountTheme = theme + private var themeSaving = false + private var themeChanges = 0 + private val notificationSettings = NotificationSettings(credentials) + var replyNotifications by mutableStateOf(notificationSettings.replies) + private set + var notificationSound by mutableStateOf(notificationSettings.sound) + private set + /** Android's own verdict, reported by the activity. */ + var notificationsAllowed by mutableStateOf(true) + var botCredentials by mutableStateOf>(emptyMap()) + var botLogins by mutableStateOf>(emptyMap()) + var credentialLoadErrors by mutableStateOf>(emptyMap()) + var loginLoadErrors by mutableStateOf>(emptyMap()) + var credentialScope by mutableStateOf(SKILLS_ALL) + var loginScope by mutableStateOf(SKILLS_ALL) + var credentialForm by mutableStateOf(null) + var loginForm by mutableStateOf(null) + var secretUses by mutableStateOf(null) + var freshSecretRequests by mutableStateOf>(emptySet()) + var passwordManagers by mutableStateOf>(emptyList()) + var passwordManagersLoaded by mutableStateOf(false) + var passwordManagersError by mutableStateOf("") + var tokenForm by mutableStateOf(null) + var providerAccounts by mutableStateOf>(emptyList()) + var providerKeyForm by mutableStateOf(null) + var providerLogin by mutableStateOf(null) + + /** How one kind of bot-owned secret is read, stored, and changed; credentials and logins behave alike. */ + private class SecretOps( + val kind: String, + val read: suspend (APIClient, String) -> D, + val delete: suspend (APIClient, String, String) -> Unit, + val decline: suspend (APIClient, String, String) -> Unit, + val withoutItem: (D, String) -> D, + val withoutRequest: (D, String) -> D, + val restored: (D, D, String) -> D, + val lists: () -> Map, + val store: (Map) -> Unit, + val failures: (Map) -> Unit, + ) + + private val credentialOps = SecretOps( + kind = "credential", + read = { api, id -> api.credentials(id) }, + delete = { api, id, name -> api.deleteCredential(id, name) }, + decline = { api, id, name -> api.declineCredential(id, name) }, + withoutItem = { list, name -> list.copy(credentials = list.credentials.filterNot { it.name == name }) }, + withoutRequest = { list, name -> list.copy(requests = list.requests.filterNot { it.name == name }) }, + restored = { list, before, name -> list.restored(before, name) }, + lists = { botCredentials }, + store = { botCredentials = it }, + failures = { credentialLoadErrors = it }, + ) + + private val loginOps = SecretOps( + kind = "login", + read = { api, id -> api.logins(id) }, + delete = { api, id, name -> api.deleteLogin(id, name) }, + decline = { api, id, name -> api.declineLogin(id, name) }, + withoutItem = { list, name -> list.copy(logins = list.logins.filterNot { it.name == name }) }, + withoutRequest = { list, name -> list.copy(requests = list.requests.filterNot { it.name == name }) }, + restored = { list, before, name -> list.restored(before, name) }, + lists = { botLogins }, + store = { botLogins = it }, + failures = { loginLoadErrors = it }, + ) + + private val secretRevisions = mutableMapOf() + private var providerLoginJob: Job? = null + private var providerLoginReads = 0 /** The MCP server whose sign-in flow is currently active. */ var signingIn by mutableStateOf(null) + // Outlives the spinner: the owner can glance at the app and still finish in the browser. + private var browserSignIn: String? = null var confirmingDelete by mutableStateOf(false) - var provider by mutableStateOf("melious") - var providerKey by mutableStateOf("") var appActive: Boolean = true @@ -286,6 +671,7 @@ class AppModel( if (!savedUrl.isNullOrEmpty()) serverURL = savedUrl val savedToken = credentials.read("server-token") if (savedToken != null) token = savedToken + credentials.read("account-email")?.let { email = it } } val envUrl = environment["CRUMBLE_URL"]?.trim() if (!envUrl.isNullOrEmpty()) { @@ -300,13 +686,45 @@ class AppModel( } } + /** The live stream the sidebar reports: the open group chat's, or else the bot chat's. */ + val liveStatus: String + get() = groupConversation?.streamStatus ?: streamStatus + val selectedAgent: Agent? get() = agents.firstOrNull { it.id == selectedAgentID } fun botState(agent: Agent): BotState { if (!agent.enabled) return BotState.sleeping - if (agent.id == selectedAgentID && snapshot?.isRunning == true) return BotState.working - return BotState.idle + return if (isWorking(agent.id)) BotState.working else BotState.idle + } + + /** No server event announces a turn, so bots without an open stream come from `refreshBotStatuses`. */ + fun isWorking(agentID: String): Boolean { + val live = snapshot?.takeIf { agentID == selectedAgentID && route !is Route.GroupChat } + return live?.isRunning ?: (agentID in workingBots) + } + + /** Reads every bot's status. A failed read keeps what was known rather than calling the bot idle. */ + suspend fun refreshBotStatuses() { + val api = client ?: return + val gen = generation + val ids = agents.filter { it.enabled && !it.id.startsWith("pending:") }.map { it.id } + val results = coroutineScope { + ids.map { id -> async { id to attempt { api.chat(id, limit = 1) } } }.awaitAll() + } + if (generation != gen) return + val running = results.mapNotNull { (id, result) -> result.getOrNull()?.let { id to it.isRunning } }.toMap() + val known = agents.mapTo(HashSet()) { it.id } + workingBots = (workingBots.filterTo(HashSet()) { running[it] != false } + running.filterValues { it }.keys) + .filterTo(HashSet()) { it in known } + } + + /** Keeps statuses fresh for as long as the caller shows the bot list. */ + suspend fun followBotStatuses() { + while (currentCoroutineContext().isActive) { + if (appActive) refreshBotStatuses() + delay(BOT_STATUS_POLL_MS) + } } // MARK: Requests @@ -347,6 +765,9 @@ class AppModel( key: String, update: () -> Unit, rollback: () -> Unit, + fail: (String) -> Unit = { errorText = it }, + touches: Set = emptySet(), + onBusy: () -> Unit = { errorText = STILL_SAVING }, work: suspend (APIClient) -> (() -> Unit)?, ) { val currentClient = client @@ -354,8 +775,12 @@ class AppModel( errorText = "Connect to your server in Settings." return } - if (pendingMutations.contains(key)) return + if (pendingMutations.contains(key)) { + onBusy() + return + } pendingMutations = pendingMutations + key + activeRecords[key] = touches + key val gen = generation mutationRevision += 1 update() @@ -366,23 +791,45 @@ class AppModel( try { val confirm = work(currentClient) if (generation != gen) return@launch - pendingMutations = pendingMutations - key - mutationRevision += 1 + settleMutation(key) finishRequest() confirm?.invoke() } catch (e: CancellationException) { throw e } catch (e: Throwable) { if (generation != gen) return@launch - pendingMutations = pendingMutations - key - mutationRevision += 1 + settleMutation(key) finishRequest() rollback() - errorText = friendlyError(e) + fail(friendlyError(e)) } } } + private fun settleMutation(key: String) { + pendingMutations = pendingMutations - key + mutationRevision += 1 + activeRecords.remove(key).orEmpty().forEach { settledRecords[it] = mutationRevision } + } + + /** Whether a read from `revision` may predate a change that finished, so it must fetch again. */ + private fun settledSince(revision: Int, vararg kinds: String): Boolean = + settledRecords.any { (record, at) -> at > revision && kinds.any(record::startsWith) } + + /** The server's list, with records that have a mutation on its way kept as they are here. */ + private fun withLocalChanges(loaded: List, local: List, kind: String, idOf: (T) -> String): List { + val changing = activeRecords.values.flatten().filter { it.startsWith(kind) }.map { it.removePrefix(kind) }.toSet() + if (changing.isEmpty()) return loaded + val mine = local.associateBy(idOf) + val known = loaded.mapTo(HashSet(), idOf) + return loaded.mapNotNull { if (idOf(it) in changing) mine[idOf(it)] else it } + + local.filter { idOf(it) in changing && idOf(it) !in known } + } + + private fun applyBots(loaded: List) { + agents = withLocalChanges(loaded, agents, BOT_RECORD, Agent::id) + } + fun showNotice(text: String) { notice = text scope.launch { @@ -394,48 +841,89 @@ class AppModel( // MARK: Agents and chat fun refresh() { + loadAccount() + loadGroupChats() + loadBotList() + } + + private fun loadBotList() { val revision = mutationRevision request { api -> - val loadedAgents = api.agents() + val loaded = api.agents() return@request { - if (mutationRevision == revision && pendingMutations.isEmpty()) { - agents = loadedAgents + if (settledSince(revision, BOT_RECORD)) { + loadBotList() + } else { + applyBots(loaded) var chosen = selectedAgentID - if (loadedAgents.none { it.id == chosen }) { - chosen = loadedAgents.firstOrNull()?.id ?: "" + if (agents.none { it.id == chosen }) { + chosen = agents.firstOrNull { !it.id.startsWith("pending:") }?.id ?: "" } - if (chosen.isEmpty()) { + val inConversation = route is Route.AgentChat || route is Route.GroupChat + if (chosen.isEmpty() || (!inConversation && chosen != selectedAgentID)) { cancelStream() - selectedAgentID = "" + switchComposer(chosen) + selectedAgentID = chosen snapshot = null messages = emptyList() - } else { + } else if (route is Route.AgentChat) { selectAgent(chosen) } + // A reconnect emptied the open page, and its reads may need the bots that just arrived. + route?.takeUnless { inConversation }?.let(::openPanel) } } } } fun navigate(to: Route?) { - if (to == null) return when (to) { + null -> openHome() is Route.AgentChat -> { if (to.id != selectedAgentID || route != to) { selectAgent(to.id) } } + is Route.GroupChat -> if (route != to) openGroupChat(to.id) else -> openPanel(to) } } + /** Parks what the owner is writing to the selected bot and picks up what they left with `id`. */ + private fun switchComposer(id: String) { + if (id == selectedAgentID) return + val current = ChatComposer(draft, attachments, replyTo) + if (current != ChatComposer()) parkedComposers[selectedAgentID] = current + val next = parkedComposers.remove(id) ?: ChatComposer(draft = savedDraft(botDraft(id))) + composerText = next.draft + attachments = next.attachments + replyTo = next.replyTo + } + /** Opens the bot's one continuous chat and follows its event stream. */ fun selectAgent(id: String) { - cancelStream() + if (route != Route.AgentChat(id)) clearSecretDrafts() + if (id != selectedAgentID) showingBotDetails = false + closeGroupChat() + stopChat() + // A refresh reselects the same bot, which must not take the desktop away from its owner. + if (botDesktop?.agentID != id) closeBotDesktop() selectionVersion += 1 val version = selectionVersion + switchComposer(id) selectedAgentID = id route = Route.AgentChat(id) + heldActions = emptyList() + codingJobs = emptyList() + botRequests = emptyList() + decisionsLoaded = false + decisionsFailed = false + decisionErrors = emptyMap() + freshSecretRequests = emptySet() + jobs = emptyList() + jobsLoaded = false + jobsFailed = false + if (agentDraft?.botRequestID != null) agentDraft = null val cached = cachedChat(id) snapshot = cached?.copy(messages = null) messages = cached?.messages.orEmpty() + pendingMessages[id].orEmpty() @@ -443,14 +931,6 @@ class AppModel( oldestEntryID = cached?.oldestEntryId ?: "" awaitingInitialSnapshot = true loadingOlder = false - replyTo = null - draft = "" - attachments = emptyList() - failedDraft = "" - failedReplyTo = "" - failedAttachments = emptyList() - sending = false - draftRequestID = "" // A stream begins with a fresh snapshot. Reopening a cached chat needs no extra GET. if (cached != null) { client?.let { api -> streamJob = scope.launch { streamChat(api, id, version) } } @@ -472,6 +952,11 @@ class AppModel( val incomingMessages = incoming.messages ?: emptyList() val acknowledged = incomingMessages.mapNotNull { it.requestId }.toSet() if (acknowledged.isNotEmpty()) { + // A send that only looked failed arrived after all, so its restored draft must not go out again. + val restored = pendingMessages[selectedAgentID].orEmpty() + .filter { it.deliveryState == MessageDeliveryState.failed && it.requestId in acknowledged } + .mapNotNull { pendingSends[selectedAgentID]?.get(it.requestId) } + if (restored.any(::composerHolds)) clearComposer() pendingMessages[selectedAgentID]?.removeAll { acknowledged.contains(it.requestId ?: "") } for (reqId in acknowledged) { pendingSends[selectedAgentID]?.remove(reqId) @@ -496,117 +981,634 @@ class AppModel( messages = confirmed + local snapshot = incoming.copy(messages = null) cacheRecentChat() + followDecisions() + refreshChatJobs() } fun cancelStream() { + stopChat() + closeBotDesktop() + } + + private fun stopChat() { + snapshot?.let { workingBots = if (it.isRunning) workingBots + selectedAgentID else workingBots - selectedAgentID } streamJob?.cancel() streamJob = null streamStatus = "" + decisionsJob?.cancel() + decisionsKey = "" + closeJobs() } - private suspend fun streamChat(api: APIClient, id: String, version: Int) { - var backoffMs = 500L - while (scope.isActive) { + private fun hasPendingDecision(): Boolean = + messages.any { message -> + message.heldAction?.let { ref -> heldActions.any { it.id == ref.id && it.status == "pending" } } == true || + message.jobQuestion?.let { ref -> codingJobs.any { it.question?.id == ref.id } } == true || + message.botRequest?.let { ref -> botRequests.any { it.id == ref.id && it.status == "pending" } } == true || + message.credentialRequest?.let { ref -> botCredentials[selectedAgentID]?.requests?.any { ref.answers(it.name, it.requestedAt) } } == true || + message.loginRequest?.let { ref -> botLogins[selectedAgentID]?.requests?.any { ref.answers(it.name, it.requestedAt) } } == true + } + + private fun secretRefs() = messages.flatMap { + listOfNotNull(it.credentialRequest?.let(::credentialReadKey), it.loginRequest?.let(::loginReadKey)) + } + + private suspend fun loadDecisions(api: APIClient, agentID: String) { + try { + val held = if (messages.any { it.heldAction != null }) api.heldActions(agentID) else emptyList() + val jobs = if (messages.any { it.jobQuestion != null }) api.codingJobs(agentID) else emptyList() + val requests = if (messages.any { it.botRequest != null }) api.botRequests(agentID) else emptyList() + val asked = secretRefs().toSet() + val credentialMark = secretMark("credential", agentID) + val loginMark = secretMark("login", agentID) + val credentialList = if (messages.any { it.credentialRequest != null }) api.credentials(agentID) else null + val loginList = if (messages.any { it.loginRequest != null }) api.logins(agentID) else null + if (selectedAgentID != agentID) return + heldActions = held + codingJobs = jobs + botRequests = requests + if (credentialList != null && secretSettled("credential", agentID, credentialMark)) botCredentials = botCredentials + (agentID to credentialList) + if (loginList != null && secretSettled("login", agentID, loginMark)) botLogins = botLogins + (agentID to loginList) + freshSecretRequests = asked + val editing = agentDraft?.botRequestID + if (editing != null && requests.none { it.id == editing && it.status == "pending" }) agentDraft = null + decisionsLoaded = true + decisionsFailed = false + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + if (selectedAgentID == agentID) decisionsFailed = true + } + } + + // Another client, a stopped job, or a restart can settle a decision, so keep reading while one waits. + private fun followDecisions() { + val refs = messages.flatMap { listOfNotNull(it.heldAction?.id, it.jobQuestion?.id, it.botRequest?.id) } + secretRefs() + val key = selectedAgentID + "\n" + refs.joinToString("\n") + val api = client + if (refs.isEmpty() || key == decisionsKey || api == null) return + val agentID = selectedAgentID + decisionsKey = key + decisionsJob?.cancel() + decisionsJob = scope.launch { + do { + loadDecisions(api, agentID) + if (decisionsFailed || hasPendingDecision()) delay(DECISION_POLL_MS) + } while (isActive && (decisionsFailed || hasPendingDecision())) + } + } + + private fun decide(id: String, work: suspend (APIClient, String) -> (() -> Unit)?) { + val api = client ?: return + if (id in decidingIDs) return + val agentID = selectedAgentID + val gen = generation + decidingIDs = decidingIDs + id + decisionErrors = decisionErrors - id + scope.launch { try { - api.chatEvents(id, limit = 5) { snap -> - if (selectionVersion != version || client !== api) return@chatEvents - applySnapshot(snap) - streamStatus = "" - errorText = "" - } + val confirm = work(api, agentID) + if (generation == gen) confirm?.invoke() } catch (e: CancellationException) { throw e - } catch (e: Throwable) { - if (selectionVersion != version) return - if (e is APIError && e.statusCode == 401) { - errorText = friendlyError(e) - streamStatus = "Disconnected" - return - } - streamStatus = "Reconnecting…" + } catch (e: Exception) { + if (generation == gen) decisionErrors = decisionErrors + (id to friendlyError(e)) + } finally { + decidingIDs = decidingIDs - id } - delay(backoffMs) - backoffMs = minOf(backoffMs * 2, 8_000L) + if (generation == gen) loadDecisions(api, agentID) } } - /** Follows server-wide activity for notifications, reconnecting as the chat stream does. */ - fun followActivity() { - activityJob?.cancel() - val api = client ?: return + fun decideHeldAction(id: String, approve: Boolean, reason: String = "") = decide(id) { api, agentID -> + if (approve) api.approveHeldAction(agentID, id) else api.declineHeldAction(agentID, id, reason.trim()) + null + } + + fun answerJobQuestion(job: String, questionID: String, text: String) { val gen = generation - activityJob = scope.launch { - var backoffMs = 500L - while (isActive && generation == gen) { - try { - api.activityEvents { event -> - if (generation != gen) return@activityEvents - handleActivity(event) - } - } catch (e: CancellationException) { - throw e - } catch (e: Throwable) { - if (e is APIError && e.statusCode == 401) return@launch + decide(questionID) { api, agentID -> + api.answerCodingJob(agentID, job, questionID, text) + if (jobPanel != null) loadJobs(api, agentID, gen) + null + } + } + + fun decideBotRequest(id: String, approve: Boolean) = decide(id) { api, agentID -> + if (approve) { + val created = api.approveBotRequest(agentID, id) + return@decide { addCreatedBot(created) } + } + api.declineBotRequest(agentID, id) + null + } + + private fun addCreatedBot(created: Agent) { + if (agents.none { it.id == created.id }) agents = agents + created + } + + /** Opens the bot editor on a pending request's proposal; its save button approves the edits. */ + fun openBotRequestEditor(id: String) { + val request = botRequests.firstOrNull { it.id == id && it.status == "pending" } ?: return + val proposal = request.proposal + val tools = proposal.tools.orEmpty() + val draft = AgentDraft( + isNew = true, + agentID = "", + name = proposal.name, + description = proposal.description.orEmpty(), + enabled = proposal.enabled ?: true, + provider = proposal.provider.orEmpty(), + model = proposal.model.orEmpty(), + instructions = proposal.instructions.orEmpty(), + avatar = proposal.avatar.domain(), + thinking = proposal.inference?.thinkingLevel ?: "off", + temperature = proposal.inference?.temperature?.toString().orEmpty(), + maxOutput = proposal.inference?.maxOutputTokens?.toString().orEmpty(), + toolsMemory = "memory" in tools, + toolsDelegate = "delegate" in tools, + mcpServers = proposal.mcpServers.orEmpty().toSet(), + skills = proposal.skills.orEmpty().map { Skill(name = it.name, instructions = it.instructions) }, + sharedSkills = proposal.sharedSkills.orEmpty().toSet(), + botRequestID = id, + otherTools = tools.toSet() - DRAFT_TOOLS, + webSearchProvider = proposal.webSearchProvider, + desktopProvider = proposal.desktopModel?.provider.orEmpty(), + desktopModel = proposal.desktopModel?.model.orEmpty(), + initialTools = tools.toSet(), + ) + errorText = "" + decisionErrors = decisionErrors - id + agentDraft = draft + loadEditorData(draft.provider) + } + + private fun approveEditedBotRequest(id: String, draft: AgentDraft, input: Agent) { + val request = botRequests.firstOrNull { it.id == id } ?: return + decide(id) { api, agentID -> + val created = api.approveBotRequest(agentID, id, request.proposal.edited(input)) + return@decide { + addCreatedBot(created) + if (agentDraft?.id == draft.id) agentDraft = null + } + } + } + + // MARK: Jobs + + private suspend fun loadJobs(api: APIClient, agentID: String, gen: Int = generation) { + fun current() = generation == gen && selectedAgentID == agentID + try { + val loaded = coroutineScope { + val coding = async { api.jobs(agentID, JobKind.coding) } + val desktop = async { api.jobs(agentID, JobKind.desktop) } + coding.await() + desktop.await() + } + if (!current()) return + jobs = loaded + jobsLoaded = true + jobsFailed = false + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + if (current()) jobsFailed = true + } + } + + // A job card's status only changes when a job message arrives; the panel follows progress itself. + private fun refreshChatJobs() { + val api = client ?: return + val count = messages.count { jobOf(it) != null || isJobOrigin(it.origin?.kind) } + val key = "$selectedAgentID\n$count" + if (messages.none { jobOf(it) != null } || key == chatJobsKey) return + val agentID = selectedAgentID + chatJobsKey = key + chatJobsLoad?.cancel() + chatJobsLoad = scope.launch { loadJobs(api, agentID) } + } + + private suspend fun loadJobHistory(api: APIClient, agentID: String, job: JobRef, version: Int) { + try { + val page = api.jobHistory(agentID, job, before = null, limit = JOB_PAGE_SIZE) + val panel = jobPanel?.takeIf { jobPanelVersion == version } ?: return + jobPanel = panel.copy( + messages = mergeJobPages(panel.messages, page.messages.orEmpty()), + hasMore = if (panel.loaded) panel.hasMore else page.hasMore == true, + oldestEntryID = if (panel.loaded) panel.oldestEntryID else page.oldestEntryId, + loaded = true, + failed = false, + ) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + jobPanel = jobPanel?.takeIf { jobPanelVersion == version }?.copy(failed = true) ?: jobPanel + } + } + + private fun followJobs() { + val api = client ?: return + val agentID = selectedAgentID + jobsFollow?.cancel() + jobsFollow = scope.launch { + var seenStatus: String? = null + while (isActive) { + loadJobs(api, agentID) + val panel = jobPanel + val status = panel?.let { open -> jobs.firstOrNull { it.ref == open.job }?.status } + if (panel != null && (!panel.loaded || panel.failed || jobWorking(status) || status != seenStatus)) { + loadJobHistory(api, agentID, panel.job, jobPanelVersion) } - delay(backoffMs) - backoffMs = minOf(backoffMs * 2, 8_000L) + seenStatus = status + val watched = if (panel != null) jobWorking(status) else jobs.any { jobWorking(it.status) } + delay(if (watched) JOB_REFRESH_MS else IDLE_JOB_REFRESH_MS) } } } - fun handleActivity(event: ActivityEvent) { - if (event.type == "chat-preview" && event.lastMessage != null && pendingPreviews[event.agentId] == null) { - val idx = agents.indexOfFirst { it.id == event.agentId } - if (idx >= 0) { - val updated = agents.toMutableList() - updated[idx] = updated[idx].copy(lastMessage = event.lastMessage) - agents = updated + fun openBotDetails() { + showingBotDetails = true + schedulesError = "" + loadSchedules() + loadEventSources() + } + + fun openJobList() { + showingJobs = true + followJobs() + } + + fun closeJobList() { + showingJobs = false + if (jobPanel == null) jobsFollow?.cancel() + } + + fun openJob(job: JobRef) { + jobPanelVersion += 1 + jobPanel = JobPanel(job.copy(status = null)) + followJobs() + } + + fun closeJob() { + jobPanelVersion += 1 + jobPanel = null + if (!showingJobs) jobsFollow?.cancel() + } + + fun retryJobHistory() = followJobs() + + private fun closeJobs() { + jobsFollow?.cancel() + chatJobsLoad?.cancel() + chatJobsKey = "" + jobPanelVersion += 1 + jobPanel = null + showingJobs = false + } + + fun loadEarlierJobActivity() { + val panel = jobPanel ?: return + val api = client ?: return + val before = panel.oldestEntryID ?: return + if (panel.loadingEarlier) return + val agentID = selectedAgentID + val version = jobPanelVersion + jobPanel = panel.copy(loadingEarlier = true) + scope.launch { + try { + val page = api.jobHistory(agentID, panel.job, before, JOB_PAGE_SIZE) + val current = jobPanel?.takeIf { jobPanelVersion == version } ?: return@launch + val known = current.messages.map { it.id }.toSet() + jobPanel = current.copy( + messages = page.messages.orEmpty().filterNot { it.id in known } + current.messages, + hasMore = page.hasMore == true, + oldestEntryID = page.oldestEntryId, + loadingEarlier = false, + failed = false, + ) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + jobPanel = jobPanel?.takeIf { jobPanelVersion == version }?.copy(loadingEarlier = false, failed = true) ?: jobPanel } } - val context = NotificationContext(appActive = appActive, route = route) - notifier.handle(event, context) } - fun loadOlder() { - if (awaitingInitialSnapshot || loadingOlder || !hasMore || oldestEntryID.isEmpty()) return - val id = selectedAgentID - val before = oldestEntryID - val version = selectionVersion - loadingOlder = true - request { api -> + /** Reads every page of the open job's transcript, then hands its Markdown to `write`. */ + fun downloadJobTranscript(write: suspend (String) -> Unit) { + val panel = jobPanel ?: return + val api = client ?: return + if (panel.downloading) return + val agentID = selectedAgentID + val version = jobPanelVersion + jobPanel = panel.copy(downloading = true, downloadFailed = false) + scope.launch { + val failed = try { + val pages = mutableListOf>() + var before: String? = null + do { + val page = api.jobHistory(agentID, panel.job, before, JOB_TRANSCRIPT_PAGE_SIZE) + pages.add(page.messages.orEmpty()) + before = page.oldestEntryId.takeIf { page.hasMore == true } + } while (before != null) + write(jobMarkdown(panel.job, pages.asReversed().flatten())) + false + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + true + } + jobPanel = jobPanel?.takeIf { jobPanelVersion == version }?.copy(downloading = false, downloadFailed = failed) ?: jobPanel + } + } + + fun openBotDesktop(agentID: String = selectedAgentID) { + val api = client ?: return + if (agentID.isEmpty() || botDesktop?.agentID == agentID) return + closeBotDesktop() + desktopVersion += 1 + val version = desktopVersion + desktopAPI = api + botDesktop = BotDesktop(agentID) + desktopFollow = scope.launch { followDesktopControl(api, agentID, version) } + reconnectDesktopViewer() + syncDesktopPreview() + } + + fun reconnectDesktopViewer() { + val desktop = botDesktop ?: return + val api = desktopAPI ?: return + if (desktop.viewer.connecting) return + val version = desktopVersion + fun finish(link: DesktopLink) { + if (version == desktopVersion) botDesktop = botDesktop?.copy(viewer = link) + } + finish(DesktopLink(connecting = true)) + scope.launch { try { - val page = api.chatHistory(id, before = before, limit = 100) - return@request { - if (selectionVersion == version) { - loadingOlder = false - messages = mergeMessages(messages, page.messages ?: emptyList()) - hasMore = page.hasMore ?: false - oldestEntryID = page.oldestEntryId ?: "" - } - } + finish(DesktopLink(api.desktopViewerURL(api.createDesktopViewer(desktop.agentID)))) + } catch (e: CancellationException) { + throw e } catch (e: Throwable) { - if (selectionVersion == version) loadingOlder = false + finish(DesktopLink(error = friendlyError(e))) + } + } + } + + /** Taking control pauses the bot's desktop job, so it reads as done only once the server confirms. */ + fun setDesktopHolder(holder: String) { + val desktop = botDesktop ?: return + val api = desktopAPI ?: return + if (desktop.control == null || desktop.taking != null) return + val version = desktopVersion + botDesktop = desktop.copy(taking = holder, takeError = "") + desktopTake = scope.launch { + try { + val control = api.setDesktopHolder(desktop.agentID, holder) + if (version == desktopVersion) { + botDesktop = botDesktop?.let { it.copy(control = newerControl(it.control, control), taking = null) } + } + } catch (e: CancellationException) { throw e + } catch (e: Throwable) { + if (version == desktopVersion) botDesktop = botDesktop?.copy(taking = null, takeError = friendlyError(e)) } } } - fun sendMessage() { - val currentClient = client ?: return - if (snapshot == null) return - val content = draft.trim() - val files = attachments - if (content.isEmpty() && files.isEmpty()) return - val id = selectedAgentID + /** The viewer's connection ended or its page failed; the link is spent. */ + fun desktopViewerLost(url: String) { + botDesktop?.takeIf { it.viewer.url == url }?.let { botDesktop = it.copy(viewer = DesktopLink(error = DESKTOP_UNAVAILABLE)) } + desktopPreview?.takeIf { it.viewer.url == url }?.let { desktopPreview = it.copy(viewer = DesktopLink(error = DESKTOP_UNAVAILABLE)) } + } + + /** Leaving hands control back so the bot's job can continue. `leaving` must outlive the screen. */ + fun closeBotDesktop(leaving: CoroutineScope = scope) { + val desktop = botDesktop ?: return + val api = desktopAPI + desktopVersion += 1 + botDesktop = null + desktopAPI = null + desktopFollow?.cancel() + desktopFollow = null + val take = desktopTake + desktopTake = null + if (api != null && (desktop.owner || desktop.taking == DESKTOP_OWNER)) { + leaving.launch { + // A take still in flight must land first, or it would leave the owner holding a closed desktop. + take?.join() + handBackDesktop(api, desktop.agentID) + } + } + syncDesktopPreview() + } + + private suspend fun handBackDesktop(api: APIClient, agentID: String) { + repeat(DESKTOP_HAND_BACK_ATTEMPTS) { attempt -> + try { + api.setDesktopHolder(agentID, DESKTOP_BOT) + return + } catch (e: CancellationException) { + throw e + } catch (_: Throwable) { + if (attempt < DESKTOP_HAND_BACK_ATTEMPTS - 1) delay(1_000L shl attempt) + } + } + errorText = DESKTOP_HAND_BACK_FAILED + } + + private suspend fun followDesktopControl(api: APIClient, agentID: String, version: Int) { + var backoffMs = 500L + while (scope.isActive) { + try { + api.desktopEvents(agentID) { control -> + if (version != desktopVersion) return@desktopEvents + backoffMs = 500L + botDesktop = botDesktop?.let { it.copy(control = newerControl(it.control, control)) } + } + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + if (e is APIError && e.statusCode == 401) { + if (version == desktopVersion) botDesktop = botDesktop?.copy(takeError = friendlyError(e)) + return + } + } + delay(backoffMs) + backoffMs = minOf(backoffMs * 2, 8_000L) + } + } + + /** Machine state has no live event, so the preview polls it while it is on screen. */ + fun watchDesktopPreview(agentID: String) { + val api = client ?: return + if (desktopPreview?.agentID == agentID) return + stopDesktopPreview() + val version = desktopPreviewVersion + desktopPreview = DesktopPreview(agentID) + desktopPreviewPoll = scope.launch { + while (isActive) { + val running = try { + api.desktopRunning(agentID) + } catch (e: CancellationException) { + throw e + } catch (_: Throwable) { + desktopPreview?.running ?: false + } + if (version != desktopPreviewVersion) return@launch + desktopPreview = desktopPreview?.copy(running = running) + syncDesktopPreview() + delay(DESKTOP_STATUS_MS) + } + } + } + + fun stopDesktopPreview() { + desktopPreviewVersion += 1 + desktopPreviewLink += 1 + desktopPreviewPoll?.cancel() + desktopPreviewPoll = null + desktopPreview = null + } + + fun wakeDesktop() { + desktopPreview = desktopPreview?.copy(asked = true) + syncDesktopPreview() + } + + /** Until asked, the link only watches: it neither boots the machine nor keeps it awake. */ + private fun syncDesktopPreview() { + val preview = desktopPreview ?: return + val api = client ?: return + if (!preview.awake || botDesktop != null) { + if (!preview.viewer.idle) { + desktopPreviewLink += 1 + desktopPreview = preview.copy(viewer = DesktopLink()) + } + return + } + if (!preview.viewer.idle) return + val version = desktopPreviewLink + fun finish(link: DesktopLink) { + if (version == desktopPreviewLink) desktopPreview = desktopPreview?.copy(viewer = link) + } + finish(DesktopLink(connecting = true)) + scope.launch { + try { + finish(DesktopLink(api.desktopViewerURL(api.createDesktopViewer(preview.agentID, passive = !preview.asked)))) + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + finish(DesktopLink(error = friendlyError(e))) + } + } + } + + private suspend fun streamChat(api: APIClient, id: String, version: Int) { + var backoffMs = 500L + while (scope.isActive) { + try { + api.chatEvents(id, limit = 5) { snap -> + if (selectionVersion != version || client !== api) return@chatEvents + applySnapshot(snap) + streamStatus = "" + errorText = "" + } + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + if (selectionVersion != version) return + if (e is APIError && e.statusCode == 401) { + errorText = friendlyError(e) + streamStatus = "Disconnected" + return + } + streamStatus = "Reconnecting…" + } + delay(backoffMs) + backoffMs = minOf(backoffMs * 2, 8_000L) + } + } + + /** Follows server-wide activity for notifications, reconnecting as the chat stream does. */ + fun followActivity() { + activityJob?.cancel() + val api = client ?: return + val gen = generation + activityJob = scope.launch { + var backoffMs = 500L + while (isActive && generation == gen) { + try { + api.activityEvents { event -> + if (generation != gen) return@activityEvents + handleActivity(event) + } + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + if (e is APIError && e.statusCode == 401) return@launch + } + delay(backoffMs) + backoffMs = minOf(backoffMs * 2, 8_000L) + // Groups may have changed while the stream was down. + if (generation == gen) loadGroupChats() + } + } + } + + fun handleActivity(event: ActivityEvent) { + if (event.type == "chat-preview" && event.lastMessage != null && pendingPreviews[event.agentId] == null) { + val idx = agents.indexOfFirst { it.id == event.agentId } + if (idx >= 0) { + val updated = agents.toMutableList() + updated[idx] = updated[idx].copy(lastMessage = event.lastMessage) + agents = updated + } + } + val context = NotificationContext(appActive = appActive, route = route) + notifier.handle(event, context) + } + + fun loadOlder() { + if (awaitingInitialSnapshot || loadingOlder || !hasMore || oldestEntryID.isEmpty()) return + val id = selectedAgentID + val before = oldestEntryID + val version = selectionVersion + loadingOlder = true + request { api -> + try { + val page = api.chatHistory(id, before = before, limit = 100) + return@request { + if (selectionVersion == version) { + loadingOlder = false + messages = mergeMessages(messages, page.messages ?: emptyList()) + hasMore = page.hasMore ?: false + oldestEntryID = page.oldestEntryId ?: "" + } + } + } catch (e: Throwable) { + if (selectionVersion == version) loadingOlder = false + throw e + } + } + } + + fun sendMessage() { + if (client == null || snapshot == null) return + val content = draft.trim() + val files = attachments + if (content.isEmpty() && files.isEmpty()) return + val id = selectedAgentID val reply = replyTo?.entryId ?: "" - draftRequestID = newRequestID() - val requestID = draftRequestID - failedDraft = content - failedReplyTo = reply - failedAttachments = files.map { it.id } - sending = true - draft = "" - attachments = emptyList() + val failed = pendingMessages[id].orEmpty().firstOrNull { message -> + val record = pendingSends[id]?.get(message.requestId) + message.deliveryState == MessageDeliveryState.failed && record != null && composerHolds(record) && + (reply.isEmpty() || reply == record.replyTo) + } + if (failed != null) { + redeliver(failed, restoreDraft = true) + return + } + val requestID = newRequestID() val optimistic = Message( id = "local:$requestID", role = "user", @@ -625,12 +1627,10 @@ class AppModel( requestId = requestID, deliveryState = MessageDeliveryState.sending, ) + clearComposer() pendingMessages.getOrPut(id) { mutableListOf() }.add(optimistic) - pendingSends.getOrPut(id) { mutableMapOf() }[requestID] = PendingSend( - content = content, - replyTo = reply, - attachments = files, - ) + val record = PendingSend(content = content, replyTo = reply, attachments = files) + pendingSends.getOrPut(id) { mutableMapOf() }[requestID] = record val previewText = content.nilIfEmpty ?: files.firstOrNull()?.let { "Attachment: ${it.name}" } ?: "" pendingPreviews[id] = PendingPreview(requestID = requestID, text = previewText) val agentIndex = agents.indexOfFirst { it.id == id } @@ -639,91 +1639,50 @@ class AppModel( updated[agentIndex] = updated[agentIndex].copy(lastMessage = previewText) agents = updated } - if (selectedAgentID == id) { - messages = messages + optimistic - } - replyTo = null - val gen = generation - val version = selectionVersion - scope.launch { - try { - currentClient.sendChatMessage( - agentID = id, - content = content, - requestID = requestID, - replyTo = reply, - attachments = files.map { it.outgoing }, - ) - if (generation != gen) return@launch - if (pendingPreviews[id]?.requestID == requestID) { - pendingPreviews.remove(id) - } - if (selectionVersion == version && selectedAgentID == id) { - sending = false - draftRequestID = "" - failedDraft = "" - failedReplyTo = "" - failedAttachments = emptyList() - } - } catch (e: CancellationException) { - throw e - } catch (e: Throwable) { - if (generation != gen) return@launch - if (selectionVersion == version && selectedAgentID == id) { - sending = false - } - val list = pendingMessages[id] - if (list == null || list.none { it.requestId == requestID }) return@launch - if (selectionVersion == version && selectedAgentID == id) { - errorText = "Message was not confirmed: ${friendlyError(e)}" - } - val idx = list.indexOfFirst { it.requestId == requestID } - if (idx >= 0) { - list[idx] = list[idx].copy(deliveryState = MessageDeliveryState.failed) - if (pendingPreviews[id]?.requestID == requestID) { - pendingPreviews.remove(id) - } - if (selectionVersion == version && selectedAgentID == id) { - messages = messages.map { msg -> - if (msg.requestId == requestID) msg.copy(deliveryState = MessageDeliveryState.failed) else msg - } - } - } - if (selectionVersion == version && selectedAgentID == id) { - if (draft.isEmpty() && attachments.isEmpty()) { - draft = content - attachments = files - } - } - } - } + messages = messages + optimistic + deliverMessage(id, requestID, record, restoreDraft = true) } /** Re-sends a failed optimistic row with its original idempotency key and attachments. */ - fun retryMessage(message: Message) { - val currentClient = client ?: return + fun retryMessage(message: Message) = redeliver(message, restoreDraft = false) + + private fun redeliver(message: Message, restoreDraft: Boolean) { val requestID = message.requestId ?: return - if (message.deliveryState != MessageDeliveryState.failed) return - val record = pendingSends[selectedAgentID]?.get(requestID) ?: return - val list = pendingMessages[selectedAgentID] ?: return - val idx = list.indexOfFirst { it.requestId == requestID } - if (idx < 0) return + if (client == null || message.deliveryState != MessageDeliveryState.failed) return + val id = selectedAgentID + val record = pendingSends[id]?.get(requestID) ?: return + if (!markMessage(id, requestID, MessageDeliveryState.sending)) return + if (composerHolds(record)) clearComposer() + deliverMessage(id, requestID, record, restoreDraft) + } - list[idx] = list[idx].copy(deliveryState = MessageDeliveryState.sending) - messages = messages.map { msg -> - if (msg.requestId == requestID) msg.copy(deliveryState = MessageDeliveryState.sending) else msg - } - if (draft == record.content && attachments.map { it.id } == record.attachments.map { it.id }) { - draft = "" - attachments = emptyList() + private fun composerHolds(record: PendingSend) = + draft.trim() == record.content && attachments.map { it.id } == record.attachments.map { it.id } + + private fun clearComposer() { + draft = "" + attachments = emptyList() + replyTo = null + } + + /** Sets a row's state wherever it is shown; false once a snapshot has already confirmed it. */ + private fun markMessage(id: String, requestID: String, state: MessageDeliveryState): Boolean { + val list = pendingMessages[id] ?: return false + val index = list.indexOfFirst { it.requestId == requestID } + if (index < 0) return false + list[index] = list[index].copy(deliveryState = state) + if (selectedAgentID == id) { + messages = messages.map { if (it.requestId == requestID) it.copy(deliveryState = state) else it } } - sending = true - val id = selectedAgentID + return true + } + + private fun deliverMessage(id: String, requestID: String, record: PendingSend, restoreDraft: Boolean) { + val api = client ?: return val gen = generation - val version = selectionVersion scope.launch { try { - currentClient.sendChatMessage( + api.sendChatMessage( agentID = id, content = record.content, requestID = requestID, @@ -731,37 +1690,30 @@ class AppModel( attachments = record.attachments.map { it.outgoing }, ) if (generation != gen) return@launch - if (pendingPreviews[id]?.requestID == requestID) { - pendingPreviews.remove(id) - } - if (selectionVersion == version && selectedAgentID == id) { - sending = false - } } catch (e: CancellationException) { throw e } catch (e: Throwable) { - if (generation != gen) return@launch - if (selectionVersion == version && selectedAgentID == id) { - sending = false - } - val currentList = pendingMessages[id] - if (currentList == null || currentList.none { it.requestId == requestID }) return@launch - if (selectionVersion == version && selectedAgentID == id) { - errorText = "Message was not confirmed: ${friendlyError(e)}" - } - val failIdx = currentList.indexOfFirst { it.requestId == requestID } - if (failIdx >= 0) { - currentList[failIdx] = currentList[failIdx].copy(deliveryState = MessageDeliveryState.failed) - if (pendingPreviews[id]?.requestID == requestID) { - pendingPreviews.remove(id) - } - if (selectionVersion == version && selectedAgentID == id) { - messages = messages.map { msg -> - if (msg.requestId == requestID) msg.copy(deliveryState = MessageDeliveryState.failed) else msg - } - } - } + if (generation != gen || !markMessage(id, requestID, MessageDeliveryState.failed)) return@launch + if (selectedAgentID == id) errorText = "Message was not confirmed: ${friendlyError(e)}" + if (restoreDraft) restoreComposer(id, record) + } + if (pendingPreviews[id]?.requestID == requestID) pendingPreviews.remove(id) + } + } + + /** Text the owner wrote since sending is never overwritten; the failed row still holds the message. */ + private fun restoreComposer(id: String, record: PendingSend) { + if (selectedAgentID == id) { + if (draft.isEmpty() && attachments.isEmpty()) { + draft = record.content + attachments = record.attachments } + return + } + val parked = parkedComposers[id] ?: ChatComposer() + if (parked.draft.isEmpty() && parked.attachments.isEmpty()) { + parkedComposers[id] = parked.copy(draft = record.content, attachments = record.attachments) + saveDraft(botDraft(id), record.content) } } @@ -794,9 +1746,10 @@ class AppModel( val currentClient = client ?: return if (entryID.startsWith("local:")) return val agent = selectedAgentID + val gen = generation try { val bytes = currentClient.attachment(agent, entryID = entryID, index = index) - if (bytes.isNotEmpty()) { + if (bytes.isNotEmpty() && generation == gen) { attachmentBytes = attachmentBytes + (key to bytes) } } catch (_: Throwable) { @@ -808,10 +1761,8 @@ class AppModel( pendingSends.clear() pendingPreviews.clear() messages = emptyList() - draftRequestID = "" - failedDraft = "" - failedReplyTo = "" - failedAttachments = emptyList() + parkedComposers.clear() + clearComposer() } fun abortChat() { @@ -820,6 +1771,7 @@ class AppModel( key = "abort:$id", update = { showNotice("Stopping…") }, rollback = {}, + onBusy = {}, work = { api -> api.abortChat(id) null @@ -827,29 +1779,401 @@ class AppModel( ) } - fun compactChat() { - val id = selectedAgentID - optimisticMutation( - key = "compact:$id", - update = { showNotice("Summarizing older context…") }, - rollback = {}, - work = { api -> - api.compactChat(id) - null - }, - ) + // MARK: Group chats + + /** Reads the sidebar's list. A failure keeps the rows already shown. */ + fun loadGroupChats() { + val api = client ?: return + val gen = generation + val revision = mutationRevision + scope.launch { + try { + val loaded = api.groupChats() + if (generation != gen) return@launch + groupsFailed = false + if (settledSince(revision, GROUP_RECORD)) loadGroupChats() + else groupChats = withLocalChanges(loaded, groupChats, GROUP_RECORD, GroupChat::id) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + if (generation == gen) groupsFailed = true + } + } } - // MARK: Agent profile + /** Opens a group chat and follows its event stream. */ + fun openGroupChat(id: String) { + if (id.startsWith("pending:")) return + closeGroupChat() + clearSecretDrafts() + route = Route.GroupChat(id) + if (id !in groupComposers) { + savedDraft(groupDraftKey(id)).nilIfEmpty?.let { groupComposers = groupComposers + (id to ChatComposer(draft = it)) } + } + val api = client ?: return + val version = groupVersion + groupConversation = GroupConversation(id) + groupStream = scope.launch { + try { + val snapshot = api.groupSnapshot(id) + if (groupVersion == version) applyGroupSnapshot(snapshot) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + if (groupVersion != version) return@launch + if (e is APIError && e.statusCode == 404) return@launch groupGone(id) + updateConversation(id) { it.copy(loadError = friendlyError(e)) } + } + followGroupChat(api, id, version) + } + } - fun createAgent() { - val draft = AgentDraft(isNew = true, agentID = "").withShuffledAvatars() - agentDraft = draft - loadEditorData(draft.provider) + private fun closeGroupChat() { + groupStream?.cancel() + groupStream = null + groupVersion += 1 + groupConversation = null } - fun openEditor(agentID: String? = null) { - val targetId = agentID ?: selectedAgentID + private fun updateConversation(id: String, change: (GroupConversation) -> GroupConversation) { + groupConversation = groupConversation?.let { if (it.groupID == id) change(it) else it } + } + + private suspend fun followGroupChat(api: APIClient, id: String, version: Int) { + var backoffMs = 500L + while (scope.isActive) { + try { + api.groupChatEvents(id) { snapshot -> + if (groupVersion != version || client !== api) return@groupChatEvents + applyGroupSnapshot(snapshot) + backoffMs = 500L + } + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + if (groupVersion != version) return + if (e is APIError && e.statusCode == 404) return groupGone(id) + if (e is APIError && e.statusCode == 401) { + errorText = friendlyError(e) + updateConversation(id) { it.copy(streamStatus = "Disconnected") } + return + } + updateConversation(id) { it.copy(streamStatus = "Reconnecting…") } + } + delay(backoffMs) + backoffMs = minOf(backoffMs * 2, 8_000L) + } + } + + private fun applyGroupSnapshot(incoming: GroupSnapshot) { + val id = incoming.groupChat.id + val acknowledged = incoming.messages.mapNotNull { it.requestId }.toSet() + val waiting = groupOutgoing[id].orEmpty() + if (waiting.any { it.requestId in acknowledged }) { + groupOutgoing = groupOutgoing + (id to waiting.filterNot { it.requestId in acknowledged }) + acknowledged.forEach { groupSends.remove(it) } + } + val editing = "group:$id" in pendingMutations + updateConversation(id) { current -> + val merged = current.merging(incoming) + if (editing) merged.copy(group = current.group) else merged + } + if (!editing) writeGroup(incoming.groupChat, adding = true) + } + + private fun writeGroup(group: GroupChat, adding: Boolean = false) { + if (groupChats.any { it.id == group.id }) { + if (group !in groupChats) groupChats = groupChats.map { if (it.id == group.id) group else it } + } else if (adding) { + groupChats = groupChats + group + } + updateConversation(group.id) { it.copy(group = group) } + } + + /** Another client deleted the group: its stream answers 404, and the chat is no longer anywhere. */ + private fun groupGone(id: String) { + dropGroup(id) + if (route == Route.GroupChat(id)) leaveGroupChat() + } + + private fun dropGroup(id: String) { + groupChats = groupChats.filterNot { it.id == id } + groupComposers = groupComposers - id + saveDraft(groupDraftKey(id), "") + groupOutgoing[id].orEmpty().forEach { message -> groupSends.remove(message.requestId) } + groupOutgoing = groupOutgoing - id + if (groupDraft?.groupID == id) groupDraft = null + } + + private fun leaveGroupChat() { + closeGroupChat() + val next = agents.firstOrNull { it.id == selectedAgentID } ?: agents.firstOrNull() + if (next != null) selectAgent(next.id) else route = null + } + + private fun resetGroupChats() { + closeGroupChat() + if (route is Route.GroupChat) route = null + groupChats = emptyList() + groupsFailed = false + groupComposers = emptyMap() + groupOutgoing = emptyMap() + groupSends.clear() + groupDraft = null + } + + fun groupComposer(id: String): ChatComposer = groupComposers[id] ?: ChatComposer() + + fun updateGroupComposer(id: String, change: (ChatComposer) -> ChatComposer) { + val current = groupComposer(id) + val next = change(current) + groupComposers = groupComposers + (id to next) + if (next.draft != current.draft) saveDraft(groupDraftKey(id), next.draft) + } + + fun addGroupAttachment(id: String, attachment: PendingAttachment) { + if (groupComposer(id).attachments.size >= AttachmentLimits.COUNT) { + errorText = "A message can carry up to ${AttachmentLimits.COUNT} files." + return + } + updateGroupComposer(id) { it.copy(attachments = it.attachments + attachment) } + } + + /** Shows the message at once; it stays until a snapshot confirms it by request ID. */ + fun sendGroupMessage() { + val conversation = groupConversation?.takeIf { it.group != null } ?: return + val id = conversation.groupID + val composer = groupComposer(id) + val content = composer.draft.trim() + if (content.isEmpty() && composer.attachments.isEmpty()) return + val requestID = newRequestID() + val reply = composer.replyTo + groupSends[requestID] = PendingSend(content, reply?.entryId.orEmpty(), composer.attachments) + val optimistic = Message( + id = "local:$requestID", + role = "user", + content = JsonPrimitive(content), + replyTo = reply?.entryId, + replyPreview = reply?.text?.nilIfEmpty, + timestamp = System.currentTimeMillis(), + attachments = composer.attachments.map { + AttachmentInfo(it.name, it.mimeType, it.data.size, if (it.isImage) "image" else "file") + }, + requestId = requestID, + deliveryState = MessageDeliveryState.sending, + ) + groupOutgoing = groupOutgoing + (id to groupOutgoing[id].orEmpty() + optimistic) + updateGroupComposer(id) { ChatComposer() } + deliverGroupMessage(id, requestID) + } + + /** Re-sends a failed row with its original request ID, so the server can tell it is the same message. */ + fun retryGroupMessage(message: Message) { + val requestID = message.requestId ?: return + val id = groupConversation?.groupID ?: return + if (message.deliveryState == MessageDeliveryState.failed) deliverGroupMessage(id, requestID) + } + + private fun markGroupMessage(id: String, requestID: String, state: MessageDeliveryState) { + groupOutgoing = groupOutgoing + (id to groupOutgoing[id].orEmpty().map { + if (it.requestId == requestID) it.copy(deliveryState = state) else it + }) + } + + private fun deliverGroupMessage(id: String, requestID: String) { + val api = client ?: return + val record = groupSends[requestID] ?: return + val gen = generation + markGroupMessage(id, requestID, MessageDeliveryState.sending) + updateConversation(id) { it.copy(sendError = null) } + scope.launch { + try { + api.sendGroupMessage(id, record.content, requestID, record.replyTo, record.attachments.map { it.outgoing }) + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + // A snapshot may already show the message, or the group may be gone. + if (generation != gen || groupOutgoing[id].orEmpty().none { it.requestId == requestID }) return@launch + markGroupMessage(id, requestID, MessageDeliveryState.failed) + updateConversation(id) { it.copy(sendError = "Message was not confirmed: ${friendlyError(e)}") } + } + } + } + + /** The server reports the stopped turn in the transcript, so success needs no local change. */ + fun stopGroupChat() { + val id = groupConversation?.groupID ?: return + optimisticMutation( + key = "group-stop:$id", + update = { showNotice("Stopping…") }, + rollback = {}, + onBusy = {}, + work = { api -> + api.stopGroupChat(id) + null + }, + ) + } + + fun loadEarlierGroupMessages() { + val conversation = groupConversation ?: return + val api = client ?: return + val before = conversation.oldestEntryID + if (before == null || conversation.loadingOlder || !conversation.hasMore) return + val id = conversation.groupID + val version = groupVersion + updateConversation(id) { it.copy(loadingOlder = true) } + scope.launch { + try { + val page = api.groupHistory(id, before, GROUP_PAGE_SIZE) + if (groupVersion == version) updateConversation(id) { it.adding(page) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + if (groupVersion != version) return@launch + updateConversation(id) { it.copy(loadingOlder = false) } + errorText = friendlyError(e) + } + } + } + + fun groupAttachmentImageBytes(message: Message, index: Int): ByteArray? { + val entryID = message.entryId + if (!entryID.isNullOrEmpty()) return attachmentBytes["$entryID/$index"] + val file = groupSends[message.requestId]?.attachments?.getOrNull(index) + return file?.takeIf { it.isImage }?.data + } + + // Group entry IDs embed the group's ID, so they cannot collide with a bot's in `attachmentBytes`. + suspend fun loadGroupAttachmentImage(entryID: String, index: Int) { + val key = "$entryID/$index" + val api = client ?: return + val id = groupConversation?.groupID ?: return + if (attachmentBytes.containsKey(key)) return + val gen = generation + try { + val bytes = api.groupAttachment(id, entryID, index) + if (bytes.isNotEmpty() && generation == gen) attachmentBytes = attachmentBytes + (key to bytes) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + } + } + + fun openNewGroup(memberIDs: List) { + errorText = "" + groupDraft = GroupDraft(memberIDs = memberIDs) + } + + /** Opens the form at once, then moves it to the server's version unless the owner already edited it. */ + fun openGroupEditor(id: String) { + val group = groupChats.firstOrNull { it.id == id } ?: groupConversation?.group?.takeIf { it.id == id } ?: return + val draft = GroupDraft(groupID = id, name = group.name, memberIDs = group.memberIds) + errorText = "" + groupDraft = draft + val api = client ?: return + val gen = generation + scope.launch { + try { + val latest = api.groupChat(id) + if (generation != gen || "group:$id" in pendingMutations) return@launch + writeGroup(latest) + if (groupDraft == draft) groupDraft = draft.copy(name = latest.name, memberIDs = latest.memberIds) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + } + } + } + + fun toggleGroupMember(botID: String, on: Boolean) { + val draft = groupDraft ?: return + val full = draft.memberIDs.size >= MAX_GROUP_MEMBERS + if (on && (full || botID in draft.memberIDs)) return + groupDraft = draft.copy(memberIDs = if (on) draft.memberIDs + botID else draft.memberIDs - botID) + } + + fun saveGroup() { + val draft = groupDraft ?: return + val name = draft.name.trim() + if (!isValidGroup(name, draft.memberIDs)) return + val isNew = draft.groupID.isEmpty() + val id = if (isNew) "pending:${newRequestID()}" else draft.groupID + val previous = groupChats.firstOrNull { it.id == id } + val provisional = GroupChat(id, name, draft.memberIDs, previous?.createdAt.orEmpty(), previous?.updatedAt.orEmpty()) + val originalRoute = route + optimisticMutation( + key = "group:$id", + update = { + writeGroup(provisional, adding = true) + groupDraft = null + }, + rollback = { + if (previous != null) writeGroup(previous) else groupChats = groupChats.filterNot { it.id == id } + if (groupDraft == null && route == originalRoute) groupDraft = draft + }, + work = { api -> + val saved = if (isNew) api.createGroupChat(name, draft.memberIDs) else api.updateGroupChat(id, name, draft.memberIDs) + return@optimisticMutation { + if (isNew) { + groupChats = upserted(groupChats, id, saved) { it.id } + if (route == originalRoute && groupDraft == null) openGroupChat(saved.id) + } else { + writeGroup(saved) + } + } + }, + ) + } + + fun deleteGroup(id: String) { + val index = groupChats.indexOfFirst { it.id == id } + if (index < 0 || id.startsWith("pending:")) return + val removed = groupChats[index] + val draft = groupDraft + val wasOpen = route == Route.GroupChat(id) + var routeAfterDeletion = route + optimisticMutation( + key = "group:$id", + update = { + groupChats = groupChats.filterNot { it.id == id } + groupDraft = null + if (wasOpen) leaveGroupChat() + routeAfterDeletion = route + }, + rollback = { + val list = groupChats.toMutableList() + list.add(minOf(index, list.size), removed) + groupChats = list + if (route == routeAfterDeletion) { + if (wasOpen) openGroupChat(id) + if (groupDraft == null) groupDraft = draft + } + }, + work = { api -> + api.deleteGroupChat(id) + return@optimisticMutation { dropGroup(id) } + }, + ) + } + + // MARK: Agent profile + + fun createAgent() { + val draft = AgentDraft( + isNew = true, + agentID = "", + avatar = placeholderAvatar(newRequestID()), + provider = firstConfiguredProvider(), + toolsDelegate = true, + otherTools = setOf("web"), + ) + agentDraft = draft + loadEditorData(draft.provider) + } + + fun openEditor(agentID: String? = null) { + val targetId = agentID ?: selectedAgentID val agent = agents.firstOrNull { it.id == targetId } ?: return val tools = agent.tools ?: emptyList() val draft = AgentDraft( @@ -861,26 +2185,38 @@ class AppModel( model = agent.model ?: "", provider = agent.provider ?: "", enabled = agent.enabled, - avatar = "bot:${agentAvatarSeed(agent)}", + avatar = agent.avatar, thinking = agent.inference?.thinkingLevel ?: "off", temperature = agent.inference?.temperature?.toString() ?: "", maxOutput = agent.inference?.maxOutputTokens?.toString() ?: "", toolsMemory = tools.contains("memory"), toolsDelegate = tools.contains("delegate"), - toolsSchedule = tools.contains("schedule"), - toolsCodemode = tools.contains("codemode"), skills = agent.skills ?: emptyList(), sharedSkills = (agent.sharedSkills ?: emptyList()).toSet(), - sharedMemory = agent.sharedMemory ?: false, - delegates = (agent.delegates ?: emptyList()).toSet(), mcpServers = (agent.mcpServers ?: emptyList()).toSet(), - ).withShuffledAvatars() + otherTools = tools.toSet() - DRAFT_TOOLS, + webSearchProvider = agent.webSearchProvider, + desktopProvider = agent.desktopModel?.provider.orEmpty(), + desktopModel = agent.desktopModel?.model.orEmpty(), + initialTools = tools.toSet(), + ) agentDraft = draft loadEditorData(draft.provider) } + private fun firstConfiguredProvider() = providers.firstOrNull { it.configured }?.provider.orEmpty() + private fun loadEditorData(provider: String) { models = emptyList() + desktopModels = emptyList() + loadEditorLists() + loadProviders() + loadCapabilities() + loadModels(provider) + agentDraft?.desktopProvider?.nilIfEmpty?.let(::loadDesktopModels) + } + + private fun loadEditorLists() { val revision = mutationRevision request { api -> coroutineScope { @@ -889,25 +2225,35 @@ class AppModel( val loadedServers = serversDeferred.await() val loadedSkills = skillsDeferred.await() return@coroutineScope { - if (mutationRevision == revision && pendingMutations.isEmpty()) { - mcpServers = loadedServers - sharedSkills = loadedSkills + if (settledSince(revision, MCP_RECORD, SKILL_RECORD)) { + loadEditorLists() + } else { + mcpServers = withLocalChanges(loadedServers, mcpServers, MCP_RECORD, MCPServer::id) + sharedSkills = withLocalChanges(loadedSkills, sharedSkills, SKILL_RECORD, SharedSkill::id) } } } } - loadProviders() - loadModels(provider) } fun loadProviders() { request { api -> - val loaded = api.providers() - return@request { providers = loaded } + val mark = secretMark("provider", "") + val loaded = api.providerAccounts() + return@request { + providers = loaded.map { it.domain() } + if (secretSettled("provider", "", mark)) providerAccounts = loaded + val chosen = firstConfiguredProvider() + if (agentDraft?.provider?.isEmpty() == true && chosen.isNotEmpty()) { + agentDraft = agentDraft?.copy(provider = chosen) + loadModels(chosen) + } + } } } fun loadModels(providerName: String) { + if (providerName.isEmpty()) return request { api -> val loaded = api.models(provider = providerName) return@request { @@ -927,16 +2273,32 @@ class AppModel( loadModels(newProvider) } - val providerChoices: List - get() { - val ordered = providers.filter { it.configured }.map { it.provider } + - providers.filter { !it.configured }.map { it.provider } - val current = agentDraft?.provider ?: "" - return if (ordered.contains(current) || current.isEmpty()) ordered else listOf(current) + ordered - } + private fun loadDesktopModels(provider: String) { + confirmed( + start = {}, + work = { api -> api.models(provider = provider) }, + finish = { result -> + result.onSuccess { if (agentDraft?.desktopProvider == provider) desktopModels = it } + }, + ) + } + + fun changeEditorDesktopProvider(provider: String) { + agentDraft = agentDraft?.copy(desktopProvider = provider, desktopModel = "") + desktopModels = emptyList() + if (provider.isNotEmpty()) loadDesktopModels(provider) + } + + /** The levels the editor's model takes. The picked level stays in the draft, so changing back restores it. */ + val editorLevels: List + get() = levelsOf(models.firstOrNull { it.id == agentDraft?.model?.trim() }) + + val editorLevel: String + get() = clampLevel(agentDraft?.thinking?.ifEmpty { "off" } ?: "off", editorLevels) val modelHint: String get() { + if (providers.none { it.configured }) return "No provider is set up yet. Add one in Settings." val p = providers.firstOrNull { it.provider == agentDraft?.provider } if (p != null && !p.configured) { return "Add an API key for this provider in Settings to load its models." @@ -951,11 +2313,15 @@ class AppModel( errorText = "Give your agent a name." return } + val chosenModel = draft.model.trim() + if (draft.provider.isEmpty() || chosenModel.isEmpty()) { + errorText = "Choose a provider and model." + return + } val tools = mutableListOf() if (draft.toolsMemory) tools.add("memory") if (draft.toolsDelegate) tools.add("delegate") - if (draft.toolsSchedule) tools.add("schedule") - if (draft.toolsCodemode) tools.add("codemode") + tools.addAll(draft.otherTools) if (draft.skills.any { it.name.trim().isEmpty() || it.instructions.trim().isEmpty() }) { errorText = "Each skill needs a name and instructions." return @@ -979,11 +2345,10 @@ class AppModel( maxOutputVal = v } val inference = Inference( - thinkingLevel = draft.thinking.ifEmpty { "off" }, + thinkingLevel = editorLevel, temperature = temperatureVal, maxOutputTokens = maxOutputVal, ) - val delegates = draft.delegates.sorted() val servers = draft.mcpServers.sorted() val shared = draft.sharedSkills.filter { id -> sharedSkills.any { it.id == id && !it.isDefault } @@ -995,20 +2360,34 @@ class AppModel( instructions = draft.instructions.nilIfEmpty, avatar = draft.avatar, enabled = draft.enabled, - provider = draft.provider.nilIfEmpty, - model = draft.model.nilIfEmpty, + provider = draft.provider, + model = chosenModel, tools = tools, - delegates = delegates, skills = draft.skills, sharedSkills = shared, - sharedMemory = draft.sharedMemory, mcpServers = servers, inference = inference, + webSearchProvider = draft.webSearchProvider, + desktopModel = draft.chosenDesktopModel, ) + draft.botRequestID?.let { requestID -> + errorText = "" + approveEditedBotRequest(requestID, draft, input.copy(sharedSkills = draft.sharedSkills.sorted())) + return + } val isNew = draft.isNew val id = if (isNew) "pending:${newRequestID()}" else draft.agentID val old = agents.firstOrNull { it.id == id } - val provisional = input.copy(id = id, lastMessage = old?.lastMessage) + // The editor only shows skills, and the server treats a submitted list as a full replacement. + val provisional = input.copy( + id = id, + lastMessage = old?.lastMessage, + skills = old?.skills ?: input.skills, + sharedSkills = old?.sharedSkills ?: input.sharedSkills, + // The server derives these and ignores what clients send. + delegates = old?.delegates, + sharedMemory = old?.sharedMemory, + ) val originalRoute = route optimisticMutation( @@ -1025,7 +2404,7 @@ class AppModel( rollback = { val idx = agents.indexOfFirst { it.id == id } agents = if (old != null && idx >= 0) { - agents.toMutableList().also { it[idx] = old } + agents.toMutableList().also { it[idx] = it[idx].undoingEdit(provisional, old) } } else { agents.filterNot { it.id == id } } @@ -1042,16 +2421,15 @@ class AppModel( "description" to JsonPrimitive(draft.description), "instructions" to JsonPrimitive(draft.instructions), "provider" to JsonPrimitive(draft.provider), - "model" to JsonPrimitive(draft.model), - "avatar" to JsonPrimitive(draft.avatar), + "model" to JsonPrimitive(chosenModel), + "avatar" to CrumblePatchJson.encodeToJsonElement(draft.avatar ?: placeholderAvatar(id)), "enabled" to JsonPrimitive(draft.enabled), "tools" to JsonArray(tools.map { JsonPrimitive(it) }), - "skills" to CrumbleJson.encodeToJsonElement(ListSerializer(Skill.serializer()), draft.skills), - "sharedSkills" to JsonArray(shared.map { JsonPrimitive(it) }), - "sharedMemory" to JsonPrimitive(draft.sharedMemory), "mcpServers" to JsonArray(servers.map { JsonPrimitive(it) }), - "delegates" to JsonArray(delegates.map { JsonPrimitive(it) }), "inference" to CrumbleJson.encodeToJsonElement(Inference.serializer(), inference), + "webSearchProvider" to JsonPrimitive(input.webSearchProvider), + // Null clears it; an absent key would keep the old model. + "desktopModel" to CrumblePatchJson.encodeToJsonElement(input.desktopModel), ) api.updateAgent(id, patch = patch) } @@ -1059,9 +2437,7 @@ class AppModel( val idx = agents.indexOfFirst { it.id == id } if (idx >= 0) { val lastMsg = agents[idx].lastMessage - val updated = agents.toMutableList() - updated[idx] = saved.copy(lastMessage = saved.lastMessage ?: lastMsg) - agents = updated + agents = upserted(agents, id, saved.copy(lastMessage = saved.lastMessage ?: lastMsg)) { it.id } } if (isNew && route == originalRoute && agentDraft == null) { selectAgent(saved.id) @@ -1096,7 +2472,7 @@ class AppModel( return@optimisticMutation { val idx = agents.indexOfFirst { it.id == temporaryID } if (idx >= 0) { - agents = agents.toMutableList().also { it[idx] = created } + agents = upserted(agents, temporaryID, created) { it.id } } if (route == originalRoute && agentDraft == null) { selectAgent(created.id) @@ -1115,6 +2491,8 @@ class AppModel( val removed = agents[index] val memories = agentMemories[id] val wasSelected = selectedAgentID == id + val originalDraft = agentDraft + val originalRoute = route var routeAfterDeletion = route optimisticMutation( key = "agent:$id", @@ -1125,6 +2503,7 @@ class AppModel( if (wasSelected) { cancelStream() selectionVersion += 1 + switchComposer("") selectedAgentID = "" snapshot = null messages = emptyList() @@ -1145,130 +2524,316 @@ class AppModel( if (wasSelected && route == routeAfterDeletion) { selectAgent(id) } + if (agentDraft == null && route == originalRoute) { + agentDraft = originalDraft + } }, work = { api -> api.deleteAgent(id) - null + return@optimisticMutation { + forgetCachedChat(id) + parkedComposers.remove(id) + saveDraft(botDraft(id), "") + } }, ) } // MARK: Workspace panels - fun openPanel(panel: Route) { - route = panel + private fun openHome() { + leaveRoute() + route = null + } + + private fun leaveRoute() { + if (route == Route.General) closeSettings() + closeGroupChat() + clearSecretDrafts() memoryDraft = null taskDraft = null mcpDraft = null skillDraft = null + gatewayForm = null + } + + fun openPanel(panel: Route) { + leaveRoute() + if (panel == Route.Activity && route != panel) activityFeed = ActivityFeedState() + route = panel when (panel) { - Route.Memory -> { - memoryLoadVersion += 1 - val version = memoryLoadVersion - val mutationVersion = mutationRevision - request { api -> - coroutineScope { - val bots = api.agents() - val sharedDeferred = async { api.memories(null) } - val personalPairs = bots.map { bot -> - async { bot.id to api.memories(bot.id) } - }.awaitAll() - val personal = personalPairs.toMap() - val sharedItems = sharedDeferred.await() - return@coroutineScope { - if (memoryLoadVersion == version && mutationRevision == mutationVersion && pendingMutations.isEmpty()) { - agents = bots - sharedMemories = sharedItems - agentMemories = personal - } - } - } - } + Route.Memory -> loadMemories() + Route.Skills -> loadSkills() + Route.Tasks -> { + loadSchedules() + loadCapabilities() + loadEventSources() } - Route.Skills -> { - val mutationVersion = mutationRevision - request { api -> - coroutineScope { - val botsDeferred = async { api.agents() } - val skillsDeferred = async { api.sharedSkills() } - val loadedBots = botsDeferred.await() - val loadedSkills = skillsDeferred.await() - return@coroutineScope { - if (mutationRevision == mutationVersion && pendingMutations.isEmpty()) { - agents = loadedBots - sharedSkills = loadedSkills - } - } - } - } + Route.Activity -> loadActivity() + Route.Providers -> { + loadProviders() + loadPasswordManagers() } - Route.Tasks -> { - val mutationVersion = mutationRevision - request { api -> - val items = api.schedules() - return@request { - if (mutationRevision == mutationVersion && pendingMutations.isEmpty()) { - schedules = items - } - } - } + Route.PasswordManagers -> loadPasswordManagers() + Route.WebSearch -> { + loadWebSearch() + loadPluginSettings() + loadPasswordManagers() } - Route.Activity -> { - request { api -> - val feed = api.activityFeed() - return@request { activities = feed.activities } - } + Route.JudgeModel -> loadJudgeModel() + Route.VisionModel -> loadVisionModel() + Route.Coding -> loadCoding() + Route.Users -> loadUsers() + Route.MessageGateways -> loadGateways() + is Route.MessageGateway -> { + seedGatewayForm() + loadGateways() + loadAgentsForPanel() + loadPluginSettings() + loadPasswordManagers() + } + Route.EventRelay -> { + loadRelay() + loadEventSources() + loadPluginSettings() + loadPasswordManagers() + } + Route.Credentials -> { + loadSecretLists(credentialOps) + loadPasswordManagers() + } + Route.Logins -> { + loadSecretLists(loginOps) + loadPasswordManagers() } + Route.Avatars -> loadAgentsForPanel() + Route.Settings, Route.General, Route.Account, Route.NewChat, Route.NewGroup -> Unit Route.Integrations -> { - val mutationVersion = mutationRevision - request { api -> - coroutineScope { - val botsDeferred = async { api.agents() } - val serversDeferred = async { api.mcpServers() } - val loadedBots = botsDeferred.await() - val loadedServers = serversDeferred.await() - return@coroutineScope { - if (mutationRevision == mutationVersion && pendingMutations.isEmpty()) { - agents = loadedBots - mcpServers = loadedServers - } - } - } - } + loadPasswordManagers() + loadIntegrations() } - is Route.AgentChat -> Unit + is Route.AgentChat, is Route.GroupChat -> Unit } } - /** Carries the entry's owner into the form so edits never depend on the active chat. */ - fun openMemoryForm(id: String, agentID: String? = null) { - val items = if (agentID != null) agentMemories[agentID].orEmpty() else sharedMemories - val existing = items.firstOrNull { it.id == id } - memoryDraft = MemoryDraft(memoryID = id, content = existing?.content ?: "", agentID = agentID) + private suspend fun attempt(work: suspend () -> T): Result = try { + Result.success(work()) + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + Result.failure(e) } - fun saveMemory() { - val form = memoryDraft ?: return - val agent = form.agentID - val content = form.content.trim() - if (content.isEmpty()) { - errorText = "Memory content is required." - return + private fun loadSchedules() { + val revision = mutationRevision + request { api -> + val items = try { + api.schedules() + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + schedulesError = friendlyError(e) + throw e + } + return@request { + if (settledSince(revision, SCHEDULE_RECORD)) { + loadSchedules() + } else { + schedules = withLocalChanges(items, schedules, SCHEDULE_RECORD, Schedule::id) + schedulesLoaded = true + schedulesError = "" + if (taskTab == TaskTab.Runs) loadTaskRuns() + } + } } - val isNew = form.memoryID.isEmpty() - val provisionalID = if (isNew) "pending-memory-${newRequestID()}" else form.memoryID - val provisional = Memory(id = provisionalID, content = content, createdAt = null) - val currentList = if (agent == null) sharedMemories else agentMemories[agent].orEmpty() - val old = currentList.firstOrNull { it.id == form.memoryID } - memoryDraft = null + } - optimisticMutation( - key = "memory:$provisionalID", - update = { - if (agent == null) { - val idx = sharedMemories.indexOfFirst { it.id == provisionalID || it.id == form.memoryID } - sharedMemories = if (idx >= 0) { - sharedMemories.toMutableList().also { it[idx] = provisional } + private fun loadIntegrations() { + val revision = mutationRevision + request { api -> + coroutineScope { + val botsDeferred = async { api.agents() } + val serversDeferred = async { api.mcpServers() } + val loadedBots = botsDeferred.await() + val loadedServers = serversDeferred.await() + return@coroutineScope { + if (settledSince(revision, BOT_RECORD, MCP_RECORD)) { + loadIntegrations() + } else { + applyBots(loadedBots) + mcpServers = withLocalChanges(loadedServers, mcpServers, MCP_RECORD, MCPServer::id) + } + } + } + } + } + + fun filterActivity(kind: String? = activityFeed.kind, botID: String? = activityFeed.botID) { + if (kind == activityFeed.kind && botID == activityFeed.botID) return + activityFeed = ActivityFeedState(kind = kind, botID = botID) + loadActivity() + } + + private fun loadActivity(keepOlder: Boolean = false) { + val api = client + if (api == null) { + errorText = "Connect to your server in Settings." + return + } + activityLoadVersion += 1 + val version = activityLoadVersion + val gen = generation + val asked = activityFeed + activityFeed = asked.copy(loading = true, loadingOlder = false, error = "", olderError = "") + fun current() = version == activityLoadVersion && generation == gen + scope.launch { + try { + val page = api.activityFeed(asked.kind, asked.botID, limit = ACTIVITY_PAGE_SIZE) + if (current()) activityFeed = activityFeed.withFirstPage(page, keepOlder) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + if (current()) activityFeed = activityFeed.copy(loading = false, error = friendlyError(e)) + } + } + } + + /** Fetches the next page; a failure keeps what is loaded and lets the owner try again. */ + fun loadOlderActivity() { + val api = client ?: return + val feed = activityFeed + val cursor = feed.nextCursor ?: return + if (feed.loading || feed.loadingOlder) return + activityLoadVersion += 1 + val version = activityLoadVersion + val gen = generation + activityFeed = feed.copy(loadingOlder = true, olderError = "") + fun current() = version == activityLoadVersion && generation == gen + scope.launch { + try { + val page = api.activityFeed(feed.kind, feed.botID, cursor, ACTIVITY_PAGE_SIZE) + if (current()) activityFeed = activityFeed.withOlderPage(page) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + if (current()) activityFeed = activityFeed.copy(loadingOlder = false, olderError = friendlyError(e)) + } + } + } + + private fun loadMemories() { + memoryLoadVersion += 1 + val version = memoryLoadVersion + val mutationVersion = mutationRevision + request { api -> + coroutineScope { + val bots = api.agents() + val sharedDeferred = async { attempt { api.memories(null) } } + val personal = bots.map { bot -> async { bot.id to attempt { api.memories(bot.id) } } }.awaitAll() + val sharedItems = sharedDeferred.await() + return@coroutineScope { + if (memoryLoadVersion == version && settledSince(mutationVersion, BOT_RECORD, MEMORY_RECORD)) { + loadMemories() + } else if (memoryLoadVersion == version) { + applyBots(bots) + sharedItems.onSuccess { sharedMemories = withLocalChanges(it, sharedMemories, MEMORY_RECORD, Memory::id) } + agentMemories = personal.mapNotNull { (id, result) -> + val local = agentMemories[id] + val merged = result.getOrNull()?.let { withLocalChanges(it, local.orEmpty(), MEMORY_RECORD, Memory::id) } + (merged ?: local)?.let { id to it } + }.toMap() + memoryErrors = (personal + (SKILLS_SHARED to sharedItems)) + .mapNotNull { (id, result) -> result.exceptionOrNull()?.let { id to friendlyError(it) } } + .toMap() + } + } + } + } + } + + private fun loadSkills() { + val mutationVersion = mutationRevision + request { api -> + coroutineScope { + val skillsDeferred = async { api.sharedSkills() } + val loadedBots = api.agents() + val personal = loadedBots.map { bot -> async { bot.id to attempt { api.botSkills(bot.id) } } }.awaitAll() + val loadedSkills = skillsDeferred.await() + return@coroutineScope { + if (settledSince(mutationVersion, BOT_RECORD, SKILL_RECORD, BOT_SKILL_RECORD)) { + loadSkills() + } else { + applyBots(loadedBots) + sharedSkills = withLocalChanges(loadedSkills, sharedSkills, SKILL_RECORD, SharedSkill::id) + agentSkills = personal.mapNotNull { (id, result) -> + val local = agentSkills[id] + val merged = result.getOrNull()?.let { withLocalChanges(it, local.orEmpty(), BOT_SKILL_RECORD, SkillPackage::id) } + (merged ?: local)?.let { id to it } + }.toMap() + agentSkillErrors = personal + .mapNotNull { (id, result) -> result.exceptionOrNull()?.let { id to friendlyError(it) } } + .toMap() + } + } + } + } + } + + /** Refetches what the current page shows, keeping open forms. */ + private fun reloadPage() { + when (route) { + Route.Memory -> loadMemories() + Route.Skills -> loadSkills() + Route.Activity -> loadActivity(keepOlder = true) + else -> Unit + } + } + + /** For work another system decides: `finish` gets the answer, and nothing reads as done before it. */ + private fun confirmed(start: () -> Unit, work: suspend (APIClient) -> T, finish: (Result) -> Unit) { + val api = client + if (api == null) { + errorText = "Connect to your server in Settings." + return + } + val gen = generation + start() + scope.launch { + val result = attempt { work(api) } + if (generation == gen) finish(result) + } + } + + /** Carries the entry's owner into the form so edits never depend on the active chat. */ + fun openMemoryForm(id: String, agentID: String? = null) { + val items = if (agentID != null) agentMemories[agentID].orEmpty() else sharedMemories + val existing = items.firstOrNull { it.id == id } + memoryDraft = MemoryDraft(memoryID = id, content = existing?.content ?: "", agentID = agentID) + } + + fun saveMemory() { + val form = memoryDraft ?: return + val agent = form.agentID + val content = form.content.trim() + if (content.isEmpty()) { + errorText = "Memory content is required." + return + } + val isNew = form.memoryID.isEmpty() + val provisionalID = if (isNew) "pending-memory-${newRequestID()}" else form.memoryID + val currentList = if (agent == null) sharedMemories else agentMemories[agent].orEmpty() + val old = currentList.firstOrNull { it.id == form.memoryID } + val provisional = old?.copy(content = content) + ?: Memory(id = provisionalID, content = content, agentId = agent, source = MemorySource(kind = "owner"), updatedAt = Instant.now().toString()) + + optimisticMutation( + key = "memory:$provisionalID", + update = { + memoryDraft = null + if (agent == null) { + val idx = sharedMemories.indexOfFirst { it.id == provisionalID || it.id == form.memoryID } + sharedMemories = if (idx >= 0) { + sharedMemories.toMutableList().also { it[idx] = provisional } } else { sharedMemories + provisional } @@ -1280,15 +2845,7 @@ class AppModel( } }, rollback = { - if (agent == null) { - val items = sharedMemories.filterNot { it.id == provisionalID }.toMutableList() - if (old != null) items.add(old) - sharedMemories = items - } else { - val items = agentMemories[agent].orEmpty().filterNot { it.id == provisionalID }.toMutableList() - if (old != null) items.add(old) - agentMemories = agentMemories + (agent to items) - } + setMemories(agent, recordRestored(memoriesOf(agent), currentList, provisionalID) { it.id }) if (route == Route.Memory && memoryDraft == null) { memoryDraft = form } @@ -1301,16 +2858,13 @@ class AppModel( } return@optimisticMutation { if (agent == null) { - val idx = sharedMemories.indexOfFirst { it.id == provisionalID } - if (idx >= 0) { - sharedMemories = sharedMemories.toMutableList().also { it[idx] = saved } + if (sharedMemories.any { it.id == provisionalID }) { + sharedMemories = upserted(sharedMemories, provisionalID, saved) { it.id } } } else { - val items = agentMemories[agent]?.toMutableList() - val idx = items?.indexOfFirst { it.id == provisionalID } ?: -1 - if (items != null && idx >= 0) { - items[idx] = saved - agentMemories = agentMemories + (agent to items) + val items = agentMemories[agent].orEmpty() + if (items.any { it.id == provisionalID }) { + agentMemories = agentMemories + (agent to upserted(items, provisionalID, saved) { it.id }) } } } @@ -1318,6 +2872,12 @@ class AppModel( ) } + private fun memoriesOf(owner: String?) = if (owner == null) sharedMemories else agentMemories[owner].orEmpty() + + private fun setMemories(owner: String?, items: List) { + if (owner == null) sharedMemories = items else agentMemories = agentMemories + (owner to items) + } + fun deleteMemory(id: String, agentID: String? = null) { val currentList = if (agentID == null) sharedMemories else agentMemories[agentID].orEmpty() val oldIndex = currentList.indexOfFirst { it.id == id } @@ -1364,7 +2924,14 @@ class AppModel( agentID = schedule.agentId, name = schedule.name, prompt = schedule.prompt, + kind = schedule.kind, + command = schedule.command.orEmpty(), + timeoutSeconds = schedule.timeoutSeconds.toString(), + notify = schedule.notify, + onEvent = schedule.eventSourceId != null, + eventSourceID = schedule.eventSourceId.orEmpty(), repeats = !schedule.cron.isNullOrEmpty(), + customCron = !schedule.cron.isNullOrEmpty() && recurrenceOf(schedule.cron) == null, cron = if (!schedule.cron.isNullOrEmpty()) schedule.cron else form.cron, timezone = schedule.timezone ?: ZoneId.systemDefault().id, enabled = schedule.enabled, @@ -1386,43 +2953,69 @@ class AppModel( val name = form.name.trim() val prompt = form.prompt.trim() val timezone = form.timezone.trim() - val cron = if (form.repeats) form.cron.trim() else "" - val runAt = if (form.repeats) "" else form.runDate.toIso8601SecondString() + val isScript = form.kind == "script" + val cron = if (!form.onEvent && form.repeats) form.cron.trim() else "" + val runAt = if (!form.onEvent && !form.repeats) form.runDate.toIso8601SecondString() else "" + val sourceID = if (form.onEvent) form.eventSourceID else "" if (form.agentID.isEmpty()) { errorText = "Choose which bot runs this task." return } - val validationError = validateTask(name = name, prompt = prompt, cron = cron, runAt = runAt, timezone = timezone) + val validationError = validateTask( + name = name, + prompt = prompt, + cron = cron, + runAt = runAt, + timezone = timezone, + kind = form.kind, + command = form.command, + timeoutSeconds = form.timeoutSeconds, + onEvent = form.onEvent, + eventSourceID = sourceID, + ) if (validationError != null) { errorText = validationError return } + val timeoutSeconds = if (isScript) form.timeoutSeconds.trim().toLong() else 600L val payload = LinkedHashMap().apply { put("agentId", JsonPrimitive(form.agentID)) put("name", JsonPrimitive(name)) - put("prompt", JsonPrimitive(prompt)) + put("kind", JsonPrimitive(form.kind)) + put("prompt", JsonPrimitive(if (isScript) "" else prompt)) + put("command", if (isScript) JsonPrimitive(form.command) else JsonNull) + put("timeoutSeconds", JsonPrimitive(timeoutSeconds)) + put("notify", JsonPrimitive(form.notify)) put("timezone", JsonPrimitive(timezone)) put("enabled", JsonPrimitive(form.enabled)) } val isNew = form.scheduleID.isEmpty() val provisionalID = if (isNew) "pending-schedule-${newRequestID()}" else form.scheduleID + val old = schedules.firstOrNull { it.id == form.scheduleID } val provisional = Schedule( id = provisionalID, agentId = form.agentID, name = name, - cron = if (form.repeats) cron else null, - prompt = prompt, + cron = cron.ifEmpty { null }, + prompt = if (isScript) "" else prompt, timezone = timezone, - runAt = if (form.repeats) null else runAt, + runAt = runAt.ifEmpty { null }, enabled = form.enabled, - createdByAgentId = null, + createdByAgentId = old?.createdByAgentId, + kind = form.kind, + command = if (isScript) form.command else null, + timeoutSeconds = timeoutSeconds, + notify = form.notify, + eventSourceId = sourceID.ifEmpty { null }, + // Without a next run a one-off reads as finished and leaves the list before it is saved. + nextRunAt = runAt.ifEmpty { old?.nextRunAt.takeIf { cron.isNotEmpty() } }, ) - val old = schedules.firstOrNull { it.id == form.scheduleID } - taskDraft = null + val original = schedules optimisticMutation( key = "schedule:$provisionalID", update = { + taskDraft = null val idx = schedules.indexOfFirst { it.id == provisionalID || it.id == form.scheduleID } schedules = if (idx >= 0) { schedules.toMutableList().also { it[idx] = provisional } @@ -1431,48 +3024,189 @@ class AppModel( } }, rollback = { - val list = schedules.filterNot { it.id == provisionalID }.toMutableList() - if (old != null) list.add(old) - schedules = list + schedules = recordRestored(schedules, original, provisionalID) { it.id } if (route == Route.Tasks && taskDraft == null) { taskDraft = form } }, work = { api -> + val trigger = mapOf("cron" to cron, "runAt" to runAt, "eventSourceId" to sourceID) val saved = if (isNew) { - if (form.repeats) { - payload["cron"] = JsonPrimitive(cron) - } else { - payload["runAt"] = JsonPrimitive(runAt) - } + trigger.filterValues { it.isNotEmpty() }.forEach { (key, value) -> payload[key] = JsonPrimitive(value) } api.createSchedule(payload) } else { - payload["cron"] = if (cron.isEmpty()) JsonNull else JsonPrimitive(cron) - payload["runAt"] = if (form.repeats) JsonNull else JsonPrimitive(runAt) + trigger.forEach { (key, value) -> payload[key] = if (value.isEmpty()) JsonNull else JsonPrimitive(value) } api.updateSchedule(form.scheduleID, patch = payload) } return@optimisticMutation { - val idx = schedules.indexOfFirst { it.id == provisionalID } - if (idx >= 0) { - schedules = schedules.toMutableList().also { it[idx] = saved } + if (schedules.any { it.id == provisionalID }) { + schedules = upserted(schedules, provisionalID, saved) { it.id } } } }, ) } + /** Picks the bot for the open form; a bot without coding jobs can't keep a script. */ + fun pickTaskBot(agentID: String) { + val form = taskDraft ?: return + val canScript = canRunScripts(capabilities, agents.firstOrNull { it.id == agentID }) + taskDraft = form.copy(agentID = agentID, kind = if (canScript) form.kind else "prompt") + } + + fun toggleSchedule(id: String) { + val old = schedules.firstOrNull { it.id == id } ?: return + fun replace(schedule: Schedule) { + schedules = schedules.map { if (it.id == id) schedule else it } + } + val enabled = !old.enabled + optimisticMutation( + key = "schedule:$id", + update = { replace(old.copy(enabled = enabled)) }, + rollback = { replace(old) }, + work = { api -> + val saved = api.updateSchedule(id, patch = mapOf("enabled" to JsonPrimitive(enabled))) + return@optimisticMutation { replace(saved) } + }, + ) + } + + fun schedulePending(id: String): Boolean = id.startsWith("pending-") || pendingMutations.contains("schedule:$id") + + fun selectTaskTab(tab: TaskTab) { + taskTab = tab + when (tab) { + TaskTab.Tasks -> Unit + TaskTab.Runs -> loadTaskRuns() + TaskTab.EventSources -> loadEventSources() + } + } + + private fun loadCapabilities() { + confirmed( + start = {}, + work = { api -> api.capabilities() }, + finish = { result -> result.onSuccess { capabilities = it } }, + ) + } + + private fun loadTaskRuns() { + taskRunsVersion += 1 + val version = taskRunsVersion + val scripts = schedules.filter { it.kind == "script" && !it.id.startsWith("pending-") } + confirmed( + start = { taskRunsLoading = true }, + work = { api -> + coroutineScope { + val history = async { attempt { api.executions() } } + val runs = scripts.map { script -> async { script.id to attempt { api.scriptRuns(script.id) } } }.awaitAll() + history.await() to runs + } + }, + finish = { result -> + if (version == taskRunsVersion) { + taskRunsLoading = false + result + .onSuccess { (history, runs) -> + history.onSuccess { executions = it } + scriptRuns = runs.mapNotNull { (id, loaded) -> + (loaded.getOrNull() ?: scriptRuns[id])?.let { id to it } + }.toMap() + taskRunsError = history.exceptionOrNull()?.let { friendlyError(it) } + ?: if (runs.any { it.second.isFailure }) "Some script runs could not be loaded." else "" + } + .onFailure { taskRunsError = friendlyError(it) } + } + }, + ) + } + + private fun loadEventSources() { + eventSourcesVersion += 1 + val version = eventSourcesVersion + confirmed( + start = {}, + work = { api -> api.eventSources() }, + finish = { result -> + if (version == eventSourcesVersion) { + result + .onSuccess { + eventSources = it + eventSourcesLoaded = true + eventSourcesError = "" + } + .onFailure { eventSourcesError = friendlyError(it) } + } + }, + ) + } + + fun openEventSourceForm() { + eventSourceDraft = EventSourceDraft() + } + + /** The relay decides, and its address is shown once, so a pending sheet can't be dismissed. */ + fun closeEventSourceForm() { + if (eventSourceDraft?.saving != true) eventSourceDraft = null + } + + /** The relay creates the source, so it joins the list only once the server confirms. */ + fun saveEventSource() { + val form = eventSourceDraft ?: return + val name = form.name.trim() + if (name.isEmpty() || form.saving) return + confirmed( + start = { eventSourceDraft = form.copy(saving = true, error = "") }, + work = { api -> api.createEventSource(name) }, + finish = { result -> + result + .onSuccess { created -> + eventSourceDraft = eventSourceDraft?.copy(saving = false, created = created) + eventSources = eventSources.filterNot { it.id == created.id } + + EventSource(created.id, created.name, created.createdAt, created.usedBy) + loadEventSources() + } + .onFailure { eventSourceDraft = eventSourceDraft?.copy(saving = false, error = friendlyError(it)) } + }, + ) + } + + /** The relay removes the address, so the row stays pending until the server confirms. */ + fun deleteEventSource(id: String) { + if (deletingEventSources.contains(id)) return + confirmed( + start = { + deletingEventSources = deletingEventSources + id + eventSourceErrors = eventSourceErrors - id + }, + work = { api -> api.deleteEventSource(id) }, + finish = { result -> + deletingEventSources = deletingEventSources - id + result + .onSuccess { + eventSources = eventSources.filterNot { it.id == id } + loadEventSources() + } + .onFailure { eventSourceErrors = eventSourceErrors + (id to friendlyError(it)) } + }, + ) + } + fun runSchedule(id: String) { val routeAtStart = route + val owner = schedules.firstOrNull { it.id == id }?.agentId showNotice("Starting task…") optimisticMutation( key = "schedule-run:$id", + onBusy = {}, update = {}, rollback = { showNotice("Task could not be started") }, work = { api -> val execution = api.runSchedule(id) return@optimisticMutation { showNotice("Task started") - val agent = execution.agentId + // A script run's admission names only the run, not the bot. + val agent = execution.agentId ?: owner if (route == routeAtStart && routeAtStart == Route.Tasks && !agent.isNullOrEmpty()) { selectAgent(agent) } @@ -1510,6 +3244,9 @@ class AppModel( name = server.name, url = server.url, enabled = server.enabled, + token = secretDraft(server.token), + clientID = server.oauthClientId.orEmpty(), + clientSecret = secretDraft(server.oauthClientSecret), ) } mcpDraft = form @@ -1533,11 +3270,14 @@ class AppModel( put("name", JsonPrimitive(name)) put("url", JsonPrimitive(rawURL)) put("enabled", JsonPrimitive(form.enabled)) - if (form.token.isNotEmpty()) put("token", JsonPrimitive(form.token)) + form.token.takeIf { it.changed }?.input?.let { put("token", it.json()) } } val isNew = form.serverID.isEmpty() val provisionalID = if (isNew) "pending-mcp-${newRequestID()}" else form.serverID val old = mcpServers.firstOrNull { it.id == form.serverID } + payload.putAll(form.oauthFields(old)) + val tokenChanged = form.token.changed + val waits = form.readsPasswordManager var provisional = MCPServer( id = provisionalID, name = name, @@ -1545,17 +3285,22 @@ class AppModel( enabled = form.enabled, agentId = form.agentID, authenticated = false, - auth = if (form.token.isEmpty()) "none" else "token", + auth = if (tokenChanged && !waits) "token" else "none", + oauthClientId = form.clientID.trim().nilIfEmpty, + token = old?.token, + oauthClientSecret = old?.oauthClientSecret, ) - if (old != null && form.token.isEmpty() && old.url == rawURL) { + if (old != null && (!tokenChanged || waits) && old.url == rawURL) { provisional = provisional.copy(authenticated = old.authenticated, auth = old.auth) } val owner = form.agentID - mcpDraft = null + val original = mcpServers optimisticMutation( key = "mcp:$provisionalID", + touches = if (isNew && owner != null) setOf("$BOT_RECORD$owner") else emptySet(), update = { + mcpDraft = if (waits) form.copy(saving = true) else null val idx = mcpServers.indexOfFirst { it.id == provisionalID || it.id == form.serverID } mcpServers = if (idx >= 0) { mcpServers.toMutableList().also { it[idx] = provisional } @@ -1574,9 +3319,7 @@ class AppModel( } }, rollback = { - val list = mcpServers.filterNot { it.id == provisionalID }.toMutableList() - if (old != null) list.add(old) - mcpServers = list + mcpServers = recordRestored(mcpServers, original, provisionalID) { it.id } if (isNew && owner != null) { val agentIdx = agents.indexOfFirst { it.id == owner } if (agentIdx >= 0) { @@ -1586,7 +3329,7 @@ class AppModel( } } } - if (route == Route.Integrations && mcpDraft == null) { + if (route == Route.Integrations && (mcpDraft == null || mcpDraft?.id == form.id)) { mcpDraft = form } }, @@ -1595,9 +3338,9 @@ class AppModel( if (owner != null) payload["agentId"] = JsonPrimitive(owner) val saved = api.createMCPServer(payload) return@optimisticMutation { - val idx = mcpServers.indexOfFirst { it.id == provisionalID } - if (idx >= 0) { - mcpServers = mcpServers.toMutableList().also { it[idx] = saved } + if (mcpDraft?.id == form.id) mcpDraft = null + if (mcpServers.any { it.id == provisionalID }) { + mcpServers = upserted(mcpServers, provisionalID, saved) { it.id } } if (owner != null) { val agentIdx = agents.indexOfFirst { it.id == owner } @@ -1614,6 +3357,7 @@ class AppModel( } val saved = api.updateMCPServer(form.serverID, patch = payload) return@optimisticMutation { + if (mcpDraft?.id == form.id) mcpDraft = null val idx = mcpServers.indexOfFirst { it.id == provisionalID } if (idx >= 0) { mcpServers = mcpServers.toMutableList().also { it[idx] = saved } @@ -1633,13 +3377,18 @@ class AppModel( val api = client ?: return errorText = "" signingIn = id + browserSignIn = null val genAtStart = generation scope.launch { try { val start = api.startMCPSignIn(id, redirectURI = oauthRedirectURI) if (generation != genAtStart) return@launch val address = start.authorizationUrl - if (!address.isNullOrEmpty()) { + if (!address.isNullOrEmpty() && !isWebLink(address)) { + signingIn = null + errorText = "This server's sign-in page isn't a web address." + } else if (!address.isNullOrEmpty()) { + browserSignIn = id openBrowser(address) } else if (start.authorized == true) { val idx = mcpServers.indexOfFirst { it.id == id } @@ -1658,15 +3407,27 @@ class AppModel( } catch (e: Throwable) { if (generation != genAtStart) return@launch signingIn = null + browserSignIn = null errorText = friendlyError(e) } } } + /** A browser never reports being abandoned. Coming back without its callback ends the wait. */ + fun browserReturned() { + if (signingIn == browserSignIn) signingIn = null + } + /** Completes an in-flight OAuth sign-in when the system redirects back to `dev.crumble.android:/oauth/callback`. */ fun handleOAuthCallback(callbackUri: String) { - val id = signingIn ?: return - val api = client ?: return + val id = browserSignIn + val api = client + if (id == null || api == null) { + errorText = "That sign-in was interrupted. Try again." + return + } + browserSignIn = null + signingIn = id val genAtStart = generation scope.launch { try { @@ -1729,6 +3490,7 @@ class AppModel( } optimisticMutation( key = "mcp:$id", + touches = affectedAgents.map { "$BOT_RECORD${it.first}" }.toSet(), update = { mcpServers = mcpServers.filterNot { it.id == id } agents = agents.map { agent -> @@ -1764,14 +3526,26 @@ class AppModel( var form = SkillDraft(skillID = id, agentID = agentID) if (agentID == null) { val skill = sharedSkills.firstOrNull { it.id == id } - if (skill != null) form = form.copy(name = skill.name, instructions = skill.instructions) + if (skill != null) form = form.copy(name = skill.name, instructions = skill.instructions, usedBy = botsUsing(agents, id)) } else { - val skill = agents.firstOrNull { it.id == agentID }?.skills.orEmpty().firstOrNull { it.id == id } + val skill = agentSkills[agentID].orEmpty().firstOrNull { it.id == id } if (skill != null) form = form.copy(name = skill.name, instructions = skill.instructions) } skillDraft = form } + /** Keeps the bot's inline skills current: saving the bot replaces its skills with that list. */ + private fun setAgentSkills(agentID: String, skills: List) { + agentSkills = agentSkills + (agentID to skills) + agents = agents.map { agent -> if (agent.id == agentID) agent.copy(skills = skills.map { it.asInline() }) else agent } + } + + private fun setSharedSkillsOf(agentID: String, change: (List) -> List) { + agents = agents.map { agent -> + if (agent.id == agentID) agent.copy(sharedSkills = change(agent.sharedSkills.orEmpty())) else agent + } + } + fun saveSkill() { val form = skillDraft ?: return val name = form.name.trim() @@ -1786,24 +3560,31 @@ class AppModel( return } val provisionalID = if (isNew) "pending-skill-${newRequestID()}" else form.skillID - val provisional = SharedSkill(id = provisionalID, name = name, instructions = instructions, source = null, path = null) - val old = sharedSkills.firstOrNull { it.id == form.skillID } - skillDraft = null + val oldSkills = sharedSkills + val old = oldSkills.firstOrNull { it.id == form.skillID } + val provisional = old?.copy(name = name, instructions = instructions) ?: SharedSkill(id = provisionalID, name = name, instructions = instructions, source = "shared") + val using = botsUsing(agents, form.skillID) + val added = form.usedBy - using + val dropped = using - form.usedBy + fun assign(id: String) { + for (bot in added) setSharedSkillsOf(bot) { (it + id).distinct().sorted() } + for (bot in dropped) setSharedSkillsOf(bot) { it - id } + } + fun unassign(id: String, bots: Set) { + for (bot in bots) setSharedSkillsOf(bot) { if (bot in added) it - id else (it + id).distinct().sorted() } + } optimisticMutation( key = "skill:$provisionalID", + touches = (added + dropped).map { "$BOT_RECORD$it" }.toSet(), update = { - val idx = sharedSkills.indexOfFirst { it.id == provisionalID || it.id == form.skillID } - sharedSkills = if (idx >= 0) { - sharedSkills.toMutableList().also { it[idx] = provisional } - } else { - sharedSkills + provisional - } + skillDraft = null + sharedSkills = upserted(sharedSkills, provisionalID, provisional) { it.id } + assign(provisionalID) }, rollback = { - val list = sharedSkills.filterNot { it.id == provisionalID }.toMutableList() - if (old != null) list.add(old) - sharedSkills = list + sharedSkills = recordRestored(sharedSkills, oldSkills, provisionalID) { it.id } + unassign(provisionalID, added + dropped) if (route == Route.Skills && skillDraft == null) { skillDraft = form } @@ -1814,11 +3595,19 @@ class AppModel( } else { api.updateSharedSkill(form.skillID, name = name, instructions = instructions) } + val failed = coroutineScope { + (added + dropped).map { bot -> + async { bot to attempt { api.assignSkill(saved.id, bot, bot in added) } } + }.awaitAll().filter { (_, result) -> result.isFailure } + } return@optimisticMutation { - val idx = sharedSkills.indexOfFirst { it.id == provisionalID } - if (idx >= 0) { - sharedSkills = sharedSkills.toMutableList().also { it[idx] = saved } + sharedSkills = upserted(sharedSkills, provisionalID, provisional.copy(id = saved.id, name = saved.name, instructions = saved.instructions)) { it.id } + if (isNew) { + for (bot in added) setSharedSkillsOf(bot) { ids -> ids.map { if (it == provisionalID) saved.id else it } } } + // The skill saved, so a failed assignment rolls back alone and retrying won't duplicate it. + unassign(saved.id, failed.map { it.first }.toSet()) + failed.firstOrNull()?.second?.exceptionOrNull()?.let { errorText = friendlyError(it) } } }, ) @@ -1826,50 +3615,58 @@ class AppModel( private fun saveAgentSkill(form: SkillDraft, name: String, instructions: String, isNew: Boolean) { val agentID = form.agentID ?: return - val oldSkills = agents.firstOrNull { it.id == agentID }?.skills.orEmpty() if (agents.none { it.id == agentID }) return - val skillID = if (isNew) UUID.randomUUID().toString() else form.skillID - val updatedSkill = Skill( - id = skillID, - name = name, - instructions = instructions, - ) - val updatedSkills = if (isNew) oldSkills + updatedSkill else oldSkills.map { if (it.id == form.skillID) updatedSkill else it } - skillDraft = null + val provisionalID = if (isNew) "pending-skill-${newRequestID()}" else form.skillID + val original = agentSkills[agentID].orEmpty() + val provisional = provisionalSkill(provisionalID, agentID, name, instructions, original.firstOrNull { it.id == form.skillID }) optimisticMutation( - key = "agent-skills:$agentID", - update = { agents = agents.map { if (it.id == agentID) it.copy(skills = updatedSkills) else it } }, + key = "agent-skill:$provisionalID", + touches = setOf("$BOT_RECORD$agentID"), + update = { + skillDraft = null + setAgentSkills(agentID, upserted(agentSkills[agentID].orEmpty(), provisionalID, provisional) { it.id }) + }, rollback = { - agents = agents.map { if (it.id == agentID) it.copy(skills = oldSkills) else it } + setAgentSkills(agentID, recordRestored(agentSkills[agentID].orEmpty(), original, provisionalID) { it.id }) if (route == Route.Skills && skillDraft == null) skillDraft = form }, work = { api -> - val patch = mapOf( - "skills" to CrumbleJson.encodeToJsonElement(ListSerializer(Skill.serializer()), updatedSkills), - ) - val saved = api.updateAgent(agentID, patch) + val saved = if (isNew) api.createBotSkill(agentID, name, instructions) else api.updateBotSkill(agentID, form.skillID, name, instructions) return@optimisticMutation { - agents = agents.map { current -> if (current.id == agentID) current.copy(skills = saved.skills) else current } + setAgentSkills(agentID, upserted(agentSkills[agentID].orEmpty(), provisionalID, saved) { it.id }) } }, ) } fun deleteAgentSkill(agentID: String, skillID: String) { - val oldSkills = agents.firstOrNull { it.id == agentID }?.skills.orEmpty() - if (agents.none { it.id == agentID }) return - val updatedSkills = oldSkills.filterNot { it.id == skillID } + val original = agentSkills[agentID].orEmpty() + if (original.none { it.id == skillID }) return optimisticMutation( - key = "agent-skills:$agentID", - update = { agents = agents.map { if (it.id == agentID) it.copy(skills = updatedSkills) else it } }, - rollback = { agents = agents.map { if (it.id == agentID) it.copy(skills = oldSkills) else it } }, + key = "agent-skill:$skillID", + touches = setOf("$BOT_RECORD$agentID"), + update = { setAgentSkills(agentID, agentSkills[agentID].orEmpty().filterNot { it.id == skillID }) }, + rollback = { setAgentSkills(agentID, recordRestored(agentSkills[agentID].orEmpty(), original, skillID) { it.id }) }, work = { api -> - val patch = mapOf( - "skills" to CrumbleJson.encodeToJsonElement(ListSerializer(Skill.serializer()), updatedSkills), - ) - val saved = api.updateAgent(agentID, patch) + api.deleteBotSkill(agentID, skillID) + null + }, + ) + } + + fun toggleSkillPin(agentID: String, skillID: String) { + val original = agentSkills[agentID].orEmpty() + val skill = original.firstOrNull { it.id == skillID } ?: return + val pinned = !skill.pinned + optimisticMutation( + key = "agent-skill:$skillID", + touches = setOf("$BOT_RECORD$agentID"), + update = { setAgentSkills(agentID, upserted(agentSkills[agentID].orEmpty(), skillID, skill.copy(pinned = pinned)) { it.id }) }, + rollback = { setAgentSkills(agentID, recordRestored(agentSkills[agentID].orEmpty(), original, skillID) { it.id }) }, + work = { api -> + val saved = api.pinBotSkill(agentID, skillID, pinned) return@optimisticMutation { - agents = agents.map { current -> if (current.id == agentID) current.copy(skills = saved.skills) else current } + setAgentSkills(agentID, upserted(agentSkills[agentID].orEmpty(), skillID, saved) { it.id }) } }, ) @@ -1884,6 +3681,7 @@ class AppModel( } optimisticMutation( key = "skill:$id", + touches = affectedAgents.map { "$BOT_RECORD${it.first}" }.toSet(), update = { sharedSkills = sharedSkills.filterNot { it.id == id } agents = agents.map { agent -> @@ -1918,6 +3716,7 @@ class AppModel( if (next == current) return optimisticMutation( key = "agent-shared-skills:$agentID", + touches = setOf("$BOT_RECORD$agentID"), update = { agents = agents.map { if (it.id == agentID) it.copy(sharedSkills = next) else it } }, rollback = { agents = agents.map { if (it.id == agentID) it.copy(sharedSkills = current) else it } }, work = { api -> @@ -1930,111 +3729,2023 @@ class AppModel( ) } - // MARK: Settings + /** An editable shared copy of an installed skill, documents included. */ + fun copySkill(id: String) { + val skill = sharedSkills.firstOrNull { it.id == id } ?: return + val provisionalID = "pending-skill-${newRequestID()}" + val provisional = skill.copy(id = provisionalID, name = "${skill.name} copy".take(100), origin = null, update = null) + optimisticMutation( + key = "skill:$provisionalID", + update = { sharedSkills = sharedSkills + provisional }, + rollback = { sharedSkills = sharedSkills.filterNot { it.id == provisionalID } }, + work = { api -> + val saved = api.copySharedSkill(api.skillPackage(id)) + return@optimisticMutation { sharedSkills = upserted(sharedSkills, provisionalID, saved) { it.id } } + }, + ) + } - fun saveSettings() { - if (savingConnection) return - val rawURL = serverURL.trim().trimmingTrailingSlashes - val trimmedToken = token.trim() - val validUrl = try { - val u = java.net.URI(rawURL) - !u.host.isNullOrEmpty() && (u.scheme == "http" || u.scheme == "https") - } catch (_: Exception) { - false - } - if (!validUrl) { - errorText = "Enter a valid server URL." - return - } - val candidate = APIClient(baseURL = rawURL, token = trimmedToken) - savingConnection = true - errorText = "" - scope.launch { - try { - candidate.agents() - credentials.write("server-token", trimmedToken) - credentials.write("server-url", rawURL) - cancelStream() - generation += 1 - pendingMutations = emptySet() - mutationRevision += 1 - resetPendingMessages() - recentChats.clear() - awaitingInitialSnapshot = false - agents = emptyList() - agentMemories = emptyMap() - sharedMemories = emptyList() - sharedSkills = emptyList() - schedules = emptyList() - executions = emptyList() - mcpServers = emptyList() - providers = emptyList() - models = emptyList() - signingIn = null - agentDraft = null - memoryDraft = null - taskDraft = null - mcpDraft = null - skillDraft = null - snapshot = null - messages = emptyList() - client = candidate - activeRequests = 0 - loading = false - errorText = "" - selectedAgentID = "" - showingSettings = false - showNotice("Connected") - refresh() - followActivity() - } catch (e: CancellationException) { - throw e - } catch (e: Throwable) { - errorText = friendlyError(e) - } finally { - savingConnection = false - } - } + fun toggleSkillSelection(ids: List, selected: Boolean) { + selectedSkills = if (selected) selectedSkills + ids else selectedSkills - ids.toSet() } - fun saveProviderKey() { - val currentProvider = provider - val key = providerKey.trim() - if (key.isEmpty()) { - errorText = "Enter an API key." - return + /** Deletes apply at once, and shared assignments too. Copies and updates show once the server has them. */ + fun runBulkAction(action: BulkAction, targets: Set = emptySet()) { + val picked = selectionCatalog(sharedSkills, agents, agentSkills).filter { it.id in selectedSkills } + if (picked.isEmpty()) return + val bots = agents.filter { it.id in targets } + val ids = picked.map { it.id }.toSet() + val shared = picked.filter { it.botID == null }.map { it.id }.toSet() + val originalShared = sharedSkills + val originalPersonal = agentSkills + val originalAgents = agents + bulkReport = emptyList() + + fun undo(agentID: String, skills: Set) { + val before = originalAgents.firstOrNull { it.id == agentID }?.sharedSkills.orEmpty() + setSharedSkillsOf(agentID) { current -> + (current - skills + before.filter { it in skills }).distinct().sorted() + } + } + + fun restoreDeleted(failed: Set) { + sharedSkills = restoring(sharedSkills, originalShared, failed) { it.id } + for ((agentID, skills) in originalPersonal) { + setAgentSkills(agentID, restoring(agentSkills[agentID].orEmpty(), skills, failed) { it.id }) + } + for (agent in originalAgents) undo(agent.id, failed intersect shared) } + optimisticMutation( - key = "provider:$currentProvider", - update = { providerKey = "" }, + key = "skills:bulk", + touches = shared.map { "$SKILL_RECORD$it" }.toSet() + (ids - shared).map { "$BOT_SKILL_RECORD$it" } + + (if (action == BulkAction.delete) agents else bots).map { "$BOT_RECORD${it.id}" }, + update = { + when (action) { + BulkAction.delete -> { + sharedSkills = sharedSkills.filterNot { it.id in ids } + for ((agentID, skills) in agentSkills) setAgentSkills(agentID, skills.filterNot { it.id in ids }) + for (agent in agents) setSharedSkillsOf(agent.id) { it - shared } + } + BulkAction.assign -> for (bot in bots) setSharedSkillsOf(bot.id) { (it + shared).distinct().sorted() } + BulkAction.remove -> for (bot in bots) setSharedSkillsOf(bot.id) { it - shared } + BulkAction.update -> Unit + } + }, rollback = { - if (provider == currentProvider && providerKey.isEmpty()) { - providerKey = key + when (action) { + BulkAction.delete -> restoreDeleted(ids) + BulkAction.assign, BulkAction.remove -> for (bot in bots) undo(bot.id, shared) + BulkAction.update -> Unit + } + }, + work = { api -> + val result = applyBulkAction(api, action, picked, bots) + return@optimisticMutation { + if (action == BulkAction.delete) restoreDeleted(result.failed) + for ((skill, bot) in result.failedAssignments) if (skill in shared) undo(bot, setOf(skill)) + selectedSkills = result.failed + bulkReport = result.messages + loadSkills() + } + }, + ) + } + + fun checkSkillUpdates() { + if (checkingSkillUpdates) return + confirmed( + start = { + checkingSkillUpdates = true + skillCheckFailures = emptyList() + }, + work = { api -> api.checkSkillUpdates() }, + finish = { result -> + checkingSkillUpdates = false + result + .onSuccess { skillCheckFailures = updateCheckFailures(it) } + .onFailure { skillCheckFailures = listOf(friendlyError(it)) } + loadSkills() + }, + ) + } + + fun openSkillInstall() { + skillBrowseVersion += 1 + skillInstall = SkillInstallForm() + } + + fun closeSkillInstall() { + skillBrowseVersion += 1 + skillInstall = null + } + + fun changeSkillLocation(location: String) { + val form = skillInstall ?: return + skillBrowseVersion += 1 + skillInstall = form.copy(location = location, listing = null, picked = emptySet(), browsing = false, error = "") + } + + /** A late answer for an older location never replaces what the owner typed since. */ + fun findSkills() { + val form = skillInstall ?: return + val location = form.location.trim() + if (location.isEmpty()) return + skillBrowseVersion += 1 + val version = skillBrowseVersion + confirmed( + start = { skillInstall = form.copy(browsing = true, error = "") }, + work = { api -> api.browseSkills(location) }, + finish = { result -> + val current = skillInstall + if (current != null && skillBrowseVersion == version) { + skillInstall = result.fold( + onSuccess = { current.copy(listing = it, picked = newSkillPaths(it), browsing = false) }, + onFailure = { current.copy(listing = null, browsing = false, error = friendlyError(it)) }, + ) + } + }, + ) + } + + fun toggleSkillCandidate(path: String, selected: Boolean) { + val form = skillInstall ?: return + skillInstall = form.copy(picked = if (selected) form.picked + path else form.picked - path) + } + + fun toggleInstallBot(id: String, selected: Boolean) { + val form = skillInstall ?: return + skillInstall = form.copy(botIDs = if (selected) form.botIDs + id else form.botIDs - id) + } + + /** Depends on GitHub, so the sheet stays open and pending until the server confirms. */ + fun installSkills() { + val form = skillInstall ?: return + val listing = form.listing ?: return + if (form.installing || form.picked.isEmpty()) return + confirmed( + start = { skillInstall = form.copy(installing = true, error = "") }, + work = { api -> api.installSkills(listing, form.picked, form.botIDs) }, + finish = { result -> + result + .onSuccess { + skillInstall = null + loadSkills() + } + .onFailure { skillInstall = skillInstall?.copy(installing = false, error = friendlyError(it)) } + }, + ) + } + + fun openInstalledSkill(id: String) { + confirmed( + start = { installedSkill = InstalledSkillView(id) }, + work = { api -> api.skillPackage(id) }, + finish = { result -> + installedSkill = installedSkill?.takeIf { it.skillID == id }?.let { view -> + result.fold({ view.copy(full = it) }, { view.copy(error = friendlyError(it)) }) + } + }, + ) + } + + fun openSkillUpdate(id: String) { + installedSkill = null + confirmed( + start = { skillUpdate = SkillUpdateView(id) }, + work = { api -> + coroutineScope { + val current = async { attempt { api.skillPackage(id) } } + val pending = async { attempt { api.pendingSkillUpdate(id) } } + current.await() to pending.await() + } + }, + finish = { result -> + val current = result.getOrNull()?.first + val pending = result.getOrNull()?.second + val failure = result.exceptionOrNull() ?: pending?.exceptionOrNull() ?: current?.exceptionOrNull() + skillUpdate = skillUpdate?.takeIf { it.skillID == id }?.copy( + current = current?.getOrNull(), + pending = pending?.getOrNull(), + error = failure?.let(::friendlyError).orEmpty(), + ) + }, + ) + } + + /** The server applies what it read from GitHub, so the row changes only once it confirms. */ + fun applySkillUpdate() { + val view = skillUpdate ?: return + if (view.pending == null || view.applying) return + val id = view.skillID + confirmed( + start = { skillUpdate = view.copy(applying = true, error = "") }, + work = { api -> api.applySkillUpdate(id) }, + finish = { result -> + result + .onSuccess { saved -> + sharedSkills = upserted(sharedSkills, id, saved.asShared()) { it.id } + skillUpdate = null + loadSkills() + } + .onFailure { failure -> skillUpdate = skillUpdate?.copy(applying = false, error = friendlyError(failure)) } + }, + ) + } + + // MARK: Change history + + fun openChanges() { + showingChanges = true + loadChanges(before = null) + } + + fun closeChanges() { + changesVersion += 1 + changesLoading = false + showingChanges = false + } + + fun loadMoreChanges() { + if (!changesLoading) changes.lastOrNull()?.let { loadChanges(before = it.id) } + } + + private fun loadChanges(before: String?) { + changesVersion += 1 + val version = changesVersion + confirmed( + start = { + changesLoading = true + changesError = "" + }, + work = { api -> api.changes(before) }, + finish = { result -> + if (changesVersion == version) { + changesLoading = false + result + .onSuccess { page -> + changes = if (before == null) page else (changes + page).distinctBy { it.id } + changesHasMore = page.size == CHANGES_PAGE + } + .onFailure { changesError = friendlyError(it) } } }, + ) + } + + private fun revertSkillRecord(change: LearnedChange): () -> Unit { + val id = change.targetId + val restored = change.beforeSkill + val owner = change.agentId + if (owner != null) { + val original = agentSkills[owner].orEmpty() + setAgentSkills(owner, upserted(original, id, restored) { it.id }) + return { setAgentSkills(owner, recordRestored(agentSkills[owner].orEmpty(), original, id) { it.id }) } + } + val original = sharedSkills + sharedSkills = upserted(original, id, restored?.asShared()) { it.id } + return { sharedSkills = recordRestored(sharedSkills, original, id) { it.id } } + } + + /** Applies the state before `change` to its record and returns how to undo that. */ + private fun revertRecord(change: LearnedChange): () -> Unit { + if (change.target == "skill") return revertSkillRecord(change) + val owner = change.agentId + val original = memoriesOf(owner) + setMemories(owner, upserted(original, change.targetId, change.beforeMemory) { it.id }) + return { setMemories(owner, recordRestored(memoriesOf(owner), original, change.targetId) { it.id }) } + } + + fun revertChange(change: LearnedChange) { + var undo: () -> Unit = {} + optimisticMutation( + key = "change:${change.id}", + touches = setOf( + when { + change.target != "skill" -> "$MEMORY_RECORD${change.targetId}" + change.agentId != null -> "$BOT_SKILL_RECORD${change.targetId}" + else -> "$SKILL_RECORD${change.targetId}" + }, + ), + update = { undo = revertRecord(change) }, + rollback = { undo() }, work = { api -> - api.setProviderKey(currentProvider, apiKey = key) + val reverted = api.revertChange(change.id) return@optimisticMutation { - showNotice("Provider key saved") - loadProviders() + changes = listOf(reverted) + changes + reloadPage() } }, ) } - fun removeProviderKey() { - val currentProvider = provider + // MARK: Avatars + + fun pickAvatarBot(id: String) { + val page = avatarPage + if (page.saving) return + val bot = agents.firstOrNull { it.id == id } + avatarPage = page.copy(botID = id, value = bot?.let { it.avatar ?: placeholderAvatar(it.id) } ?: page.value, saved = false) + } + + fun changeAvatar(value: BotAvatarDefinition) { + if (!avatarPage.saving) avatarPage = avatarPage.copy(value = value, saved = false) + } + + /** The page locks while saving: a PATCH can't be cancelled, and edits could save out of order. */ + fun saveAvatar() { + val page = avatarPage + val id = page.botID + if (page.saving) return + val old = agents.firstOrNull { it.id == id } ?: return + fun setAvatar(avatar: BotAvatarDefinition?) { + agents = agents.map { if (it.id == id) it.copy(avatar = avatar) else it } + } optimisticMutation( - key = "provider:$currentProvider", - update = {}, - rollback = {}, + key = "agent-avatar:$id", + touches = setOf("$BOT_RECORD$id"), + update = { + setAvatar(page.value) + avatarPage = page.copy(saving = true, saved = false) + }, + rollback = { + setAvatar(old.avatar) + avatarPage = avatarPage.copy(saving = false) + }, + work = { api -> + val saved = api.updateAgent(id, mapOf("avatar" to CrumblePatchJson.encodeToJsonElement(page.value))) + return@optimisticMutation { + setAvatar(saved.avatar) + avatarPage = avatarPage.copy(saving = false, saved = true) + } + }, + ) + } + + // MARK: Settings + + /** Applies at once. One save runs at a time, so the account ends on the newest choice. */ + fun chooseTheme(next: ThemeChoice) { + if (next == theme) return + themeChanges += 1 + adoptTheme(next) + if (client?.token.isNullOrEmpty()) accountTheme = next + else if (!themeSaving) saveTheme() + } + + private fun adoptTheme(next: ThemeChoice) { + theme = next + credentials.write(THEME_KEY, next.value) + } + + private fun saveTheme() { + val sending = theme + confirmed( + start = { themeSaving = true }, + work = { api -> api.updateTheme(sending.value) }, + finish = { result -> + themeSaving = false + result.onSuccess { accountTheme = sending } + if (theme != sending) saveTheme() + else result.onFailure { + adoptTheme(accountTheme) + errorText = friendlyError(it) + } + }, + ) + } + + fun changeReplyNotifications(on: Boolean) { + replyNotifications = on + notificationSettings.replies = on + onNotificationsChanged() + } + + fun changeNotificationSound(on: Boolean) { + notificationSound = on + notificationSettings.sound = on + } + + fun runPalette(action: PaletteAction) { + showingPalette = false + when (action) { + is PaletteAction.OpenBot -> navigate(Route.AgentChat(action.id)) + is PaletteAction.OpenGroup -> navigate(Route.GroupChat(action.id)) + PaletteAction.NewBot -> createAgent() + PaletteAction.NewGroup -> navigate(Route.NewGroup) + is PaletteAction.OpenPage -> navigate(action.route) + is PaletteAction.SetTheme -> chooseTheme(action.theme) + } + } + + fun closeSettings() { + errorText = "" + password = "" + inviteCode = "" + } + + fun saveSettings() { + if (savingConnection) return + val rawURL = serverURL.trim().trimmingTrailingSlashes + val trimmedToken = token.trim() + val validUrl = try { + val u = java.net.URI(rawURL) + !u.host.isNullOrEmpty() && (u.scheme == "http" || u.scheme == "https") + } catch (_: Exception) { + false + } + if (!validUrl) { + errorText = "Enter a valid server URL." + return + } + val trimmedEmail = email.trim() + val enteredPassword = password + val signingUp = accountMode == AccountMode.SignUp + if (signingUp && !canCreateAccount(accountName, trimmedEmail, enteredPassword)) { + errorText = "Enter your name, email, and password." + return + } + if (enteredPassword.isEmpty() && trimmedToken.isEmpty()) { + errorText = "Enter your email and password." + return + } + // A session belongs to one server, so it never goes to a URL the owner just typed. + if (enteredPassword.isEmpty() && !signingUp && rawURL != client?.baseURL?.trimmingTrailingSlashes) { + errorText = "Enter your password to connect to this server." + return + } + val newName = accountName.trim() + val invite = inviteToken(inviteCode) + savingConnection = true + errorText = "" + scope.launch { + var created = false + try { + val session = when { + signingUp -> APIClient(rawURL, "", transport).signUp(newName, trimmedEmail, enteredPassword, invite).also { created = true } + enteredPassword.isEmpty() -> trimmedToken + else -> APIClient(rawURL, "", transport).signIn(trimmedEmail, enteredPassword) + } + val candidate = APIClient(rawURL, session, transport) + candidate.agents() + val replaced = client?.takeIf { it.token.isNotEmpty() && it.token != session } + // The server keeps one device row per installation, so this must land before the new session registers. + replaced?.let { old -> quietly { onSignOut(old) } } + credentials.write("server-token", session) + credentials.write("account-email", trimmedEmail) + credentials.write("server-url", rawURL) + token = session + resetConnectionState() + client = candidate + if (route == Route.General) route = null + showNotice("Connected") + refresh() + followActivity() + replaced?.let { old -> scope.launch { quietly { old.signOut() } } } + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + if (created) { + // The account and any invite are spent, so a retry must sign in rather than sign up. + resetAccountForm() + errorText = "Your account was created, but connecting failed: ${friendlyError(e)}" + } else { + errorText = friendlyError(e) + } + } finally { + savingConnection = false + } + } + } + + /** Ending a replaced session is best effort: it expires on its own, and the new one must still connect. */ + private suspend fun quietly(work: suspend () -> Unit) { + try { + work() + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + } + } + + /** Drops everything that belonged to the old session, so nothing carries over to the next one. */ + private fun resetConnectionState() { + cancelStream() + generation += 1 + pendingMutations = emptySet() + mutationRevision += 1 + activeRecords.clear() + settledRecords.clear() + resetPendingMessages() + resetGroupChats() + resetSecrets() + resetConnections() + resetAccountForm() + recentChats.clear() + attachmentBytes = emptyMap() + credentials.deletePrefixed(RECENT_CHAT_PREFIX) + forgetDrafts() + awaitingInitialSnapshot = false + activityFeed = ActivityFeedState() + agents = emptyList() + agentMemories = emptyMap() + memoryErrors = emptyMap() + memoryScope = null + sharedMemories = emptyList() + sharedSkills = emptyList() + agentSkills = emptyMap() + agentSkillErrors = emptyMap() + selectedSkills = emptySet() + bulkReport = emptyList() + checkingSkillUpdates = false + skillCheckFailures = emptyList() + skillInstall = null + installedSkill = null + skillUpdate = null + changes = emptyList() + showingChanges = false + changesLoading = false + changesHasMore = false + changesError = "" + avatarPage = AvatarPage() + schedules = emptyList() + schedulesLoaded = false + schedulesError = "" + showingBotDetails = false + showingPalette = false + themeSaving = false + accountTheme = theme + workingBots = emptySet() + desktopModels = emptyList() + executions = emptyList() + scriptRuns = emptyMap() + taskRunsLoading = false + taskRunsError = "" + taskTab = TaskTab.Tasks + capabilities = null + eventSources = emptyList() + eventSourcesLoaded = false + eventSourcesError = "" + deletingEventSources = emptySet() + eventSourceErrors = emptyMap() + eventSourceDraft = null + mcpServers = emptyList() + providers = emptyList() + models = emptyList() + signingIn = null + browserSignIn = null + agentDraft = null + memoryDraft = null + taskDraft = null + mcpDraft = null + skillDraft = null + snapshot = null + messages = emptyList() + activeRequests = 0 + loading = false + errorText = "" + selectedAgentID = "" + password = "" + onSessionReset() + } + + /** Ends the session here and on the server. The device forgets it even if the server can't be reached. */ + fun signOut() { + val api = client ?: return + if (signingOut || savingConnection) return + signingOut = true + errorText = "" + scope.launch { + try { + val revoked = try { + onSignOut(api) + api.signOut() + true + } catch (e: CancellationException) { + throw e + } catch (e: APIError) { + e.statusCode == 401 + } catch (_: Exception) { + false + } + credentials.delete("server-token") + credentials.delete("account-email") + resetConnectionState() + token = "" + email = "" + client = APIClient(api.baseURL, "", transport) + if (revoked) showNotice("Signed out") + else errorText = "Signed out of this device. The server couldn't be reached, so the session may stay active there." + } finally { + signingOut = false + } + } + } + + // MARK: Credentials and logins + + private fun secretMark(kind: String, botID: String) = secretRevisions["$kind:$botID"] ?: 0 + + private fun touchSecrets(kind: String, botID: String) { + secretRevisions["$kind:$botID"] = secretMark(kind, botID) + 1 + } + + /** Whether a read started at `mark` may replace local state: nothing changed since, and nothing is on its way. */ + private fun secretSettled(kind: String, botID: String, mark: Int): Boolean { + val prefix = if (botID.isEmpty()) "$kind:" else "$kind:$botID:" + return secretMark(kind, botID) == mark && pendingMutations.none { it.startsWith(prefix) } + } + + /** Typed secrets last only as long as the screen they were typed on. */ + private fun clearSecretDrafts() { + credentialForm = null + loginForm = null + tokenForm = null + providerKeyForm = null + clearConnectionDrafts() + secretUses = null + } + + private fun resetSecrets() { + clearSecretDrafts() + hideProviderLogin() + botCredentials = emptyMap() + botLogins = emptyMap() + credentialLoadErrors = emptyMap() + loginLoadErrors = emptyMap() + credentialScope = SKILLS_ALL + loginScope = SKILLS_ALL + freshSecretRequests = emptySet() + passwordManagers = emptyList() + passwordManagersLoaded = false + passwordManagersError = "" + providerAccounts = emptyList() + } + + private fun editSecrets(ops: SecretOps, botID: String, change: (D) -> D) { + val current = ops.lists()[botID] ?: return + ops.store(ops.lists() + (botID to change(current))) + } + + private fun loadSecretLists(ops: SecretOps) { + val revision = mutationRevision + request { api -> + val bots = api.agents() + val marks = bots.associate { it.id to secretMark(ops.kind, it.id) } + val loaded = coroutineScope { + bots.map { bot -> async { bot.id to attempt { ops.read(api, bot.id) } } }.awaitAll() + } + return@request { + if (settledSince(revision, BOT_RECORD)) loadAgentsForPanel() else applyBots(bots) + for ((id, result) in loaded) { + result.onSuccess { list -> + if (secretSettled(ops.kind, id, marks.getValue(id))) ops.store(ops.lists() + (id to list)) + } + } + ops.failures(loaded.mapNotNull { (id, result) -> result.exceptionOrNull()?.let { id to friendlyError(it) } }.toMap()) + } + } + } + + private fun reloadSecrets(ops: SecretOps, botID: String) { + val api = client ?: return + val gen = generation + val mark = secretMark(ops.kind, botID) + scope.launch { + attempt { ops.read(api, botID) }.onSuccess { list -> + if (generation == gen && secretSettled(ops.kind, botID, mark)) ops.store(ops.lists() + (botID to list)) + } + } + } + + // Restored requests must be followed again: the loop stops once none waits. + private fun resumeDecisions() { + if (route !is Route.AgentChat) return + decisionsKey = "" + followDecisions() + } + + private fun canSubmit(key: String): Boolean { + if (client == null) { + errorText = "Connect to your server in Settings." + return false + } + return key !in pendingMutations + } + + private fun submitSecret( + ops: SecretOps, + botID: String, + name: String, + /** The local change to show now, or null when the outcome must wait for a password manager. */ + provisional: ((D) -> D)?, + save: suspend (APIClient) -> I, + saved: (D, I) -> D, + confirmed: () -> Unit, + recover: (String) -> Unit, + ) { + val before = ops.lists()[botID] + optimisticMutation( + key = secretKey(ops.kind, botID, name), + update = { + touchSecrets(ops.kind, botID) + if (provisional != null) editSecrets(ops, botID, provisional) + }, + rollback = { + touchSecrets(ops.kind, botID) + if (provisional != null && before != null) editSecrets(ops, botID) { ops.restored(it, before, name) } + }, + fail = { + recover(it) + resumeDecisions() + }, work = { api -> - api.deleteProviderKey(currentProvider) + val item = save(api) return@optimisticMutation { - showNotice("Provider key removed") - loadProviders() + touchSecrets(ops.kind, botID) + editSecrets(ops, botID) { saved(it, item) } + confirmed() + reloadSecrets(ops, botID) } }, ) } + + private fun submitCredential(form: CredentialForm, confirmed: () -> Unit, recover: (String) -> Unit) { + val fields = credentialFields(form) + submitSecret( + ops = credentialOps, + botID = form.owner, + name = form.name, + provisional = if (form.readsPasswordManager) null else { list -> list.withCredential(provisionalCredential(form)) }, + save = { api -> api.saveCredential(form.owner, form.name, fields) }, + saved = { list, item -> list.withCredential(item) }, + confirmed = confirmed, + recover = recover, + ) + } + + fun openCredentialForm(botID: String?, existing: Credential? = null, request: CredentialRequest? = null) { + if (existing?.github == true) return + credentialForm = credentialForm(botID ?: credentialScope.takeIf { it != SKILLS_ALL }, agents, existing, request) + loadPasswordManagers() + } + + fun closeCredentialForm() { + credentialForm = null + } + + /** A plain value applies at once; a new password manager reference stays pending until Crumble has read it. */ + fun saveCredential() { + val form = credentialForm ?: return + if (!form.ready || !canSubmit(secretKey("credential", form.owner, form.name))) return + val waits = form.readsPasswordManager + val from = route + credentialForm = if (waits) form.copy(saving = true, error = "") else null + val open = { credentialForm?.let { it.saving && it.owner == form.owner && it.name == form.name } == true } + submitCredential( + form, + confirmed = { if (open()) credentialForm = null }, + recover = { message -> + val reopen = !waits && credentialForm == null && loginForm == null && route == from + if (open() || reopen) credentialForm = form.copy(error = message) else errorText = message + }, + ) + } + + fun openLoginForm(botID: String?, existing: Login? = null, request: LoginRequest? = null) { + loginForm = loginForm(botID ?: loginScope.takeIf { it != SKILLS_ALL }, agents, existing, request) + loadPasswordManagers() + } + + fun closeLoginForm() { + loginForm = null + } + + fun saveLogin() { + val form = loginForm ?: return + if (!form.ready || !canSubmit(secretKey("login", form.owner, form.name))) return + val waits = form.readsPasswordManager + val from = route + val fields = loginFields(form) + loginForm = if (waits) form.copy(saving = true, error = "") else null + val open = { loginForm?.let { it.saving && it.owner == form.owner && it.name == form.name } == true } + submitSecret( + ops = loginOps, + botID = form.owner, + name = form.name, + provisional = if (waits) null else { list -> list.withLogin(provisionalLogin(form)) }, + save = { api -> api.saveLogin(form.owner, form.name, fields) }, + saved = { list, item -> list.withLogin(item) }, + confirmed = { if (open()) loginForm = null }, + recover = { message -> + val reopen = !waits && credentialForm == null && loginForm == null && route == from + if (open() || reopen) loginForm = form.copy(error = message) else errorText = message + }, + ) + } + + private fun changeSecret( + ops: SecretOps, + botID: String, + name: String, + change: (D, String) -> D, + call: suspend (APIClient, String, String) -> Unit, + ) { + val key = secretKey(ops.kind, botID, name) + val before = ops.lists()[botID] + optimisticMutation( + key = key, + update = { + touchSecrets(ops.kind, botID) + decisionErrors = decisionErrors - key + editSecrets(ops, botID) { change(it, name) } + }, + rollback = { + touchSecrets(ops.kind, botID) + if (before != null) editSecrets(ops, botID) { ops.restored(it, before, name) } + }, + fail = { message -> + if (route == Route.AgentChat(botID)) decisionErrors = decisionErrors + (key to message) else errorText = message + resumeDecisions() + }, + work = { api -> + call(api, botID, name) + return@optimisticMutation { + touchSecrets(ops.kind, botID) + reloadSecrets(ops, botID) + } + }, + ) + } + + fun deleteCredential(botID: String, name: String) { + if (botCredentials[botID]?.credentials?.any { it.name == name && it.github } == true) return + changeSecret(credentialOps, botID, name, credentialOps.withoutItem, credentialOps.delete) + } + + fun deleteLogin(botID: String, name: String) = changeSecret(loginOps, botID, name, loginOps.withoutItem, loginOps.delete) + + // Never a delete: a saved item and a request for more under its name can coexist. + fun declineCredentialRequest(botID: String, name: String) = + changeSecret(credentialOps, botID, name, credentialOps.withoutRequest, credentialOps.decline) + + fun declineLoginRequest(botID: String, name: String) = + changeSecret(loginOps, botID, name, loginOps.withoutRequest, loginOps.decline) + + fun openBotCredentials(botID: String) { + agentDraft = null + credentialScope = botID + navigate(Route.Credentials) + } + + fun openSecretUses(kind: SecretKind, botID: String, name: String) { + secretUses = SecretUsesView(kind, botID, name) + fetchSecretUses(null) + } + + fun closeSecretUses() { + secretUses = null + } + + fun loadMoreSecretUses() { + val view = secretUses ?: return + if (view.loading || view.loadingMore) return + secretUses = view.copy(loadingMore = true, error = "") + fetchSecretUses(view.rows.lastOrNull()?.id) + } + + private fun fetchSecretUses(before: String?) { + val view = secretUses ?: return + val api = client ?: return + val gen = generation + scope.launch { + val page = attempt { + when (view.kind) { + SecretKind.credential -> api.credentialUses(view.botID, view.name, before).map { it.row() } + SecretKind.login -> api.loginUses(view.botID, view.name, before).map { it.row() } + } + } + val current = secretUses?.takeIf { generation == gen && it.id == view.id } ?: return@launch + secretUses = page.fold( + onSuccess = { + current.copy(rows = current.rows + it, loading = false, loadingMore = false, hasMore = it.size == SECRET_USES_PAGE) + }, + onFailure = { current.copy(loading = false, loadingMore = false, error = friendlyError(it)) }, + ) + } + } + + // MARK: Password managers + + val connectedManagers: List get() = passwordManagers.filter { it.connected } + + fun loadPasswordManagers() { + val api = client ?: return + val gen = generation + val mark = secretMark("password-manager", "") + scope.launch { + val loaded = attempt { api.passwordManagers() } + if (generation != gen) return@launch + loaded.fold( + onSuccess = { + if (secretSettled("password-manager", "", mark)) passwordManagers = it + passwordManagersLoaded = true + passwordManagersError = "" + }, + onFailure = { passwordManagersError = friendlyError(it) }, + ) + } + } + + fun openManagerToken(manager: PasswordManager) { + tokenForm = ManagerTokenForm(manager) + } + + fun closeManagerToken() { + tokenForm = null + } + + private fun editManager(id: String, change: (PasswordManager) -> PasswordManager) { + passwordManagers = passwordManagers.map { if (it.id == id) change(it) else it } + } + + /** Crumble signs in to check the token, so this stays pending until the password manager has answered. */ + fun saveManagerToken() { + val form = tokenForm ?: return + val id = form.manager.id + val key = "password-manager:$id" + if (!form.ready || !canSubmit(key)) return + val token = form.token.text.trim() + tokenForm = form.copy(saving = true, error = "") + val open = { tokenForm?.let { it.saving && it.manager.id == id } == true } + optimisticMutation( + key = key, + update = { touchSecrets("password-manager", "") }, + rollback = { touchSecrets("password-manager", "") }, + fail = { message -> if (open()) tokenForm = form.copy(error = message) else errorText = message }, + work = { api -> + val saved = api.connectPasswordManager(id, token) + return@optimisticMutation { + touchSecrets("password-manager", "") + editManager(id) { saved } + if (open()) tokenForm = null + loadPasswordManagers() + } + }, + ) + } + + fun disconnectManager(manager: PasswordManager) { + val key = "password-manager:${manager.id}" + if (manager.usedBy.isNotEmpty()) return + optimisticMutation( + key = key, + update = { + touchSecrets("password-manager", "") + editManager(manager.id) { it.copy(connected = false, connectedAt = null) } + }, + rollback = { + touchSecrets("password-manager", "") + editManager(manager.id) { manager } + }, + work = { api -> + api.disconnectPasswordManager(manager.id) + return@optimisticMutation { + touchSecrets("password-manager", "") + loadPasswordManagers() + } + }, + ) + } + + // MARK: Connections + + var githubApps by mutableStateOf(Remote>()) + var githubAccounts by mutableStateOf(Remote>()) + var serverSettings by mutableStateOf(Remote()) + /** Null until `/v1/admin/settings` answers; only admins may read it. */ + var isAdmin by mutableStateOf(null) + var gateways by mutableStateOf(Remote>()) + var gatewayForm by mutableStateOf(null) + var eventRelay by mutableStateOf(Remote()) + var relayDraft by mutableStateOf("") + var relaySaving by mutableStateOf(false) + var pluginSettings by mutableStateOf(Remote()) + var pluginForm by mutableStateOf(null) + var webSearch by mutableStateOf(Remote()) + var judgeModel by mutableStateOf(Remote()) + var visionModel by mutableStateOf(Remote()) + var createAppForm by mutableStateOf(null) + var githubAppForm by mutableStateOf(null) + var addAccountForm by mutableStateOf(null) + var githubAccountForm by mutableStateOf(null) + var serverSettingsForm by mutableStateOf(null) + var githubFlow by mutableStateOf(null) + + private fun clearConnectionDrafts() { + pluginForm = null + addAccountForm = null + githubAccountForm = null + githubAppForm = null + mcpDraft = null + inviteSheet = null + } + + private fun resetConnections() { + clearConnectionDrafts() + githubApps = Remote() + githubAccounts = Remote() + serverSettings = Remote() + isAdmin = null + gateways = Remote() + gatewayForm = null + eventRelay = Remote() + relayDraft = "" + relaySaving = false + pluginSettings = Remote() + webSearch = Remote() + judgeModel = Remote() + visionModel = Remote() + createAppForm = null + serverSettingsForm = null + githubFlow = null + accountID = null + adminUsers = Remote() + invites = Remote() + outdatedWorkspaces = Remote() + } + + /** Newest read wins, and no read replaces a change that's on its way. */ + private fun loadRemote(kind: String, get: () -> Remote, set: (Remote) -> Unit, work: suspend (APIClient) -> T) { + touchSecrets(kind, "") + val mark = secretMark(kind, "") + confirmed( + start = {}, + work = work, + finish = { result -> + result.fold( + onSuccess = { if (secretSettled(kind, "", mark)) set(Remote(it, failure = get().failure)) }, + onFailure = { if (secretMark(kind, "") == mark) set(get().copy(error = friendlyError(it))) }, + ) + }, + ) + } + + private fun recordChange( + kind: String, + key: String, + update: () -> Unit, + rollback: () -> Unit, + fail: (String) -> Unit = { errorText = it }, + work: suspend (APIClient) -> (() -> Unit), + ) = optimisticMutation( + key = "$kind:$key", + update = { + touchSecrets(kind, "") + update() + }, + rollback = { + touchSecrets(kind, "") + rollback() + }, + fail = fail, + work = { api -> + val confirm = work(api) + val done: () -> Unit = { + touchSecrets(kind, "") + confirm() + } + done + }, + ) + + fun loadWebSearch() = loadRemote("web-search", { webSearch }, { webSearch = it }) { it.webSearch() } + + fun loadJudgeModel() = loadRemote("judge", { judgeModel }, { judgeModel = it }) { it.judgeModel() } + + fun loadVisionModel() = loadRemote("vision", { visionModel }, { visionModel = it }) { it.visionModel() } + + fun loadPluginSettings() = loadRemote("plugin", { pluginSettings }, { pluginSettings = it }) { it.pluginSettings() } + + fun loadGateways() = loadRemote("gateway", { gateways }, { + gateways = it + seedGatewayForm() + }) { it.messageGateways() } + + fun loadRelay() = loadRemote("relay", { eventRelay }, { next -> + val saved = eventRelay.value?.url.orEmpty() + eventRelay = next + // A typed address survives a refresh; one the owner hasn't touched follows the server. + if (relayDraft == saved) relayDraft = next.value?.url.orEmpty() + }) { it.eventRelay() } + + fun loadGitHub() { + loadRemote("github-app", { githubApps }, { githubApps = it }) { it.githubApps() } + loadRemote("github-account", { githubAccounts }, { githubAccounts = it }) { it.githubAccounts() } + } + + private fun loadCoding() { + loadAgentsForPanel() + loadCapabilities() + loadPasswordManagers() + loadGitHub() + touchSecrets("server-settings", "") + val mark = secretMark("server-settings", "") + confirmed( + start = {}, + work = { api -> api.serverSettings() }, + finish = { result -> + result.fold( + onSuccess = { + isAdmin = true + if (secretSettled("server-settings", "", mark)) serverSettings = Remote(it) + loadOutdatedWorkspaces() + loadAdminUsers() + }, + onFailure = { + if ((it as? APIError)?.statusCode == 403) { + isAdmin = false + } else { + serverSettings = serverSettings.copy(error = friendlyError(it)) + } + }, + ) + }, + ) + } + + private fun loadAgentsForPanel() { + val revision = mutationRevision + request { api -> + val loaded = api.agents() + return@request { + if (settledSince(revision, BOT_RECORD)) loadAgentsForPanel() else applyBots(loaded) + } + } + } + + // MARK: Model choices + + fun chooseJudgeModel(value: String) { + val data = judgeModel.value ?: return + val choice = judgeChoice(data, value) + if (value == judgeValue(data) || (choice == null && value != JUDGE_DEFAULT)) return + val chosen = choice?.let { JudgeModelJudgeModel(it.provider, it.model) } + recordChange( + "judge", "model", + update = { judgeModel = Remote(data.copy(judgeModel = chosen, effective = choice ?: data.effective)) }, + rollback = { judgeModel = Remote(data) }, + fail = { judgeModel = judgeModel.copy(failure = it) }, + ) { api -> + val saved = api.updateJudgeModel(chosen?.provider, chosen?.model) + return@recordChange { judgeModel = Remote(saved) } + } + } + + fun chooseVisionModel(value: String) { + val data = visionModel.value ?: return + val choice = visionChoice(data, value) + if (value == visionValue(data) || (choice == null && value != VISION_OFF)) return + val chosen = choice?.let { VisionModelVisionModel(it.provider, it.model) } + recordChange( + "vision", "model", + update = { visionModel = Remote(data.copy(visionModel = chosen)) }, + rollback = { visionModel = Remote(data) }, + fail = { visionModel = visionModel.copy(failure = it) }, + ) { api -> + val saved = api.updateVisionModel(chosen?.provider, chosen?.model) + return@recordChange { visionModel = Remote(saved) } + } + } + + fun chooseWebSearchProvider(provider: String) { + val data = webSearch.value ?: return + if (provider == data.defaultProvider) return + recordChange( + "web-search", "default", + update = { webSearch = Remote(data.copy(defaultProvider = provider)) }, + rollback = { webSearch = Remote(data) }, + fail = { webSearch = webSearch.copy(failure = it) }, + ) { api -> + val saved = api.updateWebSearch(provider) + return@recordChange { webSearch = Remote(saved) } + } + } + + // MARK: Plugin settings + + private fun editPluginSetting(pluginID: String, key: String, change: (PluginSetting) -> PluginSetting) { + val data = pluginSettings.value ?: return + val plugins = data.plugins.map { plugin -> + if (plugin.id != pluginID) plugin else plugin.copy(settings = plugin.settings.map { if (it.key == key) change(it) else it }) + } + pluginSettings = pluginSettings.copy(value = data.copy(plugins = plugins)) + } + + // These pages' own status depends on the plugin's secrets. + private fun refreshAfterPluginChange() { + loadPluginSettings() + loadPasswordManagers() + when (route) { + Route.WebSearch -> loadWebSearch() + Route.EventRelay -> loadRelay() + is Route.MessageGateway -> loadGateways() + else -> Unit + } + } + + fun openPluginSetting(row: PluginRow) { + pluginForm = PluginSecretForm(row.pluginID, row.setting, secretDraft(row.setting.secret)) + loadPasswordManagers() + } + + fun closePluginSetting() { + pluginForm = null + } + + fun savePluginSetting() { + val form = pluginForm ?: return + val input = form.secret.input ?: return + val pluginID = form.pluginID + val setting = form.setting + val key = "$pluginID:${setting.key}" + if (!form.secret.changed || form.saving || !canSubmit("plugin:$key")) return + val waits = input is SecretInput.Reference + val from = route + pluginForm = if (waits) form.copy(saving = true, error = "") else null + val open = { pluginForm?.let { it.saving && it.pluginID == pluginID && it.setting.key == setting.key } == true } + recordChange( + "plugin", key, + update = { if (!waits) editPluginSetting(pluginID, setting.key) { it.copy(secret = STORED) } }, + rollback = { if (!waits) editPluginSetting(pluginID, setting.key) { setting } }, + fail = { message -> + val reopen = !waits && pluginForm == null && route == from + if (open() || reopen) pluginForm = form.copy(saving = false, error = message) else errorText = message + }, + ) { api -> + val saved = api.setPluginSetting(pluginID, setting.key, input) + return@recordChange { + editPluginSetting(pluginID, setting.key) { saved } + if (open()) pluginForm = null + refreshAfterPluginChange() + } + } + } + + fun removePluginSetting(row: PluginRow) { + val setting = row.setting + recordChange( + "plugin", "${row.pluginID}:${setting.key}", + update = { editPluginSetting(row.pluginID, setting.key) { it.copy(secret = SecretStatus(false, null, null)) } }, + rollback = { editPluginSetting(row.pluginID, setting.key) { setting } }, + ) { api -> + val saved = api.deletePluginSetting(row.pluginID, setting.key) + return@recordChange { + editPluginSetting(row.pluginID, setting.key) { saved } + refreshAfterPluginChange() + } + } + } + + // MARK: Event relay + + /** The relay decides whether the address works, so its answer is the only status shown. */ + fun saveRelay() { + val next = relayDraft.trim().ifEmpty { null } + if (relaySaving || next == eventRelay.value?.url) return + confirmed( + start = { + relaySaving = true + eventRelay = eventRelay.copy(failure = "") + }, + work = { api -> api.updateEventRelay(next) }, + finish = { result -> + relaySaving = false + result.fold( + onSuccess = { saved -> + touchSecrets("relay", "") + eventRelay = Remote(saved) + if (relayDraft.trim().ifEmpty { null } == next) relayDraft = saved.url.orEmpty() + }, + onFailure = { eventRelay = eventRelay.copy(failure = friendlyError(it)) }, + ) + }, + ) + } + + // MARK: Message gateways + + private fun seedGatewayForm() { + val id = (route as? Route.MessageGateway)?.id ?: return + if (gatewayForm?.gatewayID == id) return + gateways.value?.firstOrNull { it.id == id }?.let { gatewayForm = gatewayForm(id, it.config) } + } + + private fun editGateway(id: String, change: (MessageGateway) -> MessageGateway) { + val list = gateways.value ?: return + gateways = gateways.copy(value = list.map { if (it.id == id) change(it) else it }) + } + + fun resetGatewayForm() { + val form = gatewayForm ?: return + gateways.value?.firstOrNull { it.id == form.gatewayID }?.let { gatewayForm = gatewayForm(it.id, it.config) } + } + + fun saveGateway() { + val form = gatewayForm ?: return + val id = form.gatewayID + val config = form.config() + val before = gateways.value?.firstOrNull { it.id == id } ?: return + if (form.saving) return + gatewayForm = form.copy(attempted = true, saved = false, error = "") + if (gatewayErrors(config, agents.map { it.id }.toSet()).isNotEmpty() || !canSubmit("gateway:$id")) return + val current = { gatewayForm?.takeIf { it.gatewayID == id } } + recordChange( + "gateway", id, + update = { + current()?.let { gatewayForm = it.copy(saving = true) } + editGateway(id) { it.copy(config = config) } + }, + rollback = { editGateway(id) { before } }, + fail = { message -> + val open = current() + if (open != null) gatewayForm = open.copy(saving = false, error = message) else errorText = message + }, + ) { api -> + val saved = api.updateMessageGateway(id, config) + return@recordChange { + editGateway(id) { saved } + // Edits made while this was saving stay in the form. + current()?.let { open -> + gatewayForm = if (open.config() == config) gatewayForm(id, saved.config).copy(saved = true) else open.copy(saving = false) + } + loadGateways() + } + } + } + + // MARK: GitHub Apps + + private fun apps() = githubApps.value.orEmpty() + + private fun accounts() = githubAccounts.value.orEmpty() + + private fun storeApp(app: GitHubApp) { + githubApps = githubApps.copy(value = upserted(apps(), app.id, app) { it.id }) + } + + private fun storeAccount(account: GitHubAccount) { + githubAccounts = githubAccounts.copy(value = upserted(accounts(), account.id, account) { it.id }) + } + + private fun appForm(id: String) = githubAppForm?.takeIf { it.appID == id } + + private fun editAppForm(id: String, change: (GitHubAppForm) -> GitHubAppForm) { + appForm(id)?.let { githubAppForm = change(it) } + } + + fun openCreateApp() { + createAppForm = CreateGitHubAppForm() + } + + fun closeCreateApp() { + if (createAppForm?.saving != true) createAppForm = null + } + + /** GitHub creates an App only from a form post with the manifest, so its page opens inside the app. */ + fun createGitHubApp() { + val form = createAppForm ?: return + val origin = client?.baseURL?.let(::webOrigin) ?: return + if (!form.ready) return + confirmed( + start = { createAppForm = form.copy(saving = true, error = "") }, + work = { api -> api.createGithubAppManifest(form.name.trim(), origin, form.organization.trim().nilIfEmpty) }, + finish = { result -> + result.fold( + onSuccess = { + createAppForm = null + githubFlow = GitHubFlow(GitHubStep.created, it.url, manifest = it.manifest) + }, + onFailure = { createAppForm = createAppForm?.copy(saving = false, error = friendlyError(it)) }, + ) + }, + ) + } + + fun installGitHubApp(app: GitHubApp) { + if (isWebLink(app.installUrl)) githubFlow = GitHubFlow(GitHubStep.installed, app.installUrl, appID = app.id) + } + + fun signInToGitHubApp(app: GitHubApp) { + val origin = client?.baseURL?.let(::webOrigin) ?: return + confirmed( + start = { editAppForm(app.id) { it.copy(signingIn = true, signInError = "") } }, + work = { api -> api.signInGithubApp(app.id, origin) }, + finish = { result -> + editAppForm(app.id) { it.copy(signingIn = false, signInError = result.exceptionOrNull()?.let(::friendlyError).orEmpty()) } + result.onSuccess { url -> if (isWebLink(url)) githubFlow = GitHubFlow(GitHubStep.authorized, url, appID = app.id) } + }, + ) + } + + fun closeGitHubFlow() { + githubFlow = null + } + + /** GitHub sent the owner back; the App counts only once the server has confirmed it. */ + fun finishGitHubFlow(url: String) { + val flow = githubFlow ?: return + if (flow.finishing) return + confirmed( + start = { githubFlow = flow.copy(finishing = true, error = "") }, + work = { api -> + when (flow.step) { + GitHubStep.installed -> api.connectGithubApp(checkNotNull(flow.appID)) + GitHubStep.created -> oauthResult(url).let { api.completeGithubApp(it.code, it.state) } + GitHubStep.authorized -> oauthResult(url).let { api.completeGithubAppSignIn(it.code, it.state) } + } + }, + finish = { result -> + result.onSuccess { + storeApp(it) + loadGitHub() + } + if (githubFlow?.id == flow.id) { + githubFlow = result.fold({ null }, { flow.copy(error = friendlyError(it)) }) + } + }, + ) + } + + fun openGitHubApp(app: GitHubApp) { + githubAppForm = GitHubAppForm(app.id, app.botIds, secretDraft(app.clientSecret)) + loadPasswordManagers() + } + + fun closeGitHubApp() { + githubAppForm = null + } + + fun saveGitHubAppBots() { + val form = githubAppForm ?: return + val before = apps().firstOrNull { it.id == form.appID } ?: return + val from = route + if (!canSubmit("github-app:${form.appID}")) return + githubAppForm = null + recordChange( + "github-app", form.appID, + update = { storeApp(before.copy(botIds = form.botIDs)) }, + rollback = { storeApp(before) }, + fail = { message -> + if (githubAppForm == null && route == from) githubAppForm = form.copy(error = message) else errorText = message + }, + ) { api -> + val saved = api.setGithubAppBots(form.appID, form.botIDs) + return@recordChange { + storeApp(saved) + // A bot uses one App per GitHub account, so the server may have moved it off another. + loadGitHub() + } + } + } + + fun deleteGitHubApp(app: GitHubApp) { + val before = apps() + recordChange( + "github-app", app.id, + update = { githubApps = githubApps.copy(value = before.filterNot { it.id == app.id }) }, + rollback = { githubApps = githubApps.copy(value = recordRestored(apps(), before, app.id) { it.id }) }, + ) { api -> + api.deleteGithubApp(app.id) + return@recordChange { loadGitHub() } + } + } + + fun checkGitHubApp(id: String) { + confirmed( + start = { editAppForm(id) { it.copy(checking = true, checkError = "") } }, + work = { api -> api.connectGithubApp(id) }, + finish = { result -> + result.onSuccess(::storeApp) + editAppForm(id) { it.copy(checking = false, checkError = result.exceptionOrNull()?.let(::friendlyError).orEmpty()) } + }, + ) + } + + fun saveGitHubClientSecret() { + val form = githubAppForm ?: return + val id = form.appID + val input = form.clientSecret.input?.takeIf { form.clientSecret.changed } ?: return + if (form.savingSecret) return + confirmed( + start = { githubAppForm = form.copy(savingSecret = true, secretError = "") }, + work = { api -> api.setGithubAppClientSecret(id, input) }, + finish = { result -> + result.onSuccess { saved -> + storeApp(saved) + loadPasswordManagers() + } + editAppForm(id) { open -> + result.fold( + { saved -> open.copy(savingSecret = false, clientSecret = secretDraft(saved.clientSecret)) }, + { open.copy(savingSecret = false, secretError = friendlyError(it)) }, + ) + } + }, + ) + } + + fun signOutOfGitHubApp(id: String) { + confirmed( + start = { editAppForm(id) { it.copy(signingOut = true, signInError = "") } }, + work = { api -> api.signOutGithubApp(id) }, + finish = { result -> + result.onSuccess(::storeApp) + editAppForm(id) { it.copy(signingOut = false, signInError = result.exceptionOrNull()?.let(::friendlyError).orEmpty()) } + }, + ) + } + + // MARK: Machine accounts + + fun openAddAccount() { + addAccountForm = AddGitHubAccountForm() + loadPasswordManagers() + } + + fun closeAddAccount() { + addAccountForm = null + } + + /** GitHub vouches for the token, so the account appears when the server has read it. */ + fun addGitHubAccount() { + val form = addAccountForm ?: return + val input = form.token.input ?: return + if (form.saving) return + confirmed( + start = { addAccountForm = form.copy(saving = true, error = "") }, + work = { api -> api.addGithubAccount(input) }, + finish = { result -> + result.fold( + onSuccess = { + storeAccount(it) + addAccountForm = null + loadGitHub() + loadPasswordManagers() + }, + onFailure = { failure -> addAccountForm = addAccountForm?.copy(saving = false, error = friendlyError(failure)) }, + ) + }, + ) + } + + fun openGitHubAccount(account: GitHubAccount) { + githubAccountForm = GitHubAccountForm(account.id, account.botIds, secretDraft(account.token)) + loadPasswordManagers() + } + + fun closeGitHubAccount() { + githubAccountForm = null + } + + fun saveGitHubAccount() { + val form = githubAccountForm ?: return + val before = accounts().firstOrNull { it.id == form.accountID } ?: return + val token = form.token.input?.takeIf { form.token.changed } + if (form.saving) return + if (token == null) return saveAccountBots(form, before) + val id = form.accountID + confirmed( + start = { githubAccountForm = form.copy(saving = true, error = "") }, + work = { api -> + val replaced = api.setGithubAccountToken(id, token) + replaced to attempt { api.setGithubAccountBots(id, form.botIDs) } + }, + finish = { result -> + val replaced = result.getOrNull()?.first + replaced?.let(::storeAccount) + val failure = result.exceptionOrNull() ?: result.getOrNull()?.second?.exceptionOrNull() + val open = githubAccountForm?.takeIf { it.accountID == id } + when { + failure == null -> { + result.getOrNull()?.second?.getOrNull()?.let(::storeAccount) + if (open != null) githubAccountForm = null + loadGitHub() + } + // A saved token isn't sent again when the owner retries the bots. + open != null -> githubAccountForm = open.copy( + saving = false, + error = friendlyError(failure), + token = replaced?.let { secretDraft(it.token) } ?: open.token, + ) + else -> errorText = friendlyError(failure) + } + if (replaced != null) loadPasswordManagers() + }, + ) + } + + private fun saveAccountBots(form: GitHubAccountForm, before: GitHubAccount) { + val from = route + if (!canSubmit("github-account:${form.accountID}")) return + githubAccountForm = null + recordChange( + "github-account", form.accountID, + update = { storeAccount(before.copy(botIds = form.botIDs)) }, + rollback = { storeAccount(before) }, + fail = { message -> + if (githubAccountForm == null && route == from) githubAccountForm = form.copy(error = message) else errorText = message + }, + ) { api -> + val saved = api.setGithubAccountBots(form.accountID, form.botIDs) + return@recordChange { + storeAccount(saved) + loadGitHub() + } + } + } + + fun deleteGitHubAccount(account: GitHubAccount) { + val before = accounts() + recordChange( + "github-account", account.id, + update = { githubAccounts = githubAccounts.copy(value = before.filterNot { it.id == account.id }) }, + rollback = { githubAccounts = githubAccounts.copy(value = recordRestored(accounts(), before, account.id) { it.id }) }, + ) { api -> + api.deleteGithubAccount(account.id) + return@recordChange { loadGitHub() } + } + } + + // MARK: Workspaces + + fun openServerSettings(field: WorkspaceField) { + serverSettings.value?.let { serverSettingsForm = serverSettingsForm(field, it) } + } + + fun saveServerSettings() { + val form = serverSettingsForm ?: return + val before = serverSettings.value ?: return + val patch = form.patch() ?: return + val from = route + if (!canSubmit("server-settings:patch")) return + serverSettingsForm = null + recordChange( + "server-settings", "patch", + update = { serverSettings = Remote(before.patched(form)) }, + rollback = { serverSettings = Remote(before) }, + fail = { message -> + if (serverSettingsForm == null && route == from) serverSettingsForm = form.copy(error = message) else errorText = message + }, + ) { api -> + val saved = api.updateServerSettings(patch) + return@recordChange { + serverSettings = Remote(saved) + loadOutdatedWorkspaces() + } + } + } + + // MARK: Users + + var accountMode by mutableStateOf(AccountMode.SignIn) + var accountName by mutableStateOf("") + var inviteCode by mutableStateOf("") + /** Null until the session answers; the rows of an unknown account offer no actions. */ + var accountID by mutableStateOf(null) + var adminUsers by mutableStateOf(Remote>()) + var invites by mutableStateOf(Remote>()) + var outdatedWorkspaces by mutableStateOf(Remote>()) + var inviteSheet by mutableStateOf(null) + private var inviteAttempt = 0 + + fun switchAccountMode() { + accountMode = if (accountMode == AccountMode.SignIn) AccountMode.SignUp else AccountMode.SignIn + errorText = "" + } + + private fun resetAccountForm() { + accountMode = AccountMode.SignIn + accountName = "" + inviteCode = "" + } + + private fun loadAccount(then: () -> Unit = {}) { + if (client == null) return + val changes = themeChanges + confirmed( + start = {}, + work = { api -> api.accountSession() }, + finish = { result -> + result.fold( + onSuccess = { + accountID = it.id + isAdmin = it.admin + // The account's theme wins unless the owner chose one since this read began. + ThemeChoice.of(it.theme)?.takeIf { changes == themeChanges && !themeSaving }?.let { saved -> + accountTheme = saved + if (saved != theme) adoptTheme(saved) + } + then() + }, + onFailure = { adminUsers = adminUsers.copy(error = friendlyError(it)) }, + ) + }, + ) + } + + private fun loadUsers() = loadAccount { + if (isAdmin == true) { + loadAdminUsers() + loadInvites() + loadRemote("server-settings", { serverSettings }, { serverSettings = it }) { it.serverSettings() } + } + } + + private fun loadAdminUsers() = loadRemote("admin-user", { adminUsers }, { adminUsers = it }) { it.adminUsers() } + + private fun loadInvites() = loadRemote("admin-invite", { invites }, { invites = it }) { it.invites() } + + private fun loadOutdatedWorkspaces() = + loadRemote("outdated-workspace", { outdatedWorkspaces }, { outdatedWorkspaces = it }) { it.outdatedWorkspaces() } + + private fun editUsers(change: (List) -> List) { + adminUsers = Remote(adminUsers.value?.let(change), error = adminUsers.error) + } + + private fun failUsers(message: String) { + adminUsers = adminUsers.copy(failure = message) + loadAdminUsers() + } + + fun setUserRole(user: AdminUser, role: String) { + val assign = { next: String -> + editUsers { users -> users.map { if (it.id == user.id) it.copy(role = next) else it } } + } + recordChange( + "admin-user", user.id, + update = { assign(role) }, + rollback = { assign(user.role) }, + fail = ::failUsers, + ) { api -> + val saved = api.setUserRole(user.id, role) + return@recordChange { editUsers { users -> users.map { if (it.id == saved.id) saved else it } } } + } + } + + fun removeUser(user: AdminUser) { + recordChange( + "admin-user", user.id, + update = { editUsers { users -> users.filter { it.id != user.id } } }, + rollback = { editUsers { users -> (users + user).sortedBy { it.createdAt } } }, + fail = ::failUsers, + ) { api -> + api.removeUser(user.id) + return@recordChange {} + } + } + + fun revokeInvite(invite: Invite) { + val edit = { change: (List) -> List -> + invites = Remote(invites.value?.let(change), error = invites.error) + } + recordChange( + "admin-invite", invite.id, + update = { edit { rows -> rows.filter { it.id != invite.id } } }, + rollback = { edit { rows -> (rows + invite).sortedByDescending { it.createdAt } } }, + fail = { message -> + invites = invites.copy(failure = message) + loadInvites() + }, + ) { api -> + api.revokeInvite(invite.id) + return@recordChange {} + } + } + + /** Mints one link per request: the server shows it once, so nothing here retries on its own. */ + fun createInvite() { + inviteAttempt += 1 + val attempt = inviteAttempt + confirmed( + start = { inviteSheet = InviteSheet() }, + work = { api -> api.createInvite() }, + finish = { result -> + val waiting = attempt == inviteAttempt && inviteSheet != null + result.fold( + onSuccess = { + if (waiting) inviteSheet = InviteSheet(url = it.url) + loadInvites() + }, + onFailure = { + val message = friendlyError(it) + if (waiting) inviteSheet = InviteSheet(error = message) else invites = invites.copy(failure = message) + }, + ) + }, + ) + } + + fun closeInviteSheet() { + inviteSheet = null + loadInvites() + } + + /** Shares the settings slot and key with the workspace sheet, so neither change overwrites the other. */ + fun setSignUpOpen(open: Boolean) { + val before = serverSettings.value ?: return + recordChange( + "server-settings", "patch", + update = { serverSettings = Remote(before.copy(signUpOpen = open)) }, + rollback = { serverSettings = Remote(before) }, + fail = { serverSettings = serverSettings.copy(failure = it) }, + ) { api -> + val saved = api.updateServerSettings(UpdateServerSettingsRequest(signUpOpen = OptionalField.Present(open))) + return@recordChange { serverSettings = Remote(saved) } + } + } + + // MARK: Provider accounts + + private fun refreshProviders() { + loadProviders() + } + + private fun editProvider(id: String, change: (Provider) -> Provider) { + providerAccounts = providerAccounts.map { if (it.provider == id) change(it) else it } + } + + fun openProviderKey(provider: Provider) { + providerKeyForm = ProviderKeyForm(provider, secretDraft(provider.apiKey)) + loadPasswordManagers() + } + + fun closeProviderKey() { + providerKeyForm = null + } + + fun saveProviderAccountKey() { + val form = providerKeyForm ?: return + val input = form.key.input ?: return + val id = form.provider.provider + val key = "provider:$id" + if (!form.key.changed || form.saving || !canSubmit(key)) return + val waits = input is SecretInput.Reference + val from = route + val before = providerAccounts.firstOrNull { it.provider == id } + providerKeyForm = if (waits) form.copy(saving = true, error = "") else null + val open = { providerKeyForm?.let { it.saving && it.provider.provider == id } == true } + optimisticMutation( + key = key, + update = { + touchSecrets("provider", "") + if (!waits) editProvider(id) { it.withKey() } + }, + rollback = { + touchSecrets("provider", "") + if (!waits && before != null) editProvider(id) { before } + }, + fail = { message -> + val reopen = !waits && providerKeyForm == null && route == from + if (open() || reopen) providerKeyForm = form.copy(error = message) else errorText = message + }, + work = { api -> + api.setProviderKey(id, input) + return@optimisticMutation { + touchSecrets("provider", "") + if (open()) providerKeyForm = null + refreshProviders() + } + }, + ) + } + + /** Removes the provider's key or signs it out; the server holds only one credential per provider. */ + fun removeProviderCredential(provider: Provider) { + val id = provider.provider + optimisticMutation( + key = "provider:$id", + update = { + touchSecrets("provider", "") + editProvider(id) { it.withoutCredential() } + }, + rollback = { + touchSecrets("provider", "") + editProvider(id) { provider } + }, + work = { api -> + api.deleteProviderKey(id) + return@optimisticMutation { + touchSecrets("provider", "") + refreshProviders() + } + }, + ) + } + + fun openProviderLogin(provider: Provider) { + providerLoginJob?.cancel() + providerLogin = ProviderLoginView(provider, sessionID = provider.activeLoginId) + provider.activeLoginId?.let(::followProviderLogin) + } + + /** The sign-in keeps going on the server; the row offers to continue it. */ + fun hideProviderLogin() { + providerLoginJob?.cancel() + providerLoginJob = null + providerLogin = null + } + + private fun ProviderLoginView.showing(next: ProviderLoginSession) = copy( + session = next, + gone = false, + error = "", + answer = if (next.prompt?.id == session?.prompt?.id) answer else SecretDraft(), + answerError = if (next.prompt?.id == session?.prompt?.id) answerError else "", + ) + + // Sign-ins advance on the server, so read until they end. + private fun followProviderLogin(id: String) { + val api = client ?: return + val gen = generation + providerLoginJob?.cancel() + providerLoginJob = scope.launch { + while (isActive) { + val read = providerLoginReads + val session = attempt { api.providerLogin(id) } + val view = providerLogin?.takeIf { generation == gen && it.sessionID == id } ?: return@launch + val failure = session.exceptionOrNull() + if ((failure as? APIError)?.statusCode == 410) { + providerLogin = view.copy(gone = true, error = "") + return@launch + } + if (read == providerLoginReads && !view.answering) { + providerLogin = session.fold({ view.showing(it) }, { view.copy(error = friendlyError(it)) }) + if (session.getOrNull()?.let { it.status != "pending" } == true) { + refreshProviders() + return@launch + } + } + delay(PROVIDER_LOGIN_POLL_MS) + } + } + } + + fun startProviderLogin() { + val view = providerLogin ?: return + val api = client ?: return + if (view.starting) return + val id = view.provider.provider + val gen = generation + providerLogin = view.copy(starting = true, error = "") + scope.launch { + val started = attempt { api.startProviderLogin(id) } + if (generation != gen) return@launch + started.onSuccess { refreshProviders() } + val current = providerLogin?.takeIf { it.provider.provider == id && it.starting } ?: return@launch + started.fold( + onSuccess = { + providerLogin = current.copy(starting = false, sessionID = it.id, session = it) + followProviderLogin(it.id) + }, + onFailure = { providerLogin = current.copy(starting = false, error = friendlyError(it)) }, + ) + } + } + + fun answerProviderLogin(value: String) { + val view = providerLogin ?: return + val id = view.sessionID ?: return + val prompt = view.session?.prompt ?: return + val api = client ?: return + if (view.answering || value.isEmpty()) return + val gen = generation + providerLoginReads += 1 + providerLogin = view.copy(answering = true, answerError = "") + scope.launch { + val answered = attempt { api.answerProviderLogin(id, prompt.id, value) } + val current = providerLogin?.takeIf { generation == gen && it.sessionID == id } ?: return@launch + providerLoginReads += 1 + providerLogin = answered.fold( + onSuccess = { current.showing(it).copy(answering = false, answer = SecretDraft(), answerError = "") }, + onFailure = { current.copy(answering = false, answerError = friendlyError(it)) }, + ) + } + } + + fun cancelProviderLogin() { + val view = providerLogin ?: return + val id = view.sessionID ?: return + val api = client ?: return + if (view.cancelling) return + val gen = generation + providerLogin = view.copy(cancelling = true) + scope.launch { + attempt { api.cancelProviderLogin(id) } + if (generation != gen) return@launch + refreshProviders() + if (providerLogin?.sessionID == id) hideProviderLogin() + } + } } diff --git a/app/src/main/java/dev/crumble/android/model/Attachments.kt b/app/src/main/java/dev/crumble/android/model/Attachments.kt index d0a1233..644f3fd 100644 --- a/app/src/main/java/dev/crumble/android/model/Attachments.kt +++ b/app/src/main/java/dev/crumble/android/model/Attachments.kt @@ -8,6 +8,7 @@ import android.provider.OpenableColumns import android.webkit.MimeTypeMap import java.io.ByteArrayOutputStream import java.io.File +import java.io.InputStream import java.nio.ByteBuffer import java.nio.charset.CharacterCodingException import java.nio.charset.CodingErrorAction @@ -54,10 +55,35 @@ object AttachmentLimits { const val COUNT = 8 const val IMAGE_BYTES = 5 * 1024 * 1024 const val TEXT_BYTES = 512 * 1024 + + /** Larger images need re-encoding, but past this one would take too much of the app's memory to hold. */ + const val IMAGE_SOURCE_BYTES = 32 * 1024 * 1024 val IMAGE_TYPES: Set = setOf("image/png", "image/jpeg", "image/gif", "image/webp") const val IMAGE_SIDE = 2048 } +/** + * The website's picker, as MIME types: providers report code files under application types, video/mp2t for + * `.ts`, or octet-stream. `loadAttachment` turns away whatever isn't really text. + */ +val ATTACHMENT_PICKER_TYPES = arrayOf( + "image/*", + "text/*", + "application/json", + "application/xml", + "application/javascript", + "application/x-javascript", + "application/typescript", + "application/x-sh", + "application/x-shellscript", + "application/yaml", + "application/x-yaml", + "application/toml", + "application/x-ruby", + "video/mp2t", + "application/octet-stream", +) + class AttachmentError(message: String) : Exception(message) /** @@ -106,27 +132,62 @@ fun loadAttachment( jpegReencoder = jpegReencoder, ) +/** Null when the stream holds more than `limit`, so a huge file never reaches memory. */ +private fun InputStream.readUpTo(limit: Int): ByteArray? { + val out = ByteArrayOutputStream() + val buffer = ByteArray(8192) + while (true) { + val count = read(buffer) + if (count < 0) return out.toByteArray() + if (out.size() + count > limit) return null + out.write(buffer, 0, count) + } +} + +/** Refuses what can't be attached before reading it; a provider's declared size may be missing or wrong. */ +internal fun readAttachment( + name: String, + mimeTypeHint: String?, + declaredSize: Long?, + jpegReencoder: (ByteArray) -> ByteArray? = ::defaultJpegReencode, + open: () -> InputStream?, +): PendingAttachment { + val ext = name.substringAfterLast('.', "").lowercase() + val mime = resolveMimeType(ext, mimeTypeHint) + val (limit, tooLarge) = when { + isImageMime(mime, ext) -> AttachmentLimits.IMAGE_SOURCE_BYTES to "$name is larger than 32 MB." + isTextMime(mime, ext) -> AttachmentLimits.TEXT_BYTES to "$name is larger than 512 KB." + else -> throw AttachmentError("$name can't be attached. Attach images or text files.") + } + if (declaredSize != null && declaredSize > limit) throw AttachmentError(tooLarge) + val bytes = try { + val stream = open() ?: throw AttachmentError("$name couldn't be read.") + stream.use { it.readUpTo(limit) } ?: throw AttachmentError(tooLarge) + } catch (_: OutOfMemoryError) { + throw AttachmentError("$name couldn't be read.") + } + return loadAttachment(name = name, mimeTypeHint = mimeTypeHint, data = bytes, jpegReencoder = jpegReencoder) +} + fun loadAttachment( resolver: ContentResolver, uri: Uri, ): PendingAttachment { - val name = queryDisplayName(resolver, uri) ?: uri.lastPathSegment?.substringAfterLast('/') ?: "attachment" - val mime = resolver.getType(uri) - val bytes = resolver.openInputStream(uri)?.use { it.readBytes() } - ?: throw AttachmentError("$name couldn't be read.") - return loadAttachment(name = name, mimeTypeHint = mime, data = bytes) + val (displayName, size) = queryOpenable(resolver, uri) + val name = displayName ?: uri.lastPathSegment?.substringAfterLast('/') ?: "attachment" + return readAttachment(name, resolver.getType(uri), size) { resolver.openInputStream(uri) } } -private fun queryDisplayName(resolver: ContentResolver, uri: Uri): String? { +private fun queryOpenable(resolver: ContentResolver, uri: Uri): Pair { return try { - resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor -> - if (cursor.moveToFirst()) { - val idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) - if (idx >= 0) cursor.getString(idx) else null - } else null - } + resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { cursor -> + if (!cursor.moveToFirst()) return@use null + val name = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME).takeIf { it >= 0 }?.let(cursor::getString) + val size = cursor.getColumnIndex(OpenableColumns.SIZE).takeIf { it >= 0 && !cursor.isNull(it) }?.let(cursor::getLong) + name to size + } ?: (null to null) } catch (_: Exception) { - null + null to null } } @@ -148,7 +209,7 @@ private fun resolveMimeType(ext: String, hint: String?): String { "json" -> "application/json" "xml" -> "text/xml" "yaml", "yml" -> "text/yaml" - "kt", "kts", "java", "swift", "py", "js", "ts", "tsx", "jsx", "go", "rs", "c", "cpp", "h", "sh", "sql", "toml" -> "text/plain" + "kt", "kts", "java", "swift", "py", "js", "ts", "tsx", "jsx", "go", "rs", "rb", "c", "cpp", "h", "sh", "sql", "toml" -> "text/plain" else -> { val fromSystem = try { MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext) @@ -168,7 +229,7 @@ private fun isTextMime(mime: String, ext: String): Boolean { if (mime.startsWith("text/") || mime == "application/json" || mime == "application/xml") return true return ext in setOf( "txt", "md", "markdown", "json", "xml", "yaml", "yml", "csv", "log", "html", "htm", "css", - "kt", "kts", "java", "swift", "py", "js", "ts", "tsx", "jsx", "go", "rs", "c", "cpp", "h", "sh", "sql", "toml", + "kt", "kts", "java", "swift", "py", "js", "ts", "tsx", "jsx", "go", "rs", "rb", "c", "cpp", "h", "sh", "sql", "toml", ) } diff --git a/app/src/main/java/dev/crumble/android/model/Automations.kt b/app/src/main/java/dev/crumble/android/model/Automations.kt new file mode 100644 index 0000000..5bc9971 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/Automations.kt @@ -0,0 +1,156 @@ +package dev.crumble.android.model + +import dev.crumble.android.generated.Capabilities +import dev.crumble.android.generated.CreateEventSourceResponse +import dev.crumble.android.generated.ListEventSourcesResponseSourcesItem +import dev.crumble.android.generated.ScriptRun +import java.time.Duration +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle +import java.util.Locale + +typealias EventSource = ListEventSourcesResponseSourcesItem + +const val MAX_COMMAND_CHARS = 8000 +const val MAX_EVENT_SOURCE_NAME_CHARS = 200 +private const val RUNS_SHOWN = 100 + +enum class TaskTab(val label: String) { + Tasks("Tasks"), + Runs("Runs"), + EventSources("Event sources"), +} + +/** A source's address is shown once, so `created` keeps the sheet open until the owner is done. */ +data class EventSourceDraft( + val name: String = "", + val saving: Boolean = false, + val error: String = "", + val created: CreateEventSourceResponse? = null, +) + +enum class ScheduleStatus(val label: String, val rank: Int) { + Active("Active", 0), + Paused("Paused", 1), + Completed("Completed", 2), +} + +/** A one-off task that already ran; its result is in the bot's chat. */ +val Schedule.finished: Boolean + get() = cron == null && eventSourceId == null && nextRunAt == null + +val Schedule.status: ScheduleStatus + get() = when { + finished -> ScheduleStatus.Completed + enabled -> ScheduleStatus.Active + else -> ScheduleStatus.Paused + } + +private val Schedule.nextTime: Instant + get() = nextRunAt?.let(::taskRunDate) ?: Instant.MAX + +/** Active tasks soonest first, then paused ones, then finished script tasks. */ +fun listedSchedules(schedules: List): List = schedules + .filter { it.kind == "script" || !it.finished } + .sortedWith(compareBy({ it.status.rank }, { it.nextTime }, { it.name })) + +/** A bot's tasks that can still run, as its details list them. */ +fun automationsOf(agentID: String, schedules: List): List = + schedules.filter { it.agentId == agentID && !it.finished } + +fun automationTiming(schedule: Schedule, sources: List, now: Instant = Instant.now()): String = + (if (schedule.enabled) "" else "Paused · ") + describeTiming(schedule, sources, now) + +fun describeTiming( + schedule: Schedule, + sources: List, + now: Instant = Instant.now(), + localZone: String = ZoneId.systemDefault().id, +): String { + val sourceID = schedule.eventSourceId + if (sourceID != null) { + val source = sources.firstOrNull { it.id == sourceID } + return if (source != null) "On event · ${source.name}" else "On event" + } + if (!schedule.cron.isNullOrEmpty()) return describeCron(schedule.cron, schedule.timezone ?: localZone, localZone) + val runAt = schedule.runAt?.let(::taskRunDate) ?: return "Once" + val zone = runCatching { ZoneId.of(schedule.timezone) }.getOrDefault(ZoneId.systemDefault()) + val text = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT).withZone(zone).format(runAt) + return if (runAt.isBefore(now) && schedule.nextRunAt == null) "Ran $text" else "Once, $text" +} + +fun canRunScripts(capabilities: Capabilities?, agent: Agent?): Boolean = + capabilities?.coding == true && agent?.tools?.contains("coding") == true + +/** One row of the Runs tab: a prompt run opens the bot's chat, a script run its output. */ +data class TaskRun( + val id: String, + val schedule: Schedule?, + val agentId: String, + val startedAt: String, + val label: String, + val failed: Boolean, + val running: Boolean, + val script: ScriptRun? = null, +) + +private val EXECUTION_STATUS = mapOf( + "pending" to "Queued", + "running" to "Running", + "done" to "Done", + "failed" to "Failed", + "cancelled" to "Cancelled", +) + +private val SCRIPT_STATUS = mapOf( + "running" to "Running", + "succeeded" to "Succeeded", + "failed" to "Failed", + "timed_out" to "Timed out", + "interrupted" to "Interrupted", +) + +fun taskRuns( + schedules: List, + executions: List, + scriptRuns: Map>, +): List { + val byId = schedules.associateBy { it.id } + val prompts = executions.mapNotNull { execution -> + val scheduleId = execution.scheduleId ?: return@mapNotNull null + val status = execution.status.orEmpty() + TaskRun( + id = execution.id, + schedule = byId[scheduleId], + agentId = execution.agentId.orEmpty(), + startedAt = execution.createdAt.orEmpty(), + label = EXECUTION_STATUS[status] ?: status, + failed = status == "failed", + running = status == "running" || status == "pending", + ) + } + val scripts = schedules.filter { it.kind == "script" }.flatMap { scriptRuns[it.id].orEmpty() }.map { run -> + TaskRun( + id = run.id, + schedule = byId[run.scheduleId], + agentId = run.agentId, + startedAt = run.startedAt, + label = SCRIPT_STATUS[run.status] ?: run.status, + failed = run.status != "succeeded" && run.status != "running", + running = run.status == "running", + script = run, + ) + } + return (prompts + scripts) + .sortedByDescending { taskRunDate(it.startedAt) ?: Instant.MIN } + .take(RUNS_SHOWN) +} + +fun scriptRunDuration(run: ScriptRun, now: Instant = Instant.now()): String { + val start = taskRunDate(run.startedAt) ?: return "—" + val end = run.finishedAt?.let(::taskRunDate) ?: now + val seconds = maxOf(0L, Duration.between(start, end).toMillis()) / 1000.0 + return "${String.format(Locale.ROOT, "%.1f", seconds)} s" +} diff --git a/app/src/main/java/dev/crumble/android/model/BotDesktop.kt b/app/src/main/java/dev/crumble/android/model/BotDesktop.kt new file mode 100644 index 0000000..d57fe4e --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/BotDesktop.kt @@ -0,0 +1,86 @@ +package dev.crumble.android.model + +import dev.crumble.android.generated.DesktopControl +import kotlinx.serialization.json.JsonPrimitive + +const val DESKTOP_OWNER = "owner" +const val DESKTOP_BOT = "bot" +const val DESKTOP_UNAVAILABLE = "The bot desktop is unavailable" +const val DESKTOP_HAND_BACK_FAILED = "Couldn't hand the bot desktop back. Open it and hand back again." + +/** A viewer link works once, so losing the page means asking for a fresh one. */ +data class DesktopLink( + val url: String? = null, + val connecting: Boolean = false, + val error: String = "", +) { + val idle: Boolean + get() = url == null && !connecting && error.isEmpty() +} + +/** The open bot desktop. `taking` is the holder asked for and not yet confirmed. */ +data class BotDesktop( + val agentID: String, + val control: DesktopControl? = null, + val taking: String? = null, + val takeError: String = "", + val viewer: DesktopLink = DesktopLink(), +) { + val owner: Boolean + get() = control?.holder == DESKTOP_OWNER +} + +/** The watch-only tile. `running` is null until the first status read. */ +data class DesktopPreview( + val agentID: String, + val running: Boolean? = null, + val asked: Boolean = false, + val viewer: DesktopLink = DesktopLink(), +) { + val awake: Boolean + get() = asked || running == true +} + +/** Responses and events can arrive out of order; the latest change wins. */ +fun newerControl(current: DesktopControl?, next: DesktopControl): DesktopControl = + if (current != null && current.changes > next.changes) current else next + +enum class DesktopKey(val label: String, val key: String, val code: String) { + Escape("Esc", "Escape", "Escape"), + Tab("Tab", "Tab", "Tab"), + Left("←", "ArrowLeft", "ArrowLeft"), + Up("↑", "ArrowUp", "ArrowUp"), + Down("↓", "ArrowDown", "ArrowDown"), + Right("→", "ArrowRight", "ArrowRight"), + Backspace("⌫", "Backspace", "Backspace"), + Enter("⏎", "Enter", "Enter"), +} + +data class DesktopPress(val key: String, val code: String = "") + +fun DesktopKey.press() = DesktopPress(key, code) + +/** noVNC turns a key with no `code` into a press and release of its character; it can't send surrogate pairs. */ +fun desktopPresses(text: String): List = + text.replace("\r\n", "\n").filterNot { it == '\r' || it.isSurrogate() }.map { + when (it) { + '\n' -> DesktopKey.Enter.press() + '\t' -> DesktopKey.Tab.press() + else -> DesktopPress(it.toString()) + } + } + +// noVNC's core has no soft keyboard, and the viewer page keeps its RFB object private; its canvas takes key events. +/** Key events for the viewer page's canvas. The script's result says whether the canvas was there. */ +fun desktopKeyScript(presses: List, ctrl: Boolean = false): String = buildString { + fun quoted(text: String) = JsonPrimitive(text).toString() + append("(function(){var c=document.querySelector('#screen canvas');if(!c)return false;") + append("function k(t,key,code){c.dispatchEvent(new KeyboardEvent(t,{key:key,code:code,bubbles:true,cancelable:true}))}") + if (ctrl) append("k('keydown','Control','ControlLeft');") + for (press in presses) { + val arguments = "${quoted(press.key)},${quoted(press.code)}" + append("k('keydown',$arguments);k('keyup',$arguments);") + } + if (ctrl) append("k('keyup','Control','ControlLeft');") + append("return true})()") +} diff --git a/app/src/main/java/dev/crumble/android/model/BotProfile.kt b/app/src/main/java/dev/crumble/android/model/BotProfile.kt new file mode 100644 index 0000000..3241ba9 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/BotProfile.kt @@ -0,0 +1,54 @@ +package dev.crumble.android.model + +import dev.crumble.android.generated.Capabilities + +data class BotCapability(val tool: String, val label: String, val help: String) + +private val BOT_CAPABILITIES = listOf( + BotCapability("memory", "Memory", "Remembers facts across chats."), + BotCapability("web", "Web search", "Searches the web and reads pages."), + BotCapability("delegate", "Message other bots", "Asks the other bots for help."), + BotCapability("coding", "Coding", "Works in its own workspace and runs coding jobs."), + BotCapability("desktop", "Bot desktop", "Runs desktop jobs on its own desktop."), + BotCapability("create_bots", "Create bots", "Asks you to approve new bots."), +) + +/** Coding and desktop need server support; a bot that already has one keeps its toggle so it can be turned off. */ +fun shownCapabilities(server: Capabilities?, initialTools: Set): List = + BOT_CAPABILITIES.filter { capability -> + when (capability.tool) { + "coding" -> server?.coding == true || "coding" in initialTools + "desktop" -> server?.desktop == true || "desktop" in initialTools + else -> true + } + } + +const val WEB_SEARCH_ACCOUNT_DEFAULT = "default" + +val WEB_SEARCH_OPTIONS = listOf(ChoiceOption(WEB_SEARCH_ACCOUNT_DEFAULT, "Account default")) + WEB_SEARCH_PROVIDERS + +/** Set-up providers, plus the current one when its key is gone, so the owner sees why. */ +private fun providerOptions(providers: List, current: String): List { + val ready = providers.filter { it.configured }.map { ChoiceOption(it.provider, it.name ?: it.provider) } + val gone = current.takeIf { it.isNotEmpty() && ready.none { option -> option.value == it } }?.let { id -> + ChoiceOption(id, "${providers.firstOrNull { it.provider == id }?.name ?: id} (not set up)") + } + return listOfNotNull(gone) + ready +} + +fun desktopProviderOptions(providers: List, current: String): List = + listOf(ChoiceOption("", "Same as the bot")) + providerOptions(providers, current) + +fun botProviderOptions(providers: List, current: String): List = + listOfNotNull(ChoiceOption("", "Choose a provider").takeIf { current.isEmpty() }) + providerOptions(providers, current) + +fun desktopModelHint(providers: List, provider: String, modelCount: Int): String = when { + providers.none { it.provider == provider && it.configured } -> + "Add an API key or sign in for this provider in Settings to load its models." + modelCount > 0 -> "$modelCount models available." + else -> "Type a model ID." +} + +/** What the bot list says under a bot's name. */ +fun botListLine(agent: Agent, working: Boolean): String = + if (working) "Working…" else preview(agent.lastMessage ?: "").nilIfEmpty ?: "No messages yet" diff --git a/app/src/main/java/dev/crumble/android/model/Changes.kt b/app/src/main/java/dev/crumble/android/model/Changes.kt new file mode 100644 index 0000000..eaebde3 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/Changes.kt @@ -0,0 +1,129 @@ +package dev.crumble.android.model + +import dev.crumble.android.generated.LearnedChange +import dev.crumble.android.generated.LearnedChangeAfter +import dev.crumble.android.generated.LearnedChangeBefore +import dev.crumble.android.generated.SkillDocument +import dev.crumble.android.generated.SkillPackage +import dev.crumble.android.network.domain +import java.time.Duration +import java.time.Instant +import kotlin.math.abs +import kotlin.math.roundToLong + +data class DiffLine(val kind: Char, val text: String) + +internal val LearnedChange.beforeSkill: SkillPackage? get() = (before as? LearnedChangeBefore.Variant1)?.value +internal val LearnedChange.beforeMemory: Memory? get() = (before as? LearnedChangeBefore.Variant2)?.value?.domain() +internal val LearnedChange.existedBefore: Boolean get() = before !is LearnedChangeBefore.Variant3 + +private fun contentLines(content: String) = content.split("\n") + +/** The state as plain lines, so a skill's name, description, instructions, and documents diff together. */ +fun skillLines(name: String, description: String, instructions: String, documents: List): List = + listOf("# $name", description, "") + contentLines(instructions) + documents.flatMap { + listOf("", "--- ${it.path}") + contentLines(it.content) + } + +fun skillLines(skill: SkillPackage) = skillLines(skill.name, skill.description, skill.instructions, skill.documents) + +private fun LearnedChangeBefore.lines() = when (this) { + is LearnedChangeBefore.Variant1 -> skillLines(value) + is LearnedChangeBefore.Variant2 -> contentLines(value.content) + is LearnedChangeBefore.Variant3 -> emptyList() +} + +private fun LearnedChangeAfter.lines() = when (this) { + is LearnedChangeAfter.Variant1 -> skillLines(value) + is LearnedChangeAfter.Variant2 -> contentLines(value.content) + is LearnedChangeAfter.Variant3 -> emptyList() +} + +fun LearnedChange.diff(): List = lineDiff(before.lines(), after.lines()) + +private fun commonLengths(a: List, b: List): Array { + val table = Array(a.size + 1) { IntArray(b.size + 1) } + for (i in a.indices.reversed()) { + for (j in b.indices.reversed()) { + table[i][j] = if (a[i] == b[j]) table[i + 1][j + 1] + 1 else maxOf(table[i + 1][j], table[i][j + 1]) + } + } + return table +} + +private fun walkDiff(a: List, b: List): List { + val table = commonLengths(a, b) + val middle = mutableListOf() + var i = 0 + var j = 0 + while (i < a.size || j < b.size) { + if (i < a.size && j < b.size && a[i] == b[j]) { + middle.add(DiffLine(' ', a[i])) + i += 1 + j += 1 + } else if (i < a.size && (j == b.size || table[i + 1][j] >= table[i][j + 1])) { + middle.add(DiffLine('-', a[i])) + i += 1 + } else { + middle.add(DiffLine('+', b[j])) + j += 1 + } + } + return middle +} + +/** A line diff by longest common subsequence, after trimming the shared head and tail. */ +fun lineDiff(before: List, after: List): List { + var head = 0 + while (head < before.size && head < after.size && before[head] == after[head]) head += 1 + var tail = 0 + while (tail < before.size - head && tail < after.size - head && before[before.size - 1 - tail] == after[after.size - 1 - tail]) tail += 1 + val middle = walkDiff(before.subList(head, before.size - tail), after.subList(head, after.size - tail)) + fun same(lines: List) = lines.map { DiffLine(' ', it) } + return same(before.subList(0, head)) + middle + same(before.subList(before.size - tail, before.size)) +} + +fun revertPrompt(change: LearnedChange): String { + val target = if (change.target == "skill") "skill" else "memory" + return if (change.existedBefore) { + "The $target goes back to how it was before this change. Anything changed since is replaced. The revert is recorded, so you can undo it too." + } else { + "The $target is deleted again. The revert is recorded, so you can undo it too." + } +} + +private val AGE_STEPS = listOf("minute" to 60.0, "hour" to 60.0, "day" to 24.0, "week" to 7.0, "month" to 4.35, "year" to 12.0) +private val LAST = mapOf("day" to "yesterday", "week" to "last week", "month" to "last month", "year" to "last year") + +/** "3 days ago", in the largest unit that is at least one. */ +fun memoryAge(iso: String, now: Instant): String? { + val then = runCatching { Instant.parse(iso) }.getOrNull() ?: return null + var value = abs(Duration.between(then, now).seconds.toDouble()) + var unit = "second" + for ((next, size) in AGE_STEPS) { + if (value < size) break + value /= size + unit = next + } + val count = value.roundToLong() + return when { + unit == "second" -> "this minute" + count == 1L -> LAST[unit] ?: "1 $unit ago" + else -> "$count ${unit}s ago" + } +} + +private val SOURCE_LABELS = mapOf String>( + "chat" to { _ -> "From the bot chat" }, + "owner" to { _ -> "Added by you" }, + "task" to { name -> "From the automation ${name.orEmpty()}".trim() }, + "bot" to { name -> "From a request by ${name ?: "a bot"}" }, + "group" to { name -> "From the group chat ${name.orEmpty()}".trim() }, +) + +fun memorySourceLabel(memory: Memory): String? = + memory.source?.let { source -> SOURCE_LABELS[source.kind]?.invoke(source.name) } + +/** Where a memory came from and when it last changed, such as "Added by you · 3 days ago". */ +fun memoryLine(memory: Memory, now: Instant): String = + listOfNotNull(memorySourceLabel(memory), memory.updatedAt?.let { memoryAge(it, now) }).joinToString(" · ") diff --git a/app/src/main/java/dev/crumble/android/model/CommandPalette.kt b/app/src/main/java/dev/crumble/android/model/CommandPalette.kt new file mode 100644 index 0000000..2f1f9f8 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/CommandPalette.kt @@ -0,0 +1,94 @@ +package dev.crumble.android.model + +import dev.crumble.android.generated.GroupChat + +private const val PENDING_PREFIX = "pending:" + +sealed class PaletteAction { + data class OpenBot(val id: String) : PaletteAction() + data class OpenGroup(val id: String) : PaletteAction() + data object NewBot : PaletteAction() + data object NewGroup : PaletteAction() + data class OpenPage(val route: Route) : PaletteAction() + data class SetTheme(val theme: ThemeChoice) : PaletteAction() +} + +/** `terms` are what a search matches, so bots with equal names stay distinct and match by name only. */ +data class PaletteItem( + val title: String, + val action: PaletteAction, + val terms: List = listOf(title), + val note: String? = null, +) + +data class PaletteSection(val heading: String, val items: List) + +fun paletteSections( + agents: List, + groups: List, + admin: Boolean, + theme: ThemeChoice, +): List { + val bots = agents.filterNot { it.id.startsWith(PENDING_PREFIX) }.map { + PaletteItem(it.name, PaletteAction.OpenBot(it.id), note = "Paused".takeUnless { _ -> it.enabled }) + } + val chats = groups.filterNot { it.id.startsWith(PENDING_PREFIX) }.map { + PaletteItem(it.name, PaletteAction.OpenGroup(it.id)) + } + val create = listOfNotNull( + PaletteItem("New bot", PaletteAction.NewBot), + PaletteItem("New group chat", PaletteAction.NewGroup).takeIf { agents.size >= MIN_GROUP_MEMBERS }, + ) + val pages = WORKSPACE_PAGES.map { route -> + val terms = if (route == Route.Tasks) listOf(route.title, "Automations") else listOf(route.title) + PaletteItem(route.title, PaletteAction.OpenPage(route), terms) + } + val settings = SETTINGS_PAGES.filter { it != Route.Users || admin }.map { + PaletteItem(it.title, PaletteAction.OpenPage(it), listOf("Settings ${it.title}")) + } + val themes = ThemeChoice.entries.map { + PaletteItem( + title = "${it.label} theme", + action = PaletteAction.SetTheme(it), + terms = listOf("Theme ${it.label}", "${it.label} theme"), + note = "Current".takeIf { _ -> it == theme }, + ) + } + return listOf( + PaletteSection("Bots", bots), + PaletteSection("Group chats", chats), + PaletteSection("Create", create), + PaletteSection("Workspace", pages), + PaletteSection("Settings", settings), + PaletteSection("Theme", themes), + ).filter { it.items.isNotEmpty() } +} + +/** Letters in order count, like the website's search: "prv" finds "Providers". Null means no match. */ +internal fun matchScore(term: String, query: String): Int? { + val text = term.lowercase() + val at = text.indexOf(query) + if (at == 0) return 400 + if (at > 0) return if (text.contains(" $query")) 300 else 200 + var next = 0 + for (letter in query) { + next = text.indexOf(letter, next) + 1 + if (next == 0) return null + } + return 100 +} + +/** Best matches first, and the section holding the best match leads, like the website's palette. */ +fun searchPalette(sections: List, query: String): List { + val search = query.trim().lowercase() + if (search.isEmpty()) return sections + return sections + .mapNotNull { section -> + val hits = section.items + .mapNotNull { item -> item.terms.mapNotNull { matchScore(it, search) }.maxOrNull()?.let { item to it } } + .sortedByDescending { it.second } + hits.firstOrNull()?.let { (_, best) -> best to section.copy(items = hits.map { it.first }) } + } + .sortedByDescending { it.first } + .map { it.second } +} diff --git a/app/src/main/java/dev/crumble/android/model/Connections.kt b/app/src/main/java/dev/crumble/android/model/Connections.kt new file mode 100644 index 0000000..6284bce --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/Connections.kt @@ -0,0 +1,443 @@ +package dev.crumble.android.model + +import dev.crumble.android.generated.GetEventRelayResponse +import dev.crumble.android.generated.GetWebSearchResponse +import dev.crumble.android.generated.JudgeChoice +import dev.crumble.android.generated.JudgeModel +import dev.crumble.android.generated.JudgeModelJudgeModel +import dev.crumble.android.generated.MessageGatewaysResponseGatewaysItem +import dev.crumble.android.generated.OptionalField +import dev.crumble.android.generated.PluginSetting +import dev.crumble.android.generated.PluginSettings +import dev.crumble.android.generated.ServerSettings +import dev.crumble.android.generated.UpdateEventRelayResponse +import dev.crumble.android.generated.UpdateMessageGatewayRequest +import dev.crumble.android.generated.UpdateMessageGatewayRequestAliasesItem +import dev.crumble.android.generated.UpdateMessageGatewayResponse +import dev.crumble.android.generated.UpdateServerSettingsRequest +import dev.crumble.android.generated.UpdateWebSearchResponse +import dev.crumble.android.generated.VisionModel +import java.net.URI +import java.text.Normalizer +import java.util.UUID +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonPrimitive + +/** A page's data: `error` is a failed read, `failure` a failed change to it. */ +data class Remote(val value: T? = null, val error: String = "", val failure: String = "") + +data class ChoiceOption(val value: String, val label: String) + +// MARK: Relay and web search + +data class RelayStatus(val url: String?, val tokenConfigured: Boolean, val status: String, val error: String?) + +internal fun GetEventRelayResponse.domain() = RelayStatus(url, tokenConfigured, status, error) +internal fun UpdateEventRelayResponse.domain() = RelayStatus(url, tokenConfigured, status, error) + +private val RELAY_LABELS = mapOf( + "disconnected" to "Not set up", + "connecting" to "Connecting", + "connected" to "Connected", + "error" to "Connection error", +) + +fun relayStatusLabel(status: String) = RELAY_LABELS[status] ?: status + +data class WebSearchSettings(val defaultProvider: String, val exaKeyConfigured: Boolean) + +internal fun GetWebSearchResponse.domain() = WebSearchSettings(defaultProvider, exaKeyConfigured) +internal fun UpdateWebSearchResponse.domain() = WebSearchSettings(defaultProvider, exaKeyConfigured) + +val WEB_SEARCH_PROVIDERS = listOf(ChoiceOption("mixed", "Mixed"), ChoiceOption("exa", "Exa")) + +// MARK: Plugin settings + +data class PluginRow(val pluginID: String, val setting: PluginSetting) + +/** The settings a page shows, as the server declares them. `secretKey` is `pluginId:key`. */ +fun pluginRows( + settings: PluginSettings?, + contributes: String? = null, + pluginID: String? = null, + secretKey: String? = null, +): List = settings?.plugins.orEmpty() + .filter { (contributes == null || contributes in it.contributes) && (pluginID == null || it.id == pluginID) } + .flatMap { plugin -> + plugin.settings + .filter { secretKey == null || "${plugin.id}:${it.key}" == secretKey } + .map { PluginRow(plugin.id, it) } + } + +data class PluginSecretForm( + val pluginID: String, + val setting: PluginSetting, + val secret: SecretDraft, + val saving: Boolean = false, + val error: String = "", +) + +// MARK: Judge and vision models + +const val JUDGE_DEFAULT = "default" +const val VISION_OFF = "off" + +fun modelKey(provider: String, model: String) = "$provider/$model" + +private val JudgeModelJudgeModel.key get() = modelKey(provider, model) +private val JudgeChoice.key get() = modelKey(provider, model) + +fun judgeValue(data: JudgeModel) = data.judgeModel?.key ?: JUDGE_DEFAULT + +fun judgeChoices(data: JudgeModel) = data.choices.filterNotNull() + +/** The classifier chosen by `value`, or null for the default. */ +fun judgeChoice(data: JudgeModel, value: String) = judgeChoices(data).firstOrNull { it.key == value } + +/** What judges now: the classifier, the chat fallback, or nothing. */ +fun judgeStatus(data: JudgeModel): String { + val effective = data.effective + ?: return "No model is available, so only commit points such as Pay or Send are held. Add an OpenAI API key for GPT-6 Luna." + return if (effective.kind == "chat") { + "${effective.name} judges as a chat model: no provider key reaches a classifier." + } else { + "${effective.name} judges now." + } +} + +/** The default, each reachable classifier, and a chosen one whose key is gone, so the owner sees why. */ +fun judgeOptions(data: JudgeModel): List { + val chosen = data.judgeModel + val choices = judgeChoices(data) + val gone = chosen?.takeIf { ref -> choices.none { it.key == ref.key } } + return listOf(ChoiceOption(JUDGE_DEFAULT, "Default (GPT-6 Luna)")) + + choices.map { ChoiceOption(it.key, it.name) } + + listOfNotNull(gone?.let { ChoiceOption(it.key, "${it.model} (no key)") }) +} + +fun visionValue(data: VisionModel) = data.visionModel?.let { modelKey(it.provider, it.model) } ?: VISION_OFF + +fun visionChoice(data: VisionModel, value: String) = data.choices.firstOrNull { modelKey(it.provider, it.model) == value } + +private fun visionUnreachable(data: VisionModel) = data.visionModel != null && visionChoice(data, visionValue(data)) == null + +fun visionStatus(data: VisionModel): String { + val chosen = data.visionModel + ?: return "Off. A bot whose model can't read images refuses them in its chat and gets only their names in group chats." + if (visionUnreachable(data)) { + return "No provider key reaches ${chosen.model}, so images can't be read. Choose another model or turn it off." + } + val name = visionChoice(data, visionValue(data))?.name ?: chosen.model + return "$name describes images for bots whose model can't read them." +} + +fun visionOptions(data: VisionModel): List { + val gone = data.visionModel?.takeIf { visionUnreachable(data) } + return listOf(ChoiceOption(VISION_OFF, "Off")) + + data.choices.map { ChoiceOption(modelKey(it.provider, it.model), it.name) } + + listOfNotNull(gone?.let { ChoiceOption(modelKey(it.provider, it.model), "${it.model} (no key)") }) +} + +// MARK: Message gateways + +data class GatewayAlias(val handle: String, val botId: String) + +data class GatewayConfig( + val enabled: Boolean = false, + val defaultBotId: String? = null, + val ownerId: String? = null, + val allowedChannelIds: List = emptyList(), + val allowDirectMessages: Boolean = false, + val aliases: List = emptyList(), +) + +data class MessageGateway( + val id: String, + val label: String, + val secretKey: String, + val tokenConfigured: Boolean, + val config: GatewayConfig, + val status: String, + val error: String?, + val pendingCount: Long, + val failedCount: Long, +) + +internal fun MessageGatewaysResponseGatewaysItem.domain() = MessageGateway( + id, label, secretKey, tokenConfigured, + GatewayConfig( + config.enabled, config.defaultBotId, config.ownerId, config.allowedChannelIds, config.allowDirectMessages, + config.aliases.map { GatewayAlias(it.handle, it.botId) }, + ), + status, error, pendingCount, failedCount, +) + +internal fun UpdateMessageGatewayResponse.domain() = MessageGateway( + id, label, secretKey, tokenConfigured, + GatewayConfig( + config.enabled, config.defaultBotId, config.ownerId, config.allowedChannelIds, config.allowDirectMessages, + config.aliases.map { GatewayAlias(it.handle, it.botId) }, + ), + status, error, pendingCount, failedCount, +) + +internal fun GatewayConfig.wire() = UpdateMessageGatewayRequest( + enabled, defaultBotId, ownerId, allowedChannelIds, allowDirectMessages, + aliases.map { UpdateMessageGatewayRequestAliasesItem(it.handle, it.botId) }, +) + +private val GATEWAY_LABELS = mapOf( + "disconnected" to "Disconnected", + "connecting" to "Connecting", + "connected" to "Connected", + "error" to "Connection error", +) + +fun gatewayStatusLabel(gateway: MessageGateway) = + if (gateway.config.enabled) GATEWAY_LABELS[gateway.status] ?: gateway.status else "Disabled" + +fun gatewayDeliveries(gateway: MessageGateway) = listOfNotNull( + gateway.pendingCount.takeIf { it > 0 }?.let { "$it pending" }, + gateway.failedCount.takeIf { it > 0 }?.let { "$it failed" }, +).joinToString(", ") + +data class GatewayChannelRow(val value: String = "", val id: String = UUID.randomUUID().toString()) + +data class GatewayAliasRow(val handle: String = "", val botId: String = "", val id: String = UUID.randomUUID().toString()) + +/** A gateway's unsaved edits. Rows carry their own IDs so text fields keep focus when one above goes. */ +data class GatewayForm( + val gatewayID: String, + val enabled: Boolean, + val defaultBotId: String?, + val owner: String, + val channels: List, + val allowDirectMessages: Boolean, + val aliases: List, + val attempted: Boolean = false, + val saving: Boolean = false, + val saved: Boolean = false, + val error: String = "", +) { + fun config() = GatewayConfig( + enabled = enabled, + defaultBotId = defaultBotId, + ownerId = owner.trim().ifEmpty { null }, + allowedChannelIds = channels.map { it.value.trim() }.filter { it.isNotEmpty() }.distinct(), + allowDirectMessages = allowDirectMessages, + aliases = aliases.map { GatewayAlias(it.handle.trim(), it.botId) }, + ) +} + +fun gatewayForm(id: String, config: GatewayConfig) = GatewayForm( + gatewayID = id, + enabled = config.enabled, + defaultBotId = config.defaultBotId, + owner = config.ownerId.orEmpty(), + channels = config.allowedChannelIds.map { GatewayChannelRow(it) }, + allowDirectMessages = config.allowDirectMessages, + aliases = config.aliases.map { GatewayAliasRow(it.handle, it.botId) }, +) + +fun gatewayStatus(dirty: Boolean, form: GatewayForm) = when { + form.saving -> "Saving…" + dirty -> "Unsaved changes" + form.saved -> "Saved" + else -> "" +} + +private val GATEWAY_OWNER = Regex("^[^\\s\\p{Z},]+$") +private val GATEWAY_HANDLE = Regex("^[\\p{L}\\p{N}_-]+$") + +private fun normalizedHandle(handle: String) = Normalizer.normalize(handle, Normalizer.Form.NFKC).lowercase() + +private fun aliasIssue(aliases: List): String? { + for (alias in aliases) { + if (!GATEWAY_HANDLE.matches(alias.handle)) return "Use letters, numbers, underscores or hyphens, without @." + if (alias.botId.isEmpty()) return "Choose a bot for every alias." + } + return "Alias handles must be unique (ignoring case)".takeIf { aliases.distinctBy { normalizedHandle(it.handle) }.size != aliases.size } +} + +/** The server's `gatewayConfigInput`, plus what only the bot list can tell: saved bots that were deleted. */ +fun gatewayErrors(config: GatewayConfig, botIDs: Set): Map = buildMap { + if (config.ownerId?.let { GATEWAY_OWNER.matches(it) } == false) put("ownerId", "Enter one user ID, without spaces or commas.") + aliasIssue(config.aliases)?.let { put("aliases", it) } + if (config.enabled && config.defaultBotId != null && config.defaultBotId !in botIDs) { + put("defaultBotId", "The saved bot was deleted. Choose another.") + } + if (config.enabled && config.aliases.any { it.botId.isNotEmpty() && it.botId !in botIDs }) { + put("aliases", "Choose an existing bot for every alias.") + } +} + +/** The bots a select offers, plus the saved one when it no longer exists. */ +fun gatewayBotOptions(bots: List, value: String?, optional: Boolean): List = buildList { + add(ChoiceOption("", if (optional) "None" else "Choose a bot")) + for (bot in bots) add(ChoiceOption(bot.id, if (bot.enabled) bot.name else "${bot.name} (disabled)")) + if (!value.isNullOrEmpty() && bots.none { it.id == value }) add(ChoiceOption(value, "Deleted bot")) +} + +// MARK: GitHub + +/** The pages GitHub sends the owner back to, from the server's `GITHUB_APP_WEB_PATHS`. */ +enum class GitHubStep(val path: String) { + created("/github-app/callback"), + installed("/github-app/installed"), + authorized("/github-app/authorized"), +} + +/** A GitHub page open inside the app, so its return can be caught instead of landing on the website. */ +data class GitHubFlow( + val step: GitHubStep, + val url: String, + /** Set when GitHub must be opened with the form post that creates an App. */ + val manifest: String? = null, + val appID: String? = null, + val finishing: Boolean = false, + val error: String = "", + val id: String = UUID.randomUUID().toString(), +) + +// Older Apps registered these pages under another prefix, so only the end of the path is fixed. +fun isGitHubReturn(url: String, step: GitHubStep): Boolean = + runCatching { URI(url).path.orEmpty().trimEnd('/').endsWith(step.path) }.getOrDefault(false) + +/** The web UI's origin, which GitHub's callbacks hang off; the app talks to the same address. */ +fun webOrigin(baseURL: String): String { + val uri = URI(baseURL) + return "${uri.scheme}://${uri.host}" + if (uri.port > 0) ":${uri.port}" else "" +} + +fun githubAuthorizedURL(baseURL: String) = webOrigin(baseURL) + GitHubStep.authorized.path + +data class CreateGitHubAppForm( + val name: String = "", + val organization: String = "", + val saving: Boolean = false, + val error: String = "", +) { + val ready: Boolean get() = name.isNotBlank() && !saving +} + +data class GitHubAppForm( + val appID: String, + val botIDs: List, + val clientSecret: SecretDraft = SecretDraft(), + val checking: Boolean = false, + val checkError: String = "", + val signingIn: Boolean = false, + val signingOut: Boolean = false, + val signInError: String = "", + val savingSecret: Boolean = false, + val secretError: String = "", + val error: String = "", +) + +data class AddGitHubAccountForm( + val token: SecretDraft = SecretDraft(), + val saving: Boolean = false, + val error: String = "", +) { + val ready: Boolean get() = token.input != null && !saving +} + +data class GitHubAccountForm( + val accountID: String, + val botIDs: List, + val token: SecretDraft, + val saving: Boolean = false, + val error: String = "", +) + +fun toggled(botIDs: List, id: String, on: Boolean) = if (on) botIDs + id else botIDs - id + +// MARK: Workspaces + +enum class WorkspaceField(val title: String) { + size("Workspace size"), + image("Coding image"), + grace("Question grace period"), +} + +data class ServerSettingsForm( + val field: WorkspaceField, + val cpus: String, + val memory: String, + val image: String, + val grace: String, + val error: String = "", +) { + /** What the sheet changes, or null while a number doesn't parse. */ + fun patch(): UpdateServerSettingsRequest? = when (field) { + WorkspaceField.size -> { + val parsedCpus = cpus.trim().toLongOrNull() + val parsedMemory = memory.trim().toDoubleOrNull()?.takeIf { it.isFinite() } + if (parsedCpus == null || parsedMemory == null) { + null + } else { + UpdateServerSettingsRequest( + workspaceCpus = OptionalField.Present(parsedCpus), + workspaceMemoryMib = OptionalField.Present(Math.round(parsedMemory * 1024)), + ) + } + } + WorkspaceField.image -> UpdateServerSettingsRequest(codingImage = OptionalField.Present(image.trim().ifEmpty { null })) + WorkspaceField.grace -> grace.trim().toLongOrNull()?.let { UpdateServerSettingsRequest(questionGraceMinutes = OptionalField.Present(it)) } + } +} + +fun serverSettingsForm(field: WorkspaceField, settings: ServerSettings) = ServerSettingsForm( + field = field, + cpus = settings.workspaceCpus.toString(), + memory = (settings.workspaceMemoryMib / 1024.0).toString().removeSuffix(".0"), + image = settings.codingImage.orEmpty(), + grace = settings.questionGraceMinutes.toString(), +) + +internal fun ServerSettings.patched(form: ServerSettingsForm): ServerSettings { + val patch = form.patch() ?: return this + return copy( + workspaceCpus = (patch.workspaceCpus as? OptionalField.Present)?.value ?: workspaceCpus, + workspaceMemoryMib = (patch.workspaceMemoryMib as? OptionalField.Present)?.value ?: workspaceMemoryMib, + codingImage = if (form.field == WorkspaceField.image) form.image.trim().ifEmpty { null } else codingImage, + questionGraceMinutes = (patch.questionGraceMinutes as? OptionalField.Present)?.value ?: questionGraceMinutes, + ) +} + +fun workspaceRowTitle(field: WorkspaceField, settings: ServerSettings) = when (field) { + WorkspaceField.size -> { + val memory = (settings.workspaceMemoryMib / 1024.0).toString().removeSuffix(".0") + "Workspace size (${settings.workspaceCpus} CPUs, $memory GB)" + } + WorkspaceField.image -> "Coding image (${settings.codingImage ?: "server default"})" + WorkspaceField.grace -> "Question grace period (${settings.questionGraceMinutes} min)" +} + +/** The setup notes for job kinds this server doesn't offer. */ +fun workspaceHelp(coding: Boolean, desktop: Boolean) = listOfNotNull( + "Coding jobs need CRUMBLE_WORKSPACE_IMAGE on the server.".takeIf { !coding }, + "Desktop jobs need CRUMBLE_WORKSPACE_DESKTOP_IMAGE on the server.".takeIf { !desktop }, +) + +// MARK: MCP servers + +val MCPDraft.readsPasswordManager: Boolean + get() = (token.changed && token.input is SecretInput.Reference) || + (clientID.isNotBlank() && clientSecret.changed && clientSecret.input is SecretInput.Reference) + +fun matchesMCP(server: MCPServer, needle: String) = + needle.isEmpty() || server.name.lowercase().contains(needle) || server.url.lowercase().contains(needle) + +/** The web's `oauthClientPatch`: clearing the client ID removes its secret too, since it has no use alone. */ +internal fun MCPDraft.oauthFields(old: MCPServer?): Map = buildMap { + val id = clientID.trim() + if (id.isNotEmpty() || old?.oauthClientId != null) { + put("oauthClientId", if (id.isNotEmpty()) JsonPrimitive(id) else JsonNull) + } + when { + id.isNotEmpty() -> clientSecret.takeIf { it.changed }?.input?.let { put("oauthClientSecret", it.json()) } + old?.oauthClientSecret?.configured == true -> put("oauthClientSecret", JsonNull) + } +} diff --git a/app/src/main/java/dev/crumble/android/model/Cron.kt b/app/src/main/java/dev/crumble/android/model/Cron.kt new file mode 100644 index 0000000..64efacb --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/Cron.kt @@ -0,0 +1,452 @@ +package dev.crumble.android.model + +import java.time.Instant +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.ZoneId +import java.time.ZonedDateTime +import java.time.temporal.TemporalAdjusters + +const val MAX_CRON_CHARS = 100 + +// Reaches the next Feb 29 from any date; anything later never fires. +private const val MAX_SCAN_DAYS = 3_000 + +private val CRON_ALIASES = mapOf( + "@yearly" to "0 0 0 1 1 *", + "@annually" to "0 0 0 1 1 *", + "@monthly" to "0 0 0 1 * *", + "@weekly" to "0 0 0 * * 0", + "@daily" to "0 0 0 * * *", + "@hourly" to "0 0 * * * *", + "@minutely" to "0 * * * * *", + "@secondly" to "* * * * * *", + "@weekdays" to "0 0 0 * * 1-5", + "@weekends" to "0 0 0 * * 0,6", +) + +private val CRON_NAMES = listOf("sun", "mon", "tue", "wed", "thu", "fri", "sat").withIndex().associate { (index, name) -> name to index } + + listOf("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec").withIndex().associate { (index, name) -> name to index + 1 } +private val CRON_NAME = Regex("[a-z]{3}", RegexOption.IGNORE_CASE) +private val CRON_FIELD = Regex("[?,*\\dL#/-]+") +private val LAST_WEEKDAY = Regex("\\dL") +private val WHITESPACE = Regex("\\s+") + +private val FIELD_DEFAULTS = listOf("0", "*", "*", "*", "*", "*") + +private class CronField(val values: Set, val wildcard: Boolean, val last: Boolean = false) + +private class CronRule( + val seconds: List, + val minutes: List, + val hours: List, + val months: Set, + val daysOfMonth: CronField, + val weekdays: CronField, + val lastWeekdays: Set, + val nthWeekday: Int?, +) { + fun matches(date: LocalDate): Boolean { + if (date.monthValue !in months) return false + val lastDay = date == date.with(TemporalAdjusters.lastDayOfMonth()) + val onDay = date.dayOfMonth in daysOfMonth.values || (daysOfMonth.last && lastDay) + val weekday = date.dayOfWeek.value % 7 + val finalWeek = date.plusDays(7).month != date.month + val onWeekday = (weekday in weekdays.values && (nthWeekday == null || (date.dayOfMonth - 1) / 7 + 1 == nthWeekday)) || + (weekday in lastWeekdays && finalWeek) + return when { + daysOfMonth.wildcard && weekdays.wildcard -> true + daysOfMonth.wildcard -> onWeekday + weekdays.wildcard -> onDay + else -> onDay || onWeekday + } + } +} + +private fun cronAtom(atom: String, min: Int, max: Int, weekday: Boolean): Set? { + val slash = atom.split("/") + if (slash.size > 2) return null + val stepped = slash.size == 2 + val range = if (stepped && '-' !in slash[0]) "${slash[0]}-$max" else slash[0] + val step = if (stepped) slash[1].toIntOrNull() ?: return null else 1 + val bounds = range.split("-") + if (bounds.size == 1) { + val value = range.toIntOrNull()?.takeIf { it in min..max } ?: return null + return setOf(if (weekday) value % 7 else value) + } + val low = bounds[0].toIntOrNull() ?: return null + val high = bounds[1].toIntOrNull() ?: return null + if (low < min || high > max || low > high || step <= 0) return null + return (low..high step step).mapTo(HashSet()) { if (weekday) it % 7 else it } +} + +private fun cronField(raw: String, min: Int, max: Int, weekday: Boolean = false, lastDay: Boolean = false, lastWeekdays: MutableSet? = null): CronField? { + var unknownName = false + val named = CRON_NAME.replace(raw) { match -> + CRON_NAMES[match.value.lowercase()]?.toString() ?: match.value.also { unknownName = true } + } + if (unknownName || !CRON_FIELD.matches(named)) return null + val values = HashSet() + var last = false + for (atom in named.replace(Regex("[*?]"), "$min-$max").split(",")) { + when { + lastDay && atom == "L" -> last = true + lastWeekdays != null && LAST_WEEKDAY.matches(atom) -> lastWeekdays.add(atom[0].digitToInt() % 7) + else -> values.addAll(cronAtom(atom, min, max, weekday) ?: return null) + } + } + return CronField(values, wildcard = raw == "*" || raw == "?", last = last) +} + +private fun cronRule(cron: String): CronRule? { + val text = cron.trim() + if (text.isEmpty() || text.length > MAX_CRON_CHARS) return null + val written = (CRON_ALIASES[text] ?: text).split(WHITESPACE) + if (written.size > 6) return null + // cron-parser fills missing leading fields, so "1 2 3" is a valid, if odd, schedule. + val fields = FIELD_DEFAULTS.take(6 - written.size) + written + val (second, minute, hour, dayOfMonth, month) = fields + val dayOfWeek = fields[5] + + val nth = dayOfWeek.split("#") + if (nth.size > 2 || (nth.size == 2 && dayOfWeek.any { it in ",-/" })) return null + val nthWeekday = if (nth.size == 2) nth[1].toIntOrNull()?.takeIf { it in 1..5 } ?: return null else null + + val lastWeekdays = HashSet() + return CronRule( + seconds = cronField(second, 0, 59)?.values?.sorted() ?: return null, + minutes = cronField(minute, 0, 59)?.values?.sorted() ?: return null, + hours = cronField(hour, 0, 23)?.values?.sorted() ?: return null, + months = cronField(month, 1, 12)?.values ?: return null, + daysOfMonth = cronField(dayOfMonth, 1, 31, lastDay = true) ?: return null, + weekdays = cronField(nth[0], 0, 7, weekday = true, lastWeekdays = lastWeekdays) ?: return null, + lastWeekdays = lastWeekdays, + nthWeekday = nthWeekday, + ) +} + +private fun instantsOf(local: LocalDateTime, zone: ZoneId, everyHour: Boolean): List { + val offsets = zone.rules.getValidOffsets(local) + return if (everyHour && offsets.size == 2) offsets.map(local::toInstant) else listOf(ZonedDateTime.of(local, zone).toInstant()) +} + +/** + * The server's next run for `cron`, or null if it never fires. Like cron-parser, a skipped time runs + * just after the gap, and only every-hour rules run again in a repeated hour. + */ +fun nextOccurrence(cron: String, zone: ZoneId, from: Instant): Instant? { + val rule = cronRule(cron) ?: return null + var date = from.atZone(zone).toLocalDate() + repeat(MAX_SCAN_DAYS) { + var soonest: Instant? = null + if (rule.matches(date)) { + for (hour in rule.hours) for (minute in rule.minutes) for (second in rule.seconds) { + val readings = instantsOf(LocalDateTime.of(date, LocalTime.of(hour, minute, second)), zone, rule.hours.size == 24) + for (at in readings) if (at.isAfter(from) && (soonest == null || at.isBefore(soonest))) soonest = at + if (soonest != null && readings.size == 1) return soonest + } + } + if (soonest != null) return soonest + date = date.plusDays(1) + } + return null +} + +/** `H` fields are randomized by the server, so the app cannot predict their next run. */ +fun hasHashedField(cron: String): Boolean = Regex("(? "*" + items.all { it.toIntOrNull() != null } -> items.sortedBy { it.toInt() }.joinToString(",") + else -> items.joinToString(",") + } +} + +private fun replaceNames(field: String, names: List, first: Int): String { + var text = field + names.forEachIndexed { index, name -> text = text.replace(name, (index + first).toString(), ignoreCase = true) } + return text +} + +private fun inBounds(field: String, min: Int, max: Int): Boolean = field.split(",").all { part -> + val step = part.substringAfter('/', "") + val first = Regex("^\\d+").find(part)?.value?.toIntOrNull() + val second = Regex("^\\d+-(\\d+)").find(part)?.groupValues?.get(1)?.toIntOrNull() + !step.matches(Regex("0+")) && (first == null || first in min..max) && (second == null || second in min..max) +} + +private fun zeroStep(field: String, start: String) = if (field.startsWith("$start/")) "*/" + field.removePrefix("$start/") else field + +private fun boundedStep(field: String, through: Int): String { + if ('/' !in field || Regex("^\\*|-|,").containsMatchIn(field)) return field + val (start, step) = field.split("/", limit = 2) + return "$start-$through/$step" +} + +/** The five fields cronstrue words after normalizing, or null when the expression needs the raw text. */ +private fun wordableFields(cron: String): CronWords? { + var text = cron.trim() + if (text.startsWith("@")) text = SPECIAL_CRONS[text] ?: return null + val parts = text.split(Regex(" +")).map(::sortedList).toMutableList() + if (parts.size == 6) { + if (Regex("\\d{4}$").containsMatchIn(parts[5]) || parts[4] == "?" || parts[2] == "?" || parts[0] != "0") return null + parts.removeAt(0) + } + if (parts.size != 5) return null + + var minute = zeroStep(parts[0], "0") + var hour = zeroStep(parts[1].replaceFirst("?", "*"), "0") + var day = zeroStep(parts[2].replaceFirst("?", "*"), "1") + var month = zeroStep(parts[3], "1") + var weekday = Regex("(^\\d+)|([^#/\\s\\d]\\d+)").replace(parts[4].replaceFirst("?", "*")) { match -> + if (match.value.replaceFirst(Regex("\\D"), "") == "7") match.value.replace("7", "0") else match.value + } + weekday = replaceNames(weekday, WEEKDAY_NUMBERS, 0) + month = replaceNames(month, MONTH_NUMBERS, 1) + if (listOf(minute, hour, day, month, weekday).any { !PLAIN_FIELD.matches(it) || it.isEmpty() }) return null + if (!Regex("[*\\-,/]").containsMatchIn(hour) && Regex("[*/]").containsMatchIn(minute)) hour = "$hour-$hour" + + fun oneStep(field: String) = if (field == "*/1") "*" else field + minute = oneStep(minute) + hour = oneStep(hour) + day = oneStep(day) + month = boundedStep(oneStep(month), 12) + weekday = boundedStep(oneStep(weekday), 6) + val valid = inBounds(minute, 0, 59) && inBounds(hour, 0, 23) && inBounds(day, 1, 31) && inBounds(month, 1, 12) && inBounds(weekday, 0, 6) + return if (valid) CronWords(minute, hour, day, month, weekday) else null +} + +private class Segment( + val all: String, + val single: (String) -> String, + val increment: (String) -> String, + val range: (String) -> String, + val format: (String) -> String, +) + +/** The English cronstrue wording, or null when only the raw expression says it right. */ +fun wordedCron(cron: String): String? = wordableFields(cron)?.sentence() + +private class CronWords(val minute: String, val hour: String, val day: String, val month: String, val weekday: String) { + fun sentence(): String = (timeOfDay() + dayOfMonth() + dayOfWeek() + monthOfYear()) + .replace(", every minute", "") + .replace(", every hour", "") + .replace(", every day", "") + .replace(Regex(", ?$"), "") + .replaceFirstChar { it.uppercase() } + + private fun time(hour: String, minute: String) = "${hour.padStart(2, '0')}:${minute.padStart(2, '0')}" + + private fun timeOfDay(): String = when { + !minute.special() && !hour.special() -> "At " + time(hour, minute) + '-' in minute && ',' !in minute && '/' !in minute && !hour.special() -> { + val bounds = minute.split("-") + "Every minute between ${time(hour, bounds[0])} and ${time(hour, bounds[1])}" + } + ',' in hour && '-' !in hour && '/' !in hour && !minute.special() -> { + val hours = hour.split(",") + buildString { + append("At") + hours.forEachIndexed { index, each -> + append(" ").append(time(each, minute)) + if (index < hours.size - 2) append(",") + if (index == hours.size - 2) append(" and") + } + } + } + else -> { + val minutes = minutesText() + val hours = hoursText() + if (minutes == hours) minutes else listOf(minutes, hours).filter { it.isNotEmpty() }.joinToString(", ") + } + } + + private fun minutesText() = described( + minute, + Segment( + all = "every minute", + single = { it }, + increment = { plural(it, "every %s minute", "every %s minutes") }, + range = { "minutes %s through %s past the hour" }, + format = { value -> + when { + value == "0" && '/' !in hour -> "every hour" + value == "0" -> "on the hour" + else -> plural(value, "at %s minute past the hour", "at %s minutes past the hour") + } + }, + ), + ) + + private fun hoursText(): String { + val rangeEnds = ArrayList>() + var index = 0 + for (range in hour.substringBefore('/').split(",")) { + val parts = range.split("-") + if (parts.size == 2) rangeEnds.add(parts[1] to index + 1) + index += parts.size + } + var evaluated = 0 + return described( + hour, + Segment( + all = "every hour", + single = { value -> + val endsRange = rangeEnds.any { it.first == value && it.second == evaluated } + evaluated += 1 + time(value, if (endsRange && minute != "0") "59" else "0") + }, + increment = { plural(it, "every %s hour", "every %s hours") }, + range = { "between %s and %s" }, + format = { "at %s" }, + ), + ) + } + + private fun dayOfWeek(): String { + if (weekday == "*") return "" + return described( + weekday, + Segment( + all = ", every day", + single = { WEEKDAY_NAMES[it.toInt()] }, + increment = { if (it.toIntOrNull() == 1) "" else ", every %s days of the week" }, + range = { ", %s through %s" }, + format = { if (day != "*") ", and on %s" else ", only on %s" }, + ), + ) + } + + private fun monthOfYear() = described( + month, + Segment( + all = "", + single = { MONTH_NAMES[it.toInt() - 1] }, + increment = { if (it.toIntOrNull() == 1) "" else ", every %s months" }, + range = { ", %s through %s" }, + format = { ", only in %s" }, + ), + ) + + private fun dayOfMonth(): String { + if (day == "*" && weekday != "*") return "" + return described( + day, + Segment( + all = ", every day", + single = { it }, + increment = { if (it == "1") ", every day" else ", every %s days in a month" }, + range = { ", between day %s and %s of the month" }, + format = { ", on day %s of the month" }, + ), + ) + } + + private fun described(field: String, segment: Segment): String = when { + field.isEmpty() -> "" + field == "*" -> segment.all + ',' in field -> listed(field, segment) + '/' in field -> stepped(field, segment) + '-' in field -> ranged(field, segment.range, segment.single) + else -> fill(segment.format(field), segment.single(field)) + } + + private fun listed(field: String, segment: Segment): String { + val stepped = '/' in field + val items = field.split(",") + val text = buildString { + items.forEachIndexed { index, item -> + if (index > 0 && items.size > 2) { + append(",") + if (index < items.size - 1) append(" ") + } + if (index > 0 && (index == items.size - 1 || items.size == 2)) append(" and ") + when { + '/' in item || '-' in item -> { + val plainRange = '-' in item && '/' !in item + val inner = Segment(segment.all, segment.single, segment.increment, if (plainRange) ({ ", %s through %s" }) else segment.range, segment.format) + val part = described(item, inner) + append( + when { + plainRange -> part.replaceFirst(", ", "") + index > 0 -> part.removePrefix(", ") + else -> part + }, + ) + } + !stepped -> append(segment.single(item)) + else -> { + val part = described(item, segment) + append(if (index > 0) part.removePrefix(", ") else part) + } + } + } + } + return if (stepped) text else fill(segment.format(field), text) + } + + private fun stepped(field: String, segment: Segment): String { + val (start, step) = field.split("/", limit = 2) + var text = fill(segment.increment(step), step) + if ('-' in start) { + val range = ranged(start, segment.range, segment.single) + if (!range.startsWith(", ")) text += ", " + text += range + } else if ('*' !in start) { + text += ", starting " + fill(segment.format(start), segment.single(start)).replaceFirst(", ", "") + } + return text + } + + private fun ranged(field: String, range: (String) -> String, single: (String) -> String): String { + val bounds = field.split("-") + val first = single(bounds[0]) + val second = single(bounds[1]) + return fill(range(field), first, second) + } +} diff --git a/app/src/main/java/dev/crumble/android/model/Display.kt b/app/src/main/java/dev/crumble/android/model/Display.kt new file mode 100644 index 0000000..ec88a14 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/Display.kt @@ -0,0 +1,300 @@ +package dev.crumble.android.model + +import kotlin.math.hypot +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.doubleOrNull + +private const val DISPLAY_TOOL = "show" +private const val DESKTOP_SCREENSHOT_TOOL = "desktop_screenshot" + +/** Web `--chart-1` to `--chart-5`, which are the same in both themes. */ +private val CHART_COLORS = listOf(0xFFD4D4D4, 0xFF737373, 0xFF525252, 0xFF404040, 0xFF262626) + +data class DisplayStat( + val label: String, + val value: String, + val change: String? = null, + val trend: String? = null, + val caption: String? = null, +) + +/** A table cell; `number` is set only for a numeric cell, which right-aligns and formats. */ +data class DisplayCell(val text: String, val number: Double? = null) + +/** What the `show` tool asked to draw. */ +sealed class DisplayCard { + abstract val title: String? + + data class Stats(override val title: String?, val items: List) : DisplayCard() + + data class Table(override val title: String?, val columns: List, val rows: List>) : DisplayCard() + + /** Layouts hold up to thousands of primitives, so they are parsed when drawn, not whenever rows are built. */ + data class Chart(override val title: String?, val layouts: JsonArray) : DisplayCard() +} + +private class InvalidDisplay : Exception() + +private fun JsonElement?.string(): String = + (this as? JsonPrimitive)?.takeIf { it.isString }?.content ?: throw InvalidDisplay() + +private fun JsonElement?.optionalString(): String? = if (this == null) null else string() + +private fun JsonElement?.array(): JsonArray = this as? JsonArray ?: throw InvalidDisplay() + +private fun JsonElement?.record(): JsonObject = this as? JsonObject ?: throw InvalidDisplay() + +private fun cellOf(element: JsonElement): DisplayCell { + val primitive = element as? JsonPrimitive ?: throw InvalidDisplay() + if (primitive.isString) return DisplayCell(primitive.content) + val number = primitive.doubleOrNull ?: throw InvalidDisplay() + return DisplayCell(primitive.content, number) +} + +private fun statOf(element: JsonElement): DisplayStat { + val item = element.record() + val trend = item["trend"].optionalString() + if (trend != null && trend !in setOf("up", "down", "flat")) throw InvalidDisplay() + return DisplayStat( + label = item["label"].string(), + value = item["value"].string(), + change = item["change"].optionalString(), + trend = trend, + caption = item["caption"].optionalString(), + ) +} + +/** The card a `show` result draws, or null when it is not one or fails the server's schema, like the website. */ +fun displayOf(message: Message): DisplayCard? { + if (message.role != "toolResult" || message.isError == true || message.toolName != DISPLAY_TOOL) return null + return try { + val details = message.toolDetails.record() + val title = details["title"].optionalString() + when (details["kind"].string()) { + "stats" -> DisplayCard.Stats(title, details["items"].array().map(::statOf)) + "table" -> DisplayCard.Table( + title, + details["columns"].array().map { it.string() }, + details["rows"].array().map { row -> row.array().map(::cellOf) }, + ) + "chart" -> DisplayCard.Chart( + title, + details["layouts"].array().also { layouts -> + layouts.forEach { layout -> + layout.record().let { it["nodes"].array(); it["points"].array() } + } + }, + ) + else -> null + } + } catch (_: InvalidDisplay) { + null + } +} + +fun isDesktopScreenshot(message: Message): Boolean = + message.role == "toolResult" && message.toolName == DESKTOP_SCREENSHOT_TOOL && message.isError != true && + !message.entryId.isNullOrEmpty() + +/** A column reads as numeric only when every row's cell is a number. */ +fun numericColumns(columnCount: Int, rows: List>): List = + List(columnCount) { index -> rows.all { it.getOrNull(index)?.number != null } } + +/** Natural widths, with spare room shared out so the table fills the card as it does on the web. */ +fun fitColumns(natural: List, available: Float): List { + val spare = available - natural.sum() + return if (spare <= 0f || natural.isEmpty()) natural else natural.map { it + spare / natural.size } +} + +sealed class ChartInk { + data object None : ChartInk() + data object Foreground : ChartInk() + data object Background : ChartInk() + data class Literal(val argb: Long) : ChartInk() +} + +/** Series colors reuse the five theme colors, offset by one as the website's are. */ +private fun seriesColor(series: Int) = CHART_COLORS[series % CHART_COLORS.size] + +/** Resolves a chart color: a token the server normalized, or a hex literal. */ +fun chartInk(color: String?, fallback: ChartInk): ChartInk { + if (color.isNullOrEmpty()) return fallback + when (color) { + "none" -> return ChartInk.None + "foreground" -> return ChartInk.Foreground + "background" -> return ChartInk.Background + } + Regex("^series-(\\d+)$").find(color)?.let { return ChartInk.Literal(seriesColor(it.groupValues[1].toInt())) } + val hex = color.removePrefix("#").takeIf { color.startsWith("#") } ?: return fallback + val digits = when (hex.length) { + 3 -> hex.flatMap { listOf(it, it) }.joinToString("") + "ff" + 6 -> hex + "ff" + 8 -> hex + else -> return fallback + } + val rgba = digits.toLongOrNull(16) ?: return fallback + return ChartInk.Literal(((rgba and 0xFF) shl 24) or (rgba shr 8)) +} + +data class ChartClip(val x: Float, val y: Float, val width: Float, val height: Float) + +data class ChartCommand(val op: String, val args: List) + +sealed class ChartShape { + data class Line(val x1: Float, val y1: Float, val x2: Float, val y2: Float) : ChartShape() + data class Curve(val commands: List, val evenOdd: Boolean) : ChartShape() + data class Circle(val x: Float, val y: Float, val radius: Float) : ChartShape() + data class Box(val x: Float, val y: Float, val width: Float, val height: Float, val radius: Float) : ChartShape() + data class Label( + val x: Float, + val y: Float, + val text: String, + val anchor: String, + val baseline: String, + val rotate: Float, + val size: Float, + val weight: Int, + ) : ChartShape() +} + +data class ChartNode( + val shape: ChartShape, + val fill: ChartInk, + val stroke: ChartInk, + val fillOpacity: Float = 1f, + val strokeOpacity: Float = 1f, + val opacity: Float = 1f, + val strokeWidth: Float = 1f, + val lineCap: String? = null, + val lineJoin: String? = null, + val dash: List = emptyList(), + val clip: ChartClip? = null, +) + +data class ChartTooltipRow(val label: String, val value: String) + +data class ChartPoint( + val x: Float, + val y: Float, + val title: String? = null, + val text: String? = null, + val rows: List = emptyList(), +) + +data class ChartLayout(val width: Float, val height: Float, val nodes: List, val points: List) + +private val COMMAND_ARGS = mapOf("M" to 2, "L" to 2, "Q" to 4, "C" to 6, "Z" to 0) + +private fun JsonObject.float(key: String): Float? = (this[key] as? JsonPrimitive)?.doubleOrNull?.toFloat() + +private fun JsonObject.text(key: String): String? = (this[key] as? JsonPrimitive)?.takeIf { it.isString }?.content + +private fun floats(element: JsonElement?): List? = + (element as? JsonArray)?.map { (it as? JsonPrimitive)?.doubleOrNull?.toFloat() ?: return null } + +private fun commandOf(element: JsonElement): ChartCommand? { + val parts = element as? JsonArray ?: return null + val op = (parts.firstOrNull() as? JsonPrimitive)?.content ?: return null + val args = floats(JsonArray(parts.drop(1))) ?: return null + return ChartCommand(op, args).takeIf { COMMAND_ARGS[op] == args.size } +} + +private fun shapeOf(node: JsonObject): ChartShape? { + fun required(key: String) = node.float(key) + return when (node.text("kind")) { + "line" -> ChartShape.Line( + required("x1") ?: return null, + required("y1") ?: return null, + required("x2") ?: return null, + required("y2") ?: return null, + ) + "path" -> ChartShape.Curve( + (node["commands"] as? JsonArray)?.mapNotNull(::commandOf) ?: return null, + (node["evenOdd"] as? JsonPrimitive)?.booleanOrNull == true, + ) + "circle" -> ChartShape.Circle(required("x") ?: return null, required("y") ?: return null, required("radius") ?: return null) + "rect" -> ChartShape.Box( + required("x") ?: return null, + required("y") ?: return null, + required("width") ?: return null, + required("height") ?: return null, + required("radius") ?: 0f, + ) + "text" -> ChartShape.Label( + required("x") ?: return null, + required("y") ?: return null, + node.text("text") ?: return null, + node.text("anchor") ?: "start", + node.text("baseline") ?: "auto", + required("rotate") ?: 0f, + required("size") ?: return null, + required("weight")?.toInt() ?: 400, + ) + else -> null + } +} + +private fun nodeOf(element: JsonElement): ChartNode? { + val node = element as? JsonObject ?: return null + val shape = shapeOf(node) ?: return null + return ChartNode( + shape = shape, + fill = chartInk(node.text("fill"), if (shape is ChartShape.Line) ChartInk.None else ChartInk.Foreground), + stroke = chartInk(node.text("stroke"), ChartInk.None), + fillOpacity = node.float("fillOpacity") ?: 1f, + strokeOpacity = node.float("strokeOpacity") ?: 1f, + opacity = node.float("opacity") ?: 1f, + strokeWidth = node.float("strokeWidth") ?: 1f, + lineCap = node.text("lineCap"), + lineJoin = node.text("lineJoin"), + dash = floats(node["dash"]).orEmpty(), + clip = floats(node["clip"])?.takeIf { it.size == 4 }?.let { ChartClip(it[0], it[1], it[2], it[3]) }, + ) +} + +private fun pointOf(element: JsonElement): ChartPoint? { + val point = element as? JsonObject ?: return null + return ChartPoint( + x = point.float("x") ?: return null, + y = point.float("y") ?: return null, + title = point.text("title"), + text = point.text("text"), + rows = (point["rows"] as? JsonArray).orEmpty().mapNotNull { row -> + val cells = row as? JsonObject ?: return@mapNotNull null + ChartTooltipRow(cells.text("label") ?: return@mapNotNull null, cells.text("value") ?: return@mapNotNull null) + }, + ) +} + +/** Each compiled width, narrowest first. Nodes are stored unchecked, so one bad node is dropped, not the chart. */ +fun chartLayouts(layouts: JsonArray): List = layouts.mapNotNull { element -> + val layout = element as? JsonObject ?: return@mapNotNull null + ChartLayout( + width = layout.float("width")?.takeIf { it > 0f } ?: return@mapNotNull null, + height = layout.float("height")?.takeIf { it > 0f } ?: return@mapNotNull null, + nodes = (layout["nodes"] as? JsonArray).orEmpty().mapNotNull(::nodeOf), + points = (layout["points"] as? JsonArray).orEmpty().mapNotNull(::pointOf), + ) +}.sortedBy { it.width } + +/** The widest layout that fits, or the narrowest when none does. */ +fun chartLayoutFor(layouts: List, width: Float): ChartLayout? = + layouts.lastOrNull { it.width <= width } ?: layouts.firstOrNull() + +/** The hover target closest to a touch, in layout units, within `reach`. */ +fun nearestChartPoint(points: List, x: Float, y: Float, reach: Float): ChartPoint? { + var best: ChartPoint? = null + var distance = reach + for (point in points) { + val d = hypot(point.x - x, point.y - y) + if (d < distance) { + best = point + distance = d + } + } + return best +} diff --git a/app/src/main/java/dev/crumble/android/model/GeneralSettings.kt b/app/src/main/java/dev/crumble/android/model/GeneralSettings.kt new file mode 100644 index 0000000..74269a1 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/GeneralSettings.kt @@ -0,0 +1,18 @@ +package dev.crumble.android.model + +enum class ThemeChoice(val value: String, val label: String) { + System("system", "System"), + Light("light", "Light"), + Dark("dark", "Dark"), + ; + + companion object { + fun of(value: String?): ThemeChoice? = entries.firstOrNull { it.value == value } + } +} + +fun replyNotificationsDescription(enabled: Boolean, allowed: Boolean): String = when { + !allowed -> "Blocked for Crumble in Android's settings." + enabled -> "Replies from chats you don't have open show as notifications." + else -> "Off on this device." +} diff --git a/app/src/main/java/dev/crumble/android/model/GroupChats.kt b/app/src/main/java/dev/crumble/android/model/GroupChats.kt new file mode 100644 index 0000000..dea586d --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/GroupChats.kt @@ -0,0 +1,140 @@ +package dev.crumble.android.model + +import dev.crumble.android.generated.GroupActivity +import dev.crumble.android.generated.GroupChat +import java.util.UUID +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.contentOrNull + +const val MIN_GROUP_MEMBERS = 2 +const val MAX_GROUP_MEMBERS = 6 +const val GROUP_NAME_LIMIT = 80 + +/** One read of a group chat: its newest page of messages and what its bots are doing. */ +data class GroupSnapshot( + val messages: List, + val hasMore: Boolean, + val oldestEntryId: String?, + val groupChat: GroupChat, + val activity: GroupActivity, +) + +/** The form for a new group chat, or for editing the one named by `groupID`. */ +data class GroupDraft( + val id: UUID = UUID.randomUUID(), + val groupID: String = "", + val name: String = "", + val memberIDs: List = emptyList(), +) + +/** What the owner is writing to one chat; it survives leaving the chat. */ +data class ChatComposer( + val draft: String = "", + val attachments: List = emptyList(), + val replyTo: Message? = null, +) + +/** The open group chat. `group` stays null until the first snapshot arrives. */ +data class GroupConversation( + val groupID: String, + val group: GroupChat? = null, + val activity: GroupActivity? = null, + val messages: List = emptyList(), + val hasMore: Boolean = false, + val oldestEntryID: String? = null, + val olderLoaded: Boolean = false, + val loadingOlder: Boolean = false, + val loadError: String? = null, + val sendError: String? = null, + val streamStatus: String = "", +) { + /** Keeps the rows and cursor of older pages; snapshots only carry the newest page. */ + fun merging(incoming: GroupSnapshot): GroupConversation { + val known = messages.mapTo(HashSet()) { it.id } + // After a long disconnect no cursor reaches the rows between the old and new pages. + val gap = incoming.hasMore && known.isNotEmpty() && incoming.messages.none { it.id in known } + val keepCursor = olderLoaded && !gap + return copy( + group = incoming.groupChat, + activity = incoming.activity, + messages = if (gap) incoming.messages else mergeMessages(messages, incoming.messages), + hasMore = if (keepCursor) hasMore else incoming.hasMore, + oldestEntryID = if (keepCursor) oldestEntryID else incoming.oldestEntryId, + olderLoaded = keepCursor, + loadError = null, + streamStatus = "", + ) + } + + fun adding(page: ChatHistoryResponse) = copy( + messages = mergeMessages(messages, page.messages.orEmpty()), + hasMore = page.hasMore == true, + oldestEntryID = page.oldestEntryId, + olderLoaded = true, + loadingOlder = false, + ) +} + +fun isValidGroup(name: String, memberIDs: List): Boolean = + name.trim().isNotEmpty() && memberIDs.size in MIN_GROUP_MEMBERS..MAX_GROUP_MEMBERS + +/** Group messages have no blocks; reactions and tool activity show elsewhere or not at all. */ +fun shownInGroup(message: Message): Boolean = + (message.role == "user" || message.role == "assistant") && + (message.text.isNotBlank() || !message.attachments.isNullOrEmpty()) + +/** A group's members in join order. A deleted bot has no row. */ +fun membersOf(group: GroupChat, agents: List): List = + group.memberIds.mapNotNull { id -> agents.firstOrNull { it.id == id } } + +fun isGroupRunning(activity: GroupActivity?): Boolean = + activity?.members.orEmpty().any { it.status == "running" || it.status == "queued" } + +private val MEMBER_STATUS = mapOf( + "running" to "is answering", + "queued" to "answers next", + "disabled" to "is disabled and skipped", +) + +/** What each member is doing, or who is here when nobody is doing anything. */ +fun groupStatusLine(members: List, activity: GroupActivity?): String { + val busy = members.mapNotNull { member -> + val status = activity?.members?.firstOrNull { it.agentId == member.id }?.status + MEMBER_STATUS[status]?.takeIf { status != "disabled" }?.let { "${member.name} $it" } + } + return if (busy.isNotEmpty()) busy.joinToString(" · ") else members.joinToString(", ") { it.name } +} + +/** How an avatar reads to a screen reader, such as "Kev is answering". */ +fun memberStatusLabel(member: Agent, status: String?): String = + "${member.name} ${MEMBER_STATUS[status] ?: "is here"}" + +/** Emoji reactions by the entry `targetOf` says they answer, each labeled with the bot that reacted. */ +private fun reactionsOf(messages: List, targetOf: (Message, String?) -> String?): Map> { + val reactions = linkedMapOf>() + var lastOwner: String? = null + for (message in messages) { + if (message.role == "user") message.entryId?.let { lastOwner = it } + if (message.role != "toolResult" || message.toolName != "react" || message.isError == true) continue + val emoji = ((message.toolDetails as? JsonObject)?.get("emoji") as? JsonPrimitive)?.contentOrNull ?: continue + val target = targetOf(message, lastOwner) ?: continue + reactions.getOrPut(target) { mutableListOf() }.add(message.origin?.name?.let { "$it $emoji" } ?: emoji) + } + return reactions +} + +/** A group records what each reaction answers. */ +fun groupReactions(messages: List) = reactionsOf(messages) { message, _ -> message.replyTo } + +/** A bot reacts to the owner's last message. */ +fun botReactions(messages: List) = reactionsOf(messages) { _, lastOwner -> lastOwner } + +/** A group message's sources, which the server stores with the message. */ +fun groupSourcesOf(message: Message): Sources? { + val sources = message.sources.orEmpty().mapNotNull { source -> sourceKey(source.url)?.let { it to source.title } } + return sources.toMap().takeIf { it.isNotEmpty() } +} + +fun groupReplyLabel(message: Message): String = + if (message.role == "user") "You" else message.origin?.name ?: "a bot" diff --git a/app/src/main/java/dev/crumble/android/model/Home.kt b/app/src/main/java/dev/crumble/android/model/Home.kt new file mode 100644 index 0000000..a000297 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/Home.kt @@ -0,0 +1,8 @@ +package dev.crumble.android.model + +/** What the home screen says under a bot's name. */ +fun botStatusLine(agent: Agent, working: Boolean): String = when { + working -> "Working…" + agent.enabled -> agent.description?.nilIfEmpty ?: "Ready" + else -> "Paused" +} diff --git a/app/src/main/java/dev/crumble/android/model/Jobs.kt b/app/src/main/java/dev/crumble/android/model/Jobs.kt new file mode 100644 index 0000000..864ae8b --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/Jobs.kt @@ -0,0 +1,179 @@ +package dev.crumble.android.model + +import dev.crumble.android.generated.CodingJobQuestion +import java.util.Locale +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.doubleOrNull + +enum class JobKind(val label: String) { + coding("Coding job"), + desktop("Desktop job"), +} + +fun isJobOrigin(kind: String?): Boolean = JobKind.entries.any { it.name == kind } + +/** A coding or desktop job; `status` is what the tool result that named it reported. */ +data class JobRef(val kind: JobKind, val name: String, val status: String? = null) + +data class JobSummary( + val kind: JobKind, + val name: String, + val status: String, + val model: String? = null, + val usage: JsonElement? = null, + val question: CodingJobQuestion? = null, +) { + val ref: JobRef + get() = JobRef(kind, name) + + val subtitle: String + get() = listOfNotNull(model, costLine(usage)).joinToString(" · ") +} + +/** The open job panel: the job's transcript, oldest message first, and where earlier pages start. */ +data class JobPanel( + val job: JobRef, + val messages: List = emptyList(), + val hasMore: Boolean = false, + val oldestEntryID: String? = null, + val loaded: Boolean = false, + val failed: Boolean = false, + val loadingEarlier: Boolean = false, + val downloading: Boolean = false, + val downloadFailed: Boolean = false, +) + +sealed class JobItem { + abstract val id: String + + data class Task(override val id: String, val text: String) : JobItem() + data class Reply(override val id: String, val text: String) : JobItem() + data class Step( + override val id: String, + val tool: String, + val subject: String?, + val result: Message? = null, + ) : JobItem() +} + +fun jobWorking(status: String?): Boolean = status == "working" || status == "running" + +/** A coding or desktop job a tool result started or messaged. */ +fun jobOf(message: Message): JobRef? { + if (message.role != "toolResult" || message.isError == true) return null + val kind = when (message.toolName) { + "coding" -> JobKind.coding + "desktop" -> JobKind.desktop + else -> return null + } + val details = message.toolDetails as? JsonObject ?: return null + val name = details.string("name")?.nilIfEmpty ?: return null + return JobRef(kind, name, details.string("status")) +} + +/** A job's cost over its models. Subscription providers such as Claude Code report zero, which says nothing. */ +fun costLine(usage: JsonElement?): String? { + val models = (usage as? JsonObject)?.get("models") as? JsonObject ?: return null + val cost = models.values.sumOf { model -> + val total = ((model as? JsonObject)?.get("cost") as? JsonObject)?.get("total") as? JsonPrimitive + total?.doubleOrNull ?: 0.0 + } + return if (cost > 0) String.format(Locale.ROOT, "$%.4f", cost) else null +} + +private fun JsonObject.string(key: String): String? = (this[key] as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull + +private fun blocksOf(message: Message): List = + (message.blocks as? JsonArray).orEmpty().filterIsInstance() + +private fun stepOf(message: Message, block: JsonObject, index: Int): JobItem.Step { + val arguments = block["arguments"] as? JsonObject + return JobItem.Step( + id = block.string("id") ?: "${message.id}:$index", + tool = block.string("name").orEmpty(), + subject = arguments?.string("command") ?: arguments?.string("path"), + ) +} + +/** The job's task, replies, and tool steps; a tool result attaches to the step that called it. */ +fun jobItems(messages: List): List { + val items = mutableListOf() + val steps = mutableMapOf() + for (message in messages) { + when (message.role) { + "user" -> if (message.text.isNotBlank()) items.add(JobItem.Task(message.id, message.text)) + "assistant" -> blocksOf(message).forEachIndexed { index, block -> + val text = block.string("text").orEmpty() + if (block.string("type") == "text" && text.isNotBlank()) { + items.add(JobItem.Reply("${message.id}:$index", text)) + } + if (block.string("type") == "toolCall" && !block.string("name").isNullOrEmpty()) { + val step = stepOf(message, block, index) + steps[step.id] = items.size + items.add(step) + } + } + "toolResult" -> steps[message.toolCallId]?.let { at -> + items[at] = (items[at] as JobItem.Step).copy(result = message) + } + } + } + return items +} + +private val STEP_VERBS = mapOf( + "bash" to "Ran", + "read" to "Read", + "write" to "Wrote", + "edit" to "Edited", + "computer_use" to "Used the bot desktop", +) + +fun jobStepVerb(tool: String): String = STEP_VERBS[tool] ?: tool.replaceFirstChar { it.uppercase() } + +/** Keeps pages loaded earlier and rows the newest page has scrolled past; entries never change. */ +fun mergeJobPages(existing: List, newest: List): List { + val first = newest.firstOrNull()?.id ?: return existing + return existing.takeWhile { it.id != first } + newest +} + +/** A fence longer than any backtick run in the text, so the text can't close it. */ +private fun fenced(text: String, info: String = ""): String { + val longest = Regex("`+").findAll(text).maxOfOrNull { it.value.length } ?: 0 + val fence = "`".repeat(maxOf(longest, 2) + 1) + return "$fence$info\n$text\n$fence" +} + +@OptIn(ExperimentalSerializationApi::class) +private val PrettyJson = Json { + prettyPrint = true + prettyPrintIndent = " " +} + +private fun messageMarkdown(message: Message): List = when (message.role) { + "user" -> listOf("## Task\n\n${message.text}") + "toolResult" -> listOf((if (message.isError == true) "Failed:\n\n" else "") + fenced(message.text)) + "assistant" -> blocksOf(message).mapNotNull { block -> + val text = block.string("text").orEmpty() + val name = block.string("name").orEmpty() + when { + block.string("type") == "text" && text.isNotBlank() -> text + block.string("type") == "toolCall" && name.isNotEmpty() -> { + val arguments = PrettyJson.encodeToString(JsonElement.serializer(), block["arguments"] ?: JsonObject(emptyMap())) + "### $name\n\n${fenced(arguments, "json")}" + } + else -> null + } + } + else -> emptyList() +} + +/** A job's transcript as the Markdown document the web app downloads. */ +fun jobMarkdown(job: JobRef, messages: List): String = + (listOf("# ${job.name}", job.kind.label) + messages.flatMap(::messageMarkdown)).joinToString("\n\n") + "\n" diff --git a/app/src/main/java/dev/crumble/android/model/MentionComposer.kt b/app/src/main/java/dev/crumble/android/model/MentionComposer.kt index 4eb80ef..1605027 100644 --- a/app/src/main/java/dev/crumble/android/model/MentionComposer.kt +++ b/app/src/main/java/dev/crumble/android/model/MentionComposer.kt @@ -91,3 +91,7 @@ fun insertingNewline(into: String, replacing: IntRange? = null): NewlineInsertio val edited = into.substring(0, start) + "\n" + into.substring(endExclusive) return NewlineInsertion(text = edited, caret = start + 1) } + +/** The bots an `@` mention can reach from `bot`. */ +fun mentionableBots(bot: Agent, bots: List): List = + if ("delegate" in bot.tools.orEmpty()) bots.filter { it.enabled && it.id != bot.id } else emptyList() diff --git a/app/src/main/java/dev/crumble/android/model/Models.kt b/app/src/main/java/dev/crumble/android/model/Models.kt index 9d7a0eb..b3f2fae 100644 --- a/app/src/main/java/dev/crumble/android/model/Models.kt +++ b/app/src/main/java/dev/crumble/android/model/Models.kt @@ -1,5 +1,6 @@ package dev.crumble.android.model +import dev.crumble.android.generated.SecretStatus import java.time.Instant import java.time.ZoneId import java.time.ZonedDateTime @@ -35,10 +36,12 @@ data class Agent( val name: String = "", val description: String? = null, val instructions: String? = null, - val avatar: String? = null, + val avatar: dev.crumble.android.generated.BotAvatarDefinition? = null, val enabled: Boolean = false, val provider: String? = null, val model: String? = null, + val webSearchProvider: String? = null, + val desktopModel: ModelChoice? = null, val tools: List? = null, val delegates: List? = null, val skills: List? = null, @@ -49,6 +52,9 @@ data class Agent( val lastMessage: String? = null, ) +@Serializable +data class ModelChoice(val provider: String = "", val model: String = "") + @Serializable data class Inference( val thinkingLevel: String = "off", @@ -63,6 +69,7 @@ data class ModelSummary( val name: String? = null, val contextWindow: Int? = null, val reasoning: Boolean? = null, + val thinkingLevels: List? = null, ) @Serializable @@ -78,6 +85,7 @@ data class MessageOrigin( val kind: String = "", val name: String? = null, val agentId: String? = null, + val source: String? = null, ) /** A persisted request or reply exchanged between two bots. */ @@ -91,6 +99,22 @@ data class BotCommunication( val status: String = "", ) +/** A desktop job action in the transcript; its live state comes from the bot's held actions. */ +@Serializable +data class HeldActionRef(val id: String = "", val job: String = "") + +/** A coding job's question in the transcript; whether it still waits comes from the job listing. */ +@Serializable +data class JobQuestionRef(val id: String = "", val job: String = "") + +/** A `request_bot` result in the transcript; its live state comes from the bot's requests. */ +@Serializable +data class BotRequestRef(val id: String = "", val name: String = "") + +/** A page a group message's bot searched or read, stored with the message. */ +@Serializable +data class MessageSource(val url: String = "", val title: String = "") + /** Client-side delivery state for an optimistic owner message. */ @Serializable enum class MessageDeliveryState { @@ -117,6 +141,16 @@ data class Message( /** The idempotency key echoed by the server for owner messages. */ val requestId: String? = null, val deliveryState: MessageDeliveryState = MessageDeliveryState.confirmed, + val heldAction: HeldActionRef? = null, + val jobQuestion: JobQuestionRef? = null, + val botRequest: BotRequestRef? = null, + val credentialRequest: SecretRequestRef? = null, + val loginRequest: SecretRequestRef? = null, + val toolName: String? = null, + val toolCallId: String? = null, + val isError: Boolean? = null, + val toolDetails: JsonElement? = null, + val sources: List? = null, ) { val text: String get() = contentText(content) @@ -162,6 +196,9 @@ data class Memory( val id: String = "", val content: String = "", val createdAt: String? = null, + val agentId: String? = null, + val source: dev.crumble.android.generated.MemorySource? = null, + val updatedAt: String? = null, ) /** A shared skill: bundled defaults apply to every bot; library entries are opt-in. */ @@ -172,6 +209,9 @@ data class SharedSkill( val instructions: String = "", val source: String? = null, val path: String? = null, + val description: String? = null, + val origin: dev.crumble.android.generated.SkillOrigin? = null, + val update: dev.crumble.android.generated.SkillUpdate? = null, ) { val isDefault: Boolean get() = source == "bundled" @@ -189,6 +229,12 @@ data class Schedule( val enabled: Boolean = false, /** The bot that saved this task. Null when the owner saved it. */ val createdByAgentId: String? = null, + val kind: String = "prompt", + val command: String? = null, + val timeoutSeconds: Long = 600, + val notify: Boolean = true, + val eventSourceId: String? = null, + val nextRunAt: String? = null, ) @Serializable @@ -201,6 +247,7 @@ data class Execution( val error: String? = null, val createdAt: String? = null, val updatedAt: String? = null, + val scheduleId: String? = null, ) @Serializable @@ -221,6 +268,10 @@ data class MCPServer( val authenticated: Boolean? = null, /** How the server signs in: "oauth", "token", or "none". */ val auth: String? = null, + val oauthClientId: String? = null, + val token: SecretStatus? = null, + val oauthClientSecret: SecretStatus? = null, + val error: String? = null, ) /** The start of an OAuth sign-in: a URL to open, or `authorized` when saved tokens still work. */ @@ -243,6 +294,8 @@ data class ActivityEvent( val eventId: String? = null, val serverId: String? = null, val createdAt: String? = null, + val groupId: String? = null, + val groupName: String? = null, ) @Serializable @@ -254,25 +307,45 @@ data class ActivityRecord( val timestamp: Long? = null, val kind: String = "", val details: JsonElement? = null, + val change: dev.crumble.android.generated.LearnedChange? = null, ) @Serializable data class ActivityFeedResponse( val activities: List = emptyList(), val hasMore: Boolean = false, + val nextCursor: String? = null, ) -fun ActivityRecord.displayLabel(): String { - val objectDetails = details as? JsonObject - val communication = objectDetails?.get("communication") as? JsonObject - val from = (communication?.get("fromName") as? JsonPrimitive)?.contentOrNull - val to = (communication?.get("toName") as? JsonPrimitive)?.contentOrNull - if (!from.isNullOrEmpty() && !to.isNullOrEmpty()) return "$from → $to" - return listOf("name", "toolName", "serverName") - .firstNotNullOfOrNull { (objectDetails?.get(it) as? JsonPrimitive)?.contentOrNull } - ?: kind.replace('-', ' ').replaceFirstChar { it.uppercase() } +private val CHANGE_VERBS = mapOf("create" to "added", "update" to "changed", "delete" to "deleted", "revert" to "reverted") + +private fun changeText(source: JsonObject?, key: String) = (source?.get(key) as? JsonPrimitive)?.contentOrNull + +/** What a learned change did, such as "Kev's review changed a skill". */ +internal fun changeSummary(change: JsonObject, botName: String?): String { + val actor = when (changeText(change, "actor")) { + "owner" -> "You" + "review" -> botName?.let { "$it's review" } ?: "A review" + "curator" -> "The curator" + else -> botName ?: "A bot" + } + val target = when { + changeText(change, "target") == "skill" -> "a skill" + changeText(change, "agentId") != null -> "a memory" + else -> "a shared memory" + } + return "$actor ${CHANGE_VERBS[changeText(change, "action")] ?: "changed"} $target" +} + +/** The record a learned change touched: a memory's first line or a skill's name. */ +internal fun changeTitle(change: JsonObject): String { + val state = change["after"] as? JsonObject ?: change["before"] as? JsonObject + return changeText(state, "content")?.substringBefore('\n') ?: changeText(state, "name") ?: changeText(change, "targetId").orEmpty() } +/** What a learned change did and to what, such as "Kev's review changed a skill · Triage". */ +internal fun changeLabel(change: JsonObject, botName: String?): String = "${changeSummary(change, botName)} · ${changeTitle(change)}" + /** Reads the visible text of message content: a string, text parts, or a text object. */ fun contentText(value: JsonElement?): String { when (value) { @@ -321,12 +394,17 @@ sealed class ChatRow { } companion object { - fun rows(messages: List, snapshot: ChatSnapshot?, hasMore: Boolean): List { + fun rows( + messages: List, + snapshot: ChatSnapshot?, + hasMore: Boolean, + shown: (Message) -> Boolean = ::shownInChat, + ): List { val rows = mutableListOf() if (hasMore) rows.add(Older) var last: Long = 0 for (message in messages) { - if (!shownInChat(message)) continue + if (!shown(message)) continue val at = message.timestamp if (at != null && at > 0) { if (at - last > 30L * 60L * 1000L) { @@ -350,12 +428,14 @@ sealed class ChatRow { /** * Keeps the conversation itself: owner and agent text and context events, not thinking, - * tool calls, or tool results. + * tool calls, or tool results other than decisions, jobs, and display cards. */ fun shownInChat(message: Message): Boolean { return when (message.role) { - "user" -> message.text.isNotEmpty() || !message.attachments.isNullOrEmpty() + "user" -> (message.text.isNotEmpty() || !message.attachments.isNullOrEmpty()) && !isJobOrigin(message.origin?.kind) "event" -> message.text.isNotEmpty() + "toolResult" -> message.botRequest != null || message.credentialRequest != null || message.loginRequest != null || + jobOf(message) != null || displayOf(message) != null || isDesktopScreenshot(message) "assistant" -> { val blocks = message.blocks if (blocks is JsonArray) { @@ -416,10 +496,25 @@ fun validateTask( cron: String, runAt: String, timezone: String = ZoneId.systemDefault().id, + kind: String = "prompt", + command: String = "", + timeoutSeconds: String = "600", + onEvent: Boolean = false, + eventSourceID: String = "", ): String? { - if (name.trim().isEmpty() || prompt.trim().isEmpty()) { + if (kind == "script") { + if (name.trim().isEmpty() || command.isBlank()) { + return "Task name and command are required." + } + if (timeoutSeconds.trim().toLongOrNull()?.takeIf { it in 1..3600 } == null) { + return "Timeout must be between 1 and 3600 seconds." + } + } else if (name.trim().isEmpty() || prompt.trim().isEmpty()) { return "Task name and prompt are required." } + if (onEvent) { + return if (eventSourceID.isEmpty()) "Choose an event source." else null + } if (cron.isEmpty() == runAt.isEmpty()) { return "Choose either a recurring cron or a one-time run time." } @@ -438,6 +533,27 @@ fun validateTask( return null } +/** Undoes one saved edit; a field someone changed since keeps its newer value. */ +internal fun Agent.undoingEdit(edit: Agent, old: Agent): Agent { + fun undone(field: (Agent) -> T) = if (field(this) == field(edit)) field(old) else field(this) + return copy( + name = undone { it.name }, + description = undone { it.description }, + instructions = undone { it.instructions }, + avatar = undone { it.avatar }, + enabled = undone { it.enabled }, + provider = undone { it.provider }, + model = undone { it.model }, + webSearchProvider = undone { it.webSearchProvider }, + desktopModel = undone { it.desktopModel }, + tools = undone { it.tools }, + delegates = undone { it.delegates }, + sharedMemory = undone { it.sharedMemory }, + mcpServers = undone { it.mcpServers }, + inference = undone { it.inference }, + ) +} + fun newRequestID(): String = UUID.randomUUID().toString().lowercase(Locale.ROOT) /** Unions transcript rows by ID in entry order. Entries are immutable, so a row that scrolled out stays valid. */ @@ -465,11 +581,26 @@ fun messageOrder(id: String): IntArray { fun messageLabel(message: Message): String { if (message.role == "assistant") return "Agent" if (message.role != "user") return "Tool result" - if (message.origin?.kind == "task") return "Task · ${message.origin.name ?: ""}" - if (message.origin?.kind == "bot") return "From ${message.origin.name ?: ""}" - return "You" + return noticeTitle(message) ?: "You" } +/** What a message the owner didn't write is collapsed under; null for the owner's own. */ +fun noticeTitle(message: Message): String? { + val origin = message.origin ?: return null + val name = origin.name.orEmpty() + return when (origin.kind) { + "task" -> "Automation · $name" + "event" -> "Automation · $name, event from ${origin.source ?: "a deleted source"}" + "script" -> "Script automation · $name" + "credential" -> "Credential · $name" + "bot" -> "From $name" + "bot_request" -> "Bot request" + else -> null + } +} + +fun isNotice(message: Message) = message.role == "user" && noticeTitle(message) != null + fun preview(text: String): String { var plain = text for (mark in listOf("**", "__", "`", "# ", "> ")) { diff --git a/app/src/main/java/dev/crumble/android/model/Notifications.kt b/app/src/main/java/dev/crumble/android/model/Notifications.kt index c67161c..9e7373f 100644 --- a/app/src/main/java/dev/crumble/android/model/Notifications.kt +++ b/app/src/main/java/dev/crumble/android/model/Notifications.kt @@ -14,6 +14,23 @@ import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat import dev.crumble.android.MainActivity import dev.crumble.android.R +import dev.crumble.android.storage.CredentialStore + +/** This device's choices, like the website's per-browser ones. Unset means on. */ +class NotificationSettings(private val credentials: CredentialStore) { + var replies: Boolean + get() = credentials.read(REPLIES_KEY) != "off" + set(on) = credentials.write(REPLIES_KEY, if (on) "on" else "off") + + var sound: Boolean + get() = credentials.read(SOUND_KEY) != "off" + set(on) = credentials.write(SOUND_KEY, if (on) "on" else "off") + + private companion object { + const val REPLIES_KEY = "notifications" + const val SOUND_KEY = "notification-sound" + } +} /** What the owner is looking at, which decides whether an event is worth a notification. */ data class NotificationContext( @@ -34,10 +51,11 @@ fun notification(forEvent: ActivityEvent, inContext: NotificationContext): Notif return when (forEvent.type) { "reply" -> { if (forEvent.origin == "bot") return null - if (inContext.appActive && inContext.route == Route.AgentChat(forEvent.agentId)) return null + val chat = forEvent.groupId?.let { Route.GroupChat(it) } ?: Route.AgentChat(forEvent.agentId) + if (inContext.appActive && inContext.route == chat) return null val text = preview(forEvent.preview ?: "") NotificationNote( - title = forEvent.agentName, + title = if (forEvent.groupId != null) "${forEvent.agentName} in ${forEvent.groupName?.nilIfEmpty ?: "a group"}" else forEvent.agentName, body = text.ifEmpty { "Replied" }, ) } @@ -61,6 +79,7 @@ object NoOpNotifier : ReplyNotifier { class AndroidReplyNotifier( private val context: Context, private val connectionIdentity: () -> String? = { null }, + private val sound: () -> Boolean = { true }, ) : ReplyNotifier { init { createChannel() @@ -79,6 +98,7 @@ class AndroidReplyNotifier( } override fun post(event: ActivityEvent, title: String, body: String) { + val chat = event.groupId ?: event.agentId if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { return @@ -87,15 +107,16 @@ class AndroidReplyNotifier( val intent = Intent(context, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP putExtra(EXTRA_AGENT_ID, event.agentId) + putExtra(EXTRA_GROUP_ID, event.groupId) putExtra(EXTRA_SERVER_ID, event.serverId) putExtra(EXTRA_CONNECTION_ID, connectionIdentity()) data = Uri.Builder().scheme("crumble-notification").authority("reply") .appendPath(event.serverId ?: connectionIdentity().orEmpty()) - .appendPath(event.agentId).build() + .appendPath(chat).build() } val pendingIntent = PendingIntent.getActivity( context, - event.agentId.hashCode(), + chat.hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) @@ -106,9 +127,10 @@ class AndroidReplyNotifier( .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setAutoCancel(true) .setContentIntent(pendingIntent) + .setSilent(!sound()) .build() try { - NotificationManagerCompat.from(context).notify("reply-${event.agentId}", event.agentId.hashCode(), notification) + NotificationManagerCompat.from(context).notify("reply-$chat", chat.hashCode(), notification) } catch (_: SecurityException) { } } @@ -116,6 +138,7 @@ class AndroidReplyNotifier( companion object { const val CHANNEL_ID = "crumble_replies" const val EXTRA_AGENT_ID = "dev.crumble.android.AGENT_ID" + const val EXTRA_GROUP_ID = "dev.crumble.android.GROUP_ID" const val EXTRA_SERVER_ID = "dev.crumble.android.SERVER_ID" const val EXTRA_CONNECTION_ID = "dev.crumble.android.CONNECTION_ID" } diff --git a/app/src/main/java/dev/crumble/android/model/Reasoning.kt b/app/src/main/java/dev/crumble/android/model/Reasoning.kt new file mode 100644 index 0000000..93b1a22 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/Reasoning.kt @@ -0,0 +1,28 @@ +package dev.crumble.android.model + +data class ThinkingLevel(val value: String, val label: String) + +val THINKING_LEVELS = listOf( + ThinkingLevel("off", "Off"), + ThinkingLevel("minimal", "Minimal"), + ThinkingLevel("low", "Low"), + ThinkingLevel("medium", "Medium"), + ThinkingLevel("high", "High"), + ThinkingLevel("xhigh", "Extra high"), + ThinkingLevel("max", "Maximum"), +) + +private val ORDER = THINKING_LEVELS.map { it.value } + +/** The levels `model` takes; a model ID outside the catalog may take any. */ +fun levelsOf(model: ModelSummary?): List = model?.thinkingLevels ?: ORDER + +/** The level a turn runs at, the nearest supported one preferring higher, as Pi AI's `clampThinkingLevel`. */ +fun clampLevel(level: String, levels: List): String { + if (level in levels) return level + val index = ORDER.indexOf(level) + return ORDER.drop(index + 1).firstOrNull { it in levels } + ?: ORDER.take(maxOf(index, 0)).lastOrNull { it in levels } + ?: levels.firstOrNull() + ?: "off" +} diff --git a/app/src/main/java/dev/crumble/android/model/Recurrence.kt b/app/src/main/java/dev/crumble/android/model/Recurrence.kt new file mode 100644 index 0000000..bd6d212 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/Recurrence.kt @@ -0,0 +1,151 @@ +package dev.crumble.android.model + +import java.time.DayOfWeek +import java.time.Instant +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.ZonedDateTime +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle +import java.time.format.TextStyle +import java.time.temporal.ChronoUnit +import java.util.Locale + +enum class TaskWhen(val label: String) { + Once("Once"), + Hourly("Every hour"), + Daily("Every day"), + Weekdays("Every weekday"), + Weekly("Every week"), + Monthly("Every month"), + Custom("Custom (cron)"), +} + +/** A cron the friendly picker can show. Fields a kind ignores keep their value across kind switches. */ +data class Recurrence( + val kind: TaskWhen, + val minute: Int = 0, + val hour: Int = 9, + val days: List = listOf(1), + val day: Int = 1, +) + +/** Monday first; cron counts Sunday as 0. */ +val WEEK = listOf(1, 2, 3, 4, 5, 6, 0) + +private val NUMBER = "(\\d+)" +private val HOURLY = Regex("^$NUMBER \\* \\* \\* \\*$") +private val DAILY = Regex("^$NUMBER $NUMBER \\* \\* \\*$") +private val WEEKDAYS = Regex("^$NUMBER $NUMBER \\* \\* 1-5$") +private val WEEKLY = Regex("^$NUMBER $NUMBER \\* \\* ([0-7](?:,[0-7])*)$") +private val MONTHLY = Regex("^$NUMBER $NUMBER $NUMBER \\* \\*$") + +private fun parsedRecurrence(text: String): Recurrence? { + fun Regex.numbers() = matchEntire(text)?.groupValues?.drop(1) + fun time(fields: List, build: (Int, Int) -> Recurrence): Recurrence? { + val minute = fields[0].toIntOrNull() ?: return null + val hour = fields[1].toIntOrNull() ?: return null + return build(minute, hour) + } + HOURLY.numbers()?.let { fields -> return fields[0].toIntOrNull()?.let { Recurrence(TaskWhen.Hourly, minute = it) } } + DAILY.numbers()?.let { fields -> return time(fields) { minute, hour -> Recurrence(TaskWhen.Daily, minute, hour) } } + WEEKDAYS.numbers()?.let { fields -> return time(fields) { minute, hour -> Recurrence(TaskWhen.Weekdays, minute, hour) } } + WEEKLY.numbers()?.let { fields -> + val days = fields[2].split(",").map { it.toInt() % 7 }.distinct() + return time(fields) { minute, hour -> Recurrence(TaskWhen.Weekly, minute, hour, days) } + } + MONTHLY.numbers()?.let { fields -> + val day = fields[2].toIntOrNull() ?: return null + return time(fields) { minute, hour -> Recurrence(TaskWhen.Monthly, minute, hour, day = day) } + } + return null +} + +fun recurrenceOf(cron: String): Recurrence? = parsedRecurrence(cron.trim().replace(Regex("\\s+"), " "))?.takeIf { + it.minute <= 59 && it.hour <= 23 && (it.kind != TaskWhen.Monthly || it.day in 1..31) +} + +fun cronOf(recurrence: Recurrence): String = with(recurrence) { + when (kind) { + TaskWhen.Hourly -> "$minute * * * *" + TaskWhen.Weekdays -> "$minute $hour * * 1-5" + TaskWhen.Weekly -> "$minute $hour * * ${days.sorted().joinToString(",")}" + TaskWhen.Monthly -> "$minute $hour $day * *" + else -> "$minute $hour * * *" + } +} + +fun weekdayName(day: Int, style: TextStyle, locale: Locale = Locale.getDefault()): String = + DayOfWeek.of(if (day == 0) 7 else day).getDisplayName(style, locale) + +/** Five-minute steps, plus the current minute when a hand-written cron uses another one. */ +fun minuteChoices(minute: Int): List = ((0 until 12).map { it * 5 } + minute).distinct().sorted() + +val TaskDraft.choice: TaskWhen + get() { + if (!repeats) return TaskWhen.Once + return (if (customCron) null else recurrenceOf(cron)?.kind) ?: TaskWhen.Custom + } + +fun TaskDraft.choosing(next: TaskWhen): TaskDraft = when (next) { + TaskWhen.Once -> copy(repeats = false, customCron = false) + TaskWhen.Custom -> copy(repeats = true, customCron = true) + else -> copy( + repeats = true, + customCron = false, + cron = cronOf(recurrenceOf(cron)?.copy(kind = next) ?: Recurrence(next)), + ) +} + +fun TaskDraft.recurring(next: Recurrence): TaskDraft = copy(repeats = true, cron = cronOf(next)) + +val TaskDraft.zone: ZoneId + get() = runCatching { ZoneId.of(timezone.trim()) }.getOrDefault(ZoneId.systemDefault()) + +val TaskDraft.wallClock: LocalDateTime + get() = LocalDateTime.ofInstant(runDate, zone) + +fun TaskDraft.runningAt(local: LocalDateTime): TaskDraft = copy(runDate = local.atZone(zone).toInstant()) + +/** A new zone keeps the time the owner picked, so the same clock reading runs at another instant. */ +fun TaskDraft.inTimezone(id: String): TaskDraft = copy(timezone = id).runningAt(wallClock) + +/** The zones a task can run in, narrowed by `query`; the current one stays listed even if the device lacks it. */ +fun timezoneChoices(query: String, current: String, available: Set = ZoneId.getAvailableZoneIds()): List { + val needle = query.trim().replace(' ', '_').lowercase() + val regions = available.filter { it == "UTC" || ('/' in it && !it.startsWith("Etc/") && !it.startsWith("SystemV/")) } + return (regions + current).distinct().filter { it.isNotEmpty() && it.lowercase().contains(needle) }.sorted() +} + +sealed interface NextRun { + data object Never : NextRun + data object Passed : NextRun + data object Unknown : NextRun + data class At(val label: String, val time: String, val zone: String) : NextRun +} + +private fun validZone(id: String) = runCatching { ZoneId.of(id) }.isSuccess + +fun nextRunOf(draft: TaskDraft, now: Instant = Instant.now(), locale: Locale = Locale.getDefault()): NextRun { + val zoneID = draft.timezone.trim() + if (!validZone(zoneID)) return NextRun.Never + if (draft.repeats && hasHashedField(draft.cron)) return NextRun.Unknown + val zone = ZoneId.of(zoneID) + val run = if (draft.repeats) nextOccurrence(draft.cron, zone, now) ?: return NextRun.Never else draft.runDate + if (run.isBefore(now)) return NextRun.Passed + return NextRun.At(if (draft.repeats) "Next run" else "Runs", humanRun(run, zone, now, locale), zoneID) +} + +/** "today at 09:00", "tomorrow at 09:00", a weekday this week, or a short date further out. */ +fun humanRun(run: Instant, zone: ZoneId, now: Instant, locale: Locale = Locale.getDefault()): String { + val date: ZonedDateTime = run.atZone(zone) + val days = ChronoUnit.DAYS.between(now.atZone(zone).toLocalDate(), date.toLocalDate()) + val time = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(locale).format(date) + val day = when (days) { + 0L -> "today" + 1L -> "tomorrow" + in 2L..6L -> date.format(DateTimeFormatter.ofPattern("EEEE", locale)) + else -> date.format(DateTimeFormatter.ofPattern("EEE, MMM d", locale)) + } + return "$day at $time" +} diff --git a/app/src/main/java/dev/crumble/android/model/Secrets.kt b/app/src/main/java/dev/crumble/android/model/Secrets.kt new file mode 100644 index 0000000..4fdf832 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/Secrets.kt @@ -0,0 +1,435 @@ +package dev.crumble.android.model + +import dev.crumble.android.generated.Credential +import dev.crumble.android.generated.CredentialRequest +import dev.crumble.android.generated.CredentialSecret +import dev.crumble.android.generated.CredentialUse +import dev.crumble.android.generated.Credentials +import dev.crumble.android.generated.Login +import dev.crumble.android.generated.LoginFields +import dev.crumble.android.generated.LoginRequest +import dev.crumble.android.generated.LoginUse +import dev.crumble.android.generated.Logins +import dev.crumble.android.generated.PasswordManager +import dev.crumble.android.generated.Provider +import dev.crumble.android.generated.ProviderLoginSession +import dev.crumble.android.generated.SecretStatus +import java.net.Inet6Address +import java.net.InetAddress +import java.net.URI +import java.util.UUID +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive + +private val CREDENTIAL_NAME = Regex("^[A-Z_][A-Z0-9_]{0,63}$") +private val LOGIN_NAME = Regex("^[a-z0-9][a-z0-9._-]{0,63}$") +private val LOGIN_ITEM = Regex("^op://[^/]+/[^/]+$") +private val HOST_SEPARATOR = Regex("[\\s,]+") + +const val SECRET_USES_PAGE = 50 +const val ONE_PASSWORD = "1password" + +/** Hosts as the owner types them: separated by commas, spaces, or lines. */ +fun hostList(text: String): List = + text.split(HOST_SEPARATOR).map { it.trim().lowercase() }.filter { it.isNotEmpty() } + +/** The body every secret endpoint takes. */ +sealed class SecretInput { + data class Value(val value: String) : SecretInput() { + override fun toString() = "Value(redacted)" + } + + data class Reference(val passwordManager: String, val reference: String) : SecretInput() +} + +internal fun SecretInput.json(): JsonObject = when (this) { + is SecretInput.Value -> JsonObject(mapOf("value" to JsonPrimitive(value))) + is SecretInput.Reference -> JsonObject(mapOf("reference" to json(passwordManager, reference))) +} + +private fun json(manager: String, reference: String) = + JsonObject(mapOf("passwordManager" to JsonPrimitive(manager), "reference" to JsonPrimitive(reference))) + +/** + * A typed secret, or where a password manager holds it. Lives only in memory: never in saveable state or the + * credential store. `toString` stays redacted so a log or crash report can't carry the value. + */ +data class SecretDraft( + /** The password manager to read from, or null for a value stored in Crumble. */ + val manager: String? = null, + val text: String = "", + val saved: SecretInput.Reference? = null, +) { + /** What to send, or null while the draft is empty. */ + val input: SecretInput? + get() = when { + manager != null -> text.trim().takeIf { it.isNotEmpty() }?.let { SecretInput.Reference(manager, it) } + text.isNotEmpty() -> SecretInput.Value(text) + else -> null + } + + /** False for the saved reference, so saving other fields doesn't read it again. */ + val changed: Boolean get() = input.let { it != null && it != saved } + + fun source(manager: String?) = copy(manager = manager, text = "") + + override fun toString() = "SecretDraft(manager=$manager)" +} + +// A value stored in Crumble is never shown, so only a saved reference starts the draft. +fun secretDraft(manager: String?, reference: String?): SecretDraft = + if (manager != null && reference != null) { + SecretDraft(manager, reference, SecretInput.Reference(manager, reference)) + } else { + SecretDraft() + } + +fun secretDraft(saved: SecretStatus?): SecretDraft = secretDraft(saved?.passwordManager, saved?.reference) + +private fun secretDraft(saved: CredentialSecret?): SecretDraft = secretDraft(saved?.passwordManager, saved?.reference) + +private val SecretDraft.readsPasswordManager: Boolean get() = changed && input is SecretInput.Reference + +private fun SecretDraft.body(): JsonElement? = if (changed) input?.json() else null + +/** Editor for a credential, a bot's request to answer, or a new credential. */ +data class CredentialForm( + /** Null for a new credential from all bots: the sheet asks which bot it is for. */ + val botID: String?, + val owner: String, + val existing: Credential? = null, + val request: CredentialRequest? = null, + val name: String = "", + val hosts: String = "", + val secret: SecretDraft = SecretDraft(), + val saving: Boolean = false, + val error: String = "", +) { + val locked: Boolean get() = existing != null || request != null + val nameInvalid: Boolean get() = name.isNotEmpty() && !CREDENTIAL_NAME.matches(name) + val ready: Boolean + get() = CREDENTIAL_NAME.matches(name) && hostList(hosts).isNotEmpty() && (existing != null || secret.input != null) && !saving + + /** Crumble checks a new reference when it saves, so the outcome depends on the password manager. */ + val readsPasswordManager: Boolean get() = secret.readsPasswordManager +} + +fun credentialForm( + botID: String?, + bots: List, + existing: Credential? = null, + request: CredentialRequest? = null, + secret: SecretDraft = secretDraft(existing?.secret), +) = CredentialForm( + botID = botID, + owner = botID ?: bots.firstOrNull()?.id.orEmpty(), + existing = existing, + request = request, + name = existing?.name ?: request?.name.orEmpty(), + hosts = (existing?.hosts ?: request?.hosts.orEmpty()).joinToString(", "), + secret = secret, +) + +fun credentialFields(form: CredentialForm): Map = buildMap { + put("hosts", JsonArray(hostList(form.hosts).map(::JsonPrimitive))) + form.secret.body()?.let { put("secret", it) } +} + +/** A value stored in Crumble is kept unless a new one is typed. */ +fun keepPlaceholder(existing: Credential?): String? = + existing?.secret?.takeIf { it.configured && it.passwordManager == null }?.let { "Keep the saved value" } + +fun keepPlaceholder(field: SecretStatus?): String? = + field?.takeIf { it.passwordManager == null }?.let { "Keep the saved value" } + +enum class LoginMode { fields, item } + +/** Editor for a login, a bot's request to answer, or a new login. */ +data class LoginForm( + val botID: String?, + val owner: String, + val existing: Login? = null, + val request: LoginRequest? = null, + val name: String = "", + val hosts: String = "", + val mode: LoginMode = LoginMode.fields, + val item: String = "", + val hasCode: Boolean = false, + val username: SecretDraft = SecretDraft(), + val password: SecretDraft = SecretDraft(), + val code: SecretDraft = SecretDraft(), + val saving: Boolean = false, + val error: String = "", +) { + val locked: Boolean get() = existing != null || request != null + val nameInvalid: Boolean get() = name.isNotEmpty() && !LOGIN_NAME.matches(name) + + private val fieldsReady: Boolean + get() = !(hasCode && existing?.fields?.one_time_code == null && code.input == null) && + (existing != null || (username.input != null && password.input != null)) + + val ready: Boolean + get() = LOGIN_NAME.matches(name) && hostList(hosts).isNotEmpty() && !saving && + if (mode == LoginMode.item) LOGIN_ITEM.matches(item.trim()) else fieldsReady + + val readsPasswordManager: Boolean + get() = mode == LoginMode.item || username.readsPasswordManager || password.readsPasswordManager || + (hasCode && code.readsPasswordManager) +} + +fun loginForm(botID: String?, bots: List, existing: Login? = null, request: LoginRequest? = null) = LoginForm( + botID = botID, + owner = botID ?: bots.firstOrNull()?.id.orEmpty(), + existing = existing, + request = request, + name = existing?.name ?: request?.name.orEmpty(), + hosts = (existing?.hosts ?: request?.hosts.orEmpty()).joinToString(", "), + hasCode = existing?.fields?.one_time_code != null || request?.oneTimeCode == true, + username = secretDraft(existing?.fields?.username), + password = secretDraft(existing?.fields?.password), + code = secretDraft(existing?.fields?.one_time_code), +) + +fun loginFields(form: LoginForm): Map { + val hosts = "hosts" to JsonArray(hostList(form.hosts).map(::JsonPrimitive)) + if (form.mode == LoginMode.item) return mapOf(hosts, "item" to json(ONE_PASSWORD, form.item.trim())) + val fields = buildMap { + form.username.body()?.let { put("username", it) } + form.password.body()?.let { put("password", it) } + when { + form.hasCode -> form.code.body()?.let { put("one_time_code", it) } + form.existing?.fields?.one_time_code != null -> put("one_time_code", JsonNull) + } + } + return mapOf(hosts, "fields" to JsonObject(fields)) +} + +internal val STORED = SecretStatus(configured = true, passwordManager = null, reference = null) + +/** A row to show until the server answers. Editing keeps everything the form doesn't touch. */ +internal fun provisionalCredential(form: CredentialForm): Credential { + val hosts = hostList(form.hosts) + val secret = form.secret.takeIf { it.changed }?.let { CredentialSecret(true, null, null) } + return form.existing?.let { it.copy(hosts = hosts, secret = secret ?: it.secret) } ?: Credential( + name = form.name, hosts = hosts, secret = secret, createdAt = "", updatedAt = "", + lastUsedAt = null, lastError = null, github = false, + ) +} + +private fun fieldStatus(draft: SecretDraft, saved: SecretStatus?) = if (draft.changed) STORED else saved + +internal fun provisionalLogin(form: LoginForm): Login { + val saved = form.existing?.fields + val fields = LoginFields( + username = fieldStatus(form.username, saved?.username), + password = fieldStatus(form.password, saved?.password), + one_time_code = if (form.hasCode) fieldStatus(form.code, saved?.one_time_code) else null, + ) + val hosts = hostList(form.hosts) + return form.existing?.copy(hosts = hosts, fields = fields) ?: Login( + name = form.name, hosts = hosts, fields = fields, createdAt = "", updatedAt = "", + lastUsedAt = null, lastError = null, + ) +} + +internal fun Credentials.withCredential(item: Credential) = copy( + credentials = upserted(credentials, item.name, item) { it.name }, + requests = requests.filterNot { it.name == item.name }, +) + +internal fun Logins.withLogin(item: Login) = copy( + logins = upserted(logins, item.name, item) { it.name }, + requests = requests.filterNot { it.name == item.name }, +) + +// A failure restores only this record, in its old place, keeping newer changes to the others. +private fun restored(current: List, before: List, name: String, nameOf: (T) -> String): List { + val without = current.filterNot { nameOf(it) == name } + val index = before.indexOfFirst { nameOf(it) == name } + if (index < 0) return without + return without.take(index) + before[index] + without.drop(index) +} + +internal fun Credentials.restored(before: Credentials, name: String) = Credentials( + credentials = restored(credentials, before.credentials, name) { it.name }, + requests = restored(requests, before.requests, name) { it.name }, +) + +internal fun Logins.restored(before: Logins, name: String) = Logins( + logins = restored(logins, before.logins, name) { it.name }, + requests = restored(requests, before.requests, name) { it.name }, +) + +/** A secret's row on the Credentials and Logins pages. */ +data class SecretRow( + val name: String, + val hosts: List, + val lastUsedAt: String?, + val lastError: String?, + /** A GitHub token follows its App or machine account; the server refuses to change it here. */ + val managed: Boolean = false, +) + +/** A bot's request for a secret, waiting for the owner. */ +data class SecretAsk(val name: String, val hosts: List, val reason: String) + +fun matchesSecret(name: String, hosts: List, needle: String): Boolean = + needle.isEmpty() || name.lowercase().contains(needle) || hosts.any { it.contains(needle) } + +/** The bots in scope; with every bot in scope, only those with matches or a failed read get a frame. */ +fun secretBotsShown( + botIDs: List, + scope: String, + needle: String, + rowsOf: (String) -> List, + failed: (String) -> Boolean, +): List = botIDs.filter { id -> + if (scope == SKILLS_ALL) failed(id) || rowsOf(id).any { matchesSecret(it.name, it.hosts, needle) } else id == scope +} + +/** A `request_credential` or `request_login` result in the transcript; its live state comes from the bot's lists. */ +@Serializable +data class SecretRequestRef(val name: String = "", val hosts: List = emptyList(), val requestedAt: String? = null) { + fun answers(requestName: String, at: String) = requestName == name && (requestedAt == null || requestedAt == at) +} + +sealed class SecretRequestState { + data object Loading : SecretRequestState() + data object Unavailable : SecretRequestState() + data object Saved : SecretRequestState() + data object Declined : SecretRequestState() + data class Waiting(val request: R) : SecretRequestState() +} + +/** A list read before the request arrived can't say it was answered, so only a `fresh` read settles a card. */ +fun secretRequestState(request: R?, listed: Boolean, saved: Boolean, fresh: Boolean, failed: Boolean): SecretRequestState = when { + !listed || (request == null && !fresh) -> if (failed) SecretRequestState.Unavailable else SecretRequestState.Loading + request != null -> SecretRequestState.Waiting(request) + saved -> SecretRequestState.Saved + else -> SecretRequestState.Declined +} + +enum class SecretKind { credential, login } + +/** One line of a secret's use log. */ +data class SecretUseRow(val id: String, val at: String, val detail: String, val note: String?, val failed: Boolean) + +data class SecretUsesView( + val kind: SecretKind, + val botID: String, + val name: String, + val id: UUID = UUID.randomUUID(), + val rows: List = emptyList(), + val loading: Boolean = true, + val loadingMore: Boolean = false, + val hasMore: Boolean = false, + val error: String = "", +) + +private val LOGIN_FIELD_LABELS = mapOf("username" to "Username", "password" to "Password", "one_time_code" to "One-time code") + +internal fun CredentialUse.row() = SecretUseRow(id, at, "$method $host$path", status?.toString() ?: "failed", status == null) + +internal fun LoginUse.row() = SecretUseRow(id, at, "${LOGIN_FIELD_LABELS[field] ?: field} on $host", error, error != null) + +data class ManagerTokenForm( + val manager: PasswordManager, + val token: SecretDraft = SecretDraft(), + val saving: Boolean = false, + val error: String = "", +) { + val ready: Boolean get() = token.text.isNotBlank() && !saving +} + +data class ProviderKeyForm( + val provider: Provider, + val key: SecretDraft, + val saving: Boolean = false, + val error: String = "", +) + +/** A provider's account sign-in; closing keeps it going on the server so it can be continued. */ +data class ProviderLoginView( + val provider: Provider, + val sessionID: String? = null, + val session: ProviderLoginSession? = null, + val starting: Boolean = false, + val cancelling: Boolean = false, + val answering: Boolean = false, + /** Answers can be secrets, so they go when the prompt changes or the dialog closes. */ + val answer: SecretDraft = SecretDraft(), + val answerError: String = "", + val gone: Boolean = false, + val error: String = "", +) + +fun providerKeyStatus(provider: Provider, managers: List): String { + val id = provider.apiKey.passwordManager ?: return "Key saved" + return "Key in ${managers.firstOrNull { it.id == id }?.name ?: "a password manager"}" +} + +private val EXTERNAL_STATUS = mapOf( + "signed_in" to "Signed in", + "signed_out" to "Not signed in", + "cli_missing" to "Not installed", + "error" to "Unavailable", +) + +fun providerStatus(provider: Provider, managers: List): String? { + val external = provider.externalAuth + return when { + external != null -> EXTERNAL_STATUS[external.status] + provider.credentialType == "oauth" -> "Signed in" + provider.credentialType == "api_key" -> providerKeyStatus(provider, managers) + provider.configured -> "From environment" + provider.activeLoginId != null -> "Signing in…" + else -> null + } +} + +fun Provider.signInAvailable(): Boolean = authMethods.any { it.type == "oauth" } && credentialType != "oauth" + +fun Provider.keyAvailable(): Boolean = authMethods.any { it.type == "api_key" } + +fun matchingProviders(providers: List, needle: String): List = + providers.filter { needle.isEmpty() || it.name.lowercase().contains(needle) || it.provider.contains(needle) } + .sortedBy { it.name.lowercase() } + +internal fun Provider.withKey() = copy(configured = true, credentialType = "api_key", apiKey = STORED) + +internal fun Provider.withoutCredential() = copy(configured = false, credentialType = null, apiKey = SecretStatus(false, null, null)) + +/** Sign-in links come from the provider through the server; only web pages may leave the app. */ +fun isWebLink(url: String): Boolean = url.startsWith("https://", ignoreCase = true) || url.startsWith("http://", ignoreCase = true) + +/** Whether the server URL sends the session in the clear beyond this device and its private network. */ +fun isExposedHttp(url: String): Boolean { + val uri = runCatching { URI(url.trim()) }.getOrNull() ?: return false + val host = uri.host?.lowercase()?.trimEnd('.') ?: return false + return uri.scheme.equals("http", ignoreCase = true) && !isLocalHost(host) +} + +private fun isLocalHost(host: String): Boolean { + if (host == "localhost" || host.endsWith(".localhost")) return true + val address = addressLiteral(host) ?: return false + val uniqueLocal = address is Inet6Address && address.address[0].toInt() and 0xfe == 0xfc + return address.isLoopbackAddress || address.isSiteLocalAddress || address.isLinkLocalAddress || uniqueLocal +} + +// Literals only: InetAddress.getByName would look a name up in DNS, and this runs while the owner types. +private fun addressLiteral(host: String): InetAddress? { + if (host.startsWith("[")) return runCatching { InetAddress.getByName(host.trim('[', ']')) }.getOrNull() + val octets = host.split('.').map { it.toIntOrNull() } + if (octets.size != 4 || octets.any { it == null || it !in 0..255 }) return null + return InetAddress.getByAddress(octets.map { it!!.toByte() }.toByteArray()) +} + +fun secretKey(kind: String, botID: String, name: String) = "$kind:$botID:$name" + +fun credentialReadKey(ref: SecretRequestRef) = "credential:${ref.name}:${ref.requestedAt.orEmpty()}" + +fun loginReadKey(ref: SecretRequestRef) = "login:${ref.name}:${ref.requestedAt.orEmpty()}" diff --git a/app/src/main/java/dev/crumble/android/model/Skills.kt b/app/src/main/java/dev/crumble/android/model/Skills.kt new file mode 100644 index 0000000..a27584d --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/Skills.kt @@ -0,0 +1,234 @@ +package dev.crumble.android.model + +import dev.crumble.android.generated.PendingSkillUpdate +import dev.crumble.android.generated.SkillCheck +import dev.crumble.android.generated.SkillListing +import dev.crumble.android.generated.SkillPackage +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.friendlyError +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.sync.Semaphore +import kotlinx.coroutines.sync.withPermit + +const val SKILLS_ALL = "all" +const val SKILLS_SHARED = "shared" +const val SKILLS_DEFAULT = "default" + +/** A skill the bulk actions can pick: shared, or a bot's own. Default skills are files on the server. */ +data class SelectableSkill( + val id: String, + val name: String, + val instructions: String, + val botID: String?, + val ownerName: String, + val installed: Boolean, +) + +enum class BulkAction { delete, update, assign, remove } + +data class BulkMessage(val id: String, val text: String) + +data class BulkResult( + val failed: Set, + val messages: List, + /** Skill and bot pairs whose assignment did not apply. */ + val failedAssignments: Set>, +) + +data class SkillInstallForm( + val location: String = "", + val listing: SkillListing? = null, + val picked: Set = emptySet(), + val botIDs: Set = emptySet(), + val browsing: Boolean = false, + val installing: Boolean = false, + val error: String = "", +) + +data class InstalledSkillView( + val skillID: String, + val full: SkillPackage? = null, + val error: String = "", +) + +data class SkillUpdateView( + val skillID: String, + val current: SkillPackage? = null, + val pending: PendingSkillUpdate? = null, + val applying: Boolean = false, + val error: String = "", +) + +val SelectableSkill.label: String get() = "$name ($ownerName)" + +/** Whether a skill's name or instructions contain `needle`, already lowercased. */ +fun matchesSkill(name: String, instructions: String, needle: String): Boolean = + needle.isEmpty() || name.lowercase().contains(needle) || instructions.lowercase().contains(needle) + +/** The first line of a skill's instructions, as a glimpse of what it does. */ +fun skillGlimpse(instructions: String): String = + instructions.lines().map { it.trimStart('#').trim() }.firstOrNull { it.isNotEmpty() } ?: "No instructions." + +fun skillSummary(description: String?, instructions: String): String = + description?.nilIfEmpty ?: skillGlimpse(instructions) + +/** Selectable packages only; default server files never enter the selection catalog. */ +fun selectionCatalog(shared: List, bots: List, personal: Map>): List = + shared.filter { !it.isDefault }.map { + SelectableSkill(it.id, it.name, it.instructions, null, "Shared", it.origin != null) + } + bots.flatMap { bot -> + personal[bot.id].orEmpty().map { SelectableSkill(it.id, it.name, it.instructions, bot.id, bot.name, false) } + } + +fun List.visibleIn(scope: String, needle: String): List = filter { + (scope == SKILLS_ALL || scope == (it.botID ?: SKILLS_SHARED)) && matchesSkill(it.name, it.instructions, needle) +} + +fun botsUsing(bots: List, skillID: String): Set = + bots.filter { it.sharedSkills?.contains(skillID) == true }.map { it.id }.toSet() + +/** Skipped files, the first few by name. */ +fun skippedNote(skipped: List): String? { + if (skipped.isEmpty()) return null + val shown = skipped.take(3).joinToString(", ") + return if (skipped.size > 3) "Skips $shown and ${skipped.size - 3} more" else "Skips $shown" +} + +fun newSkillPaths(listing: SkillListing): Set = + listing.skills.filter { it.status == "new" }.map { it.path }.toSet() + +fun installLabel(count: Int): String = "Install $count ${if (count == 1) "skill" else "skills"}" + +fun updateCheckFailures(check: SkillCheck): List = + check.failed.map { "Couldn't check ${it.repository} (${it.branch}): ${it.message}" } + +internal fun SkillPackage.asInline() = Skill(id = id, name = name, instructions = instructions) + +internal fun SkillPackage.asShared() = SharedSkill( + id = id, name = name, instructions = instructions, source = "shared", + description = description, origin = origin, update = null, +) + +/** A row to show until the server answers. Editing keeps everything the form doesn't touch. */ +internal fun provisionalSkill(id: String, agentID: String, name: String, instructions: String, old: SkillPackage?): SkillPackage = + old?.copy(name = name, instructions = instructions) ?: SkillPackage( + id = id, name = name, instructions = instructions, createdAt = "", updatedAt = "", agentId = agentID, + description = "", documents = emptyList(), createdBy = "owner", sourceExecutionId = null, useCount = 0, + lastUsedAt = null, state = "active", pinned = false, + ) + +/** `current` with the records in `ids` back at their place in `original`. */ +internal fun restoring(current: List, original: List, ids: Set, idOf: (T) -> String): List { + val list = current.toMutableList() + original.forEachIndexed { index, item -> + if (idOf(item) in ids && list.none { idOf(it) == idOf(item) }) list.add(minOf(index, list.size), item) + } + return list +} + +/** `current` with one record as it was in `original`, or without it if it wasn't there. Other records stay. */ +internal fun recordRestored(current: List, original: List, id: String, idOf: (T) -> String): List { + val old = original.firstOrNull { idOf(it) == id } ?: return current.filterNot { idOf(it) == id } + return if (current.any { idOf(it) == id }) current.map { if (idOf(it) == id) old else it } else restoring(current, original, setOf(id), idOf) +} + +/** + * `current` with one record replaced, added, or removed when `item` is null. A read can bring a created + * record's real row before its save answers, so swapping in the saved record also drops that row. + */ +internal fun upserted(current: List, id: String, item: T?, idOf: (T) -> String): List = when { + item == null -> current.filterNot { idOf(it) == id } + current.any { idOf(it) == id } -> current + .filterNot { idOf(it) == idOf(item) && idOf(it) != id } + .map { if (idOf(it) == id) item else it } + else -> current + item +} + +private class UpdateCheck(val catalog: List, val check: SkillCheck, val error: Throwable? = null) + +/** The checker refreshes upstream metadata; only selected skills are applied. */ +private suspend fun checkUpdates(api: APIClient): UpdateCheck = try { + val check = api.checkSkillUpdates() + UpdateCheck(api.sharedSkills(), check) +} catch (e: CancellationException) { + throw e +} catch (e: Throwable) { + UpdateCheck(emptyList(), SkillCheck(emptyList()), e) +} + +/** Returns why the skill was skipped, or null once it updated. */ +private suspend fun updateSkill(api: APIClient, skill: SelectableSkill, updates: UpdateCheck): String? { + if (!skill.installed) return "not installed from GitHub" + updates.error?.let { throw it } + val current = updates.catalog.firstOrNull { it.id == skill.id } + val origin = current?.origin ?: throw IllegalStateException("Installed skill no longer exists.") + updates.check.failed.firstOrNull { it.repository == origin.repository && it.branch == origin.branch } + ?.let { throw IllegalStateException(it.message) } + if (current.update == null) return "already up to date" + api.applySkillUpdate(skill.id) + return null +} + +private class Assigned(val botID: String, val failed: Boolean, val message: BulkMessage?) + +private suspend fun assignBot(api: APIClient, skill: SelectableSkill, bot: Agent, assigned: Boolean): Assigned { + val label = "${skill.label} → ${bot.name}" + return try { + val skipped = api.assignSkill(skill.id, bot.id, assigned) + val message = if (skipped) BulkMessage("skipped:${skill.id}:${bot.id}", "Skipped $label: already in the requested state.") else null + Assigned(bot.id, false, message) + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + Assigned(bot.id, true, BulkMessage("failed:${skill.id}:${bot.id}", "Failed $label: ${friendlyError(e)}")) + } +} + +/** Different bots are independent, so at most four run at once. Skills run in order: two never race on one bot. */ +private suspend fun assignBots(api: APIClient, skill: SelectableSkill, bots: List, assigned: Boolean): List { + val slots = Semaphore(4) + return coroutineScope { + bots.map { bot -> async { slots.withPermit { assignBot(api, skill, bot, assigned) } } }.awaitAll() + } +} + +/** Each request is independent: failures stay selected, successes never roll back. */ +suspend fun applyBulkAction(api: APIClient, action: BulkAction, picked: List, bots: List): BulkResult { + val failed = linkedSetOf() + val messages = mutableListOf() + val failedAssignments = mutableSetOf>() + val updates = if (action == BulkAction.update) checkUpdates(api) else null + + for (skill in picked) { + try { + when (action) { + BulkAction.delete -> { + val owner = skill.botID + if (owner != null) api.deleteBotSkill(owner, skill.id) else api.deleteSharedSkill(skill.id) + } + BulkAction.update -> updateSkill(api, skill, checkNotNull(updates))?.let { + messages.add(BulkMessage("skipped:${skill.id}", "Skipped ${skill.label}: $it.")) + } + BulkAction.assign, BulkAction.remove -> { + val results = assignBots(api, skill, bots, action == BulkAction.assign) + messages.addAll(results.mapNotNull { it.message }) + val bad = results.filter { it.failed } + if (bad.isNotEmpty()) failed.add(skill.id) + failedAssignments.addAll(bad.map { skill.id to it.botID }) + } + } + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + failed.add(skill.id) + messages.add(BulkMessage("failed:${skill.id}", "Failed ${skill.label}: ${friendlyError(e)}")) + } + } + + val summary = "${picked.size - failed.size} of ${picked.size} skills processed" + + (if (failed.isNotEmpty()) "; ${failed.size} failed and remain selected" else "") + "." + return BulkResult(failed, listOf(BulkMessage("summary", summary)) + messages, failedAssignments) +} diff --git a/app/src/main/java/dev/crumble/android/model/Sources.kt b/app/src/main/java/dev/crumble/android/model/Sources.kt new file mode 100644 index 0000000..42c63ac --- /dev/null +++ b/app/src/main/java/dev/crumble/android/model/Sources.kt @@ -0,0 +1,116 @@ +package dev.crumble.android.model + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.contentOrNull + +/** Pages a reply may cite, keyed by `sourceKey` of their URL, with their titles. */ +typealias Sources = Map + +data class SourceChip(val href: String, val title: String) + +data class SplitReply(val text: String, val chips: List) + +// Parsed by hand: java.net.URI rejects characters real page URLs carry, such as `|` in a query. +private val WEB_URL = Regex("^https?://(?:[^/?#@]*@)?([^/?#]+)([^?#]*)(\\?[^#]*)?", RegexOption.IGNORE_CASE) + +private val DEFAULT_PORT = Regex("^(https://.*:443|http://.*:80)$", RegexOption.IGNORE_CASE) + +private val WEB_TOOLS = setOf("web_search", "web_extract") + +/** Ignores the fragment, a trailing slash, and the host's case, so a cited link matches the page that was read. */ +fun sourceKey(href: String): String? { + val match = WEB_URL.find(href) ?: return null + val (authority, path, query) = match.destructured + val origin = href.substring(0, href.indexOf("://") + 3) + authority + val host = if (DEFAULT_PORT.matches(origin)) authority.substringBeforeLast(':') else authority + return host.lowercase() + path.trimEnd('/') + query.takeIf { it.length > 1 }.orEmpty() +} + +/** The host a source chip names, without its port or `www.`. */ +fun siteOf(href: String): String { + val authority = WEB_URL.find(href)?.groupValues?.get(1) ?: return href + return authority.lowercase().replace(Regex(":\\d+$"), "").removePrefix("www.") +} + +private fun pagesOf(message: Message): List { + if (message.role != "toolResult" || message.isError == true || message.toolName !in WEB_TOOLS) return emptyList() + val pages = message.toolDetails as? JsonArray ?: return emptyList() + return pages.filterIsInstance().filterNot { "error" in it } +} + +/** For each bot reply, the pages its turn searched or read; a turn starts at each message to the bot. */ +fun sourcesOf(messages: List): Map { + val replies = mutableMapOf() + var turn = mutableMapOf() + for (message in messages) { + if (message.role == "user") turn = mutableMapOf() + for (page in pagesOf(message)) { + val url = (page["url"] as? JsonPrimitive)?.contentOrNull ?: continue + val key = sourceKey(url) ?: continue + turn[key] = (page["title"] as? JsonPrimitive)?.contentOrNull.orEmpty() + } + if (message.role == "assistant" && turn.isNotEmpty()) replies[message.id] = turn.toMap() + } + return replies +} + +// A citation: a Markdown link labeled "source", whose URL may hold one pair of parentheses. +private val CITATION = Regex("\\[sources?\\]\\((https?://[^\\s()]*(?:\\([^\\s()]*\\)[^\\s()]*)*)\\)", RegexOption.IGNORE_CASE) + +// A private-use character marks where a chip was; bot text never contains it. +private const val SLOT = "" + +private val SEPARATOR = Regex("$SLOT[ \\t]*(?:,|;|&|and)[ \\t]*(?=$SLOT)") + +private val LEFTOVER = Regex("[ \\t]*$SLOT") + +private val EMPTY_PARENS = Regex("[ \\t]*\\((?:\\s*sources?:?)?\\s*\\)", RegexOption.IGNORE_CASE) + +private val FENCE = Regex("^\\s*(?:```|~~~)") + +private val CODE_SPAN = Regex("`[^`]*`") + +private fun takeSources(prose: String, sources: Sources, chips: MutableMap): String { + val marked = CITATION.replace(prose) { citation -> + val href = citation.groupValues[1] + val key = sourceKey(href) + val title = key?.let { sources[it] } + if (key == null || title == null) { + citation.value + } else { + chips.getOrPut(key) { SourceChip(href, title) } + SLOT + } + } + return EMPTY_PARENS.replace(LEFTOVER.replace(SEPARATOR.replace(marked, SLOT), ""), "") +} + +private fun takeOutsideCode(line: String, sources: Sources, chips: MutableMap): String { + fun prose(part: String) = if (part.startsWith("`")) part else takeSources(part, sources, chips) + val kept = StringBuilder() + var end = 0 + for (span in CODE_SPAN.findAll(line)) { + kept.append(prose(line.substring(end, span.range.first))).append(span.value) + end = span.range.last + 1 + } + return kept.append(prose(line.substring(end))).toString() +} + +/** Takes the reply's citations of pages its turn read out of its text, outside code, so they show once as chips after it. */ +fun splitSources(markdown: String, sources: Sources): SplitReply { + val chips = linkedMapOf() + var fenced = false + val text = markdown.split("\n").joinToString("\n") { line -> + when { + FENCE.containsMatchIn(line) -> { + fenced = !fenced + line + } + fenced -> line + else -> takeOutsideCode(line, sources, chips) + } + } + return SplitReply(text, chips.values.toList()) +} diff --git a/app/src/main/java/dev/crumble/android/network/APIClient.kt b/app/src/main/java/dev/crumble/android/network/APIClient.kt index cbead55..2b2a6c6 100644 --- a/app/src/main/java/dev/crumble/android/network/APIClient.kt +++ b/app/src/main/java/dev/crumble/android/network/APIClient.kt @@ -1,5 +1,49 @@ package dev.crumble.android.network +import dev.crumble.android.generated.AssignSkillBotRequest +import dev.crumble.android.generated.BrowseSkillRepositoryRequest +import dev.crumble.android.generated.Capabilities +import dev.crumble.android.generated.CompleteGithubAppRequest +import dev.crumble.android.generated.CompleteGithubAppSignInRequest +import dev.crumble.android.generated.CreateEventSourceRequest +import dev.crumble.android.generated.CreateEventSourceResponse +import dev.crumble.android.generated.CreateGithubAppManifestRequest +import dev.crumble.android.generated.CreateSkillRequest +import dev.crumble.android.generated.CreateSkillRequestDocumentsItem +import dev.crumble.android.generated.AdminUser +import dev.crumble.android.generated.CreatedInvite +import dev.crumble.android.generated.DesktopControl +import dev.crumble.android.generated.DesktopViewer +import dev.crumble.android.generated.GitHubAccount +import dev.crumble.android.generated.Invite +import dev.crumble.android.generated.ListOutdatedWorkspacesResponseWorkspacesItem +import dev.crumble.android.generated.SetUserRoleRequest +import dev.crumble.android.generated.GitHubApp +import dev.crumble.android.generated.GroupChat +import dev.crumble.android.generated.InstallSkillsRequest +import dev.crumble.android.generated.JudgeModel +import dev.crumble.android.generated.LearnedChange +import dev.crumble.android.generated.OptionalField +import dev.crumble.android.generated.PendingSkillUpdate +import dev.crumble.android.generated.PluginSetting +import dev.crumble.android.generated.PluginSettings +import dev.crumble.android.generated.PutDesktopControlRequest +import dev.crumble.android.generated.ScriptRun +import dev.crumble.android.generated.ServerSettings +import dev.crumble.android.generated.SetGithubAccountBotsRequest +import dev.crumble.android.generated.SetGithubAppBotsRequest +import dev.crumble.android.generated.SignInGithubAppRequest +import dev.crumble.android.generated.SkillCheck +import dev.crumble.android.generated.SkillListing +import dev.crumble.android.generated.SkillPackage +import dev.crumble.android.generated.UpdateEventRelayRequest +import dev.crumble.android.generated.UpdateJudgeModelRequest +import dev.crumble.android.generated.UpdateJudgeModelRequestJudgeModel +import dev.crumble.android.generated.UpdateServerSettingsRequest +import dev.crumble.android.generated.UpdateVisionModelRequest +import dev.crumble.android.generated.UpdateVisionModelRequestVisionModel +import dev.crumble.android.generated.UpdateWebSearchRequest +import dev.crumble.android.generated.VisionModel import dev.crumble.android.model.Agent import dev.crumble.android.model.ActivityFeedResponse import dev.crumble.android.model.ChatHistoryResponse @@ -7,12 +51,25 @@ import dev.crumble.android.model.ChatSnapshot import dev.crumble.android.model.CrumbleJson import dev.crumble.android.model.CrumblePatchJson import dev.crumble.android.model.Execution +import dev.crumble.android.model.GatewayConfig +import dev.crumble.android.model.GroupSnapshot +import dev.crumble.android.model.JobKind +import dev.crumble.android.model.JobRef +import dev.crumble.android.model.JobSummary import dev.crumble.android.model.MCPServer import dev.crumble.android.model.Memory +import dev.crumble.android.model.MessageGateway import dev.crumble.android.model.ModelSummary import dev.crumble.android.model.OAuthStart import dev.crumble.android.model.OutgoingAttachment -import dev.crumble.android.model.ProviderStatus +import dev.crumble.android.model.RelayStatus +import dev.crumble.android.model.SECRET_USES_PAGE +import dev.crumble.android.model.SecretInput +import dev.crumble.android.model.WebSearchSettings +import dev.crumble.android.model.domain +import dev.crumble.android.model.wire +import dev.crumble.android.model.json +import dev.crumble.android.model.EventSource import dev.crumble.android.model.Schedule import dev.crumble.android.model.SharedSkill import dev.crumble.android.model.nilIfEmpty @@ -30,6 +87,7 @@ import java.net.URL import java.net.URLDecoder import java.net.URLEncoder import java.nio.charset.StandardCharsets +import java.time.ZoneId import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.currentCoroutineContext @@ -42,6 +100,11 @@ import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.decodeFromJsonElement +const val CHANGES_PAGE = 50 +private const val SCRIPT_RUNS_PAGE = 20L +// The server reads GitHub while these run. +private const val GITHUB_TIMEOUT_MS = 60_000 + data class APIError( val method: String, val path: String, @@ -53,6 +116,11 @@ class SSEClosedError : Exception("server-sent event stream closed") class SignInError(message: String) : Exception(message) +/** Who a session belongs to, from Better Auth rather than the /v1 contract. */ +data class AccountSession(val id: String, val admin: Boolean, val theme: String? = null) + +const val INVITE_HEADER = "x-crumble-invite" + data class HttpRequestData( val method: String, val url: String, @@ -155,6 +223,7 @@ class APIClient( path: String, body: ByteArray? = null, timeoutMs: Int = 20_000, + extraHeaders: Map = emptyMap(), ): HttpRequestData { val fullUrl = this.baseURL + path // Validate URL format @@ -166,7 +235,7 @@ class APIClient( if (parsed.scheme.isNullOrEmpty() || parsed.host.isNullOrEmpty()) { throw IllegalArgumentException("Bad URL: $fullUrl") } - val headers = LinkedHashMap() + val headers = LinkedHashMap(extraHeaders) if (token.isNotEmpty()) { headers["Authorization"] = "Bearer $token" } @@ -188,8 +257,9 @@ class APIClient( path: String, body: ByteArray? = null, timeoutMs: Int = 20_000, + extraHeaders: Map = emptyMap(), ): ByteArray { - val request = makeRequest(method, path, body, timeoutMs) + val request = makeRequest(method, path, body, timeoutMs, extraHeaders) val response = transport.execute(request) if (response.statusCode !in 200..299) { val prefixLen = minOf(response.body.size, 8 shl 10) @@ -219,6 +289,92 @@ class APIClient( private fun strings(vararg pairs: Pair): Map = pairs.associate { (key, value) -> key to JsonPrimitive(value) } + // Better Auth's routes, so they sit outside the /v1 contract. + suspend fun signIn(email: String, password: String): String { + val fields = strings("email" to email, "password" to password) + val bytes = try { + send("POST", "/api/auth/sign-in/email", CrumbleJson.encodeToString(JsonObject(fields)).toByteArray(StandardCharsets.UTF_8)) + } catch (e: APIError) { + throw if (e.statusCode == 401) SignInError("Invalid email or password.") else e + } + return sessionToken(bytes) ?: throw SignInError("Sign-in returned no session.") + } + + /** Creates the account; an invite lets it through while sign-up is closed. */ + suspend fun signUp(name: String, email: String, password: String, invite: String): String { + val fields = strings("email" to email, "password" to password, "name" to name) + val bytes = try { + send( + "POST", + "/api/auth/sign-up/email", + CrumbleJson.encodeToString(JsonObject(fields)).toByteArray(StandardCharsets.UTF_8), + extraHeaders = if (invite.isEmpty()) emptyMap() else mapOf(INVITE_HEADER to invite), + ) + } catch (e: APIError) { + throw SignInError(authMessage(e) ?: friendlyError(e)) + } + return sessionToken(bytes) ?: throw SignInError("Sign-up returned no session.") + } + + /** Revokes this client's session on the server. */ + suspend fun signOut() { + send("POST", "/api/auth/sign-out", "{}".toByteArray(StandardCharsets.UTF_8)) + } + + suspend fun accountSession(): AccountSession { + val path = "/api/auth/get-session" + val bytes = send("GET", path) + val session = CrumbleJson.parseToJsonElement(bytes.toString(StandardCharsets.UTF_8)) as? JsonObject + val user = session?.get("user") as? JsonObject + val id = (user?.get("id") as? JsonPrimitive)?.contentOrNull + ?: throw APIError(method = "GET", path = path, statusCode = 401, body = "") + return AccountSession( + id, + admin = (user["role"] as? JsonPrimitive)?.contentOrNull == "admin", + theme = (user["theme"] as? JsonPrimitive)?.contentOrNull, + ) + } + + suspend fun updateTheme(theme: String) { + val body = CrumbleJson.encodeToString(JsonObject(strings("theme" to theme))) + send("POST", "/api/auth/update-user", body.toByteArray(StandardCharsets.UTF_8)) + } + + private fun sessionToken(bytes: ByteArray): String? { + val response = CrumbleJson.parseToJsonElement(bytes.toString(StandardCharsets.UTF_8)) as? JsonObject + return (response?.get("token") as? JsonPrimitive)?.contentOrNull + } + + // Better Auth answers with `message`, where the /v1 routes use `error`. + private fun authMessage(error: APIError): String? = try { + val body = CrumbleJson.parseToJsonElement(error.body) as? JsonObject + (body?.get("message") as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotEmpty() } + } catch (_: Exception) { + null + } + + suspend fun heldActions(agentID: String) = operations.listAgentHeldActions(agentID) + suspend fun approveHeldAction(agentID: String, id: String) { operations.approveAgentHeldAction(agentID, id) } + suspend fun declineHeldAction(agentID: String, id: String, reason: String) { + operations.declineAgentHeldAction(request(if (reason.isEmpty()) emptyMap() else strings("reason" to reason)), agentID, id) + } + suspend fun codingJobs(agentID: String) = operations.listCodingJobs(agentID).jobs + suspend fun answerCodingJob(agentID: String, job: String, questionID: String, text: String) { + operations.answerCodingJob(request(strings("questionId" to questionID, "text" to text)), agentID, job) + } + suspend fun botRequests(agentID: String) = operations.listBotRequests(agentID) + suspend fun jobs(agentID: String, kind: JobKind): List = when (kind) { + JobKind.coding -> operations.listCodingJobs(agentID).jobs.map { it.domain() } + JobKind.desktop -> operations.listDesktopJobs(agentID).jobs.map { it.domain() } + } + suspend fun jobHistory(agentID: String, job: JobRef, before: String?, limit: Int): ChatHistoryResponse = when (job.kind) { + JobKind.coding -> operations.getCodingJobHistory(agentID, job.name, limit.toLong(), before) + JobKind.desktop -> operations.getDesktopJobHistory(agentID, job.name, limit.toLong(), before) + }.domain() + suspend fun approveBotRequest(agentID: String, id: String, proposal: Map? = null): Agent = + operations.approveBotRequest(request(proposal?.let { mapOf("proposal" to JsonObject(it)) }.orEmpty()), agentID, id).agent.domain() + suspend fun declineBotRequest(agentID: String, id: String) { operations.declineBotRequest(agentID, id) } + suspend fun agents(): List = operations.listAgents().map { it.domain() } suspend fun createAgent(agent: Agent): Agent = operations.createAgent(agent.wire()).domain() @@ -232,22 +388,61 @@ class APIClient( suspend fun chatHistory(agentID: String, before: String, limit: Int): ChatHistoryResponse = operations.getChatHistory(agentID, before = before.nilIfEmpty, limit = limit.takeIf { it > 0 }?.toLong()).domain() - suspend fun sendChatMessage(agentID: String, content: String, requestID: String, replyTo: String, attachments: List = emptyList()) { + private fun messageFields(content: String, requestID: String, replyTo: String, attachments: List): Map { val fields = strings("content" to content, "requestId" to requestID).toMutableMap() replyTo.nilIfEmpty?.let { fields["replyTo"] = JsonPrimitive(it) } if (attachments.isNotEmpty()) fields["attachments"] = CrumbleJson.encodeToJsonElement(ListSerializer(OutgoingAttachment.serializer()), attachments) + return fields + } + + suspend fun sendChatMessage(agentID: String, content: String, requestID: String, replyTo: String, attachments: List = emptyList()) { + val fields = messageFields(content, requestID, replyTo, attachments) + ("timezone" to JsonPrimitive(ZoneId.systemDefault().id)) operations.sendMessage(request(fields), agentID, timeoutMs = if (attachments.isEmpty()) 20_000 else 120_000) } suspend fun attachment(agentID: String, entryID: String, index: Int): ByteArray = operations.getAttachment(agentID, entryID, index.toLong()) suspend fun abortChat(agentID: String) = operations.abortChat(agentID) - suspend fun compactChat(agentID: String) { operations.compactChat(agentID) } suspend fun chatEvents(agentID: String, limit: Int? = null, onEvent: suspend (ChatSnapshot) -> Unit): Nothing = events(operations.streamChatEvents(agentID, limit?.toLong(), timeoutMs = 24 * 60 * 60 * 1000), SSEParser()) { onEvent(CrumblePatchJson.decodeFromString(it).domain()) } + suspend fun groupChats(): List = operations.listGroupChats() + suspend fun groupChat(id: String): GroupChat = operations.getGroupChat(id) + suspend fun createGroupChat(name: String, memberIDs: List): GroupChat = + operations.createGroupChat(dev.crumble.android.generated.CreateGroupChatRequest(name, memberIDs)) + suspend fun updateGroupChat(id: String, name: String, memberIDs: List): GroupChat = + operations.updateGroupChat(dev.crumble.android.generated.UpdateGroupChatRequest(OptionalField.Present(name), OptionalField.Present(memberIDs)), id) + suspend fun deleteGroupChat(id: String) = operations.deleteGroupChat(id) + suspend fun groupSnapshot(id: String): GroupSnapshot = operations.getGroupChatSnapshot(id).domain() + suspend fun groupHistory(id: String, before: String, limit: Int): ChatHistoryResponse = + operations.getGroupChatHistory(id, limit.toLong(), before).domain() + suspend fun sendGroupMessage(id: String, content: String, requestID: String, replyTo: String, attachments: List = emptyList()) { + operations.sendGroupMessage(request(messageFields(content, requestID, replyTo, attachments)), id, timeoutMs = if (attachments.isEmpty()) 20_000 else 120_000) + } + suspend fun groupAttachment(id: String, entryID: String, index: Int): ByteArray = operations.getGroupAttachment(id, entryID, index.toLong()) + suspend fun stopGroupChat(id: String) = operations.stopGroupChat(id) + + suspend fun groupChatEvents(id: String, onEvent: suspend (GroupSnapshot) -> Unit): Nothing = + events(operations.streamGroupChatEvents(id, timeoutMs = 24 * 60 * 60 * 1000), SSEParser(accepting = setOf("snapshot"), requiresAgent = false)) { + onEvent(CrumblePatchJson.decodeFromString(it).domain()) + } + + suspend fun desktopRunning(agentID: String): Boolean = operations.getDesktopStatus(agentID).running + suspend fun createDesktopViewer(agentID: String, passive: Boolean = false): DesktopViewer = + operations.createDesktopViewer(agentID, if (passive) "true" else null) + suspend fun setDesktopHolder(agentID: String, holder: String): DesktopControl = + operations.putDesktopControl(PutDesktopControlRequest(holder), agentID) + + /** The viewer page, which needs no sign-in: its one-use link is the credential. */ + fun desktopViewerURL(viewer: DesktopViewer): String = URI(baseURL).resolve(viewer.path).toString() + + suspend fun desktopEvents(agentID: String, onEvent: suspend (DesktopControl) -> Unit): Nothing = + events(operations.streamDesktopEvents(agentID, timeoutMs = 24 * 60 * 60 * 1000), SSEParser(accepting = setOf("control"), requiresAgent = false)) { + onEvent(CrumbleJson.decodeFromString(it)) + } + suspend fun activityEvents(onEvent: suspend (dev.crumble.android.model.ActivityEvent) -> Unit): Nothing = events(operations.streamActivityEvents(timeoutMs = 24 * 60 * 60 * 1000), SSEParser(accepting = setOf("activity"))) { onEvent(CrumblePatchJson.decodeFromString(it).domain()) @@ -323,6 +518,37 @@ class APIClient( suspend fun createSharedSkill(name: String, instructions: String): SharedSkill = operations.createSkill(request(strings("name" to name, "instructions" to instructions))).domain() suspend fun updateSharedSkill(id: String, name: String, instructions: String): SharedSkill = requireNotNull(operations.updateSkill(request(strings("name" to name, "instructions" to instructions)), id)).domain() suspend fun deleteSharedSkill(id: String) = operations.deleteSkill(id) + suspend fun skillPackage(id: String): SkillPackage = operations.getSkill(id) + suspend fun copySharedSkill(full: SkillPackage): SharedSkill = operations.createSkill( + CreateSkillRequest( + name = "${full.name} copy".take(100), + description = OptionalField.Present(full.description), + instructions = full.instructions, + documents = OptionalField.Present(full.documents.map { CreateSkillRequestDocumentsItem(it.path, it.content) }), + ), + ).domain().copy(description = full.description, source = "shared") + suspend fun botSkills(agentID: String): List = operations.listAgentSkills(agentID) + suspend fun createBotSkill(agentID: String, name: String, instructions: String): SkillPackage = + operations.createAgentSkill(request(strings("name" to name, "instructions" to instructions)), agentID) + suspend fun updateBotSkill(agentID: String, skillID: String, name: String, instructions: String): SkillPackage = + requireNotNull(operations.updateAgentSkill(request(strings("name" to name, "instructions" to instructions)), agentID, skillID)) + suspend fun pinBotSkill(agentID: String, skillID: String, pinned: Boolean): SkillPackage = + requireNotNull(operations.updateAgentSkill(request(mapOf("pinned" to JsonPrimitive(pinned))), agentID, skillID)) + suspend fun deleteBotSkill(agentID: String, skillID: String) = operations.deleteAgentSkill(agentID, skillID) + /** Returns whether the bot already had the requested state. */ + suspend fun assignSkill(skillID: String, botID: String, assigned: Boolean): Boolean = + operations.assignSkillBot(AssignSkillBotRequest(botID, assigned), skillID).skipped + suspend fun browseSkills(location: String): SkillListing = + operations.browseSkillRepository(BrowseSkillRepositoryRequest(location), timeoutMs = GITHUB_TIMEOUT_MS) + suspend fun installSkills(listing: SkillListing, paths: Set, botIDs: Set): List = operations.installSkills( + InstallSkillsRequest(listing.repository, listing.branch, listing.commit, paths.toList(), OptionalField.Present(botIDs.toList())), + timeoutMs = GITHUB_TIMEOUT_MS, + ) + suspend fun checkSkillUpdates(): SkillCheck = operations.checkSkillUpdates(timeoutMs = GITHUB_TIMEOUT_MS) + suspend fun pendingSkillUpdate(id: String): PendingSkillUpdate = operations.getPendingSkillUpdate(id, timeoutMs = GITHUB_TIMEOUT_MS) + suspend fun applySkillUpdate(id: String): SkillPackage = operations.applySkillUpdate(id, timeoutMs = GITHUB_TIMEOUT_MS) + suspend fun changes(before: String? = null, limit: Int = CHANGES_PAGE): List = operations.listChanges(limit.toLong(), before) + suspend fun revertChange(id: String): LearnedChange = operations.revertChange(id) suspend fun schedules(): List = operations.listSchedules().map { it.domain() } suspend fun createSchedule(payload: Map): Schedule = operations.createSchedule(request(payload)).domain() suspend fun updateSchedule(id: String, patch: Map): Schedule = requireNotNull(operations.updateSchedule(request(patch), id)).domain() @@ -338,7 +564,17 @@ class APIClient( ) } suspend fun executions(): List = operations.listExecutions().map { it.domain() } - suspend fun activityFeed(): ActivityFeedResponse = operations.getActivityFeed().domain() + suspend fun scriptRuns(scheduleID: String): List = operations.listScriptRuns(scheduleID, SCRIPT_RUNS_PAGE) + suspend fun eventSources(): List = operations.listEventSources().sources + suspend fun createEventSource(name: String): CreateEventSourceResponse = operations.createEventSource(CreateEventSourceRequest(name)) + suspend fun deleteEventSource(id: String) = operations.deleteEventSource(id) + suspend fun capabilities(): Capabilities = operations.getCapabilities() + suspend fun activityFeed( + kind: String? = null, + agentID: String? = null, + cursor: String? = null, + limit: Long? = null, + ): ActivityFeedResponse = operations.getActivityFeed(agentID, limit, kind, cursor).domain() suspend fun pushInfo(): PushInfo = operations.getPushStatus().domain() suspend fun registerPushDevice(installationId: String, registration: PushRegistration): PushRegistrationResult = @@ -352,10 +588,32 @@ class APIClient( return installationId } - suspend fun providers(): List = operations.listProviders().map { it.domain() } suspend fun models(provider: String): List = operations.listModels(provider).map { it.domain() } - suspend fun setProviderKey(provider: String, apiKey: String) { operations.putProviderKey(request(strings("apiKey" to apiKey)), provider) } suspend fun deleteProviderKey(provider: String) = operations.deleteProviderKey(provider) + suspend fun providerAccounts() = operations.listProviders() + suspend fun setProviderKey(provider: String, secret: SecretInput) { operations.putProviderKey(request(secret.json()), provider) } + suspend fun startProviderLogin(provider: String) = operations.startProviderLogin(request(strings("method" to "oauth")), provider) + suspend fun providerLogin(id: String) = operations.getProviderLogin(id) + suspend fun cancelProviderLogin(id: String) = operations.cancelProviderLogin(id) + suspend fun answerProviderLogin(id: String, promptID: String, value: String) = + operations.answerProviderLogin(request(strings("promptId" to promptID, "value" to value)), id) + suspend fun passwordManagers() = operations.listPasswordManagers().passwordManagers + suspend fun connectPasswordManager(id: String, token: String) = operations.connectPasswordManager(request(strings("token" to token)), id) + suspend fun disconnectPasswordManager(id: String) = operations.disconnectPasswordManager(id) + suspend fun credentials(agentID: String) = operations.listAgentCredentials(agentID) + suspend fun saveCredential(agentID: String, name: String, fields: Map) = + operations.saveAgentCredential(request(fields), agentID, name) + suspend fun deleteCredential(agentID: String, name: String) = operations.deleteAgentCredential(agentID, name) + suspend fun declineCredential(agentID: String, name: String) = operations.declineAgentCredential(agentID, name) + suspend fun credentialUses(agentID: String, name: String, before: String?) = + operations.listAgentCredentialUses(agentID, name, SECRET_USES_PAGE.toLong(), before) + suspend fun logins(agentID: String) = operations.listAgentLogins(agentID) + suspend fun saveLogin(agentID: String, name: String, fields: Map) = + operations.saveAgentLogin(request(fields), agentID, name) + suspend fun deleteLogin(agentID: String, name: String) = operations.deleteAgentLogin(agentID, name) + suspend fun declineLogin(agentID: String, name: String) = operations.declineAgentLogin(agentID, name) + suspend fun loginUses(agentID: String, name: String, before: String?) = + operations.listAgentLoginUses(agentID, name, SECRET_USES_PAGE.toLong(), before) suspend fun mcpServers(): List = operations.listMcpServers().map { it.domain() } suspend fun createMCPServer(payload: Map): MCPServer = operations.createMcpServer(request(payload)).domain() suspend fun updateMCPServer(id: String, patch: Map): MCPServer = requireNotNull(operations.updateMcpServer(request(patch), id)).domain() @@ -367,14 +625,65 @@ class APIClient( return operations.finishMcpOAuth(request(fields), id, timeoutMs = 60_000).domain() } suspend fun signOutOfMCP(id: String): MCPServer = operations.signOutMcpOAuth(id).domain() + + suspend fun githubApps(): List = operations.listGithubApps().apps + suspend fun createGithubAppManifest(name: String, origin: String, organization: String?) = operations.createGithubAppManifest( + CreateGithubAppManifestRequest(name, origin, organization?.let { OptionalField.Present(it) } ?: OptionalField.Absent), + ) + suspend fun completeGithubApp(code: String, state: String): GitHubApp = + operations.completeGithubApp(CompleteGithubAppRequest(code, state), timeoutMs = GITHUB_TIMEOUT_MS) + suspend fun connectGithubApp(id: String): GitHubApp = operations.connectGithubApp(id, timeoutMs = GITHUB_TIMEOUT_MS) + suspend fun setGithubAppBots(id: String, botIDs: List): GitHubApp = operations.setGithubAppBots(SetGithubAppBotsRequest(botIDs), id) + suspend fun deleteGithubApp(id: String) = operations.deleteGithubApp(id) + suspend fun signInGithubApp(id: String, origin: String): String = operations.signInGithubApp(SignInGithubAppRequest(origin), id).url + suspend fun completeGithubAppSignIn(code: String, state: String): GitHubApp = + operations.completeGithubAppSignIn(CompleteGithubAppSignInRequest(code, state), timeoutMs = GITHUB_TIMEOUT_MS) + suspend fun signOutGithubApp(id: String): GitHubApp = operations.signOutGithubApp(id, timeoutMs = GITHUB_TIMEOUT_MS) + suspend fun setGithubAppClientSecret(id: String, secret: SecretInput): GitHubApp = operations.setGithubAppClientSecret(request(secret.json()), id) + suspend fun githubAccounts(): List = operations.listGithubAccounts().accounts + suspend fun addGithubAccount(token: SecretInput): GitHubAccount = operations.addGithubAccount(request(token.json()), timeoutMs = GITHUB_TIMEOUT_MS) + suspend fun setGithubAccountToken(id: String, token: SecretInput): GitHubAccount = + operations.setGithubAccountToken(request(token.json()), id, timeoutMs = GITHUB_TIMEOUT_MS) + suspend fun setGithubAccountBots(id: String, botIDs: List): GitHubAccount = operations.setGithubAccountBots(SetGithubAccountBotsRequest(botIDs), id) + suspend fun deleteGithubAccount(id: String) = operations.deleteGithubAccount(id) + + suspend fun adminUsers(): List = operations.listUsers().users + suspend fun setUserRole(id: String, role: String): AdminUser = operations.setUserRole(SetUserRoleRequest(role), id) + suspend fun removeUser(id: String) = operations.removeUser(id) + suspend fun invites(): List = operations.listInvites().invites + suspend fun createInvite(): CreatedInvite = operations.createInvite() + suspend fun revokeInvite(id: String) = operations.revokeInvite(id) + suspend fun outdatedWorkspaces(): List = operations.listOutdatedWorkspaces().workspaces + suspend fun serverSettings(): ServerSettings = operations.getServerSettings() + suspend fun updateServerSettings(patch: UpdateServerSettingsRequest): ServerSettings = operations.updateServerSettings(patch) + + suspend fun messageGateways(): List = operations.messageGateways().gateways.map { it.domain() } + suspend fun updateMessageGateway(id: String, config: GatewayConfig): MessageGateway = operations.updateMessageGateway(config.wire(), id).domain() + suspend fun eventRelay(): RelayStatus = operations.getEventRelay().domain() + suspend fun updateEventRelay(url: String?): RelayStatus = operations.updateEventRelay(UpdateEventRelayRequest(url)).domain() + suspend fun pluginSettings(): PluginSettings = operations.listPluginSettings() + suspend fun setPluginSetting(pluginID: String, key: String, secret: SecretInput): PluginSetting = + operations.setPluginSetting(request(secret.json()), pluginID, key) + suspend fun deletePluginSetting(pluginID: String, key: String): PluginSetting = operations.deletePluginSetting(pluginID, key) + suspend fun webSearch(): WebSearchSettings = operations.getWebSearch().domain() + suspend fun updateWebSearch(defaultProvider: String): WebSearchSettings = operations.updateWebSearch(UpdateWebSearchRequest(defaultProvider)).domain() + suspend fun judgeModel(): JudgeModel = operations.getJudgeModel() + suspend fun updateJudgeModel(provider: String?, model: String?): JudgeModel = operations.updateJudgeModel( + UpdateJudgeModelRequest(if (provider != null && model != null) UpdateJudgeModelRequestJudgeModel(provider, model) else null), + ) + suspend fun visionModel(): VisionModel = operations.getVisionModel() + suspend fun updateVisionModel(provider: String?, model: String?): VisionModel = operations.updateVisionModel( + UpdateVisionModelRequest(if (provider != null && model != null) UpdateVisionModelRequestVisionModel(provider, model) else null), + ) } /** * Splits a server-sent event stream into snapshot payloads, line by line. Heartbeats and other - * event types are skipped; a snapshot without an agentId is a protocol error. + * event types are skipped; a bot snapshot without an agentId is a protocol error. */ class SSEParser( private val accepting: Set = setOf("snapshot", "message"), + private val requiresAgent: Boolean = true, ) { private val data = mutableListOf() private var eventType = "message" @@ -408,6 +717,7 @@ class SSEParser( } catch (_: Exception) { null } ?: throw InvalidPayload("invalid SSE payload") + if (!requiresAgent) return payload val agentID = (element["agentId"] as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull if (agentID.isNullOrEmpty()) { throw InvalidPayload("snapshot event missing agentId") @@ -419,7 +729,7 @@ class SSEParser( fun friendlyError(error: Throwable): String { if (error is APIError) { if (error.statusCode == 401) { - return "Authentication failed. Check the server token in Settings." + return "Authentication failed. Sign in again in Settings." } try { val obj = CrumbleJson.parseToJsonElement(error.body) as? JsonObject diff --git a/app/src/main/java/dev/crumble/android/network/ContractAdapters.kt b/app/src/main/java/dev/crumble/android/network/ContractAdapters.kt index da7d19d..5eeb89a 100644 --- a/app/src/main/java/dev/crumble/android/network/ContractAdapters.kt +++ b/app/src/main/java/dev/crumble/android/network/ContractAdapters.kt @@ -4,16 +4,40 @@ import dev.crumble.android.generated.* import dev.crumble.android.model.* import dev.crumble.android.push.PushInfo import dev.crumble.android.push.PushRegistrationResult +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.decodeFromJsonElement +import kotlinx.serialization.json.encodeToJsonElement private fun T?.optional(): OptionalField = if (this == null) OptionalField.Absent else OptionalField.Present(this) +internal fun BotAvatarDefinition?.wire(): CreateAgentRequestAvatar? = + this?.let { CrumblePatchJson.decodeFromJsonElement(CrumblePatchJson.encodeToJsonElement(it)) } + +internal fun BotRequestProposalAvatar?.domain(): BotAvatarDefinition? = + this?.let { CrumblePatchJson.decodeFromJsonElement(CrumblePatchJson.encodeToJsonElement(it)) } + +// The server replaces the proposal whole, so fields the editor doesn't show must travel with the edits. +internal fun BotRequestProposal.edited(input: dev.crumble.android.model.Agent): Map = + (CrumbleJson.encodeToJsonElement(this) as JsonObject) + + (CrumblePatchJson.encodeToJsonElement(input.wire()) as JsonObject) + + mapOf( + "description" to JsonPrimitive(input.description.orEmpty()), + "instructions" to JsonPrimitive(input.instructions.orEmpty()), + "webSearchProvider" to JsonPrimitive(input.webSearchProvider), + "desktopModel" to CrumblePatchJson.encodeToJsonElement(input.desktopModel), + ) + internal fun dev.crumble.android.model.Agent.wire() = CreateAgentRequest( - name = name, avatar = avatar.optional(), description = description.optional(), + name = name, avatar = avatar.wire().optional(), description = description.optional(), instructions = instructions.optional(), provider = provider.optional(), model = model.optional(), enabled = OptionalField.Present(enabled), tools = tools.optional(), + webSearchProvider = webSearchProvider.optional(), + desktopModel = desktopModel?.let { CreateAgentRequestDesktopModel(it.provider, it.model) }.optional(), skills = skills?.map { CreateAgentRequestSkillsItem(it.name, it.instructions) }.optional(), sharedSkills = sharedSkills.optional(), sharedMemory = sharedMemory.optional(), mcpServers = mcpServers.optional(), delegates = delegates.optional(), @@ -29,6 +53,7 @@ internal fun dev.crumble.android.push.PushRegistration.wire() = PutPushDeviceReq internal fun AgentPreview.domain() = dev.crumble.android.model.Agent( id = id, name = name, description = description, instructions = instructions, avatar = avatar, enabled = enabled, provider = provider, model = model, + webSearchProvider = webSearchProvider, desktopModel = desktopModel?.let { ModelChoice(it.provider, it.model) }, tools = tools, delegates = delegates, skills = skills.map { dev.crumble.android.model.Skill(name = it.name, instructions = it.instructions) }, sharedSkills = sharedSkills, sharedMemory = sharedMemory, mcpServers = mcpServers, @@ -39,28 +64,59 @@ internal fun AgentPreview.domain() = dev.crumble.android.model.Agent( internal fun dev.crumble.android.generated.Agent.domain() = dev.crumble.android.model.Agent( id = id, name = name, description = description, instructions = instructions, avatar = avatar, enabled = enabled, provider = provider, model = model, + webSearchProvider = webSearchProvider, desktopModel = desktopModel?.let { ModelChoice(it.provider, it.model) }, tools = tools, delegates = delegates, skills = skills.map { dev.crumble.android.model.Skill(name = it.name, instructions = it.instructions) }, sharedSkills = sharedSkills, sharedMemory = sharedMemory, mcpServers = mcpServers, inference = inference?.let { dev.crumble.android.model.Inference(it.thinkingLevel ?: "off", it.temperature, it.maxOutputTokens?.toInt()) }, ) +private fun botRequestRef(toolName: String?, isError: Boolean?, details: JsonElement?): BotRequestRef? { + if (toolName != "request_bot" || isError == true) return null + val request = details as? JsonObject ?: return null + val id = (request["id"] as? JsonPrimitive)?.contentOrNull ?: return null + val name = ((request["proposal"] as? JsonObject)?.get("name") as? JsonPrimitive)?.contentOrNull ?: return null + return BotRequestRef(id, name) +} + +private fun secretRequestRef(tool: String, toolName: String?, isError: Boolean?, details: JsonElement?): SecretRequestRef? { + if (toolName != tool || isError == true) return null + val request = details as? JsonObject ?: return null + val name = (request["name"] as? JsonPrimitive)?.contentOrNull?.nilIfEmpty ?: return null + val hosts = (request["hosts"] as? JsonArray).orEmpty().mapNotNull { (it as? JsonPrimitive)?.contentOrNull } + return SecretRequestRef(name, hosts, (request["requestedAt"] as? JsonPrimitive)?.contentOrNull?.nilIfEmpty) +} + internal fun TranscriptMessage.domain() = Message( id = id, entryId = entryId, role = role, content = JsonPrimitive(content), blocks = blocks, kind = kind, replyTo = replyTo, replyPreview = replyPreview, - origin = origin?.let { dev.crumble.android.model.MessageOrigin(it.kind, it.name, it.agentId) }, + origin = origin?.let { dev.crumble.android.model.MessageOrigin(it.kind, it.name, it.agentId, it.source) }, communication = communication?.let { dev.crumble.android.model.BotCommunication(it.executionId, it.fromAgentId, it.fromName, it.toAgentId, it.toName, it.status) }, timestamp = timestamp?.toLong(), attachments = attachments?.map { dev.crumble.android.model.AttachmentInfo(it.name, it.mimeType, it.size.toInt(), it.kind) }, requestId = requestId, + heldAction = heldAction?.let { HeldActionRef(it.id, it.job) }, + jobQuestion = jobQuestion?.let { JobQuestionRef(it.id, it.job) }, + botRequest = botRequestRef(toolName, isError, toolDetails), + credentialRequest = secretRequestRef("request_credential", toolName, isError, toolDetails), + loginRequest = secretRequestRef("request_login", toolName, isError, toolDetails), + toolName = toolName, toolCallId = toolCallId, isError = isError, toolDetails = toolDetails, + sources = sources?.map { MessageSource(it.url, it.title) }, ) internal fun SnapshotEventPayloadMessagesItem.domain() = Message( id = id, entryId = entryId, role = role, content = JsonPrimitive(content), blocks = blocks, kind = kind, replyTo = replyTo, replyPreview = replyPreview, - origin = origin?.let { dev.crumble.android.model.MessageOrigin(it.kind, it.name, it.agentId) }, + origin = origin?.let { dev.crumble.android.model.MessageOrigin(it.kind, it.name, it.agentId, it.source) }, communication = communication?.let { dev.crumble.android.model.BotCommunication(it.executionId, it.fromAgentId, it.fromName, it.toAgentId, it.toName, it.status) }, timestamp = timestamp?.toLong(), attachments = attachments?.map { dev.crumble.android.model.AttachmentInfo(it.name, it.mimeType, it.size.toInt(), it.kind) }, requestId = requestId, + heldAction = heldAction?.let { HeldActionRef(it.id, it.job) }, + jobQuestion = jobQuestion?.let { JobQuestionRef(it.id, it.job) }, + botRequest = botRequestRef(toolName, isError, toolDetails), + credentialRequest = secretRequestRef("request_credential", toolName, isError, toolDetails), + loginRequest = secretRequestRef("request_login", toolName, isError, toolDetails), + toolName = toolName, toolCallId = toolCallId, isError = isError, toolDetails = toolDetails, + sources = sources?.map { MessageSource(it.url, it.title) }, ) internal fun dev.crumble.android.generated.ChatSnapshot.domain() = dev.crumble.android.model.ChatSnapshot( @@ -73,26 +129,39 @@ internal fun SnapshotEventPayload.domain() = dev.crumble.android.model.ChatSnaps agentId = agentId, hasMore = hasMore, oldestEntryId = oldestEntryId, ) +internal fun GroupChatSnapshot.domain() = GroupSnapshot(messages.map { it.domain() }, hasMore, oldestEntryId, groupChat, activity) + internal fun TranscriptPage.domain() = ChatHistoryResponse(messages.map { it.domain() }, hasMore, oldestEntryId) -internal fun dev.crumble.android.generated.Memory.domain() = dev.crumble.android.model.Memory(id, content, createdAt) +internal fun dev.crumble.android.generated.Memory.domain() = dev.crumble.android.model.Memory(id, content, createdAt, agentId, source, updatedAt) internal fun dev.crumble.android.generated.Skill.domain() = SharedSkill(id, name, instructions) internal fun ListedSkill.domain(): SharedSkill = when (this) { - is ListedSkill.Variant1 -> SharedSkill(value.id, value.name, value.instructions, value.source) - is ListedSkill.Variant2 -> SharedSkill(value.id, value.name, value.instructions, value.source, value.path) + is ListedSkill.Variant1 -> SharedSkill(value.id, value.name, value.instructions, value.source, description = value.description, origin = value.origin, update = value.update) + is ListedSkill.Variant2 -> SharedSkill(value.id, value.name, value.instructions, value.source, value.path, value.description) } internal fun dev.crumble.android.generated.Schedule.domain() = dev.crumble.android.model.Schedule( id, agentId, name, cron, prompt, timezone, runAt, enabled, createdByAgentId, + kind, command, timeoutSeconds, notify, eventSourceId, nextRunAt, ) internal fun dev.crumble.android.generated.Execution.domain() = dev.crumble.android.model.Execution( - id, agentId, conversationId, status, prompt, error, createdAt, updatedAt, + id, agentId, conversationId, status, prompt, error, createdAt, updatedAt, scheduleId, ) internal fun ActivityFeed.domain() = ActivityFeedResponse(activities.map { - ActivityRecord(it.id, it.agentId, it.agentName, it.entryId, it.timestamp?.toLong(), it.kind, JsonObject(it.details)) -}, hasMore) + when (it) { + is ActivityFeedActivitiesItem.Variant1 -> it.value.run { ActivityRecord(id, agentId, agentName, entryId, timestamp?.toLong(), kind, JsonObject(details)) } + is ActivityFeedActivitiesItem.Variant2 -> it.value.run { + ActivityRecord(id, agentId.orEmpty(), agentName.orEmpty(), null, timestamp.toLong(), kind, CrumbleJson.encodeToJsonElement(LearnedChange.serializer(), change), change) + } + } +}, hasMore, nextCursor) internal fun Provider.domain() = ProviderStatus(provider, name, configured) -internal fun Model.domain() = ModelSummary(provider, id, name, contextWindow.toInt(), reasoning) -internal fun McpServer.domain() = MCPServer(id, name, url, enabled, agentId) -internal fun McpServerStatus.domain() = MCPServer(id, name, url, enabled, agentId, authenticated, auth) +internal fun Model.domain() = ModelSummary(provider, id, name, contextWindow.toInt(), reasoning, thinkingLevels) +internal fun CodingJob.domain() = JobSummary(JobKind.coding, name, status, model?.model, usage, question) +internal fun DesktopJob.domain() = JobSummary( + JobKind.desktop, name, status, model?.model, usage, + question?.let { CodingJobQuestion(it.id, it.text, it.askedAt, it.options, it.multiple) }, +) +internal fun McpServer.domain() = MCPServer(id, name, url, enabled, agentId, oauthClientId = oauthClientId, token = token, oauthClientSecret = oauthClientSecret) +internal fun McpServerStatus.domain() = MCPServer(id, name, url, enabled, agentId, authenticated, auth, oauthClientId, token, oauthClientSecret, error) internal fun McpOAuthStart.domain(): OAuthStart = when (this) { is McpOAuthStart.Variant1 -> OAuthStart(authorizationUrl = value.authorizationUrl) is McpOAuthStart.Variant2 -> OAuthStart(authorized = value.authorized) @@ -104,6 +173,7 @@ internal fun ActivityEventPayload.domain(): dev.crumble.android.model.ActivityEv type = value.type, agentId = value.agentId, agentName = value.agentName, entryId = value.entryId, origin = value.origin, preview = value.preview, eventId = value.eventId, serverId = value.serverId, createdAt = value.createdAt, + groupId = value.groupId, groupName = value.groupName, ) is ActivityEventPayload.Variant2 -> dev.crumble.android.model.ActivityEvent( type = value.type, agentId = value.agentId, agentName = value.agentName, lastMessage = value.lastMessage, diff --git a/app/src/main/java/dev/crumble/android/push/PushContract.kt b/app/src/main/java/dev/crumble/android/push/PushContract.kt index 2152958..83104a8 100644 --- a/app/src/main/java/dev/crumble/android/push/PushContract.kt +++ b/app/src/main/java/dev/crumble/android/push/PushContract.kt @@ -48,6 +48,8 @@ data class PushReply( val origin: String? = null, val preview: String = "", val createdAt: String? = null, + val groupId: String? = null, + val groupName: String? = null, ) { fun toActivityEvent(): ActivityEvent = ActivityEvent( type = type, @@ -59,6 +61,8 @@ data class PushReply( eventId = eventId, serverId = serverId, createdAt = createdAt, + groupId = groupId?.takeIf { it.isNotEmpty() }, + groupName = groupName, ) } diff --git a/app/src/main/java/dev/crumble/android/push/PushRuntime.kt b/app/src/main/java/dev/crumble/android/push/PushRuntime.kt index 1eba24d..f4e83ac 100644 --- a/app/src/main/java/dev/crumble/android/push/PushRuntime.kt +++ b/app/src/main/java/dev/crumble/android/push/PushRuntime.kt @@ -15,6 +15,7 @@ import com.google.firebase.FirebaseApp import dev.crumble.android.model.ActivityEvent import dev.crumble.android.model.AndroidReplyNotifier import dev.crumble.android.model.NotificationContext +import dev.crumble.android.model.NotificationSettings import dev.crumble.android.model.ReplyNotifier import dev.crumble.android.model.Route import dev.crumble.android.network.APIClient @@ -22,17 +23,24 @@ import dev.crumble.android.storage.AndroidKeyStoreCredentials import java.io.File import java.util.UUID import java.util.concurrent.TimeUnit +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext /** Process-wide receiver state; registration and duplicate tracking survive process death. */ class PushRuntime private constructor(private val context: Context) : ReplyNotifier { val store = PushStateStore(AndroidKeyStoreCredentials(context, synchronousWrites = true)) - private val notifier = AndroidReplyNotifier(context) { store.read().current?.identity() } + private val settings = NotificationSettings(AndroidKeyStoreCredentials(context)) + private val notifier = AndroidReplyNotifier( + context, + connectionIdentity = { store.read().current?.identity() }, + sound = { settings.sound }, + ) private val delivery = PushDelivery(store) private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private val presenceMutex = Mutex() @@ -47,6 +55,7 @@ class PushRuntime private constructor(private val context: Context) : ReplyNotif } fun configure(api: APIClient) { + if (api.token.isEmpty()) return val previous = store.read().current if (previous != null && (previous.url != api.baseURL || previous.bearer != api.token)) { NotificationManagerCompat.from(context).cancelAll() @@ -56,7 +65,28 @@ class PushRuntime private constructor(private val context: Context) : ReplyNotif if (FirebaseApp.getApps(context).isEmpty()) store.clearRemoteDelivery() } - fun notificationsEnabled(): Boolean { + /** Runs while the session still works, because unregistering needs it. */ + suspend fun signedOut(api: APIClient) { + withContext(Dispatchers.IO) { + try { + api.unregisterPushDevice(installationId) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + // Sign-out goes ahead when the server can't be reached. + } + } + store.forget(api.baseURL, api.token) + NotificationManagerCompat.from(context).cancelAll() + } + + /** Whether this device should get replies: the owner wants them and Android lets them show. */ + fun notificationsEnabled(): Boolean = settings.replies && notificationsAllowed() + + val repliesWanted: Boolean + get() = settings.replies + + fun notificationsAllowed(): Boolean { val channel = context.getSystemService(NotificationManager::class.java) .getNotificationChannel(AndroidReplyNotifier.CHANNEL_ID) return NotificationManagerCompat.from(context).areNotificationsEnabled() && @@ -123,6 +153,14 @@ class PushRuntime private constructor(private val context: Context) : ReplyNotif ) } + fun groupFromIntent(intent: Intent): String? { + return store.agentForTap( + intent.getStringExtra(AndroidReplyNotifier.EXTRA_SERVER_ID), + intent.getStringExtra(AndroidReplyNotifier.EXTRA_CONNECTION_ID), + intent.getStringExtra(AndroidReplyNotifier.EXTRA_GROUP_ID), + ) + } + companion object { // get() stores applicationContext only, whose lifetime matches this singleton. @SuppressLint("StaticFieldLeak") diff --git a/app/src/main/java/dev/crumble/android/push/PushState.kt b/app/src/main/java/dev/crumble/android/push/PushState.kt index 3274b91..b4dcbe2 100644 --- a/app/src/main/java/dev/crumble/android/push/PushState.kt +++ b/app/src/main/java/dev/crumble/android/push/PushState.kt @@ -60,6 +60,17 @@ class PushStateStore(private val credentials: CredentialStore) { true } + /** Drops a signed-out session, whose bearer can never unregister again. */ + fun forget(url: String, bearer: String) = synchronized(lock) { + val state = read() + val gone = { connection: PushConnection -> connection.url == url.trimEnd('/') && connection.bearer == bearer } + write(state.copy( + current = state.current?.takeUnless(gone), + retired = state.retired.filterNot(gone), + revision = state.revision + 1, + )) + } + fun updateToken(token: String): Boolean = synchronized(lock) { val state = read() if (token.isBlank() || state.token == token) return false diff --git a/app/src/main/java/dev/crumble/android/storage/CredentialStore.kt b/app/src/main/java/dev/crumble/android/storage/CredentialStore.kt index dc250aa..2bdc1d5 100644 --- a/app/src/main/java/dev/crumble/android/storage/CredentialStore.kt +++ b/app/src/main/java/dev/crumble/android/storage/CredentialStore.kt @@ -14,6 +14,8 @@ import javax.crypto.spec.GCMParameterSpec interface CredentialStore { fun read(account: String): String? fun write(account: String, value: String) + fun delete(account: String) + fun deletePrefixed(prefix: String) } class InMemoryCredentialStore( @@ -26,6 +28,14 @@ class InMemoryCredentialStore( override fun write(account: String, value: String) { map[account] = value } + + override fun delete(account: String) { + map.remove(account) + } + + override fun deletePrefixed(prefix: String) { + map.keys.removeAll { it.startsWith(prefix) } + } } /** @@ -53,6 +63,16 @@ class AndroidKeyStoreCredentials( else edit.apply() } + override fun delete(account: String) { + prefs.edit().remove(account).apply() + } + + override fun deletePrefixed(prefix: String) { + val edit = prefs.edit() + prefs.all.keys.filter { it.startsWith(prefix) }.forEach(edit::remove) + edit.apply() + } + private fun getOrCreateSecretKey(): SecretKey { val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) } val existing = keyStore.getEntry(KEY_ALIAS, null) as? KeyStore.SecretKeyEntry diff --git a/app/src/main/java/dev/crumble/android/theme/Theme.kt b/app/src/main/java/dev/crumble/android/theme/Theme.kt index 2377a90..5dcf08a 100644 --- a/app/src/main/java/dev/crumble/android/theme/Theme.kt +++ b/app/src/main/java/dev/crumble/android/theme/Theme.kt @@ -1,5 +1,8 @@ package dev.crumble.android.theme +import androidx.compose.ui.unit.dp +import androidx.compose.material3.Shapes +import androidx.compose.foundation.shape.RoundedCornerShape import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme @@ -29,6 +32,8 @@ private val LightColorScheme = */ ) +private val AppShapes = Shapes(extraSmall = RoundedCornerShape(12.dp)) + @Composable fun CrumbleTheme( darkTheme: Boolean = isSystemInDarkTheme(), @@ -46,5 +51,5 @@ fun CrumbleTheme( else -> LightColorScheme } - MaterialTheme(colorScheme = colorScheme, typography = Typography, content = content) + MaterialTheme(colorScheme = colorScheme, typography = Typography, shapes = AppShapes, content = content) } diff --git a/app/src/main/java/dev/crumble/android/theme/Type.kt b/app/src/main/java/dev/crumble/android/theme/Type.kt index 2c3a2dd..c75e91c 100644 --- a/app/src/main/java/dev/crumble/android/theme/Type.kt +++ b/app/src/main/java/dev/crumble/android/theme/Type.kt @@ -1,36 +1,17 @@ package dev.crumble.android.theme import androidx.compose.material3.Typography -import androidx.compose.ui.text.TextStyle -import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp -// Set of Material typography styles to start with -val Typography = - Typography( - bodyLarge = - TextStyle( - fontFamily = FontFamily.Default, - fontWeight = FontWeight.Normal, - fontSize = 16.sp, - lineHeight = 24.sp, - letterSpacing = 0.5.sp, - ) - /* Other default text styles to override - titleLarge = TextStyle( - fontFamily = FontFamily.Default, - fontWeight = FontWeight.Normal, - fontSize = 22.sp, - lineHeight = 28.sp, - letterSpacing = 0.sp - ), - labelSmall = TextStyle( - fontFamily = FontFamily.Default, - fontWeight = FontWeight.Medium, - fontSize = 11.sp, - lineHeight = 16.sp, - letterSpacing = 0.5.sp - ) - */ - ) +private val base = Typography() + +// Material's default tracking reads wider than the system apps. +val Typography = base.copy( + titleMedium = base.titleMedium.copy(letterSpacing = 0.sp), + titleSmall = base.titleSmall.copy(letterSpacing = 0.sp), + bodyLarge = base.bodyLarge.copy(letterSpacing = 0.sp), + bodyMedium = base.bodyMedium.copy(letterSpacing = 0.sp), + bodySmall = base.bodySmall.copy(letterSpacing = 0.1.sp), + labelLarge = base.labelLarge.copy(letterSpacing = 0.sp), + labelMedium = base.labelMedium.copy(letterSpacing = 0.1.sp), +) diff --git a/app/src/main/java/dev/crumble/android/ui/AccountScreen.kt b/app/src/main/java/dev/crumble/android/ui/AccountScreen.kt new file mode 100644 index 0000000..b85a88d --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/AccountScreen.kt @@ -0,0 +1,138 @@ +package dev.crumble.android.ui + +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.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +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.Role +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 dev.crumble.android.model.AppModel +import dev.crumble.android.model.Route +import dev.crumble.android.model.WORKSPACE_PAGES + +@Composable +private fun AccountCircle(model: AppModel, size: Dp) { + Box( + modifier = Modifier.size(size).background(MaterialTheme.colorScheme.primaryContainer, CircleShape), + contentAlignment = Alignment.Center, + ) { + Text( + text = model.email.trim().take(1).uppercase().ifEmpty { "?" }, + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onPrimaryContainer, + ) + } +} + +/** The account circle at the top right of Home, as in Messages. */ +@Composable +fun AccountButton(model: AppModel) { + Box( + modifier = Modifier + .padding(start = 4.dp, end = 12.dp) + .size(48.dp) + .clickable(role = Role.Button) { model.navigate(Route.Account) } + .semantics { contentDescription = "Account" }, + contentAlignment = Alignment.Center, + ) { + AccountCircle(model, 36.dp) + } +} + +/** Everything that isn't a conversation: the workspace pages, then Settings. */ +@Composable +fun AccountPanel(model: AppModel) { + val pages = WORKSPACE_PAGES + Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 24.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + GroupCard { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(16.dp), + ) { + AccountCircle(model, 56.dp) + Column { + Text( + text = model.email.ifEmpty { "Not signed in" }, + style = MaterialTheme.typography.titleMedium, + ) + ConnectionStatus(model) + } + } + } + Column(verticalArrangement = Arrangement.spacedBy(ROW_GAP)) { + pages.forEachIndexed { index, page -> + GroupedRow( + title = page.title, + shape = groupedShape(index, pages.size), + onClick = { model.navigate(page) }, + leading = { IconTile(routeIcon(page), Tone.entries[index % Tone.entries.size]) }, + ) + } + } + GroupedRow( + title = Route.Settings.title, + shape = groupedShape(0, 1), + onClick = { model.navigate(Route.Settings) }, + leading = { IconTile(routeIcon(Route.Settings), Tone.Lavender) }, + ) + } +} + +class ChatMenuScope(private val close: () -> Unit) { + val entries = mutableListOf Unit>>() + + fun item(title: String, action: () -> Unit) { + entries += title to { + close() + action() + } + } +} + +/** The overflow menu in a chat's top bar: what belongs to this chat. */ +@Composable +fun ChatMenu(build: ChatMenuScope.() -> Unit) { + var open by remember { mutableStateOf(false) } + Box { + IconButton(onClick = { open = true }) { + Icon(Icons.Default.MoreVert, contentDescription = "More options") + } + DropdownMenu(expanded = open, onDismissRequest = { open = false }) { + ChatMenuScope { open = false }.apply(build).entries.forEach { (title, action) -> + DropdownMenuItem(text = { Text(title) }, onClick = action) + } + } + } +} diff --git a/app/src/main/java/dev/crumble/android/ui/ActivityScreen.kt b/app/src/main/java/dev/crumble/android/ui/ActivityScreen.kt new file mode 100644 index 0000000..66a705e --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/ActivityScreen.kt @@ -0,0 +1,291 @@ +package dev.crumble.android.ui + +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.PaddingValues +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.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Build +import androidx.compose.material.icons.filled.ExpandLess +import androidx.compose.material.icons.filled.ExpandMore +import androidx.compose.material.icons.filled.Forum +import androidx.compose.material.icons.filled.History +import androidx.compose.material.icons.filled.Power +import androidx.compose.material.icons.filled.Psychology +import androidx.compose.material.icons.filled.SubdirectoryArrowRight +import androidx.compose.material.icons.filled.Timeline +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.FilterChip +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +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.graphics.Shape +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.text.withStyle +import androidx.compose.ui.unit.dp +import dev.crumble.android.model.ActivityHeadline +import dev.crumble.android.model.ActivityKind +import dev.crumble.android.model.ActivityRecord +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.activityDays +import dev.crumble.android.model.clock +import dev.crumble.android.model.detailText +import dev.crumble.android.model.failed +import dev.crumble.android.model.headline +import dev.crumble.android.model.preview + +private fun kindIcon(kind: String): ImageVector = when (kind) { + ActivityKind.ToolResult.value -> Icons.Default.SubdirectoryArrowRight + ActivityKind.McpCall.value -> Icons.Default.Power + ActivityKind.BotMessage.value -> Icons.Default.Forum + ActivityKind.Change.value -> Icons.Default.History + else -> Icons.Default.Build +} + +@Composable +internal fun ActivityPanel(model: AppModel) { + val feed = model.activityFeed + Column(modifier = Modifier.fillMaxSize()) { + ActivityFilters(model) + if (feed.error.isNotEmpty()) { + Box(modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) { SheetErrorBanner(feed.error) } + } + when { + feed.items.isNotEmpty() || feed.nextCursor != null -> ActivityList(model) + feed.loading -> Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() } + feed.error.isEmpty() -> EmptyWorkspacePlaceholder( + icon = Icons.Default.Timeline, + title = "No Activity", + description = if (feed.kind == null) "Tool calls and bot messages will appear here." else "Nothing of this kind yet.", + ) + } + } +} + +@Composable +private fun ActivityFilters(model: AppModel) { + val feed = model.activityFeed + Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Row( + modifier = Modifier.horizontalScroll(rememberScrollState()), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + FilterChip(selected = feed.kind == null, onClick = { model.filterActivity(kind = null) }, label = { Text("All") }) + for (kind in ActivityKind.entries) { + FilterChip( + selected = feed.kind == kind.value, + onClick = { model.filterActivity(kind = kind.value) }, + label = { Text(kind.label) }, + leadingIcon = { Icon(kindIcon(kind.value), contentDescription = null, modifier = Modifier.size(16.dp)) }, + ) + } + } + BotFilter(model) + } +} + +@Composable +private fun BotFilter(model: AppModel) { + var open by remember { mutableStateOf(false) } + val selected = model.agents.firstOrNull { it.id == model.activityFeed.botID } + Box { + OutlinedButton(onClick = { open = true }) { + if (selected != null) { + BotAvatarView(selected, size = 18.dp) + Box(modifier = Modifier.size(6.dp)) + } + Text(selected?.name ?: "All bots", maxLines = 1, overflow = TextOverflow.Ellipsis) + } + DropdownMenu(expanded = open, onDismissRequest = { open = false }) { + DropdownMenuItem( + text = { Text("All bots") }, + onClick = { + open = false + model.filterActivity(botID = null) + }, + ) + for (bot in model.agents) { + DropdownMenuItem( + text = { Text(bot.name) }, + leadingIcon = { BotAvatarView(bot, size = 18.dp) }, + onClick = { + open = false + model.filterActivity(botID = bot.id) + }, + ) + } + } + } +} + +@Composable +private fun ActivityList(model: AppModel) { + val feed = model.activityFeed + val days = remember(feed.items) { activityDays(feed.items) } + val bots = remember(model.agents) { model.agents.associateBy { it.id } } + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 16.dp), + verticalArrangement = Arrangement.spacedBy(ROW_GAP), + ) { + for (day in days) { + item(key = "day:${day.key}") { + Box(modifier = Modifier.padding(top = 8.dp)) { GroupLabel(day.label) } + } + itemsIndexed(day.items, key = { _, activity -> activity.id }) { index, activity -> + ActivityRow(model, activity, bots[activity.agentId], groupedShape(index, day.items.size)) + } + } + if (feed.nextCursor != null) { + item(key = "older") { + Column( + modifier = Modifier.fillMaxWidth().padding(top = 8.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + if (feed.olderError.isNotEmpty()) { + Text(feed.olderError, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) + } + OutlinedButton(onClick = { model.loadOlderActivity() }, enabled = !feed.loadingOlder) { + if (feed.loadingOlder) { + CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) + Box(modifier = Modifier.size(8.dp)) + } + Text("Show older activity") + } + } + } + } + } +} + +@Composable +private fun headlineText(headline: ActivityHeadline): AnnotatedString { + val muted = MaterialTheme.colorScheme.onSurfaceVariant + return buildAnnotatedString { + withStyle(SpanStyle(fontWeight = FontWeight.Medium)) { append(headline.lead) } + if (headline.verb.isNotEmpty()) withStyle(SpanStyle(color = muted)) { append(" ${headline.verb}") } + append(" ") + val style = when { + headline.code -> SpanStyle(fontWeight = FontWeight.Medium, fontFamily = FontFamily.Monospace) + headline.muted -> SpanStyle(color = muted) + else -> SpanStyle(fontWeight = FontWeight.Medium) + } + withStyle(style) { append(headline.target) } + } +} + +@Composable +private fun ActivityMark(activity: ActivityRecord, bot: Agent?) { + Box(modifier = Modifier.size(48.dp)) { + if (bot != null) BotAvatarView(bot, size = 44.dp) else IconTile(Icons.Default.Psychology, Tone.Lavender) + Surface( + shape = CircleShape, + color = sheetColor, + contentColor = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(18.dp).align(Alignment.BottomEnd), + ) { + Box(contentAlignment = Alignment.Center) { + Icon(kindIcon(activity.kind), contentDescription = null, modifier = Modifier.size(12.dp)) + } + } + } +} + +@Composable +private fun ActivityRow(model: AppModel, activity: ActivityRecord, bot: Agent?, shape: Shape) { + var expanded by remember(activity.id) { mutableStateOf(false) } + val preview = remember(activity.id) { activity.preview() } + GroupedItem( + shape = shape, + onClick = { expanded = !expanded }, + clickBelow = true, + leading = { ActivityMark(activity, bot) }, + trailing = { + Column(horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(activity.clock(), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + if (activity.failed) ErrorBadge() + Icon(if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore, contentDescription = null, modifier = Modifier.size(18.dp)) + } + }, + below = if (expanded) { + { ActivityDetails(model, activity) } + } else { + null + }, + ) { + Text(headlineText(activity.headline()), style = MaterialTheme.typography.titleMedium, maxLines = 2, overflow = TextOverflow.Ellipsis) + if (preview.isNotEmpty()) ActivityPreview(activity, preview) + } +} + +@Composable +private fun ActivityPreview(activity: ActivityRecord, text: String) { + val message = activity.kind == ActivityKind.BotMessage.value + RowSubtitle(text, maxLines = if (message) 2 else 1, fontFamily = if (message) null else FontFamily.Monospace) +} + +@Composable +private fun ErrorBadge() { + Surface(color = MaterialTheme.colorScheme.errorContainer, shape = RoundedCornerShape(50)) { + Text( + "Error", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onErrorContainer, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 1.dp), + ) + } +} + +@Composable +private fun ActivityDetails(model: AppModel, activity: ActivityRecord) { + val change = activity.change + if (change != null) { + ChangeDiff(change) + RevertChangeButton(model, change) + return + } + val text = remember(activity.id) { activity.detailText() } + Surface(color = sheetColor, shape = RoundedCornerShape(8.dp), modifier = Modifier.fillMaxWidth()) { + Text( + text, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + modifier = Modifier.heightIn(max = 320.dp).verticalScroll(rememberScrollState()).padding(10.dp), + ) + } + if (activity.agentId.isNotEmpty()) { + OutlinedButton(onClick = { model.selectAgent(activity.agentId) }) { Text("Open Chat") } + } +} diff --git a/app/src/main/java/dev/crumble/android/ui/AgentEditorSheet.kt b/app/src/main/java/dev/crumble/android/ui/AgentEditorSheet.kt index 4d56420..56f7817 100644 --- a/app/src/main/java/dev/crumble/android/ui/AgentEditorSheet.kt +++ b/app/src/main/java/dev/crumble/android/ui/AgentEditorSheet.kt @@ -1,12 +1,12 @@ package dev.crumble.android.ui import androidx.compose.animation.AnimatedVisibility -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.ColumnScope import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -19,21 +19,23 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Code +import androidx.compose.material.icons.filled.DesktopWindows import androidx.compose.material.icons.filled.ExpandLess import androidx.compose.material.icons.filled.ExpandMore -import androidx.compose.material.icons.filled.Shuffle +import androidx.compose.material.icons.filled.Forum +import androidx.compose.material.icons.filled.Language +import androidx.compose.material.icons.filled.Psychology +import androidx.compose.material.icons.filled.SmartToy import androidx.compose.material3.AlertDialog import androidx.compose.material3.AssistChip import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults -import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExposedDropdownMenuBox -import androidx.compose.material3.ExposedDropdownMenuDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.ExposedDropdownMenuAnchorType import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold @@ -42,14 +44,12 @@ import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults 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.graphics.Color +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog @@ -57,8 +57,16 @@ import androidx.compose.ui.window.DialogProperties import dev.crumble.android.model.Agent import dev.crumble.android.model.AgentDraft import dev.crumble.android.model.AppModel +import dev.crumble.android.model.ChoiceOption import dev.crumble.android.model.Skill +import dev.crumble.android.model.THINKING_LEVELS +import dev.crumble.android.model.WEB_SEARCH_ACCOUNT_DEFAULT +import dev.crumble.android.model.WEB_SEARCH_OPTIONS +import dev.crumble.android.model.botProviderOptions +import dev.crumble.android.model.desktopModelHint +import dev.crumble.android.model.desktopProviderOptions import dev.crumble.android.model.nilIfEmpty +import dev.crumble.android.model.shownCapabilities @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -66,7 +74,8 @@ fun AgentEditorDialog( model: AppModel, draft: AgentDraft, ) { - var providerMenuExpanded by remember { mutableStateOf(false) } + val requestID = draft.botRequestID + val complete = draft.name.isNotBlank() && draft.provider.isNotEmpty() && draft.model.isNotBlank() Dialog( onDismissRequest = { @@ -76,9 +85,19 @@ fun AgentEditorDialog( properties = DialogProperties(usePlatformDefaultWidth = false), ) { Scaffold( + containerColor = pageColor, topBar = { TopAppBar( - title = { Text(if (draft.isNew) "New Agent" else "Agent Profile") }, + colors = TopAppBarDefaults.topAppBarColors(containerColor = pageColor, scrolledContainerColor = pageColor), + title = { + Text( + when { + requestID != null -> "Edit bot proposal" + draft.isNew -> "New Agent" + else -> "Agent Profile" + }, + ) + }, navigationIcon = { IconButton( onClick = { @@ -90,11 +109,24 @@ fun AgentEditorDialog( } }, actions = { - TextButton( - onClick = { model.saveAgentEditor() }, - enabled = !model.loading, - ) { - Text(if (draft.isNew) "Create" else "Save") + if (requestID != null) { + val deciding = requestID in model.decidingIDs + if (deciding) { + CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp) + } + TextButton( + onClick = { model.saveAgentEditor() }, + enabled = !deciding && complete, + ) { + Text("Approve") + } + } else { + TextButton( + onClick = { model.saveAgentEditor() }, + enabled = !model.loading && complete, + ) { + Text(if (draft.isNew) "Create" else "Save") + } } }, ) @@ -107,51 +139,33 @@ fun AgentEditorDialog( contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp), ) { + if (requestID != null) { + item { + Text( + text = "Review the proposed bot before approving it.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + model.decisionErrors[requestID]?.let { error -> + item { SheetErrorBanner(error) } + } + } + item { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp), ) { - BotAvatarView( - seed = agentAvatarSeed(Agent(id = draft.agentID, avatar = draft.avatar)), - size = 96.dp, - live = true, + AvatarPicker( + value = draft.avatar ?: placeholderAvatar(draft.id.toString()), + onChange = { model.agentDraft = draft.copy(avatar = it) }, ) Text( text = draft.name.trim().nilIfEmpty ?: "New Agent", style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold), ) - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp), - modifier = Modifier.horizontalScroll(rememberScrollState()), - ) { - for (seed in draft.avatarChoices) { - val selected = draft.avatar == "bot:$seed" - Box( - modifier = Modifier - .border( - width = if (selected) 2.dp else 0.dp, - color = if (selected) MaterialTheme.colorScheme.primary else Color.Transparent, - shape = RoundedCornerShape(10.dp), - ) - .clickable { - model.agentDraft = draft.copy(avatar = "bot:$seed") - } - .padding(4.dp), - ) { - BotAvatarView(seed = seed, size = 36.dp) - } - } - IconButton( - onClick = { - model.agentDraft = draft.withShuffledAvatars() - }, - ) { - Icon(Icons.Default.Shuffle, contentDescription = "More Avatars") - } - } } } @@ -198,46 +212,12 @@ fun AgentEditorDialog( title = "Model", footer = model.modelHint, ) { - val choices = model.providerChoices - if (choices.isEmpty()) { - OutlinedTextField( - value = draft.provider, - onValueChange = { model.changeEditorProvider(it) }, - label = { Text("Provider") }, - singleLine = true, - modifier = Modifier.fillMaxWidth(), - ) - } else { - ExposedDropdownMenuBox( - expanded = providerMenuExpanded, - onExpandedChange = { providerMenuExpanded = it }, - ) { - OutlinedTextField( - value = draft.provider, - onValueChange = {}, - readOnly = true, - label = { Text("Provider") }, - trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = providerMenuExpanded) }, - modifier = Modifier - .menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable) - .fillMaxWidth(), - ) - ExposedDropdownMenu( - expanded = providerMenuExpanded, - onDismissRequest = { providerMenuExpanded = false }, - ) { - for (choice in choices) { - DropdownMenuItem( - text = { Text(choice) }, - onClick = { - model.changeEditorProvider(choice) - providerMenuExpanded = false - }, - ) - } - } - } - } + ChoiceField( + label = "Provider", + options = botProviderOptions(model.providers, draft.provider), + value = draft.provider, + onChoose = { if (it.isNotEmpty()) model.changeEditorProvider(it) }, + ) OutlinedTextField( value = draft.model, onValueChange = { model.agentDraft = draft.copy(model = it) }, @@ -261,6 +241,14 @@ fun AgentEditorDialog( } } } + if (model.editorLevels.size > 1) { + ChoiceField( + label = "Reasoning", + options = THINKING_LEVELS.filter { it.value in model.editorLevels }.map { ChoiceOption(it.value, it.label) }, + value = model.editorLevel, + onChoose = { model.agentDraft = draft.copy(thinking = it) }, + ) + } } } @@ -279,90 +267,93 @@ fun AgentEditorDialog( } item { - SectionCard( + RowsSection( title = "Capabilities", - footer = "Memory lets the agent keep notes between chats; with shared memory it also recalls and keeps notes every bot using shared memory sees. Schedule tasks lets it save one-time and recurring tasks for itself, or for a bot it is allowed to message. When Message other bots is enabled, it can ask the permitted bots you select and relay their answers. Code mode has the agent write a short script that calls its tools.", + footer = "Memory lets the agent keep notes between chats, including notes every bot with memory sees. When Message other bots is enabled, it can ask any other bot and relay their answers.", ) { - ToggleRow( - label = "Memory", - checked = draft.toolsMemory, - onCheckedChange = { model.agentDraft = draft.copy(toolsMemory = it) }, - ) - if (draft.toolsMemory) { - ToggleRow( - label = "Use shared memory", - checked = draft.sharedMemory, - onCheckedChange = { model.agentDraft = draft.copy(sharedMemory = it) }, - modifier = Modifier.padding(start = 16.dp), - ) + for (capability in shownCapabilities(model.capabilities, draft.initialTools)) { + row { shape -> + when (capability.tool) { + "memory" -> ToggleRow( + label = capability.label, + icon = capabilityIcon(capability.tool), + shape = shape, + subtitle = capability.help, + checked = draft.toolsMemory, + onCheckedChange = { model.agentDraft = draft.copy(toolsMemory = it) }, + ) + "delegate" -> ToggleRow( + label = capability.label, + icon = capabilityIcon(capability.tool), + shape = shape, + subtitle = capability.help, + checked = draft.toolsDelegate, + onCheckedChange = { model.agentDraft = draft.copy(toolsDelegate = it) }, + ) + else -> ToggleRow( + label = capability.label, + icon = capabilityIcon(capability.tool), + shape = shape, + subtitle = capability.help, + checked = capability.tool in draft.otherTools, + onCheckedChange = { on -> + val tool = capability.tool + model.agentDraft = draft.copy(otherTools = if (on) draft.otherTools + tool else draft.otherTools - tool) + }, + below = if (capability.tool == "desktop" && capability.tool in draft.otherTools) { + { DesktopModelFields(model, draft) } + } else { + null + }, + ) + } + } } - ToggleRow( - label = "Schedule tasks", - checked = draft.toolsSchedule, - onCheckedChange = { model.agentDraft = draft.copy(toolsSchedule = it) }, - ) - ToggleRow( - label = "Message other bots", - checked = draft.toolsDelegate, - onCheckedChange = { model.agentDraft = draft.copy(toolsDelegate = it) }, - ) - if (draft.toolsDelegate) { - for (other in model.agents.filter { it.id != draft.agentID }) { - val permitted = draft.delegates.contains(other.id) - ToggleRow( - label = other.name, - checked = permitted, - onCheckedChange = { enabled -> - val next = if (enabled) draft.delegates + other.id else draft.delegates - other.id - model.agentDraft = draft.copy(delegates = next) - }, - modifier = Modifier.padding(start = 16.dp), - ) + if ("web" in draft.otherTools) { + row { shape -> + GroupCard(shape) { + ChoiceField( + label = "Web search provider", + options = WEB_SEARCH_OPTIONS, + value = draft.webSearchProvider ?: WEB_SEARCH_ACCOUNT_DEFAULT, + onChoose = { choice -> + model.agentDraft = draft.copy(webSearchProvider = choice.takeIf { it != WEB_SEARCH_ACCOUNT_DEFAULT }) + }, + ) + Text( + text = "Manage the default and Exa key in Settings → Web search.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } } } - ToggleRow( - label = "Code mode", - checked = draft.toolsCodemode, - onCheckedChange = { model.agentDraft = draft.copy(toolsCodemode = it) }, - ) } } item { - SectionCard(title = "Integrations") { + RowsSection(title = "Integrations") { val servers = model.usableServers(forAgentID = draft.agentID) - if (servers.isEmpty()) { - Text( - text = "Add an MCP server under Integrations to use its tools here.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } + if (servers.isEmpty()) note("Add an MCP server under Integrations to use its tools here.") for (server in servers) { - val checked = draft.mcpServers.contains(server.id) - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, - ) { - Column(modifier = Modifier.weight(1f)) { - Text(server.name) - if (server.agentId != null) { - Text( - text = "Only this agent", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, + row { shape -> + GroupedItem( + shape = shape, + leading = { LetterTile(server.name) }, + trailing = { + Switch( + checked = draft.mcpServers.contains(server.id), + enabled = server.enabled, + onCheckedChange = { enabled -> + val next = if (enabled) draft.mcpServers + server.id else draft.mcpServers - server.id + model.agentDraft = draft.copy(mcpServers = next) + }, ) - } - } - Switch( - checked = checked, - enabled = server.enabled, - onCheckedChange = { enabled -> - val next = if (enabled) draft.mcpServers + server.id else draft.mcpServers - server.id - model.agentDraft = draft.copy(mcpServers = next) }, - ) + ) { + RowTitle(server.name) + if (server.agentId != null) RowSubtitle("Only this agent") + } } } } @@ -386,6 +377,13 @@ fun AgentEditorDialog( } if (!draft.isNew) { + item { + SectionCard(title = "Credentials") { + OutlinedButton(onClick = { model.openBotCredentials(draft.agentID) }) { + Text("Manage in Settings") + } + } + } item { SectionCard(title = "Actions") { Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { @@ -437,29 +435,70 @@ fun AgentEditorDialog( } } +@Composable +private fun DesktopModelFields(model: AppModel, draft: AgentDraft) { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + ChoiceField( + label = "Desktop job provider", + options = desktopProviderOptions(model.providers, draft.desktopProvider), + value = draft.desktopProvider, + onChoose = { model.changeEditorDesktopProvider(it) }, + ) + if (draft.desktopProvider.isNotEmpty()) { + OutlinedTextField( + value = draft.desktopModel, + onValueChange = { model.agentDraft = draft.copy(desktopModel = it) }, + label = { Text("Desktop job model") }, + placeholder = { Text("Model ID") }, + supportingText = { Text(desktopModelHint(model.providers, draft.desktopProvider, model.desktopModels.size)) }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + if (model.desktopModels.isNotEmpty()) { + Row( + modifier = Modifier + .fillMaxWidth() + .horizontalScroll(rememberScrollState()), + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + for (summary in model.desktopModels) { + AssistChip( + onClick = { model.agentDraft = draft.copy(desktopModel = summary.id) }, + label = { Text(summary.id) }, + ) + } + } + } + } + } +} + +private fun capabilityIcon(tool: String): ImageVector = when (tool) { + "memory" -> Icons.Default.Psychology + "web" -> Icons.Default.Language + "delegate" -> Icons.Default.Forum + "coding" -> Icons.Default.Code + "desktop" -> Icons.Default.DesktopWindows + else -> Icons.Default.SmartToy +} + @Composable private fun ToggleRow( label: String, + icon: ImageVector, + shape: Shape, checked: Boolean, onCheckedChange: (Boolean) -> Unit, - modifier: Modifier = Modifier, subtitle: String? = null, + below: (@Composable ColumnScope.() -> Unit)? = null, ) { - Row( - modifier = modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, + GroupedItem( + shape = shape, + leading = { IconTile(icon, Tone.Lavender) }, + trailing = { Switch(checked = checked, onCheckedChange = onCheckedChange) }, + below = below, ) { - Column(modifier = Modifier.weight(1f)) { - Text(label) - if (subtitle != null) { - Text( - text = subtitle, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - Switch(checked = checked, onCheckedChange = onCheckedChange) + RowTitle(label) + if (subtitle != null) RowSubtitle(subtitle) } } diff --git a/app/src/main/java/dev/crumble/android/ui/AvatarEditor.kt b/app/src/main/java/dev/crumble/android/ui/AvatarEditor.kt new file mode 100644 index 0000000..ca99d4e --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/AvatarEditor.kt @@ -0,0 +1,230 @@ +package dev.crumble.android.ui + +import androidx.compose.foundation.BorderStroke +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.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.PrimaryTabRow +import androidx.compose.material3.Surface +import androidx.compose.material3.Tab +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +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.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import dev.crumble.android.R +import dev.crumble.android.generated.BotAvatarDefinition +import re.leob.openbotavatar.kt.AvatarCatalog +import re.leob.openbotavatar.kt.ValidationResult +import re.leob.openbotavatar.kt.validateAvatar + +private const val GALLERY_COLUMNS = 4 + +/** Geometry imports use the library validator; colors are separate from the portable definition. */ +internal fun importAvatar(json: String, current: BotAvatarDefinition): Result = + when (val result = validateAvatar(json)) { + is ValidationResult.Valid -> Result.success(result.value.withColors(current.color, current.eyeColor)) + is ValidationResult.Invalid -> Result.failure(IllegalArgumentException(result.errors.joinToString("\n"))) + } + +internal fun avatarGenerationPrompt(template: String, description: String) = + "$template\n\n## User description\n\n${description.trim()}\n" + +/** The portrait with a pencil, which opens the editor in a dialog as the web's popover, so the form stays short. */ +@Composable +fun AvatarPicker(value: BotAvatarDefinition, onChange: (BotAvatarDefinition) -> Unit) { + var editing by remember { mutableStateOf(false) } + Box( + modifier = Modifier + .clip(RoundedCornerShape(24.dp)) + .clickable(onClickLabel = "Change avatar") { editing = true } + .padding(4.dp), + ) { + BotAvatarView(avatar = value, size = 96.dp, live = true) + Surface( + modifier = Modifier.align(Alignment.BottomEnd).size(30.dp), + shape = CircleShape, + color = sheetColor, + ) { + Icon(Icons.Filled.Edit, contentDescription = null, modifier = Modifier.padding(7.dp)) + } + } + if (editing) { + Dialog(onDismissRequest = { editing = false }) { + Surface(shape = RoundedCornerShape(24.dp), color = sheetColor) { + Column(modifier = Modifier.padding(16.dp)) { + Column(modifier = Modifier.weight(1f, fill = false).verticalScroll(rememberScrollState())) { + AvatarEditor(value = value, onChange = onChange) + } + TextButton(onClick = { editing = false }, modifier = Modifier.align(Alignment.End)) { + Text("Done") + } + } + } + } + } +} + +@Composable +fun AvatarEditor(value: BotAvatarDefinition, onChange: (BotAvatarDefinition) -> Unit, enabled: Boolean = true) { + var tab by remember { mutableIntStateOf(0) } + var colorDraft by remember { mutableStateOf(value.color) } + var eyeDraft by remember { mutableStateOf(value.eyeColor) } + var json by remember { mutableStateOf("") } + var description by remember { mutableStateOf("") } + var error by remember { mutableStateOf("") } + var status by remember { mutableStateOf("") } + val clipboard = LocalClipboardManager.current + val resources = LocalContext.current.resources + + fun colors(color: String, eyeColor: String) { + if (isAvatarColor(color) && isAvatarColor(eyeColor)) { + onChange(value.copy(color = color, eyeColor = eyeColor)) + error = "" + } else { + error = "Colors must be #rgb or #rrggbb." + } + } + + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + OutlinedTextField( + value = colorDraft, + onValueChange = { colorDraft = it.take(7); colors(colorDraft, eyeDraft) }, + enabled = enabled, + label = { Text("Body color") }, + singleLine = true, + modifier = Modifier.weight(1f), + ) + OutlinedTextField( + value = eyeDraft, + onValueChange = { eyeDraft = it.take(7); colors(colorDraft, eyeDraft) }, + enabled = enabled, + label = { Text("Eye color") }, + singleLine = true, + modifier = Modifier.weight(1f), + ) + } + PrimaryTabRow(selectedTabIndex = tab, containerColor = Color.Transparent) { + listOf("Gallery", "Import", "Generate").forEachIndexed { index, label -> + Tab(selected = tab == index, onClick = { tab = index }, text = { Text(label) }) + } + } + when (tab) { + 0 -> Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + for (row in AvatarCatalog.examples.chunked(GALLERY_COLUMNS)) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + for (shape in row) { + val picked = shape.id == value.definition.id + Surface( + modifier = Modifier.weight(1f).clickable(enabled = enabled) { + onChange(shape.withColors(value.color, value.eyeColor)) + error = "" + status = "" + }, + shape = RoundedCornerShape(12.dp), + color = sheetColor, + border = if (picked) BorderStroke(2.dp, MaterialTheme.colorScheme.primary) else null, + ) { + Column( + modifier = Modifier.padding(6.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + BotAvatarView(shape.withColors(value.color, value.eyeColor), size = 44.dp) + Text( + shape.name, + style = MaterialTheme.typography.labelSmall, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + textAlign = TextAlign.Center, + ) + } + } + } + repeat(GALLERY_COLUMNS - row.size) { Spacer(Modifier.weight(1f)) } + } + } + } + 1 -> Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField( + value = json, + onValueChange = { json = it.take(16_000) }, + enabled = enabled, + label = { Text("Definition JSON") }, + minLines = 4, + modifier = Modifier.fillMaxWidth(), + ) + OutlinedButton(enabled = enabled, onClick = { + importAvatar(json, value).fold( + onSuccess = { + onChange(it) + error = "" + status = "Avatar imported. Save the bot to keep it." + }, + onFailure = { + error = it.message ?: "Invalid avatar JSON" + status = "" + }, + ) + }) { Text("Validate and Import") } + } + else -> Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField( + value = description, + onValueChange = { description = it.take(4_000) }, + enabled = enabled, + label = { Text("Describe your avatar") }, + placeholder = { Text("A gardening companion shaped like a watering can") }, + modifier = Modifier.fillMaxWidth(), + ) + Text( + "Copy the Open Bot Avatar prompt with your description. Give it to any bot or model, then paste its definition JSON into Import. A bot can also suggest its own avatar in chat. Nothing is generated or sent from this page.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + OutlinedButton( + enabled = enabled && description.isNotBlank(), + onClick = { + val template = resources.openRawResource(R.raw.generate_avatar_prompt).bufferedReader().use { it.readText() } + clipboard.setText(AnnotatedString(avatarGenerationPrompt(template, description))) + status = "Prompt copied. Give it to any bot or model, then paste its JSON into Import." + error = "" + }, + ) { Text("Copy Generation Prompt") } + } + } + if (error.isNotEmpty()) Text(error, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) + if (status.isNotEmpty()) Text(status, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } +} diff --git a/app/src/main/java/dev/crumble/android/ui/AvatarsScreen.kt b/app/src/main/java/dev/crumble/android/ui/AvatarsScreen.kt new file mode 100644 index 0000000..88676be --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/AvatarsScreen.kt @@ -0,0 +1,98 @@ +package dev.crumble.android.ui + +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.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ExposedDropdownMenuAnchorType +import androidx.compose.material3.ExposedDropdownMenuBox +import androidx.compose.material3.ExposedDropdownMenuDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +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 dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun AvatarBotField(bots: List, selected: String, enabled: Boolean, onSelect: (String) -> Unit) { + var open by remember { mutableStateOf(false) } + ExposedDropdownMenuBox(expanded = open, onExpandedChange = { open = it && enabled }) { + OutlinedTextField( + value = bots.firstOrNull { it.id == selected }?.name ?: "Preview only", + onValueChange = {}, + readOnly = true, + enabled = enabled, + label = { Text("Bot to edit") }, + trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(open) }, + modifier = Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable, enabled), + ) + ExposedDropdownMenu(expanded = open, onDismissRequest = { open = false }) { + DropdownMenuItem(text = { Text("Preview only") }, onClick = { open = false; onSelect("") }) + for (bot in bots) { + DropdownMenuItem(text = { Text(bot.name) }, onClick = { open = false; onSelect(bot.id) }) + } + } + } +} + +/** Try portable definitions and save one to a bot. */ +@Composable +fun AvatarsPanel(model: AppModel) { + val page = model.avatarPage + val bots = model.agents.filterNot { it.id.startsWith("pending:") } + Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 24.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + Text( + "Choose a gallery shape, import a definition, or copy a prompt to design your own.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 16.dp), + ) + GroupCard { + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) { + for (state in BotState.entries) { + Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp)) { + BotAvatarView(avatar = page.value, size = 88.dp, state = state, live = true) + Text(state.name.replaceFirstChar { it.uppercase() }, style = MaterialTheme.typography.bodySmall) + } + } + } + } + GroupCard { + AvatarBotField(bots, page.botID, enabled = !page.saving, onSelect = { model.pickAvatarBot(it) }) + // The editor keeps its color drafts, which start over for each bot. + key(page.botID) { + AvatarEditor(value = page.value, enabled = !page.saving, onChange = { model.changeAvatar(it) }) + } + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Button(enabled = page.botID.isNotEmpty() && !page.saving, onClick = { model.saveAvatar() }) { Text("Save avatar to bot") } + if (page.saving) CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp) + } + if (page.saved) Text("Avatar saved.", style = MaterialTheme.typography.bodySmall) + } +} diff --git a/app/src/main/java/dev/crumble/android/ui/BotAvatar.kt b/app/src/main/java/dev/crumble/android/ui/BotAvatar.kt index 6b5ba97..3e7e06f 100644 --- a/app/src/main/java/dev/crumble/android/ui/BotAvatar.kt +++ b/app/src/main/java/dev/crumble/android/ui/BotAvatar.kt @@ -1,359 +1,61 @@ package dev.crumble.android.ui -import android.database.ContentObserver -import android.os.Handler -import android.os.Looper -import android.provider.Settings -import androidx.compose.foundation.Canvas -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.size -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text import androidx.compose.runtime.Composable -import androidx.compose.runtime.DisposableEffect -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.SideEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableDoubleStateOf -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.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.Brush +import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.Path -import androidx.compose.ui.graphics.PathOperation -import androidx.compose.ui.graphics.StrokeCap -import androidx.compose.ui.graphics.StrokeJoin -import androidx.compose.ui.graphics.drawscope.DrawScope -import androidx.compose.ui.graphics.drawscope.Stroke -import androidx.compose.ui.graphics.drawscope.clipPath -import androidx.compose.ui.graphics.drawscope.withTransform -import androidx.compose.ui.graphics.graphicsLayer -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.Dp -import androidx.compose.ui.unit.IntOffset +import dev.crumble.android.generated.BotAvatarDefinition +import dev.crumble.android.generated.BotAvatarDefinitionDefinition +import dev.crumble.android.generated.BotAvatarDefinitionDefinitionBody +import dev.crumble.android.generated.BotAvatarDefinitionDefinitionEyes import dev.crumble.android.model.Agent -import kotlin.math.PI -import kotlin.math.abs -import kotlin.math.cos -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 - -// A port of apfelkern's BotAvatar (itself grown from Hermex's drawn faces, MIT, see -// THIRD_PARTY_NOTICES.md), so a seed draws the same bot here as on iOS and macOS. Only the dither -// finish the Swift apps use is ported; keep the numbers in step with apfelkern. +import re.leob.openbotavatar.kt.AVATAR_CONTRACT_VERSION +import re.leob.openbotavatar.kt.AvatarCatalog +import re.leob.openbotavatar.kt.AvatarDefinition +import re.leob.openbotavatar.kt.AvatarEyes +import re.leob.openbotavatar.kt.AvatarMood +import re.leob.openbotavatar.kt.DEFAULT_COLOR +import re.leob.openbotavatar.kt.DEFAULT_EYE_COLOR +import re.leob.openbotavatar.kt.compose.BotAvatar enum class BotState { idle, working, sleeping } -fun agentAvatarSeed(agent: Agent): String { - val avatar = agent.avatar ?: "" - for (prefix in listOf("bot:", "critters:")) { - if (avatar.startsWith(prefix)) { - val seed = avatar.removePrefix(prefix).trim() - if (seed.isNotEmpty()) return seed - } - } - val id = agent.id.trim() - return id.ifEmpty { "crumble" } -} - -enum class BotShape { circle, squircle, pill, triangle, hexagon, cloud, drop } - -enum class BotMouth { smile, grin, cat, tiny } - -enum class BotTopper { none, antenna, sprout, tuft } - -/** How the face reads, apart from its motion. */ -enum class BotExpression { calm, delighted, focused, asleep } - -private fun seedHash(seed: String): ULong = - seed.encodeToByteArray().fold(1_469_598_103_934_665_603UL) { acc, byte -> - (acc xor (byte.toInt() and 0xFF).toULong()) * 1_099_511_628_211UL - } - -data class BotLook( - val shape: BotShape, - val hex: String, - val hash: ULong, - val mouth: BotMouth, - val topper: BotTopper, -) { - private constructor(hash: ULong) : this( - shape = BotShape.entries[(hash % BotShape.entries.size.toULong()).toInt()], - hex = palette[(hash % palette.size.toULong()).toInt()], - hash = hash, - mouth = BotMouth.entries[((hash shr 16) % BotMouth.entries.size.toULong()).toInt()], - topper = BotTopper.entries[((hash shr 24) % BotTopper.entries.size.toULong()).toInt()], - ) - - constructor(seed: String) : this(seedHash(seed)) - - val color: Color - get() { - val value = hex.removePrefix("#").toLongOrNull(16) ?: 0L - return Color( - red = ((value shr 16) and 0xFF) / 255f, - green = ((value shr 8) and 0xFF) / 255f, - blue = (value and 0xFF) / 255f, - ) - } - - /** The body color moved toward white for positive amounts and toward black for negative ones. */ - fun tint(amount: Double): Color = color.mixed(if (amount > 0) Color.White else Color.Black, abs(amount)) - - val inkColor: Color get() = tint(-0.8) - - /** Pink cheeks vanish on warm bodies, so those blush white instead. */ - val blushColor: Color - get() = if (hex in listOf("#ef4444", "#ec4899", "#f97316", "#f59e0b")) { - Color.White.copy(alpha = 0.5f) - } else { - Color(red = 1f, green = 0.42f, blue = 0.6f, alpha = 0.55f) - } - - companion object { - val palette = listOf( - "#8b5cf6", "#38bdf8", "#14b8a6", "#22c55e", - "#f59e0b", "#f97316", "#ef4444", "#ec4899", - ) - } -} - -private fun Color.mixed(target: Color, amount: Double): Color { - val mix = amount.toFloat() - return Color( - red = red + (target.red - red) * mix, - green = green + (target.green - green) * mix, - blue = blue + (target.blue - blue) * mix, - alpha = alpha, - ) -} - -private fun Color.faded(opacity: Float): Color = copy(alpha = alpha * opacity) - -/** - * One frame of a face: gaze as a fraction of the size, roll in degrees, the lid factor, a lift as a - * fraction of the size, the squash and stretch of the body anchored at its base, how far the mouth - * opens, the topper's lag in degrees and the antenna's glow. - */ -data class BotPose( - val gazeX: Double = 0.0, - val gazeY: Double = 0.0, - val roll: Double = 0.0, - val lid: Double = 1.0, - val lift: Double = 0.0, - val scaleX: Double = 1.0, - val scaleY: Double = 1.0, - val mouthOpen: Double = 0.0, - val sway: Double = 0.0, - val glow: Double = 0.0, -) { - operator fun times(weight: Double) = BotPose( - gazeX * weight, gazeY * weight, roll * weight, lid * weight, lift * weight, - scaleX * weight, scaleY * weight, mouthOpen * weight, sway * weight, glow * weight, - ) - - operator fun plus(other: BotPose) = BotPose( - gazeX + other.gazeX, gazeY + other.gazeY, roll + other.roll, lid + other.lid, lift + other.lift, - scaleX + other.scaleX, scaleY + other.scaleY, mouthOpen + other.mouthOpen, sway + other.sway, - glow + other.glow, - ) - - companion object { - val rest = BotPose() - const val shutLid = 0.06 - - // Every rhythm in a state repeats a whole number of times per loop, as in apfelkern. - private const val idleLoop = 36.0 - private const val workingLoop = 25.2 - private const val sleepingLoop = 16.0 - - private fun rate(count: Double, loop: Double) = 2 * PI * count / loop - - private fun snap(period: Double, loop: Double): Pair { - val count = max(1.0, (loop / period).roundToInt().toDouble()) - return Pair(loop / count, count.toInt()) - } - - /** Breathes, rocks a little, glances around and blinks, sometimes twice. */ - fun idle(time: Double, hash: ULong): BotPose { - val local = time + (hash % 10_000UL).toDouble() / 1000 - val breath = sin(local * rate(10.0, idleLoop)) - val roll = sin(local * rate(3.0, idleLoop)) * 2.2 - val gaze = glance(local, hash) - val stretchPhase = positive(local, if (hash % 2UL == 0UL) 12.0 else 18.0) - val stretch = if (stretchPhase < 1.8) sin(stretchPhase / 1.8 * PI).pow(4) else 0.0 - return BotPose( - gazeX = gaze.first, - gazeY = gaze.second, - roll = roll, - lid = blink(local, hash), - lift = 0.006 * (breath + 1), - scaleX = 1 - 0.012 * breath - 0.035 * stretch, - scaleY = 1 + 0.022 * breath + 0.055 * stretch, - sway = -roll * 1.6 + sin(local * rate(8.0, idleLoop)) * 3 + stretch * 7, - ) - } - - /** Leans aside and sways, hopping on the spot; each landing squashes into the next jump. */ - fun working(time: Double): BotPose { - val loop = workingLoop - val turn = -11 + sin(time * rate(2.0, loop)) * 8 - val tilt = sin(time * rate(2.0, loop) + 1.3) * 8 + sin(time * rate(4.0, loop)) * 1.6 - val blinkPeriod = loop / 17 - val blink = positive(time, blinkPeriod) > blinkPeriod * 0.869 - val hop = positive(time, 0.9) / 0.9 - val ground = 0.12 - val contact = min(hop, 1 - hop) - val squash = if (contact < ground) 1 - 0.055 * cos(contact / ground * PI / 2) else 1.0 - val air = if (contact < ground) 0.0 else (hop - ground) / (1 - 2 * ground) - return BotPose( - gazeX = turn * 0.0025, - gazeY = -tilt * 0.0025, - roll = sin(time * rate(3.0, loop)) * 4.2, - lid = if (blink) shutLid else 1.0, - lift = 0.04 * sin(air * PI), - scaleX = 2 - squash, - scaleY = squash, - mouthOpen = 0.5 + 0.5 * sin(time * rate(18.0, loop)), - sway = -sin(air * 2 * PI) * 9 - sin(time * rate(3.0, loop)) * 4, - glow = 0.55 + 0.45 * sin(time * rate(20.0, loop)), - ) - } - - /** Breathes slowly with the head dropped a little and the mouth rising and falling. */ - fun sleeping(time: Double): BotPose { - val breath = sin(time * rate(4.0, sleepingLoop)) - return BotPose( - gazeY = 0.03, - roll = -5 + sin(time * rate(1.0, sleepingLoop)) * 1.5, - lid = shutLid, - scaleX = 1 - 0.02 * breath, - scaleY = 1 + 0.035 * breath, - mouthOpen = 0.5 + 0.5 * breath, - sway = 6 + breath * 3, - ) - } - - /** Blinks for 180 ms every 3 to 5 seconds, seeded; every third blink is a double. */ - fun blink(time: Double, hash: ULong): Double { - val (period, count) = snap(3 + (hash % 2001UL).toDouble() / 1000, idleLoop) - val cycle = floor(time / period) - val offset = time - cycle * period - val shut = 0.18 - val closed = { moment: Double -> 1 - (1 - shutLid) * sin(moment / shut * PI) } - if (offset < shut) return closed(offset) - val double = mix(hash, wrap(cycle, count)) % 3UL == 0UL - if (double && offset > 0.28 && offset < 0.28 + shut) return closed(offset - 0.28) - return 1.0 - } - - /** Holds a gaze for two to three and a half seconds, then darts to the next one. */ - fun glance(time: Double, hash: ULong): Pair { - val (hold, count) = snap(2 + ((hash shr 8) % 1500UL).toDouble() / 1000, idleLoop) - val step = floor(time / hold) - val into = (time - step * hold) / 0.14 - val ease = if (into >= 1) 1.0 else into * into * (3 - 2 * into) - val from = target(hash, wrap(step - 1, count)) - val next = target(hash, wrap(step, count)) - return Pair(from.first + (next.first - from.first) * ease, from.second + (next.second - from.second) * ease) - } - - private fun positive(value: Double, modulo: Double): Double { - val remainder = value % modulo - return if (remainder < 0) remainder + modulo else remainder - } - - private fun wrap(step: Double, count: Int): Long = positive(step, count.toDouble()).toLong() - - private fun target(hash: ULong, step: Long): Pair { - val value = mix(hash, step) - if (value % 3UL == 0UL) return Pair(0.0, 0.0) - return Pair( - ((value % 1000UL).toDouble() / 500 - 1) * 0.035, - (((value shr 20) % 1000UL).toDouble() / 500 - 1) * 0.022, - ) - } - - // Swift's `>>` binds tighter than `&*`, so the shift applies to the constant. - private fun mix(hash: ULong, step: Long): ULong { - var value = (hash xor step.toULong()) * 0x9E3779B97F4A7C15UL - value = value xor (value shr 31) - return value * (0xBF58476D1CE4E5B9UL shr 7) - } - } -} - -/** How much of each state a live avatar shows; state changes ease between two blends. */ -private data class BotBlend(val idle: Double, val working: Double, val sleeping: Double) { - constructor(state: BotState) : this( - idle = if (state == BotState.idle) 1.0 else 0.0, - working = if (state == BotState.working) 1.0 else 0.0, - sleeping = if (state == BotState.sleeping) 1.0 else 0.0, - ) - - fun mixed(target: BotBlend, amount: Double) = BotBlend( - idle + (target.idle - idle) * amount, - working + (target.working - working) * amount, - sleeping + (target.sleeping - sleeping) * amount, - ) - - fun pose(time: Double, hash: ULong): BotPose { - val local = time + (hash % 10_000UL).toDouble() / 1000 - if (sleeping == 1.0) return BotPose.sleeping(local) - val workTime = local * (0.92 + (hash % 17UL).toDouble() / 100) - if (working == 1.0) return BotPose.working(workTime) - val rest = if (idle > 0) BotPose.idle(time, hash) else BotPose.rest - if (idle == 1.0) return rest - val work = if (working > 0) BotPose.working(workTime) else BotPose.rest - val sleep = if (sleeping > 0) BotPose.sleeping(local) else BotPose.rest - return rest * idle + work * working + sleep * sleeping - } - - val expressions: List> - get() = listOf( - BotExpression.calm to idle, - BotExpression.focused to working, - BotExpression.asleep to sleeping, - ) +fun BotAvatarDefinition.geometry() = AvatarDefinition( + id = definition.id, + name = definition.name, + path = definition.body.path, + eyes = definition.eyes.run { AvatarEyes(x, y, spacing, scale) }, +) + +fun AvatarDefinition.withColors(color: String, eyeColor: String) = BotAvatarDefinition( + definition = BotAvatarDefinitionDefinition( + version = AVATAR_CONTRACT_VERSION.toDouble(), + id = id, + name = name, + body = BotAvatarDefinitionDefinitionBody(path), + eyes = eyes.run { BotAvatarDefinitionDefinitionEyes(x, y, spacing, scale) }, + ), + color = color, + eyeColor = eyeColor, +) + +/** The look for a bot the server hasn't given one yet, such as a new or unconfirmed bot. */ +fun placeholderAvatar(seed: String): BotAvatarDefinition { + val shapes = AvatarCatalog.examples + return shapes[Math.floorMod(seed.hashCode(), shapes.size)].withColors(DEFAULT_COLOR, DEFAULT_EYE_COLOR) } -private class BotMotion(state: BotState) { - private var from = BotBlend(state) - private var target = BotBlend(state) - private var since = Double.NEGATIVE_INFINITY - private var duration = 0.6 - var shown = state - private set +private val HEX_COLOR = Regex("#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})") - fun blend(time: Double): BotBlend { - val progress = ((time - since) / duration).coerceIn(0.0, 1.0) - return from.mixed(target, progress * progress * (3 - 2 * progress)) - } +fun isAvatarColor(value: String) = HEX_COLOR.matches(value) - fun move(state: BotState, time: Double) { - from = blend(time) - target = BotBlend(state) - since = time - duration = if (state == BotState.sleeping) 0.95 else 0.55 - shown = state - } +internal fun avatarColor(value: String): Color { + val digits = value.removePrefix("#") + val full = if (digits.length == 3) digits.flatMap { listOf(it, it) }.joinToString("") else digits + return Color(0xFF000000 or full.toLong(16)) } @Composable @@ -364,519 +66,26 @@ fun BotAvatarView( live: Boolean = false, modifier: Modifier = Modifier, ) { - BotAvatarView( - seed = agentAvatarSeed(agent), - size = size, - state = state, - live = live, - modifier = modifier, - ) + BotAvatarView(agent.avatar ?: placeholderAvatar(agent.id), size, state, live, modifier) } @Composable fun BotAvatarView( - seed: String, + avatar: BotAvatarDefinition, size: Dp, state: BotState = BotState.idle, live: Boolean = false, modifier: Modifier = Modifier, ) { - val look = remember(seed) { BotLook(seed) } - val context = LocalContext.current - val resolver = context.contentResolver - var animationsEnabled by remember(resolver) { - mutableStateOf(Settings.Global.getFloat(resolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f) > 0f) - } - DisposableEffect(resolver) { - val observer = object : ContentObserver(Handler(Looper.getMainLooper())) { - override fun onChange(selfChange: Boolean) { - animationsEnabled = Settings.Global.getFloat(resolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f) > 0f - } - } - resolver.registerContentObserver(Settings.Global.getUriFor(Settings.Global.ANIMATOR_DURATION_SCALE), false, observer) - observer.onChange(false) - onDispose { resolver.unregisterContentObserver(observer) } - } - val animating = live && animationsEnabled - // Seconds on the frame clock. Only the draw phase reads it, so frames redraw without recomposing. - var time by remember { mutableDoubleStateOf(0.0) } - val motion = remember(look) { BotMotion(state) } - SideEffect { if (motion.shown != state) motion.move(state, time) } - - if (animating) { - LaunchedEffect(Unit) { - while (true) withFrameNanos { time = it / 1_000_000_000.0 } - } - } - - Box(modifier = modifier.size(size), contentAlignment = Alignment.Center) { - Canvas(modifier = Modifier.size(size)) { - val side = this.size.minDimension - if (animating) { - val now = time - val blend = motion.blend(now) - BotPainter(look, side, density, blend.pose(now, look.hash), BotExpression.calm) - .paint(this, blend.expressions) - } else { - BotPainter(look, side, density, BotPose.rest, state.expression).paint(this, null) - } - } - - if (animating) { - SleepZs(size, { time + (look.hash % 1000UL).toDouble() / 1000 }, { motion.blend(time).sleeping }) - } - } -} - -private val BotState.expression: BotExpression - get() = when (this) { - BotState.idle -> BotExpression.calm - BotState.working -> BotExpression.focused - BotState.sleeping -> BotExpression.asleep - } - -/** Two Zs that rise from a sleeping bot, grow, and fade, one after the other. */ -@Composable -private fun SleepZs(size: Dp, time: () -> Double, sleeping: () -> Double) { - val fontSize = with(LocalDensity.current) { (size * 0.26f).toSp() } - for (index in 0 until 2) { - val phase = { (time() / 3 + index * 0.5).mod(1.0).toFloat() } - Text( - text = "z", - fontSize = fontSize, - fontWeight = FontWeight.Black, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier - .offset { - IntOffset( - (size * (0.34f + 0.12f * phase())).roundToPx(), - (-size * (0.22f + 0.32f * phase())).roundToPx(), - ) - } - .graphicsLayer { - val scale = (0.16f + 0.1f * phase()) / 0.26f - scaleX = scale - scaleY = scale - alpha = (sin(phase() * PI) * sleeping()).toFloat().coerceIn(0f, 1f) - }, - ) - } -} - -/** Where a shape's face and topper sit, as fractions of the body's frame, and how big the face is. */ -private class BotLayout(val face: Offset, val faceScale: Float, val top: Offset) { - companion object { - fun of(shape: BotShape) = when (shape) { - BotShape.circle, BotShape.squircle -> BotLayout(Offset(0.6f, 0.47f), 1f, Offset(0.5f, 0.08f)) - BotShape.hexagon -> BotLayout(Offset(0.58f, 0.49f), 0.95f, Offset(0.5f, 0.08f)) - BotShape.pill -> BotLayout(Offset(0.6f, 0.49f), 0.8f, Offset(0.5f, 0.23f)) - BotShape.triangle -> BotLayout(Offset(0.54f, 0.64f), 0.78f, Offset(0.5f, 0.08f)) - BotShape.cloud -> BotLayout(Offset(0.56f, 0.52f), 0.85f, Offset(0.53f, 0.12f)) - BotShape.drop -> BotLayout(Offset(0.54f, 0.62f), 0.9f, Offset(0.5f, 0.08f)) - } - } -} - -/** - * Paints one frame of a bot. Lengths are fractions of `side` in pixels; the body sits low enough in - * the square to leave room for its topper above and its shadow below. `density` converts - * apfelkern's point minimums. `fade` scales the face's opacity while expressions blend. - */ -private class BotPainter( - val look: BotLook, - val side: Float, - val density: Float, - val pose: BotPose, - val expression: BotExpression, - val fade: Float = 1f, -) { - private val frame = Rect(side * 0.04f, side * 0.1f, side * 0.96f, side * 1.02f) - private val layout = BotLayout.of(look.shape) - private val detailed = side >= 22 * density - private val faceCenter = point(layout.face) - private val unit = side * layout.faceScale - private val gazeX = pose.gazeX.toFloat() - private val gazeY = pose.gazeY.toFloat() - - private fun point(unit: Offset) = Offset(frame.left + unit.x * frame.width, frame.top + unit.y * frame.height) - - private val topperBase: Offset get() = point(Offset(layout.top.x, layout.top.y + 0.06f)) - - private fun eyeCenter(side: Float) = Offset( - faceCenter.x + unit * side * 0.0875f + side * gazeX, - faceCenter.y - unit * 0.045f + side * gazeY, - ) - - private val mouthCenter: Offset - get() = Offset( - faceCenter.x - unit * 0.012f + side * gazeX * 0.65f, - faceCenter.y + unit * 0.125f + side * gazeY * 0.65f, - ) - - private val ink: Color get() = look.inkColor.faded(fade) - - fun paint(scope: DrawScope, expressions: List>?) = with(scope) { - val body = bodyPath(look.shape, frame) - val bounds = body.getBounds() - paintShadow(bounds) - val base = Offset(bounds.center.x, bounds.bottom) - withTransform({ - translate(top = -side * pose.lift.toFloat()) - translate(base.x, base.y) - scale(pose.scaleX.toFloat(), pose.scaleY.toFloat(), Offset.Zero) - rotate(pose.roll.toFloat(), Offset.Zero) - translate(-base.x, -base.y) - }) { - paintTopper() - paintBody(body, bounds) - if (expressions == null) { - paintFace() - } else { - for ((face, opacity) in expressions) { - if (opacity > 0.001) { - BotPainter(look, side, density, pose, face, opacity.toFloat()).run { paintFace() } - } - } - } - } - } - - private fun DrawScope.paintShadow(bounds: Rect) { - val rise = min(1.0, pose.lift * 9).toFloat() - val width = bounds.width * 0.66f * pose.scaleX.toFloat() * (1 - 0.35f * rise) - val height = side * 0.055f * (1 - 0.3f * rise) - val grow = side * 0.012f - softOval( - Rect( - bounds.center.x - width / 2 - grow, - bounds.bottom - height * 0.45f - grow, - bounds.center.x + width / 2 + grow, - bounds.bottom + height * 0.55f + grow, - ), - Color.Black.copy(alpha = 0.2f * (1 - 0.55f * rise)), - ) - } - - private fun DrawScope.paintBody(body: Path, bounds: Rect) { - drawPath(body, look.color) - clipPath(body) { - paintDither(bounds) - if (detailed) paintCheeks() - } - drawPath(body, look.tint(-0.45).copy(alpha = 0.3f), style = Stroke(max(0.6f * density, side * 0.01f))) - } - - /** Light from the top left with a soft highlight, from -1 in shadow to 1 fully lit. */ - private fun light(point: Offset, bounds: Rect): Float { - val across = (point.x - bounds.left) / bounds.width - val down = (point.y - bounds.top) / bounds.height - val falloff = (0.42f - (0.4f * across + 0.6f * down)) * 1.9f - val spot = max(0f, 1 - hypot(across - 0.33f, down - 0.22f) / 0.26f) - return (falloff + 0.6f * spot).coerceIn(-1f, 1f) - } - - /** A 4×4 ordered dither between the body color and a lighter and a darker step of it. */ - private fun DrawScope.paintDither(bounds: Rect) { - // apfelkern's side / 44 cell, in whole pixels so the squares stay sharp. - val cell = max(1f, (side / 44).roundToInt().toFloat()) - val origin = Offset(floor(bounds.left), floor(bounds.top)) - val lit = Path() - val shade = Path() - for (row in 0 until ((bounds.bottom - origin.y) / cell + 1).toInt()) { - for (column in 0 until ((bounds.right - origin.x) / cell + 1).toInt()) { - val square = Rect(Offset(origin.x + column * cell, origin.y + row * cell), Size(cell, cell)) - val value = light(square.center, bounds) - val threshold = (bayer[row % 4][column % 4] + 0.5f) / 16 - if (value > threshold) { - lit.addRect(square) - } else if (-value > threshold) { - shade.addRect(square) - } - } - } - drawPath(lit, look.tint(0.3)) - drawPath(shade, look.tint(-0.24)) - } - - private fun DrawScope.paintCheeks() { - val glow = if (expression == BotExpression.delighted) 0.22f else 0.12f - for (side in listOf(-1f, 1f)) { - val center = Offset( - faceCenter.x + unit * (side * 0.175f + gazeX * 0.5f / layout.faceScale - 0.01f), - faceCenter.y + unit * 0.085f + side * gazeY * 0.5f, - ) - softOval( - Rect(center.x - unit * 0.045f, center.y - unit * 0.025f, center.x + unit * 0.045f, center.y + unit * 0.025f), - look.blushColor.faded(glow), - ) - } - } - - // Face - - private fun DrawScope.paintFace() { - for (side in listOf(-1f, 1f)) { - if (expression == BotExpression.asleep) paintClosedEye(eyeCenter(side)) else paintEye(eyeCenter(side)) - } - paintMouth() - } - - private fun DrawScope.paintEye(center: Offset) { - val width = unit * 0.068f - val height = max(width * 0.55f, unit * 0.145f * pose.lid.toFloat()) - withTransform({ - translate(center.x, center.y) - rotate(-8f, Offset.Zero) - }) { - drawRoundRect(ink, Offset(-width / 2, -height / 2), Size(width, height), CornerRadius(min(width, height) / 2)) - if (detailed && pose.lid > 0.6) { - val spark = width * 0.25f - drawOval(Color.White.copy(alpha = 0.5f * fade), Offset(-width * 0.28f, -height * 0.36f), Size(spark, spark)) - } - } - } - - private fun DrawScope.paintClosedEye(center: Offset) { - val half = unit * 0.05f - val lid = Path().apply { - moveTo(center.x - half, center.y + unit * 0.02f) - quadraticTo(center.x, center.y + unit * 0.065f, center.x + half, center.y + unit * 0.005f) - } - drawPath(lid, ink, style = Stroke(unit * 0.034f, cap = StrokeCap.Round)) - } - - private fun DrawScope.paintMouth() { - val center = mouthCenter - val line = Stroke(max(0.8f * density, unit * 0.026f), cap = StrokeCap.Round, join = StrokeJoin.Round) - val open = pose.mouthOpen.toFloat() - when (expression) { - BotExpression.asleep -> drawPath(oval(center, unit * 0.034f, unit * (0.022f + 0.016f * open)), ink) - BotExpression.focused -> drawPath(oval(center, unit * 0.046f, unit * (0.03f + 0.022f * open)), ink) - BotExpression.delighted -> paintGrin(center, unit * 0.105f, unit * 0.035f) - BotExpression.calm -> when (look.mouth) { - BotMouth.smile -> drawPath(smile(center, unit * 0.1f, unit * 0.025f), ink, style = line) - BotMouth.tiny -> drawPath(smile(center, unit * 0.06f, unit * 0.015f), ink, style = line) - BotMouth.grin -> paintGrin(center, unit * 0.09f, unit * 0.025f) - BotMouth.cat -> { - val cat = smile(Offset(center.x - unit * 0.026f, center.y), unit * 0.052f, unit * 0.03f) - cat.addPath(smile(Offset(center.x + unit * 0.026f, center.y), unit * 0.052f, unit * 0.03f)) - drawPath(cat, ink, style = line) - } - } - } - } - - private fun DrawScope.paintGrin(center: Offset, width: Float, depth: Float) { - val grin = Path().apply { - moveTo(center.x - width / 2, center.y - depth * 0.25f) - lineTo(center.x + width / 2, center.y - depth * 0.25f) - quadraticTo(center.x, center.y + depth * 1.6f, center.x - width / 2, center.y - depth * 0.25f) - close() - } - drawPath(grin, ink) - if (!detailed) return - clipPath(grin) { - drawPath( - oval(Offset(center.x, center.y + depth * 0.95f), width * 0.32f, depth * 0.45f), - Color(red = 1f, green = 0.45f, blue = 0.55f).faded(fade), - ) - } - } - - // Topper - - private fun DrawScope.paintTopper() { - if (look.topper == BotTopper.none) return - val base = topperBase - withTransform({ - translate(base.x, base.y) - rotate(pose.sway.toFloat(), Offset.Zero) - }) { - when (look.topper) { - BotTopper.none -> Unit - BotTopper.antenna -> paintAntenna() - BotTopper.sprout -> paintSprout() - BotTopper.tuft -> paintTuft() - } - } - } - - private fun DrawScope.paintAntenna() { - val stalk = quad(Offset.Zero, Offset(side * 0.025f, -side * 0.09f), Offset(0f, -side * 0.16f)) - drawPath(stalk, look.tint(-0.35), style = Stroke(side * 0.036f, cap = StrokeCap.Round)) - val glow = pose.glow.toFloat() - val tip = Offset(0f, -side * 0.16f) - val radius = side * 0.058f - if (glow > 0) { - val halo = radius + side * 0.07f * glow - softOval(Rect(tip, halo), look.tint(0.5).copy(alpha = glow * 0.6f)) - } - drawCircle(look.tint(0.4 + 0.3 * glow), radius, tip) - } - - private fun DrawScope.paintSprout() { - val green = if (look.hex == "#22c55e" || look.hex == "#14b8a6") { - Color(red = 0.75f, green = 0.95f, blue = 0.39f) - } else { - Color(red = 0.29f, green = 0.85f, blue = 0.5f) - } - val top = Offset(0f, -side * 0.1f) - val stem = quad(Offset.Zero, Offset(-side * 0.02f, -side * 0.05f), top) - drawPath(stem, green.mixed(Color.Black, 0.3), style = Stroke(side * 0.03f, cap = StrokeCap.Round)) - for (side in listOf(-1f, 1f)) { - withTransform({ - translate(top.x, top.y) - rotate(side * 50 - 8, Offset.Zero) - }) { - drawPath( - oval(Offset(0f, -side * 0.05f), side * 0.075f, side * 0.115f), - Brush.linearGradient( - listOf(green.mixed(Color.White, 0.25), green), - start = Offset(0f, -side * 0.1f), - end = Offset.Zero, - ), - ) - } - } - } - - private fun DrawScope.paintTuft() { - val color = look.tint(-0.3) - for ((angle, length) in listOf(-28f to 0.085f, 0f to 0.11f, 28f to 0.08f)) { - withTransform({ rotate(angle, Offset.Zero) }) { - val hair = quad(Offset.Zero, Offset(-side * 0.03f, -side * length * 0.6f), Offset(side * 0.035f, -side * length)) - drawPath(hair, color, style = Stroke(side * 0.034f, cap = StrokeCap.Round)) - } - } - } - - // Helpers - - /** A radial falloff filling `area`: full color in the middle, fading out at the edge. */ - private fun DrawScope.softOval(area: Rect, color: Color) { - withTransform({ - translate(area.center.x, area.center.y) - scale(area.width / 2, area.height / 2, Offset.Zero) - }) { - drawCircle( - Brush.radialGradient( - listOf(color, color.faded(0.65f), color.copy(alpha = 0f)), - center = Offset.Zero, - radius = 1f, - ), - radius = 1f, - center = Offset.Zero, - ) - } - } - - companion object { - private val bayer = listOf( - floatArrayOf(0f, 8f, 2f, 10f), - floatArrayOf(12f, 4f, 14f, 6f), - floatArrayOf(3f, 11f, 1f, 9f), - floatArrayOf(15f, 7f, 13f, 5f), - ) - } -} - -private fun quad(from: Offset, control: Offset, to: Offset) = Path().apply { - moveTo(from.x, from.y) - quadraticTo(control.x, control.y, to.x, to.y) -} - -private fun smile(center: Offset, width: Float, depth: Float) = - quad( - Offset(center.x - width / 2, center.y - depth / 2), - Offset(center.x, center.y + depth * 1.1f), - Offset(center.x + width / 2, center.y - depth / 2), + val geometry = remember(avatar.definition) { avatar.geometry() } + BotAvatar( + definition = geometry, + modifier = modifier.size(size).alpha(if (state == BotState.sleeping) 0.45f else 1f), + color = avatarColor(avatar.color), + eyeColor = avatarColor(avatar.eyeColor), + mood = if (state == BotState.working) AvatarMood.THINKING else AvatarMood.IDLE, + followPointer = live, + still = !live || state == BotState.sleeping, + label = "", ) - -private fun oval(center: Offset, width: Float, height: Float) = Path().apply { - addOval(Rect(center.x - width / 2, center.y - height / 2, center.x + width / 2, center.y + height / 2)) -} - -/** The body outline in `rect`, as apfelkern's `BotBody` draws it. */ -private fun bodyPath(shape: BotShape, rect: Rect): Path { - val dx = rect.width * 0.08f - val dy = rect.height * 0.08f - val inset = Rect(rect.left + dx, rect.top + dy, rect.right - dx, rect.bottom - dy) - val path = Path() - when (shape) { - BotShape.circle -> { - path.addOval(inset) - } - BotShape.squircle -> { - val r = rect.width * 0.28f - path.addRoundRect(RoundRect(inset, CornerRadius(r, r))) - } - BotShape.pill -> { - val h = rect.height * 0.54f - val top = rect.center.y - rect.height * 0.27f - val pill = Rect(inset.left, top, inset.right, top + h) - path.addRoundRect(RoundRect(pill, CornerRadius(h / 2f, h / 2f))) - } - BotShape.triangle -> { - path.moveTo(rect.center.x, inset.top) - path.lineTo(inset.right, inset.bottom) - path.lineTo(inset.left, inset.bottom) - path.close() - } - BotShape.hexagon -> { - path.moveTo(rect.center.x, inset.top) - path.lineTo(inset.right, rect.top + rect.height * 0.3f) - path.lineTo(inset.right, rect.top + rect.height * 0.7f) - path.lineTo(rect.center.x, inset.bottom) - path.lineTo(inset.left, rect.top + rect.height * 0.7f) - path.lineTo(inset.left, rect.top + rect.height * 0.3f) - path.close() - } - BotShape.cloud -> { - // Three puffs merged into one outline, so strokes and shading never show the seams. - val puffs = listOf( - floatArrayOf(0.08f, 0.38f, 0.48f, 0.48f), - floatArrayOf(0.28f, 0.12f, 0.5f, 0.64f), - floatArrayOf(0.55f, 0.35f, 0.38f, 0.45f), - ).map { (left, top, width, height) -> - Path().apply { - addOval( - Rect( - Offset(rect.left + rect.width * left, rect.top + rect.height * top), - Size(rect.width * width, rect.height * height), - ), - ) - } - } - return puffs.drop(1).fold(puffs[0]) { union, puff -> Path.combine(PathOperation.Union, union, puff) } - } - BotShape.drop -> { - path.moveTo(rect.center.x, inset.top) - path.cubicTo( - rect.center.x + rect.width * 0.22f, - rect.top + rect.height * 0.2f, - inset.right, - rect.top + rect.height * 0.42f, - inset.right, - rect.top + rect.height * 0.62f, - ) - path.cubicTo( - inset.right, - inset.bottom, - inset.left, - inset.bottom, - inset.left, - rect.top + rect.height * 0.62f, - ) - path.cubicTo( - inset.left, - rect.top + rect.height * 0.42f, - rect.center.x - rect.width * 0.22f, - rect.top + rect.height * 0.2f, - rect.center.x, - inset.top, - ) - path.close() - } - } - return path } diff --git a/app/src/main/java/dev/crumble/android/ui/BotDesktopScreen.kt b/app/src/main/java/dev/crumble/android/ui/BotDesktopScreen.kt new file mode 100644 index 0000000..0f28662 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/BotDesktopScreen.kt @@ -0,0 +1,311 @@ +package dev.crumble.android.ui + +import android.annotation.SuppressLint +import android.graphics.Color as AndroidColor +import android.view.ViewGroup +import android.webkit.RenderProcessGoneDetail +import android.webkit.WebChromeClient +import android.webkit.WebResourceError +import android.webkit.WebResourceRequest +import android.webkit.WebResourceResponse +import android.webkit.WebView +import android.webkit.WebViewClient +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.aspectRatio +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.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.Send +import androidx.compose.material.icons.filled.Bedtime +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.FilterChip +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +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.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.viewinterop.AndroidView +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.BotDesktop +import dev.crumble.android.model.DESKTOP_BOT +import dev.crumble.android.model.DESKTOP_OWNER +import dev.crumble.android.model.DesktopKey +import dev.crumble.android.model.DesktopLink +import dev.crumble.android.model.DesktopPress +import dev.crumble.android.model.desktopKeyScript +import dev.crumble.android.model.desktopPresses +import dev.crumble.android.model.press + +private const val DISCONNECTED_TITLE = "Bot desktop (disconnected)" + +@Composable +fun BotDesktopDialog(model: AppModel, desktop: BotDesktop) { + val bot = model.agents.firstOrNull { it.id == desktop.agentID } + var view by remember { mutableStateOf(null) } + JobDialog( + onClose = { model.closeBotDesktop() }, + title = { + Column { + Text( + text = bot?.let { "${it.name}'s desktop" } ?: "Bot desktop", + style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.SemiBold), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + desktop.control?.let { + Text( + text = if (desktop.owner) "You have control" else "The bot has control", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + }, + actions = { DesktopControls(model, desktop) }, + ) { padding -> + Column(modifier = Modifier.fillMaxSize().padding(padding).imePadding()) { + if (desktop.takeError.isNotEmpty()) { + Text( + text = desktop.takeError, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) + } + Box(modifier = Modifier.fillMaxWidth().weight(1f).background(Color.Black)) { + ViewerPane(model, desktop.viewer) { view = it } + } + if (desktop.owner) DesktopKeyboard(view) + } + } +} + +@Composable +private fun DesktopControls(model: AppModel, desktop: BotDesktop) { + if (desktop.taking != null) { + CircularProgressIndicator(modifier = Modifier.padding(horizontal = 8.dp).size(20.dp), strokeWidth = 2.dp) + } + IconButton(onClick = { model.reconnectDesktopViewer() }, enabled = !desktop.viewer.connecting) { + Icon(Icons.Default.Refresh, contentDescription = "Reconnect") + } + val enabled = desktop.control != null && desktop.taking == null + if (desktop.owner) { + OutlinedButton(onClick = { model.setDesktopHolder(DESKTOP_BOT) }, enabled = enabled) { Text("Hand back") } + } else { + Button(onClick = { model.setDesktopHolder(DESKTOP_OWNER) }, enabled = enabled) { Text("Take control") } + } +} + +@Composable +private fun ViewerPane(model: AppModel, viewer: DesktopLink, onView: (WebView?) -> Unit) { + when { + viewer.url != null -> DesktopPage(viewer.url, Modifier.fillMaxSize(), model::desktopViewerLost, onView) + viewer.connecting -> Row( + modifier = Modifier.fillMaxSize(), + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally), + verticalAlignment = Alignment.CenterVertically, + ) { + CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp, color = Color.White) + Text("Connecting", style = MaterialTheme.typography.bodySmall, color = Color.White) + } + viewer.error.isNotEmpty() -> Surface( + color = MaterialTheme.colorScheme.errorContainer, + shape = RoundedCornerShape(12.dp), + modifier = Modifier.padding(16.dp).fillMaxWidth(), + ) { + Column(modifier = Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text("Can't show the bot desktop", style = MaterialTheme.typography.titleSmall) + Text(viewer.error, style = MaterialTheme.typography.bodySmall) + } + } + } +} + +/** noVNC draws on a canvas, so soft keyboard text comes from a native field and reaches the canvas as key events. */ +@Composable +private fun DesktopKeyboard(view: WebView?) { + var text by remember { mutableStateOf("") } + var ctrl by remember { mutableStateOf(false) } + fun send(presses: List, onSent: () -> Unit = {}) { + view?.evaluateJavascript(desktopKeyScript(presses, ctrl)) { result -> + if (result == "true") { + ctrl = false + onSent() + } + } + } + fun sendText() { + if (text.isNotEmpty()) send(desktopPresses(text)) { text = "" } + } + Column( + modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Row( + modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), + horizontalArrangement = Arrangement.spacedBy(6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + FilterChip(selected = ctrl, onClick = { ctrl = !ctrl }, label = { Text("Ctrl") }) + for (key in DesktopKey.entries) { + OutlinedButton(onClick = { send(listOf(key.press())) }, enabled = view != null) { Text(key.label) } + } + } + Row(verticalAlignment = Alignment.CenterVertically) { + OutlinedTextField( + value = text, + onValueChange = { text = it }, + placeholder = { Text("Type on the desktop") }, + singleLine = true, + keyboardOptions = KeyboardOptions(autoCorrectEnabled = false, imeAction = ImeAction.Send), + keyboardActions = KeyboardActions(onSend = { sendText() }), + modifier = Modifier.weight(1f), + ) + IconButton(onClick = { sendText() }, enabled = view != null && text.isNotEmpty()) { + Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send to the desktop") + } + } + Text( + text = "The bot's desktop job waits while you have control. Hand back when you're done.", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + text = "Tap to click, touch and hold to right-click, and drag two fingers to scroll.", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} + +/** Shows the bot's machine state and a live view, which opens the full desktop. */ +@Composable +fun DesktopPreviewSection(model: AppModel, agentID: String) { + DisposableEffect(agentID) { + model.watchDesktopPreview(agentID) + onDispose { model.stopDesktopPreview() } + } + val preview = model.desktopPreview?.takeIf { it.agentID == agentID } ?: return + Column(modifier = Modifier.padding(horizontal = 16.dp).padding(top = 12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + GroupLabel("Desktop") + val tile = Modifier.fillMaxWidth().aspectRatio(16f / 9f).background(Color.Black, RoundedCornerShape(12.dp)) + when { + preview.running == null -> Box(tile, contentAlignment = Alignment.Center) { + CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp, color = Color.White) + } + !preview.awake -> Column( + modifier = tile.clickable { model.wakeDesktop() }, + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterVertically), + ) { + Icon(Icons.Default.Bedtime, contentDescription = null, tint = Color.White.copy(alpha = 0.6f)) + Text("Sleeping", style = MaterialTheme.typography.bodySmall, color = Color.White.copy(alpha = 0.6f)) + Text("Tap to wake", style = MaterialTheme.typography.labelSmall, color = Color.White.copy(alpha = 0.4f)) + } + else -> Box(tile) { + val url = preview.viewer.url + if (url != null) DesktopPage(url, Modifier.fillMaxSize(), model::desktopViewerLost) + if (preview.viewer.connecting) { + CircularProgressIndicator(modifier = Modifier.align(Alignment.Center).size(20.dp), strokeWidth = 2.dp, color = Color.White) + } + if (preview.viewer.error.isNotEmpty()) { + Text( + text = preview.viewer.error, + style = MaterialTheme.typography.labelSmall, + color = Color.White.copy(alpha = 0.6f), + textAlign = TextAlign.Center, + modifier = Modifier.align(Alignment.Center).padding(12.dp), + ) + } + // Sits over the page, whose touches would otherwise reach the desktop while the owner holds control. + Box(Modifier.matchParentSize().clickable(onClickLabel = "Open the bot desktop") { model.openBotDesktop(agentID) }) + } + } + } +} + +// The viewer is the server's own noVNC page and needs scripts. It gets no JavaScript interfaces and no file access. +@SuppressLint("SetJavaScriptEnabled") +@Composable +private fun DesktopPage(url: String, modifier: Modifier, onLost: (String) -> Unit, onView: (WebView?) -> Unit = {}) { + val lost by rememberUpdatedState(onLost) + val attach by rememberUpdatedState(onView) + // A new link needs a new page: reloading would spend a link that already ran. + key(url) { + AndroidView( + modifier = modifier, + factory = { context -> + WebView(context).apply { + layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) + setBackgroundColor(AndroidColor.BLACK) + settings.javaScriptEnabled = true + settings.allowFileAccess = false + settings.allowContentAccess = false + webViewClient = object : WebViewClient() { + override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean = + request.url.toString() != url + + override fun onReceivedHttpError(view: WebView, request: WebResourceRequest, errorResponse: WebResourceResponse) { + if (request.isForMainFrame) lost(url) + } + + override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) { + if (request.isForMainFrame) lost(url) + } + + // Unhandled, a dead renderer takes the whole app down. + override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean { + lost(url) + return true + } + } + webChromeClient = object : WebChromeClient() { + // The page's only signal that its connection ended. + override fun onReceivedTitle(view: WebView, title: String?) { + if (title == DISCONNECTED_TITLE) lost(url) + } + } + attach(this) + loadUrl(url) + } + }, + onRelease = { + attach(null) + it.destroy() + }, + ) + } +} diff --git a/app/src/main/java/dev/crumble/android/ui/BotDetailsDialog.kt b/app/src/main/java/dev/crumble/android/ui/BotDetailsDialog.kt new file mode 100644 index 0000000..eb4fab2 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/BotDetailsDialog.kt @@ -0,0 +1,116 @@ +package dev.crumble.android.ui + +import androidx.compose.foundation.layout.Arrangement +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.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Switch +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.Shape +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.Route +import dev.crumble.android.model.Schedule +import dev.crumble.android.model.automationTiming +import dev.crumble.android.model.automationsOf +import dev.crumble.android.model.nilIfEmpty + +@Composable +fun BotDetailsDialog(model: AppModel, bot: Agent) { + val onClose = { model.showingBotDetails = false } + JobDialog( + onClose = onClose, + title = {}, + actions = { + IconButton( + onClick = { + onClose() + model.openEditor(bot.id) + }, + ) { + Icon(Icons.Default.Edit, contentDescription = "Edit bot") + } + }, + ) { padding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(padding) + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + Column( + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + BotAvatarView(agent = bot, size = 84.dp, state = model.botState(bot), live = true) + Text(bot.name, style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.SemiBold)) + Text( + text = bot.description?.nilIfEmpty ?: if (bot.enabled) "Ready" else "Paused", + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + } + if ("desktop" in bot.tools.orEmpty()) DesktopPreviewSection(model, bot.id) + AutomationsSection(model, bot) + } + } +} + +@Composable +private fun AutomationsSection(model: AppModel, bot: Agent) { + val automations = automationsOf(bot.id, model.schedules) + Column( + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 16.dp), + verticalArrangement = Arrangement.spacedBy(ROW_GAP), + ) { + GroupLabel("Automations") + when { + model.schedulesLoaded -> GroupedRows { + for (schedule in automations) row { shape -> AutomationRow(model, schedule, shape) } + if (automations.isEmpty()) note("No automations yet") + } + model.schedulesError.isNotEmpty() -> SheetErrorBanner(model.schedulesError) + else -> CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp) + } + } +} + +@Composable +private fun AutomationRow(model: AppModel, schedule: Schedule, shape: Shape) { + GroupedItem( + shape = shape, + leading = { IconTile(routeIcon(Route.Tasks), Tone.Lavender) }, + trailing = { + Switch( + checked = schedule.enabled, + enabled = !model.schedulePending(schedule.id), + onCheckedChange = { model.toggleSchedule(schedule.id) }, + modifier = Modifier.semantics { contentDescription = "Run ${schedule.name}" }, + ) + }, + ) { + RowTitle(schedule.name, maxLines = 1) + RowSubtitle(automationTiming(schedule, model.eventSources)) + } +} diff --git a/app/src/main/java/dev/crumble/android/ui/ChangeHistory.kt b/app/src/main/java/dev/crumble/android/ui/ChangeHistory.kt new file mode 100644 index 0000000..06c9960 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/ChangeHistory.kt @@ -0,0 +1,178 @@ +package dev.crumble.android.ui + +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.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.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.History +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.FilterChip +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +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.Shape +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.unit.dp +import dev.crumble.android.generated.LearnedChange +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.CrumbleJson +import dev.crumble.android.model.DiffLine +import dev.crumble.android.model.SKILLS_ALL +import dev.crumble.android.model.SKILLS_SHARED +import dev.crumble.android.model.changeLabel +import dev.crumble.android.model.diff +import dev.crumble.android.model.revertPrompt +import kotlinx.serialization.json.JsonObject + +private val ADDED = Color(0xFF16A34A) + +/** What happened and to what, such as "Kev's review changed a skill · Triage". */ +private fun changeText(change: LearnedChange, botName: String?): String = + changeLabel(CrumbleJson.encodeToJsonElement(LearnedChange.serializer(), change) as JsonObject, botName) + +@Composable +fun DiffView(lines: List) { + Column( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(8.dp)) + .background(sheetColor) + .padding(vertical = 8.dp), + ) { + for (line in lines) { + val color = when (line.kind) { + '-' -> MaterialTheme.colorScheme.error + '+' -> ADDED + else -> MaterialTheme.colorScheme.onSurfaceVariant + } + val tint = if (line.kind == ' ') Color.Transparent else color.copy(alpha = 0.1f) + Text( + text = "${line.kind} ${line.text}", + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + color = color, + modifier = Modifier.fillMaxWidth().background(tint).padding(horizontal = 10.dp), + ) + } + } +} + +@Composable +fun ChangeDiff(change: LearnedChange) { + val lines = remember(change.id) { change.diff() } + DiffView(lines) +} + +/** Reverts a change after confirming; the server records the revert as a change of its own. */ +@Composable +fun RevertChangeButton(model: AppModel, change: LearnedChange) { + var confirming by remember(change.id) { mutableStateOf(false) } + Box(contentAlignment = Alignment.CenterStart) { + TextButton(enabled = "change:${change.id}" !in model.pendingMutations, onClick = { confirming = true }) { Text("Revert") } + } + if (confirming) { + ConfirmDialog( + title = "Revert this change?", + text = revertPrompt(change), + confirmLabel = "Revert", + onConfirm = { model.revertChange(change) }, + onDismiss = { confirming = false }, + destructive = false, + ) + } +} + +@Composable +private fun ChangeRow(model: AppModel, change: LearnedChange, shape: Shape) { + var expanded by remember(change.id) { mutableStateOf(false) } + val bot = model.agents.firstOrNull { it.id == change.agentId } + GroupedItem( + shape = shape, + onClick = { expanded = !expanded }, + clickBelow = true, + leading = { if (bot != null) BotAvatarView(bot, size = 44.dp) else IconTile(Icons.Default.History, Tone.Lavender) }, + below = if (expanded) { + { + ChangeDiff(change) + RevertChangeButton(model, change) + } + } else { + null + }, + ) { + RowTitle(changeText(change, bot?.name)) + } +} + +/** Skill and memory changes, newest first. */ +@Composable +fun ChangeHistoryDialog(model: AppModel) { + var scope by remember { mutableStateOf(SKILLS_ALL) } + val shown = model.changes.filter { change -> + scope == SKILLS_ALL || scope == (change.agentId ?: SKILLS_SHARED) + } + JobDialog(onClose = { model.closeChanges() }, title = { Text("Changes") }) { padding -> + LazyColumn( + modifier = Modifier.fillMaxSize().padding(padding), + contentPadding = PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(ROW_GAP), + ) { + item { + Column(modifier = Modifier.padding(bottom = 8.dp)) { + SheetErrorBanner(model.errorText) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) { + FilterChip(scope == SKILLS_ALL, { scope = SKILLS_ALL }, { Text("All") }) + FilterChip(scope == SKILLS_SHARED, { scope = SKILLS_SHARED }, { Text("Shared") }) + for (bot in model.agents) { + FilterChip(scope == bot.id, { scope = bot.id }, { Text(bot.name) }) + } + } + } + } + if (model.changesError.isNotEmpty()) { + item { Text(model.changesError, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) } + } + if (!model.changesLoading && model.changesError.isEmpty() && shown.isEmpty()) { + item { Text("Skill and memory changes will appear here.", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } + } + itemsIndexed(shown, key = { _, change -> change.id }) { index, change -> + ChangeRow(model, change, groupedShape(index, shown.size)) + } + if (model.changesLoading) { + item { + Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { + CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp) + } + } + } else if (model.changesHasMore) { + item { + Box(modifier = Modifier.padding(top = 8.dp)) { + OutlinedButton(onClick = { model.loadMoreChanges() }) { Text("Show older changes") } + } + } + } + } + } +} diff --git a/app/src/main/java/dev/crumble/android/ui/ChatScreen.kt b/app/src/main/java/dev/crumble/android/ui/ChatScreen.kt index 5f5f80e..7aba295 100644 --- a/app/src/main/java/dev/crumble/android/ui/ChatScreen.kt +++ b/app/src/main/java/dev/crumble/android/ui/ChatScreen.kt @@ -1,6 +1,7 @@ package dev.crumble.android.ui import android.graphics.BitmapFactory +import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedVisibility @@ -17,11 +18,13 @@ import androidx.compose.foundation.layout.IntrinsicSize 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.fillMaxHeight 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.navigationBars import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width @@ -37,13 +40,17 @@ import androidx.compose.material.icons.automirrored.filled.Reply import androidx.compose.material.icons.automirrored.filled.Send import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Cancel +import androidx.compose.material.icons.filled.ChevronRight import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.Description import androidx.compose.material.icons.filled.ExpandLess import androidx.compose.material.icons.filled.ExpandMore import androidx.compose.material.icons.filled.Group +import androidx.compose.material.icons.filled.Key import androidx.compose.material.icons.filled.Stop +import androidx.compose.material.icons.outlined.AddCircleOutline +import androidx.compose.material.icons.outlined.Image import androidx.compose.material3.AssistChip import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.DropdownMenu @@ -58,26 +65,38 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Surface import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults -import androidx.compose.material3.TextButton 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.setValue +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.draw.drawBehind +import androidx.compose.ui.draw.rotate +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign @@ -90,13 +109,31 @@ import dev.crumble.android.model.MentionCompletion import dev.crumble.android.model.Message import dev.crumble.android.model.MessageDeliveryState import dev.crumble.android.model.PendingAttachment +import dev.crumble.android.model.Route +import dev.crumble.android.model.Sources +import dev.crumble.android.model.SplitReply +import dev.crumble.android.model.botReactions +import dev.crumble.android.model.displayOf +import dev.crumble.android.model.isDesktopScreenshot +import dev.crumble.android.model.isNotice +import dev.crumble.android.model.isWebLink +import dev.crumble.android.model.jobOf import dev.crumble.android.model.loadAttachment +import dev.crumble.android.model.mentionableBots import dev.crumble.android.model.messageLabel import dev.crumble.android.model.nilIfEmpty +import dev.crumble.android.model.noticeTitle import dev.crumble.android.model.preview -import androidx.compose.runtime.snapshotFlow -import kotlinx.coroutines.flow.distinctUntilChanged +import dev.crumble.android.model.siteOf +import dev.crumble.android.model.sourcesOf +import dev.crumble.android.model.splitSources +import java.util.UUID +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext @Composable fun ChatView( @@ -107,6 +144,8 @@ fun ChatView( val rows = remember(model.messages, model.snapshot, model.hasMore) { ChatRow.rows(messages = model.messages, snapshot = model.snapshot, hasMore = model.hasMore) } + val sources = remember(model.messages) { sourcesOf(model.messages) } + val reactions = remember(model.messages) { botReactions(model.messages) } // Keep each agent's scroll position isolated. Reverse layout means the // newest row is index 0 and is naturally anchored at the bottom. val listState = remember(agent.id) { LazyListState() } @@ -153,7 +192,7 @@ fun ChatView( verticalArrangement = Arrangement.spacedBy(10.dp, Alignment.Bottom), ) { items(rows.asReversed(), key = { it.id }) { row -> - ChatRowView(model = model, agent = agent, row = row) + ChatRowView(model = model, agent = agent, row = row, sources = sources, reactions = reactions) } } } @@ -208,35 +247,19 @@ fun ChatRowView( model: AppModel, agent: Agent, row: ChatRow, + sources: Map = emptyMap(), + reactions: Map> = emptyMap(), ) { when (row) { - is ChatRow.Older -> { - Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { - if (model.loadingOlder) { - CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp) - } else { - TextButton(onClick = { model.loadOlder() }) { - Text("Load Earlier Messages") - } - } - } - } - is ChatRow.Time -> { - Box( - modifier = Modifier - .fillMaxWidth() - .padding(top = 6.dp), - contentAlignment = Alignment.Center, - ) { - Text( - text = row.label, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } + is ChatRow.Older -> OlderRow(loading = model.loadingOlder, onLoad = { model.loadOlder() }) + is ChatRow.Time -> TimeRow(row.label) is ChatRow.MessageRow -> { - MessageView(model = model, message = row.message) + MessageView( + model = model, + message = row.message, + sources = sources[row.message.id], + reactions = reactions[row.message.entryId].orEmpty(), + ) } is ChatRow.Partial -> { Row(modifier = Modifier.fillMaxWidth()) { @@ -286,7 +309,7 @@ fun ChatRowView( style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error, ) - OutlinedButton(onClick = { model.showingSettings = true }) { + OutlinedButton(onClick = { model.navigate(Route.Providers) }) { Text("Provider Settings…") } } @@ -295,23 +318,70 @@ fun ChatRowView( } } +@Composable +internal fun OlderRow(loading: Boolean, onLoad: () -> Unit) { + Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { + if (loading) { + CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp) + } else { + TextButton(onClick = onLoad) { + Text("Load Earlier Messages") + } + } + } +} + +@Composable +internal fun TimeRow(label: String) { + Box( + modifier = Modifier + .fillMaxWidth() + .padding(top = 6.dp), + contentAlignment = Alignment.Center, + ) { + Text( + text = label, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} + @OptIn(ExperimentalFoundationApi::class) @Composable fun MessageView( model: AppModel, message: Message, + sources: Sources? = null, + reactions: List = emptyList(), ) { val replyable = !message.entryId.isNullOrEmpty() && (message.role == "user" || message.role == "assistant") - val owner = message.origin == null || message.origin.kind == "owner" var menuExpanded by remember { mutableStateOf(false) } val clipboard = LocalClipboardManager.current + if (isNotice(message)) { + NoticeRow(model, message) + return + } when (message.role) { "event" -> { - if (message.kind == "bot-message") { - BotMessageView(message = message) - } else { - EventView(model = model, message = message) + when { + message.heldAction != null -> HeldActionCard(model, message.heldAction, message.text) + message.jobQuestion != null -> JobQuestionCard(model, message.jobQuestion, message.text) + message.kind == "bot-message" -> BotMessageView(message = message) + else -> EventView(model = model, message = message) + } + } + "toolResult" -> { + val job = jobOf(message) + val display = remember(message.toolDetails) { displayOf(message) } + when { + display != null -> DisplayCardView(display) + isDesktopScreenshot(message) -> DesktopScreenshotCard(model, message) + message.botRequest != null -> BotRequestCard(model, message.botRequest) + message.credentialRequest != null -> CredentialRequestCard(model, message.credentialRequest) + message.loginRequest != null -> LoginRequestCard(model, message.loginRequest) + job != null -> JobCard(model, job) } } "user" -> { @@ -325,29 +395,12 @@ fun MessageView( horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(4.dp), ) { - if (!owner) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(4.dp), - modifier = Modifier.padding(horizontal = 6.dp), - ) { - if (message.origin?.kind == "bot") { - Icon( - imageVector = Icons.Default.Group, - contentDescription = null, - modifier = Modifier.size(14.dp), - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - Text( - text = messageLabel(message), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - ReplyQuote(model = model, message = message) - SentAttachments(model = model, message = message) + ReplyQuote(message = message, transcript = model.messages) + SentAttachments( + message = message, + imageBytes = { model.attachmentImageBytes(message, it) }, + loadImage = { entryID, index -> model.loadAttachmentImage(entryID = entryID, index = index) }, + ) if (message.text.isEmpty() && message.attachments.orEmpty().isNotEmpty() && replyable) { ReplyButton(onClick = { model.replyTo = message }) } @@ -361,7 +414,7 @@ fun MessageView( } Box { ChatBubble( - owner = owner, + owner = true, modifier = Modifier .widthIn(max = 310.dp) .combinedClickable( @@ -391,33 +444,8 @@ fun MessageView( } } } - if (message.deliveryState != MessageDeliveryState.confirmed) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp), - ) { - if (message.deliveryState == MessageDeliveryState.sending) { - CircularProgressIndicator(modifier = Modifier.size(12.dp), strokeWidth = 1.5.dp) - Text( - text = "Sending…", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } else { - Text( - text = "Not sent", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.error, - ) - Text( - text = "Retry", - style = MaterialTheme.typography.labelSmall.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.primary, - modifier = Modifier.clickable { model.retryMessage(message) }, - ) - } - } - } + Reactions(reactions) + DeliveryStatus(message = message, onRetry = { model.retryMessage(message) }) } } } @@ -437,7 +465,7 @@ fun MessageView( onLongClick = { menuExpanded = true }, ), ) { - MarkdownText(text = message.text) + ReplyContent(message.text, sources) } MessageContextMenu( expanded = menuExpanded, @@ -461,7 +489,63 @@ fun MessageView( } @Composable -private fun ReplyButton(onClick: () -> Unit) { +internal fun DeliveryStatus(message: Message, onRetry: () -> Unit) { + if (message.deliveryState == MessageDeliveryState.confirmed) return + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + if (message.deliveryState == MessageDeliveryState.sending) { + CircularProgressIndicator(modifier = Modifier.size(12.dp), strokeWidth = 1.5.dp) + Text( + text = "Sending…", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } else { + Text( + text = "Not sent", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.error, + ) + Text( + text = "Retry", + style = MaterialTheme.typography.labelSmall.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.clickable(onClick = onRetry), + ) + } + } +} + +/** A bot's Markdown; citations of pages its turn read show as chips after it. */ +@Composable +internal fun ReplyContent(text: String, sources: Sources?) { + val reply = remember(text, sources) { + if (sources != null) splitSources(text, sources) else SplitReply(text, emptyList()) + } + val uriHandler = LocalUriHandler.current + Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + MarkdownText(text = reply.text) + if (reply.chips.isNotEmpty()) { + Row( + modifier = Modifier.horizontalScroll(rememberScrollState()), + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + for (chip in reply.chips) { + AssistChip( + onClick = { if (isWebLink(chip.href)) runCatching { uriHandler.openUri(chip.href) } }, + label = { Text(siteOf(chip.href), maxLines = 1) }, + modifier = Modifier.semantics { contentDescription = chip.title.ifEmpty { chip.href } }, + ) + } + } + } + } +} + +@Composable +internal fun ReplyButton(onClick: () -> Unit) { IconButton( onClick = onClick, modifier = Modifier.size(32.dp), @@ -476,7 +560,7 @@ private fun ReplyButton(onClick: () -> Unit) { } @Composable -private fun MessageContextMenu( +internal fun MessageContextMenu( expanded: Boolean, onDismiss: () -> Unit, replyable: Boolean, @@ -572,6 +656,55 @@ fun BotMessageView(message: Message) { } } +/** A message from an automation, a credential, or another bot, collapsed like the website's. */ +@Composable +fun NoticeRow(model: AppModel, message: Message) { + val open = message.id in model.expanded + val tint = MaterialTheme.colorScheme.onSurfaceVariant + Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { model.expanded = if (open) model.expanded - message.id else model.expanded + message.id } + .semantics { stateDescription = if (open) "Expanded" else "Collapsed" } + .padding(vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterHorizontally), + ) { + Icon( + imageVector = Icons.Default.ChevronRight, + contentDescription = null, + modifier = Modifier.size(14.dp).rotate(if (open) 90f else 0f), + tint = tint, + ) + noticeIcon(message)?.let { icon -> + Icon(icon, contentDescription = null, modifier = Modifier.size(14.dp), tint = tint) + } + Text( + text = noticeTitle(message).orEmpty(), + style = MaterialTheme.typography.labelSmall, + color = tint, + modifier = Modifier.weight(1f, fill = false), + ) + } + AnimatedVisibility(visible = open) { + Surface( + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f), + shape = RoundedCornerShape(12.dp), + modifier = Modifier.fillMaxWidth(), + ) { + MarkdownText(text = message.text, modifier = Modifier.padding(12.dp)) + } + } + } +} + +private fun noticeIcon(message: Message): ImageVector? = when (message.origin?.kind) { + "credential" -> Icons.Default.Key + "bot" -> Icons.Default.Group + else -> null +} + @Composable fun EventView( model: AppModel, @@ -615,13 +748,13 @@ fun EventView( @Composable fun ReplyQuote( - model: AppModel, message: Message, + transcript: List, ) { val reply = message.replyTo if (!reply.isNullOrEmpty()) { val quoted = message.replyPreview?.nilIfEmpty - ?: model.messages.firstOrNull { it.entryId == reply }?.text + ?: transcript.firstOrNull { it.entryId == reply }?.text ?: "" if (quoted.isNotEmpty()) { Surface( @@ -657,51 +790,93 @@ fun ReplyQuote( fun Composer( model: AppModel, agent: Agent, +) { + val permittedBots = remember(model.agents, agent) { mentionableBots(agent, model.agents) } + val reply = model.replyTo + ComposerBar( + draft = model.draft, + onDraftChange = { model.draft = it }, + attachments = model.attachments, + // Files load in the background; a late one must not land in another bot's draft. + onAddAttachment = { if (model.selectedAgentID == agent.id) model.addAttachment(it) }, + onRemoveAttachment = model::removeAttachment, + onAttachmentError = { model.errorText = it }, + replyTitle = reply?.let { "Replying to ${messageLabel(it)}" }, + replyPreview = reply?.text.orEmpty(), + onCancelReply = { model.replyTo = null }, + mentionable = permittedBots, + enabled = agent.enabled, + placeholder = if (agent.enabled) "Message ${agent.name}" else "${agent.name} is paused. Enable it in its profile.", + running = model.snapshot?.isRunning == true, + onStop = { model.abortChat() }, + onSend = { model.sendMessage() }, + ) +} + +/** The message field with its reply preview, mention suggestions, attachments, and send and stop buttons. */ +private val COMPOSER_HEIGHT = 56.dp +private val IMAGE_PICKER_TYPES = arrayOf("image/*") + +@Composable +fun ComposerBar( + draft: String, + onDraftChange: (String) -> Unit, + attachments: List, + onAddAttachment: (PendingAttachment) -> Unit, + onRemoveAttachment: (UUID) -> Unit, + onAttachmentError: (String) -> Unit, + replyTitle: String?, + replyPreview: String, + onCancelReply: () -> Unit, + mentionable: List, + enabled: Boolean, + placeholder: String, + running: Boolean, + onStop: () -> Unit, + onSend: () -> Unit, + stopEnabled: Boolean = true, ) { val context = LocalContext.current - val running = model.snapshot?.isRunning == true + val focusManager = LocalFocusManager.current + val attachmentScope = rememberCoroutineScope() + var attachPanelOpen by remember { mutableStateOf(false) } + BackHandler(enabled = attachPanelOpen) { attachPanelOpen = false } val filePicker = rememberLauncherForActivityResult( contract = ActivityResultContracts.OpenMultipleDocuments(), ) { uris -> - for (uri in uris) { - try { - val attachment = loadAttachment(context.contentResolver, uri) - model.addAttachment(attachment) - } catch (e: Exception) { - model.errorText = e.message ?: "Failed to attach file." + val resolver = context.contentResolver + val attach = onAddAttachment + val fail = onAttachmentError + attachmentScope.launch { + for (uri in uris) { + try { + attach(withContext(Dispatchers.IO) { loadAttachment(resolver, uri) }) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + fail(e.message ?: "Failed to attach file.") + } } } } - val permittedBots = remember(model.agents, agent) { - model.agents.filter { - it.enabled && - it.id != agent.id && - (agent.delegates ?: emptyList()).contains(it.id) && - (agent.tools ?: emptyList()).contains("delegate") - } - } - val completion = remember(model.draft, permittedBots) { + val completion = remember(draft, mentionable) { MentionCompletion.find( - text = model.draft, - selectionStart = model.draft.length, - selectionEnd = model.draft.length, - bots = permittedBots, + text = draft, + selectionStart = draft.length, + selectionEnd = draft.length, + bots = mentionable, ) } - Surface( - tonalElevation = 2.dp, - modifier = Modifier.fillMaxWidth(), - ) { + Column(modifier = Modifier.fillMaxWidth()) { Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = 12.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp), ) { - val reply = model.replyTo - if (reply != null) { + if (replyTitle != null) { Surface( color = MaterialTheme.colorScheme.surfaceVariant, shape = RoundedCornerShape(12.dp), @@ -720,12 +895,12 @@ fun Composer( ) Column(modifier = Modifier.weight(1f)) { Text( - text = "Replying to ${messageLabel(reply)}", + text = replyTitle, style = MaterialTheme.typography.labelSmall.copy(fontWeight = FontWeight.Bold), color = MaterialTheme.colorScheme.primary, ) Text( - text = preview(reply.text), + text = preview(replyPreview), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, @@ -733,7 +908,7 @@ fun Composer( ) } IconButton( - onClick = { model.replyTo = null }, + onClick = onCancelReply, modifier = Modifier.size(28.dp), ) { Icon( @@ -756,7 +931,7 @@ fun Composer( for (bot in completion.bots) { AssistChip( onClick = { - model.draft = model.draft.replaceRange(completion.range, "@${bot.name} ") + onDraftChange(draft.replaceRange(completion.range, "@${bot.name} ")) }, label = { Text("@${bot.name}") }, leadingIcon = { @@ -767,17 +942,17 @@ fun Composer( } } - if (model.attachments.isNotEmpty()) { + if (attachments.isNotEmpty()) { Row( modifier = Modifier .fillMaxWidth() .horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { - for (file in model.attachments) { + for (file in attachments) { PendingAttachmentChip( file = file, - onRemove = { model.removeAttachment(file.id) }, + onRemove = { onRemoveAttachment(file.id) }, ) } } @@ -788,43 +963,56 @@ fun Composer( verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(8.dp), ) { - IconButton( - onClick = { - filePicker.launch(arrayOf("image/*", "text/*", "application/json", "application/xml")) - }, - enabled = agent.enabled, + Surface( + shape = RoundedCornerShape(COMPOSER_HEIGHT / 2), + color = MaterialTheme.colorScheme.surfaceContainerHigh, + modifier = Modifier.weight(1f).heightIn(min = COMPOSER_HEIGHT), ) { - Icon( - imageVector = Icons.Default.Add, - contentDescription = "Attach Files", - ) - } - - TextField( - value = model.draft, - onValueChange = { model.draft = it }, - modifier = Modifier.weight(1f), - enabled = agent.enabled, - placeholder = { - Text( - if (agent.enabled) "Message ${agent.name}" - else "${agent.name} is paused. Enable it in its profile.", + Row( + modifier = Modifier.padding(horizontal = 4.dp), + verticalAlignment = Alignment.Bottom, + ) { + IconButton( + onClick = { + focusManager.clearFocus() + attachPanelOpen = !attachPanelOpen + }, + enabled = enabled, + modifier = Modifier.padding(vertical = 4.dp), + ) { + Icon( + imageVector = if (attachPanelOpen) Icons.Default.Cancel else Icons.Outlined.AddCircleOutline, + contentDescription = if (attachPanelOpen) "Close Attachments" else "Attach", + ) + } + TextField( + value = draft, + onValueChange = onDraftChange, + modifier = Modifier + .weight(1f) + .onFocusChanged { if (it.isFocused) attachPanelOpen = false }, + enabled = enabled, + placeholder = { Text(placeholder) }, + maxLines = 6, + colors = TextFieldDefaults.colors( + unfocusedContainerColor = Color.Transparent, + focusedContainerColor = Color.Transparent, + disabledContainerColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent, + focusedIndicatorColor = Color.Transparent, + disabledIndicatorColor = Color.Transparent, + ), ) - }, - maxLines = 6, - shape = RoundedCornerShape(22.dp), - colors = TextFieldDefaults.colors( - unfocusedContainerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.72f), - focusedContainerColor = MaterialTheme.colorScheme.surfaceVariant, - disabledContainerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.42f), - unfocusedIndicatorColor = Color.Transparent, - focusedIndicatorColor = Color.Transparent, - disabledIndicatorColor = Color.Transparent, - ), - ) + } + } + val canSend = enabled && (draft.isNotBlank() || attachments.isNotEmpty()) if (running) { - FilledTonalIconButton(onClick = { model.abortChat() }) { + FilledTonalIconButton( + onClick = onStop, + enabled = stopEnabled, + modifier = Modifier.size(COMPOSER_HEIGHT), + ) { Icon( imageVector = Icons.Default.Stop, contentDescription = "Stop", @@ -832,19 +1020,78 @@ fun Composer( ) } } - - val canSend = agent.enabled && (model.draft.isNotBlank() || model.attachments.isNotEmpty()) - FilledIconButton( - onClick = { model.sendMessage() }, - enabled = canSend, - ) { - Icon( - imageVector = Icons.AutoMirrored.Filled.Send, - contentDescription = "Send", - ) + if (!running || canSend) { + FilledIconButton( + onClick = onSend, + enabled = canSend, + modifier = Modifier.size(COMPOSER_HEIGHT), + ) { + Icon( + imageVector = Icons.AutoMirrored.Filled.Send, + contentDescription = "Send", + ) + } } } } + if (attachPanelOpen) { + AttachPanel( + onGallery = { + attachPanelOpen = false + filePicker.launch(IMAGE_PICKER_TYPES) + }, + ) + } + } +} + +/** Stands in for the keyboard under the composer. */ +@Composable +private fun AttachPanel(onGallery: () -> Unit) { + val color = pageColor + val gestureBar = WindowInsets.navigationBars.getBottom(LocalDensity.current).toFloat() + Surface( + color = color, + shape = RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp), + modifier = Modifier + .fillMaxWidth() + // The chat pads its content above the gesture bar; the panel still runs to the screen's edge. + .drawBehind { + drawRect(color, topLeft = Offset(0f, size.height), size = Size(size.width, gestureBar)) + }, + ) { + Row(modifier = Modifier.padding(horizontal = 12.dp, vertical = 24.dp)) { + AttachTile( + label = "Gallery", + icon = Icons.Outlined.Image, + onClick = onGallery, + modifier = Modifier.weight(1f), + ) + Spacer(modifier = Modifier.weight(3f)) + } + } +} + +@Composable +private fun AttachTile(label: String, icon: ImageVector, onClick: () -> Unit, modifier: Modifier = Modifier) { + Column( + modifier = modifier + .clip(RoundedCornerShape(16.dp)) + .clickable(onClick = onClick) + .padding(vertical = 4.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Surface( + shape = CircleShape, + color = sheetColor, + modifier = Modifier.size(width = 72.dp, height = 56.dp), + ) { + Box(contentAlignment = Alignment.Center) { + Icon(imageVector = icon, contentDescription = null) + } + } + Text(text = label, style = MaterialTheme.typography.labelLarge) } } @@ -887,8 +1134,9 @@ fun PendingAttachmentChip( @Composable fun SentAttachments( - model: AppModel, message: Message, + imageBytes: (Int) -> ByteArray?, + loadImage: suspend (String, Int) -> Unit, ) { val files = message.attachments ?: emptyList() if (files.isNotEmpty()) { @@ -898,14 +1146,14 @@ fun SentAttachments( ) { files.forEachIndexed { index, file -> if (file.isImage) { - val bytes = model.attachmentImageBytes(message, index) + val bytes = imageBytes(index) val bitmap = remember(bytes) { bytes?.let { BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() } } LaunchedEffect(message.entryId, index) { val entryID = message.entryId if (!entryID.isNullOrEmpty()) { - model.loadAttachmentImage(entryID = entryID, index = index) + loadImage(entryID, index) } } if (bitmap != null) { @@ -973,14 +1221,14 @@ fun ChatBubble( modifier: Modifier = Modifier, content: @Composable () -> Unit, ) { - val bg = if (owner) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceVariant - val fg = if (owner) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant + val bg = if (owner) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceContainerHigh + val fg = if (owner) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface Surface( color = bg, - shape = RoundedCornerShape(18.dp), + shape = RoundedCornerShape(20.dp), modifier = modifier, ) { - Box(modifier = Modifier.padding(horizontal = 14.dp, vertical = 9.dp)) { + Box(modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)) { CompositionLocalProvider(LocalContentColor provides fg) { content() } diff --git a/app/src/main/java/dev/crumble/android/ui/CommandPaletteScreen.kt b/app/src/main/java/dev/crumble/android/ui/CommandPaletteScreen.kt new file mode 100644 index 0000000..31875d4 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/CommandPaletteScreen.kt @@ -0,0 +1,162 @@ +package dev.crumble.android.ui + +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.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.systemBarsPadding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.DarkMode +import androidx.compose.material.icons.filled.Group +import androidx.compose.material.icons.filled.LightMode +import androidx.compose.material.icons.filled.PhoneAndroid +import androidx.compose.material.icons.filled.Tune +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextField +import androidx.compose.material3.TextFieldDefaults +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.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.PaletteAction +import dev.crumble.android.model.PaletteItem +import dev.crumble.android.model.ThemeChoice +import dev.crumble.android.model.paletteSections +import dev.crumble.android.model.searchPalette + +private const val PLACEHOLDER = "Search chats, pages, and settings" + +@Composable +fun CommandPaletteDialog(model: AppModel) { + var query by rememberSaveable { mutableStateOf("") } + val sections = remember(query, model.agents, model.groupChats, model.isAdmin, model.theme) { + val all = paletteSections(model.agents, model.groupChats, model.isAdmin == true, model.theme) + searchPalette(all, query) + } + val focus = remember { FocusRequester() } + + Dialog( + onDismissRequest = { model.showingPalette = false }, + properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false), + ) { + Surface(color = pageColor, modifier = Modifier.fillMaxSize()) { + Column(modifier = Modifier.systemBarsPadding().imePadding()) { + TextField( + value = query, + onValueChange = { query = it }, + placeholder = { Text(PLACEHOLDER) }, + singleLine = true, + shape = CircleShape, + leadingIcon = { + IconButton(onClick = { model.showingPalette = false }) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Close") + } + }, + trailingIcon = { + if (query.isNotEmpty()) { + IconButton(onClick = { query = "" }) { + Icon(Icons.Default.Close, contentDescription = "Clear") + } + } + }, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Go), + keyboardActions = KeyboardActions( + onGo = { sections.firstOrNull()?.items?.firstOrNull()?.let { model.runPalette(it.action) } }, + ), + colors = TextFieldDefaults.colors( + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent, + focusedContainerColor = sheetColor, + unfocusedContainerColor = sheetColor, + ), + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp) + .focusRequester(focus), + ) + LaunchedEffect(Unit) { focus.requestFocus() } + if (sections.isEmpty()) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text( + text = "No results", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } else { + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 16.dp), + verticalArrangement = Arrangement.spacedBy(ROW_GAP), + ) { + sections.forEachIndexed { sectionIndex, section -> + item(key = section.heading) { + Box(modifier = Modifier.padding(top = 8.dp)) { GroupLabel(section.heading) } + } + itemsIndexed(section.items) { index, item -> + PaletteRow(model, item, groupedShape(index, section.items.size), Tone.entries[sectionIndex % Tone.entries.size]) + } + } + } + } + } + } + } +} + +@Composable +private fun PaletteRow(model: AppModel, item: PaletteItem, shape: Shape, tone: Tone) { + val bot = (item.action as? PaletteAction.OpenBot)?.let { action -> model.agents.firstOrNull { it.id == action.id } } + GroupedRow( + title = item.title, + subtitle = item.note, + shape = shape, + onClick = { model.runPalette(item.action) }, + leading = { + if (bot != null) BotAvatarView(agent = bot, size = 44.dp) else IconTile(paletteIcon(item.action), tone) + }, + ) +} + +private fun paletteIcon(action: PaletteAction): ImageVector = when (action) { + is PaletteAction.OpenBot, is PaletteAction.OpenGroup -> Icons.Default.Group + PaletteAction.NewBot, PaletteAction.NewGroup -> Icons.Default.Add + is PaletteAction.OpenPage -> routeIcon(action.route) + is PaletteAction.SetTheme -> when (action.theme) { + ThemeChoice.System -> Icons.Default.PhoneAndroid + ThemeChoice.Light -> Icons.Default.LightMode + ThemeChoice.Dark -> Icons.Default.DarkMode + } +} diff --git a/app/src/main/java/dev/crumble/android/ui/ConnectionsScreen.kt b/app/src/main/java/dev/crumble/android/ui/ConnectionsScreen.kt new file mode 100644 index 0000000..72efb61 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/ConnectionsScreen.kt @@ -0,0 +1,1320 @@ +package dev.crumble.android.ui + +import android.annotation.SuppressLint +import android.content.ClipData +import android.graphics.Bitmap +import android.os.PersistableBundle +import android.view.ViewGroup +import android.webkit.WebResourceRequest +import android.webkit.WebView +import android.webkit.WebViewClient +import androidx.activity.compose.BackHandler +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.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +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.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.Link +import androidx.compose.material.icons.filled.Warning +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ExposedDropdownMenuAnchorType +import androidx.compose.material3.ExposedDropdownMenuBox +import androidx.compose.material3.ExposedDropdownMenuDefaults +import androidx.compose.material3.FilterChip +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +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.graphics.Shape +import androidx.compose.ui.platform.ClipEntry +import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.platform.LocalUriHandler +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import androidx.compose.ui.viewinterop.AndroidView +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import dev.crumble.android.generated.GitHubAccount +import dev.crumble.android.generated.GitHubApp +import dev.crumble.android.model.AddGitHubAccountForm +import dev.crumble.android.generated.AdminUser +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.ChoiceOption +import dev.crumble.android.model.CreateGitHubAppForm +import dev.crumble.android.model.GatewayAliasRow +import dev.crumble.android.model.GatewayChannelRow +import dev.crumble.android.model.GatewayForm +import dev.crumble.android.model.GitHubAccountForm +import dev.crumble.android.model.GitHubAppForm +import dev.crumble.android.model.GitHubFlow +import dev.crumble.android.model.InviteSheet +import dev.crumble.android.model.MessageGateway +import dev.crumble.android.model.PluginRow +import dev.crumble.android.model.PluginSecretForm +import dev.crumble.android.model.Route +import dev.crumble.android.model.SecretDraft +import dev.crumble.android.model.ServerSettingsForm +import dev.crumble.android.model.WEB_SEARCH_PROVIDERS +import dev.crumble.android.model.WorkspaceField +import dev.crumble.android.model.gatewayBotOptions +import dev.crumble.android.model.gatewayDeliveries +import dev.crumble.android.model.gatewayErrors +import dev.crumble.android.model.gatewayStatus +import dev.crumble.android.model.gatewayStatusLabel +import dev.crumble.android.model.githubAuthorizedURL +import dev.crumble.android.model.isGitHubReturn +import dev.crumble.android.model.isWebLink +import dev.crumble.android.model.judgeOptions +import dev.crumble.android.model.judgeStatus +import dev.crumble.android.model.judgeValue +import dev.crumble.android.model.pluginRows +import dev.crumble.android.model.relayStatusLabel +import dev.crumble.android.model.toggled +import dev.crumble.android.model.visionOptions +import dev.crumble.android.model.visionStatus +import dev.crumble.android.model.visionValue +import dev.crumble.android.model.workspaceHelp +import dev.crumble.android.model.dateOnly +import dev.crumble.android.model.outdatedWorkspaceRows +import dev.crumble.android.model.userRowTitle +import dev.crumble.android.model.workspaceRowTitle +import java.net.URLEncoder +import java.nio.charset.StandardCharsets + +@Composable +private fun ConnectionPage(content: @Composable ColumnScope.() -> Unit) { + Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 24.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + content = content, + ) +} + +@Composable +private fun ErrorLine(text: String) { + if (text.isNotEmpty()) Text(text, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) +} + +@Composable +private fun Spinner() = CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) + +@Composable +private fun StatusBadge(text: String, error: Boolean = false) { + Surface( + shape = MaterialTheme.shapes.small, + color = if (error) MaterialTheme.colorScheme.errorContainer else MaterialTheme.colorScheme.secondaryContainer, + ) { + Text( + text, + style = MaterialTheme.typography.labelSmall, + color = if (error) MaterialTheme.colorScheme.onErrorContainer else MaterialTheme.colorScheme.onSecondaryContainer, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp), + ) + } +} + +/** A setting inside a card; a list of settings uses SettingItem. */ +@Composable +private fun SettingRow( + title: String, + badge: @Composable () -> Unit = {}, + trailing: @Composable RowScope.() -> Unit = {}, +) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Row( + modifier = Modifier.weight(1f), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + RowTitle(title, modifier = Modifier.weight(1f, fill = false)) + badge() + } + trailing() + } +} + +@Composable +private fun SettingItem( + title: String, + shape: Shape, + leading: @Composable () -> Unit, + description: String = "", + descriptionIsError: Boolean = false, + badge: @Composable () -> Unit = {}, + trailing: @Composable RowScope.() -> Unit = {}, + below: (@Composable ColumnScope.() -> Unit)? = null, +) { + GroupedItem(shape = shape, leading = leading, trailing = trailing, below = below) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + RowTitle(title, modifier = Modifier.weight(1f, fill = false)) + badge() + } + if (description.isNotEmpty()) { + RowSubtitle(description, color = if (descriptionIsError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant) + } + } +} + +private fun GroupScope.error(text: String) { + if (text.isNotEmpty()) note(text, isError = true) +} + +private fun GroupScope.attention(title: String, text: String) { + row { shape -> + SettingItem( + title = title, + shape = shape, + leading = { IconTile(Icons.Default.Warning, Tone.Lavender) }, + description = text, + descriptionIsError = true, + ) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun ChoiceField( + label: String, + options: List, + value: String, + enabled: Boolean = true, + isError: Boolean = false, + onChoose: (String) -> Unit, +) { + var expanded by remember { mutableStateOf(false) } + ExposedDropdownMenuBox(expanded = expanded, onExpandedChange = { expanded = it && enabled }) { + OutlinedTextField( + value = options.firstOrNull { it.value == value }?.label.orEmpty(), + onValueChange = {}, + readOnly = true, + enabled = enabled, + isError = isError, + singleLine = true, + label = { Text(label) }, + trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) }, + modifier = Modifier + .menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable) + .fillMaxWidth(), + ) + ExposedDropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { + for (option in options) { + DropdownMenuItem( + text = { Text(option.label) }, + onClick = { + expanded = false + onChoose(option.value) + }, + ) + } + } + } +} + +@Composable +private fun ConfirmDelete(title: String, description: String, action: String, onConfirm: () -> Unit, onDismiss: () -> Unit) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title) }, + text = { Text(description) }, + confirmButton = { + TextButton( + onClick = { + onDismiss() + onConfirm() + }, + ) { + Text(action, color = MaterialTheme.colorScheme.error) + } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} + +// ClipDescription.EXTRA_IS_SENSITIVE as a literal: it arrived in API 33, and older versions read the same key. +private const val CLIP_IS_SENSITIVE = "android.content.extra.IS_SENSITIVE" + +/** Keeps the value out of clipboard previews and sync. */ +private fun sensitiveClip(label: String, value: String): ClipEntry { + val clip = ClipData.newPlainText(label, value) + clip.description.extras = PersistableBundle().apply { putBoolean(CLIP_IS_SENSITIVE, true) } + return ClipEntry(clip) +} + +@Composable +internal fun CopyField(label: String, value: String, sensitive: Boolean = false) { + val clipboard = LocalClipboardManager.current + OutlinedTextField( + value = value, + onValueChange = {}, + readOnly = true, + singleLine = true, + label = { Text(label) }, + textStyle = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace), + trailingIcon = { + IconButton( + onClick = { + if (sensitive) clipboard.setClip(sensitiveClip(label, value)) + else clipboard.setText(AnnotatedString(value)) + }, + ) { + Icon(Icons.Default.ContentCopy, contentDescription = "Copy") + } + }, + modifier = Modifier.fillMaxWidth(), + ) +} + +@Composable +private fun SimpleSheet( + title: String, + description: String = "", + error: String = "", + submitLabel: String, + ready: Boolean, + saving: Boolean, + onSubmit: () -> Unit, + onClose: () -> Unit, + content: @Composable ColumnScope.() -> Unit, +) { + AlertDialog( + onDismissRequest = onClose, + title = { Text(title) }, + text = { + Column(modifier = Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) { + if (description.isNotEmpty()) SecretNote(description) + SheetErrorBanner(error) + content() + } + }, + confirmButton = { + Button(enabled = ready && !saving, onClick = onSubmit) { + if (saving) Spinner() else Text(submitLabel) + } + }, + dismissButton = { TextButton(onClick = onClose) { Text("Cancel") } }, + ) +} + +// MARK: Plugin settings + +private fun GroupScope.pluginItems(model: AppModel, contributes: String? = null, pluginID: String? = null, secretKey: String? = null) { + error(model.pluginSettings.error) + for (plugin in pluginRows(model.pluginSettings.value, contributes, pluginID, secretKey)) { + row { shape -> PluginRowView(model, plugin, shape) } + } +} + +@Composable +private fun PluginRowView(model: AppModel, row: PluginRow, shape: Shape) { + val secret = row.setting.secret + val manager = model.passwordManagers.firstOrNull { it.id == secret.passwordManager } + val busy = "plugin:${row.pluginID}:${row.setting.key}" in model.pendingMutations + SettingItem( + title = row.setting.label + (manager?.let { " (${it.name})" } ?: ""), + shape = shape, + leading = { LetterTile(row.setting.label) }, + trailing = { + when { + busy -> Spinner() + secret.configured -> SecretOverflowMenu { close -> + DropdownMenuItem(text = { Text("Edit") }, onClick = { + close() + model.openPluginSetting(row) + }) + DropdownMenuItem(text = { Text("Remove") }, onClick = { + close() + model.removePluginSetting(row) + }) + } + else -> OutlinedButton(onClick = { model.openPluginSetting(row) }) { Text("Add") } + } + }, + ) +} + +@Composable +private fun PluginSecretDialog(model: AppModel, form: PluginSecretForm) { + SimpleSheet( + title = form.setting.label, + error = form.error, + submitLabel = "Save", + ready = form.secret.changed, + saving = form.saving, + onSubmit = { model.savePluginSetting() }, + onClose = { model.closePluginSetting() }, + ) { + SecretSourceField( + model = model, + label = "Value", + draft = form.secret, + onChange = { next -> model.pluginForm = model.pluginForm?.copy(secret = next) }, + valueDescription = "Stored encrypted and never shown again.", + ) + } +} + +// MARK: Web search, judge and vision models + +@Composable +fun WebSearchPanel(model: AppModel) { + ConnectionPage { + RowsSection(title = "Search provider", footer = "Bots use this unless their own settings choose another provider.") { + error(model.webSearch.error) + model.webSearch.value?.let { data -> + val description = if (data.defaultProvider == "exa" && !data.exaKeyConfigured) { + "Exa needs a key before bots can search with it." + } else { + model.webSearch.failure + } + row { shape -> + val busy = "web-search:default" in model.pendingMutations + SettingItem( + title = "Default", + shape = shape, + leading = { IconTile(routeIcon(Route.WebSearch), Tone.Lavender) }, + description = description, + descriptionIsError = model.webSearch.failure == description && description.isNotEmpty(), + below = { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) { + for (provider in WEB_SEARCH_PROVIDERS) { + FilterChip( + selected = data.defaultProvider == provider.value, + enabled = !busy, + onClick = { model.chooseWebSearchProvider(provider.value) }, + label = { Text(provider.label) }, + ) + } + } + }, + ) + } + pluginItems(model, contributes = "webSearchProviders") + } + } + } +} + +@Composable +private fun ModelPage( + section: String, + footer: String, + title: String, + readError: String, + failure: String, + status: String?, + options: List, + value: String?, + busy: Boolean, + onChoose: (String) -> Unit, +) { + ConnectionPage { + SectionCard(title = section, footer = footer) { + ErrorLine(readError) + if (value != null && status != null) { + ChoiceField(title, options, value, enabled = !busy, onChoose = onChoose) + if (failure.isNotEmpty()) ErrorLine(failure) else SecretNote(status) + } + } + } +} + +@Composable +fun JudgeModelPanel(model: AppModel) { + val data = model.judgeModel.value + ModelPage( + section = "Intent checks", + footer = "Before a desktop job clicks, types, or presses a key, this model checks whether the action is irreversible and whether you asked for it. Actions it can't clear wait for your approval in the bot's chat.", + title = "Judge model", + readError = model.judgeModel.error, + failure = model.judgeModel.failure, + status = data?.let(::judgeStatus), + options = data?.let(::judgeOptions).orEmpty(), + value = data?.let(::judgeValue), + busy = "judge:model" in model.pendingMutations, + onChoose = model::chooseJudgeModel, + ) +} + +@Composable +fun VisionModelPanel(model: AppModel) { + val data = model.visionModel.value + ModelPage( + section = "Images for text-only models", + footer = "When a bot's model can't read images, this model describes each image it gets, including any visible text, and the bot works from the description. The bot can also ask it questions about an image. Its tokens count toward the conversation's usage.", + title = "Vision model", + readError = model.visionModel.error, + failure = model.visionModel.failure, + status = data?.let(::visionStatus), + options = data?.let(::visionOptions).orEmpty(), + value = data?.let(::visionValue), + busy = "vision:model" in model.pendingMutations, + onChoose = model::chooseVisionModel, + ) +} + +// MARK: Event relay + +@Composable +fun EventRelayPanel(model: AppModel) { + ConnectionPage { + RowsSection( + title = "Relay", + footer = "A Doorstep relay receives webhooks for this account and forwards them to this server, so the server needs no public address.", + ) { + error(model.eventRelay.error) + model.eventRelay.value?.let { relay -> + val next = model.relayDraft.trim().ifEmpty { null } + row { shape -> + GroupCard(shape) { + SettingRow(title = "Relay URL", badge = { StatusBadge(relayStatusLabel(relay.status), relay.status == "error") }) + OutlinedTextField( + value = model.relayDraft, + onValueChange = { model.relayDraft = it }, + placeholder = { Text("https://relay.example.com") }, + singleLine = true, + enabled = !model.relaySaving, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri), + modifier = Modifier.fillMaxWidth(), + ) + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedButton(onClick = { model.saveRelay() }, enabled = !model.relaySaving && next != relay.url) { Text("Save") } + if (model.relaySaving) Spinner() + } + ErrorLine(model.eventRelay.failure) + } + } + relay.error?.let { attention("Relay needs attention", it) } + pluginItems(model, pluginID = "doorstep") + } + } + RowsSection( + title = "Event sources", + footer = "Each source is one webhook address. Automations that use a source run when an event arrives there.", + ) { + error(model.eventSourcesError) + if (model.eventSourcesLoaded && model.eventSources.isEmpty()) note("No event sources yet.") + for (source in model.eventSources) row { shape -> EventSourceRow(model, source, shape) } + add("Add source") { model.openEventSourceForm() } + } + } +} + +// MARK: Message gateways + +@Composable +private fun GatewayBadge(gateway: MessageGateway) { + StatusBadge(gatewayStatusLabel(gateway), gateway.config.enabled && gateway.status == "error") +} + +@Composable +fun MessageGatewaysPanel(model: AppModel) { + ConnectionPage { + ErrorLine(model.gateways.error) + model.gateways.value?.let { list -> + RowsSection(title = "Gateways", footer = "Message your bots from other chat apps.") { + if (list.isEmpty()) note("This server has no message gateways.") + for (gateway in list) { + row { shape -> + GroupedItem( + shape = shape, + onClick = { model.navigate(Route.MessageGateway(gateway.id)) }, + leading = { LetterTile(gateway.label) }, + trailing = { + GatewayBadge(gateway) + Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null) + }, + ) { + RowTitle(gateway.label) + } + } + } + } + } + } +} + +@Composable +fun MessageGatewayPanel(model: AppModel, id: String) { + BackHandler { model.navigate(Route.MessageGateways) } + val gateway = model.gateways.value?.firstOrNull { it.id == id } + val form = model.gatewayForm?.takeIf { it.gatewayID == id } + ConnectionPage { + ErrorLine(model.gateways.error) + if (model.gateways.value != null && gateway == null) { + SectionCard(title = "Not found") { SecretNote("This server has no gateway $id.") } + } + if (gateway != null && form != null) GatewayEditor(model, gateway, form) + } +} + +@Composable +private fun GatewayEditor(model: AppModel, gateway: MessageGateway, form: GatewayForm) { + val config = form.config() + val dirty = config != gateway.config + val errors = if (form.attempted) gatewayErrors(config, model.agents.map { it.id }.toSet()) else emptyMap() + val edit: ((GatewayForm) -> GatewayForm) -> Unit = { change -> + model.gatewayForm?.let { model.gatewayForm = change(it).copy(saved = false, error = "") } + } + + RowsSection(title = "Connection") { + val deliveries = gatewayDeliveries(gateway) + row { shape -> + SettingItem( + title = gateway.label + if (deliveries.isEmpty()) "" else " ($deliveries)", + shape = shape, + leading = { LetterTile(gateway.label) }, + badge = { GatewayBadge(gateway) }, + trailing = { Switch(checked = form.enabled, onCheckedChange = { on -> edit { it.copy(enabled = on) } }) }, + ) + } + gateway.error?.let { attention("Connection needs attention", it) } + pluginItems(model, contributes = "chatAdapters", secretKey = gateway.secretKey) + } + + SectionCard(title = "Bots", footer = "Start a message with @alias to pick a bot.") { + ChoiceField( + label = "Default bot", + options = gatewayBotOptions(model.agents, form.defaultBotId, optional = true), + value = form.defaultBotId.orEmpty(), + isError = "defaultBotId" in errors, + onChoose = { value -> edit { it.copy(defaultBotId = value.ifEmpty { null }) } }, + ) + ErrorLine(errors["defaultBotId"].orEmpty()) + form.aliases.forEachIndexed { index, alias -> AliasRow(model, form, alias, index, "aliases" in errors, edit) } + ErrorLine(errors["aliases"].orEmpty()) + TextButton(enabled = model.agents.isNotEmpty(), onClick = { edit { it.copy(aliases = it.aliases + GatewayAliasRow()) } }) { + Icon(Icons.Default.Add, contentDescription = null, modifier = Modifier.size(18.dp)) + Text("Alias") + } + } + + SectionCard(title = "Access") { + OutlinedTextField( + value = form.owner, + onValueChange = { text -> edit { it.copy(owner = text.take(200)) } }, + label = { Text("Owner ${gateway.label} user ID") }, + isError = "ownerId" in errors, + singleLine = true, + textStyle = MaterialTheme.typography.bodyLarge.copy(fontFamily = FontFamily.Monospace), + modifier = Modifier.fillMaxWidth(), + ) + ErrorLine(errors["ownerId"].orEmpty()) + SettingRow(title = "Direct messages") { + Switch(checked = form.allowDirectMessages, onCheckedChange = { on -> edit { it.copy(allowDirectMessages = on) } }) + } + form.channels.forEachIndexed { index, channel -> ChannelRow(channel, index, edit) } + TextButton(onClick = { edit { it.copy(channels = it.channels + GatewayChannelRow()) } }) { + Icon(Icons.Default.Add, contentDescription = null, modifier = Modifier.size(18.dp)) + Text("Channel") + } + } + + ErrorLine(form.error) + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + gatewayStatus(dirty, form), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.weight(1f), + ) + TextButton(enabled = dirty && !form.saving, onClick = { model.resetGatewayForm() }) { Text("Reset") } + Button(enabled = dirty && !form.saving, onClick = { model.saveGateway() }) { Text("Save") } + } +} + +@Composable +private fun AliasRow( + model: AppModel, + form: GatewayForm, + alias: GatewayAliasRow, + index: Int, + invalid: Boolean, + edit: ((GatewayForm) -> GatewayForm) -> Unit, +) { + val update = { change: (GatewayAliasRow) -> GatewayAliasRow -> + edit { current -> current.copy(aliases = current.aliases.map { if (it.id == alias.id) change(it) else it }) } + } + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + OutlinedTextField( + value = alias.handle, + onValueChange = { text -> update { it.copy(handle = text.take(100)) } }, + label = { Text("Alias ${index + 1}") }, + placeholder = { Text("research") }, + isError = invalid, + singleLine = true, + modifier = Modifier.weight(1f), + ) + IconButton(onClick = { edit { current -> current.copy(aliases = current.aliases.filterNot { it.id == alias.id }) } }) { + Icon(Icons.Default.Delete, contentDescription = "Remove alias") + } + } + ChoiceField( + label = "Bot for alias ${index + 1}", + options = gatewayBotOptions(model.agents, alias.botId, optional = false), + value = alias.botId, + isError = invalid, + onChoose = { value -> update { it.copy(botId = value) } }, + ) + } +} + +@Composable +private fun ChannelRow(channel: GatewayChannelRow, index: Int, edit: ((GatewayForm) -> GatewayForm) -> Unit) { + Row(verticalAlignment = Alignment.CenterVertically) { + OutlinedTextField( + value = channel.value, + onValueChange = { text -> + edit { current -> current.copy(channels = current.channels.map { if (it.id == channel.id) it.copy(value = text.take(200)) else it }) } + }, + label = { Text("Channel ID ${index + 1}") }, + singleLine = true, + textStyle = MaterialTheme.typography.bodyLarge.copy(fontFamily = FontFamily.Monospace), + modifier = Modifier.weight(1f), + ) + IconButton(onClick = { edit { current -> current.copy(channels = current.channels.filterNot { it.id == channel.id }) } }) { + Icon(Icons.Default.Delete, contentDescription = "Remove channel") + } + } +} + +// MARK: Coding + +@Composable +fun CodingPanel(model: AppModel) { + ConnectionPage { + WorkspaceSection(model) + AppsSection(model) + AccountsSection(model) + } +} + +@Composable +private fun WorkspaceSection(model: AppModel) { + val capabilities = model.capabilities + val missing = capabilities?.let { workspaceHelp(it.coding, it.desktop) }.orEmpty() + val admin = model.isAdmin == true + if (!admin && missing.isEmpty()) return + RowsSection(title = "Workspaces") { + for (help in missing) note(help, fontFamily = FontFamily.Monospace) + error(model.serverSettings.error) + val settings = model.serverSettings.value + if (admin && settings != null) { + val busy = "server-settings:patch" in model.pendingMutations + for (field in WorkspaceField.entries) { + row { shape -> + SettingItem( + title = workspaceRowTitle(field, settings), + shape = shape, + leading = { IconTile(routeIcon(Route.Coding), Tone.Lavender) }, + trailing = { OutlinedButton(enabled = !busy, onClick = { model.openServerSettings(field) }) { Text("Edit") } }, + ) + } + } + } + if (admin) outdatedWorkspaces(model) + } +} + +private fun GroupScope.outdatedWorkspaces(model: AppModel) { + error(model.outdatedWorkspaces.error) + val rows = outdatedWorkspaceRows(model.outdatedWorkspaces.value.orEmpty(), model.agents, model.adminUsers.value.orEmpty()) + if (rows.isEmpty()) return + note("Running on an older image. Each workspace switches at its next idle stop, keeping its files.") + for (outdated in rows) { + row { shape -> SettingItem(title = outdated.bot, shape = shape, leading = { LetterTile(outdated.bot) }, description = outdated.owner) } + } +} + +// MARK: Users + +@Composable +fun UsersPanel(model: AppModel) { + ConnectionPage { + when (model.isAdmin) { + true -> { + UsersSection(model) + SignUpSection(model) + } + false -> SectionCard(title = "Users") { SecretNote("Only admins manage users.") } + null -> SectionCard(title = "Users") { + ErrorLine(model.adminUsers.error) + if (model.adminUsers.error.isEmpty()) Spinner() + } + } + } +} + +@Composable +private fun UsersSection(model: AppModel) { + RowsSection(title = "Users") { + add("Invite") { model.createInvite() } + error(model.adminUsers.error) + error(model.adminUsers.failure) + error(model.invites.error) + error(model.invites.failure) + if (model.adminUsers.value == null && model.adminUsers.error.isEmpty()) row { shape -> GroupCard(shape) { Spinner() } } + for (user in model.adminUsers.value.orEmpty()) { + row { shape -> UserRow(model, user, shape) } + } + for (invite in model.invites.value.orEmpty()) { + row { shape -> + SettingItem( + title = "Invite from ${dateOnly(invite.createdAt)}", + shape = shape, + leading = { IconTile(Icons.Default.Link, Tone.Lavender) }, + trailing = { OutlinedButton(onClick = { model.revokeInvite(invite) }) { Text("Revoke") } }, + ) + } + } + } +} + +@Composable +private fun UserRow(model: AppModel, user: AdminUser, shape: Shape) { + var removing by remember { mutableStateOf(false) } + val busy = "admin-user:${user.id}" in model.pendingMutations + SettingItem( + title = userRowTitle(user), + shape = shape, + leading = { LetterTile(user.name.ifEmpty { user.email }) }, + trailing = { + when { + busy -> Spinner() + model.accountID != null && user.id != model.accountID -> SecretOverflowMenu { close -> + val admin = user.role == "admin" + DropdownMenuItem(text = { Text(if (admin) "Make regular user" else "Make admin") }, onClick = { + close() + model.setUserRole(user, if (admin) "user" else "admin") + }) + DropdownMenuItem( + text = { Text("Remove account and data", color = MaterialTheme.colorScheme.error) }, + onClick = { + close() + removing = true + }, + ) + } + } + }, + ) + if (removing) { + ConfirmDelete( + title = "Remove account and data", + description = "This removes ${user.name.ifEmpty { user.email }}, their bots, and all their data. It can't be undone.", + action = "Remove", + onConfirm = { model.removeUser(user) }, + onDismiss = { removing = false }, + ) + } +} + +@Composable +private fun SignUpSection(model: AppModel) { + SectionCard(title = "Sign-up") { + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + ErrorLine(model.serverSettings.error) + ErrorLine(model.serverSettings.failure) + SettingRow(title = "Open sign-up") { + val settings = model.serverSettings.value + if (settings == null) { + if (model.serverSettings.error.isEmpty()) Spinner() + } else { + Switch( + checked = settings.signUpOpen, + enabled = "server-settings:patch" !in model.pendingMutations, + onCheckedChange = { model.setSignUpOpen(it) }, + ) + } + } + } + } +} + +@Composable +private fun InviteDialog(model: AppModel, sheet: InviteSheet) { + val failed = sheet.error.isNotEmpty() + SimpleSheet( + title = "Invite link", + description = "Anyone with this link can create one account. It's shown only now.", + error = sheet.error, + submitLabel = if (failed) "Try again" else "Done", + ready = true, + saving = sheet.url == null && !failed, + onSubmit = { if (failed) model.createInvite() else model.closeInviteSheet() }, + onClose = { model.closeInviteSheet() }, + ) { + sheet.url?.let { CopyField("Invite link", it, sensitive = true) } + } +} + +@Composable +private fun NumberField(label: String, value: String, onChange: (String) -> Unit) { + OutlinedTextField( + value = value, + onValueChange = onChange, + label = { Text(label) }, + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + modifier = Modifier.fillMaxWidth(), + ) +} + +@Composable +private fun ServerSettingsDialog(model: AppModel, form: ServerSettingsForm) { + val edit = { change: (ServerSettingsForm) -> ServerSettingsForm -> model.serverSettingsForm?.let { model.serverSettingsForm = change(it) } } + SimpleSheet( + title = form.field.title, + error = form.error, + submitLabel = "Save", + ready = form.patch() != null, + saving = false, + onSubmit = { model.saveServerSettings() }, + onClose = { model.serverSettingsForm = null }, + ) { + when (form.field) { + WorkspaceField.size -> { + NumberField("CPUs", form.cpus) { text -> edit { it.copy(cpus = text) } } + NumberField("Memory (GB)", form.memory) { text -> edit { it.copy(memory = text) } } + } + WorkspaceField.image -> OutlinedTextField( + value = form.image, + onValueChange = { text -> edit { it.copy(image = text) } }, + label = { Text("Image") }, + placeholder = { Text("ghcr.io/owner/image:tag") }, + singleLine = true, + textStyle = MaterialTheme.typography.bodyLarge.copy(fontFamily = FontFamily.Monospace), + modifier = Modifier.fillMaxWidth(), + ) + WorkspaceField.grace -> NumberField("Minutes", form.grace) { text -> edit { it.copy(grace = text) } } + } + } +} + +@Composable +private fun AppsSection(model: AppModel) { + RowsSection( + title = "GitHub Apps", + footer = "Each App is a GitHub identity in one account. Bots assigned to it push, commit, and open pull requests as it there.", + ) { + error(model.githubApps.error) + val apps = model.githubApps.value + if (apps?.isEmpty() == true) note("No GitHub Apps yet.") + apps?.forEach { app -> row { shape -> AppRow(model, app, shape) } } + add("New GitHub App") { model.openCreateApp() } + } +} + +@Composable +private fun AppRow(model: AppModel, app: GitHubApp, shape: Shape) { + var confirming by remember { mutableStateOf(false) } + val busy = "github-app:${app.id}" in model.pendingMutations + val detail = (app.user?.let { "as $it, " } ?: "") + "used by ${app.botIds.size}" + SettingItem( + title = "${app.login} ($detail)", + shape = shape, + leading = { LetterTile(app.login) }, + trailing = { + IconButton(onClick = { model.openGitHubApp(app) }) { Icon(Icons.Default.Edit, contentDescription = "Edit") } + if (busy) { + Spinner() + } else { + IconButton(onClick = { confirming = true }) { Icon(Icons.Default.Delete, contentDescription = "Remove") } + } + }, + below = if (app.installed) { + null + } else { + { OutlinedButton(onClick = { model.installGitHubApp(app) }) { Text("Install") } } + }, + ) + if (confirming) { + ConfirmDelete( + title = "Remove ${app.login}?", + description = "Its bots lose access to GitHub through it. The App stays on GitHub; delete it in its settings there.", + action = "Remove", + onConfirm = { model.deleteGitHubApp(app) }, + onDismiss = { confirming = false }, + ) + } +} + +@Composable +private fun CreateAppDialog(model: AppModel, form: CreateGitHubAppForm) { + SimpleSheet( + title = "New GitHub App", + description = "GitHub opens to create a private App on one account. Bots you assign to it commit and open pull requests as it in that account's repositories.", + error = form.error, + submitLabel = "Create on GitHub", + ready = form.ready, + saving = form.saving, + onSubmit = { model.createGitHubApp() }, + onClose = { model.closeCreateApp() }, + ) { + OutlinedTextField( + value = form.name, + onValueChange = { text -> model.createAppForm = model.createAppForm?.copy(name = text.take(34)) }, + label = { Text("Name") }, + placeholder = { Text("frien-bot") }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + SecretNote("Unique across GitHub. Commits show it as name[bot].") + OutlinedTextField( + value = form.organization, + onValueChange = { text -> model.createAppForm = model.createAppForm?.copy(organization = text) }, + label = { Text("Organization") }, + placeholder = { Text("Your account") }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + SecretNote("The App can only work in its owner's repositories. Create one App per account.") + } +} + +@Composable +private fun BotsField(model: AppModel, botIDs: List, description: String, onChange: (List) -> Unit) { + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text("Bots", style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.SemiBold)) + SecretNote(description) + BotPills(model.agents, { it.id in botIDs }, { bot, on -> onChange(toggled(botIDs, bot.id, on)) }) + } +} + +@Composable +private fun GitHubLink(url: String) { + val uriHandler = LocalUriHandler.current + TextButton(onClick = { if (isWebLink(url)) runCatching { uriHandler.openUri(url) } }) { Text("Open on GitHub") } +} + +@Composable +private fun AppDialog(model: AppModel, form: GitHubAppForm, app: GitHubApp) { + SimpleSheet( + title = app.login, + error = form.error, + submitLabel = "Save", + ready = true, + saving = false, + onSubmit = { model.saveGitHubAppBots() }, + onClose = { model.closeGitHubApp() }, + ) { + GitHubLink(app.htmlUrl) + InstallationField(model, form, app) + ActAsField(model, form, app) + BotsField( + model, + form.botIDs, + "They get GH_TOKEN once the App is installed. A bot uses one App per GitHub account; its first App is its default for commits and gh pr.", + ) { next -> model.githubAppForm = model.githubAppForm?.copy(botIDs = next) } + } +} + +@Composable +private fun InstallationField(model: AppModel, form: GitHubAppForm, app: GitHubApp) { + Text("Installation", style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.SemiBold)) + Text( + if (app.installed) "Installed on ${app.account}" else "Not installed" + (app.account?.let { " on $it" } ?: ""), + style = MaterialTheme.typography.bodyMedium, + ) + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + if (!app.installed) OutlinedButton(onClick = { model.installGitHubApp(app) }) { Text("Install") } + OutlinedButton(enabled = !form.checking, onClick = { model.checkGitHubApp(app.id) }) { + if (form.checking) Spinner() else Text("Check") + } + } + ErrorLine(form.checkError) +} + +/** Whether the App's bots act as its `slug[bot]` user or as the owner, signed in through the App. */ +@Composable +private fun ActAsField(model: AppModel, form: GitHubAppForm, app: GitHubApp) { + Text("Bots act as", style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.SemiBold)) + val user = app.user + if (user != null) { + Text("$user, marked as ${app.login}", style = MaterialTheme.typography.bodyMedium) + OutlinedButton(enabled = !form.signingOut, onClick = { model.signOutOfGitHubApp(app.id) }) { + if (form.signingOut) Spinner() else Text("Sign out") + } + SecretNote("GitHub shows their pull requests and comments with the App's badge, and their commits list ${app.login} as co-author.") + } else { + Text(app.login, style = MaterialTheme.typography.bodyMedium) + if (app.clientSecret.configured) { + OutlinedButton(enabled = !form.signingIn, onClick = { model.signInToGitHubApp(app) }) { + if (form.signingIn) Spinner() else Text("Sign in as me") + } + } + model.client?.baseURL?.let { CopyField("Callback URL", githubAuthorizedURL(it)) } + if (!app.clientSecret.configured) ClientSecretFields(model, form) + } + ErrorLine(form.signInError) +} + +@Composable +private fun ClientSecretFields(model: AppModel, form: GitHubAppForm) { + SecretSourceField( + model = model, + label = "Client secret", + draft = form.clientSecret, + onChange = { next -> model.githubAppForm = model.githubAppForm?.copy(clientSecret = next) }, + valueDescription = "To let bots act as you, open the App's settings on GitHub, add the callback URL above, and generate a client secret.", + enabled = !form.savingSecret, + ) + OutlinedButton(enabled = form.clientSecret.changed && !form.savingSecret, onClick = { model.saveGitHubClientSecret() }) { + if (form.savingSecret) Spinner() else Text("Save") + } + ErrorLine(form.secretError) +} + +@Composable +private fun AccountsSection(model: AppModel) { + RowsSection( + title = "Machine accounts", + footer = "GitHub users for your bots to act as wherever none of their Apps does.", + ) { + error(model.githubAccounts.error) + val accounts = model.githubAccounts.value + if (accounts?.isEmpty() == true) note("No machine accounts yet.") + accounts?.forEach { account -> row { shape -> AccountRow(model, account, shape) } } + add("New machine account") { model.openAddAccount() } + } +} + +@Composable +private fun AccountRow(model: AppModel, account: GitHubAccount, shape: Shape) { + var confirming by remember { mutableStateOf(false) } + val busy = "github-account:${account.id}" in model.pendingMutations + SettingItem( + title = "${account.login} (used by ${account.botIds.size})", + shape = shape, + leading = { LetterTile(account.login) }, + trailing = { + IconButton(onClick = { model.openGitHubAccount(account) }) { Icon(Icons.Default.Edit, contentDescription = "Edit") } + if (busy) { + Spinner() + } else { + IconButton(onClick = { confirming = true }) { Icon(Icons.Default.Delete, contentDescription = "Remove") } + } + }, + ) + if (confirming) { + ConfirmDelete( + title = "Remove ${account.login}?", + description = "Crumble forgets its token and its bots stop acting as it. The user stays on GitHub; revoke the token there too.", + action = "Remove", + onConfirm = { model.deleteGitHubAccount(account) }, + onDismiss = { confirming = false }, + ) + } +} + +@Composable +private fun TokenField(model: AppModel, label: String, draft: SecretDraft, enabled: Boolean, onChange: (SecretDraft) -> Unit) { + val uriHandler = LocalUriHandler.current + SecretSourceField( + model = model, + label = label, + draft = draft, + onChange = onChange, + valuePlaceholder = "github_pat_…", + valueDescription = "Signed in as the machine account on GitHub, create a personal access token with access to the repositories its bots work in.", + enabled = enabled, + ) + TextButton(onClick = { runCatching { uriHandler.openUri("https://github.com/settings/personal-access-tokens/new") } }) { Text("New token") } +} + +@Composable +private fun AddAccountDialog(model: AppModel, form: AddGitHubAccountForm) { + SimpleSheet( + title = "New machine account", + description = "A GitHub user you made for your bots. They act as it wherever none of their Apps does, such as other people's repositories.", + error = form.error, + submitLabel = "Add", + ready = form.ready, + saving = form.saving, + onSubmit = { model.addGitHubAccount() }, + onClose = { model.closeAddAccount() }, + ) { + TokenField(model, "Token", form.token, !form.saving) { next -> model.addAccountForm = model.addAccountForm?.copy(token = next) } + } +} + +@Composable +private fun AccountDialog(model: AppModel, form: GitHubAccountForm, account: GitHubAccount) { + val uriHandler = LocalUriHandler.current + SimpleSheet( + title = account.login, + error = form.error, + submitLabel = "Save", + ready = true, + saving = form.saving, + onSubmit = { model.saveGitHubAccount() }, + onClose = { model.closeGitHubAccount() }, + ) { + GitHubLink(account.htmlUrl) + BotsField( + model, + form.botIDs, + "They get GH_TOKEN and act as this user wherever none of their Apps does; their commits default to it. A bot acts as one machine account.", + ) { next -> model.githubAccountForm = model.githubAccountForm?.copy(botIDs = next) } + TokenField(model, if (account.token.passwordManager != null) "Token" else "Replace token", form.token, !form.saving) { next -> + model.githubAccountForm = model.githubAccountForm?.copy(token = next) + } + CopyField("Signing key", account.signingKey) + SecretNote("Commits its bots make are signed with this key. Add it to ${account.login} on GitHub as a signing key so they show as verified.") + TextButton(onClick = { runCatching { uriHandler.openUri("https://github.com/settings/ssh/new") } }) { Text("Add key") } + } +} + +// MARK: GitHub pages + +/** + * GitHub creates Apps only from a form post, which a browser intent can't send, and each page returns to the website, + * where this app's session isn't. An embedded page can do the first and catch the second. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun GitHubFlowDialog(model: AppModel, flow: GitHubFlow) { + Dialog( + onDismissRequest = { model.closeGitHubFlow() }, + properties = DialogProperties(usePlatformDefaultWidth = false), + ) { + Scaffold( + topBar = { + TopAppBar( + title = { Text("GitHub") }, + navigationIcon = { + IconButton(onClick = { model.closeGitHubFlow() }) { + Icon(Icons.Default.Close, contentDescription = "Close") + } + }, + ) + }, + ) { padding -> + Box(modifier = Modifier.padding(padding).fillMaxSize(), contentAlignment = Alignment.Center) { + when { + flow.error.isNotEmpty() -> Column( + modifier = Modifier.padding(24.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + ErrorLine(flow.error) + OutlinedButton(onClick = { model.closeGitHubFlow() }) { Text("Back to Coding") } + } + flow.finishing -> Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Spinner() + Text("Finishing GitHub setup…", style = MaterialTheme.typography.bodyMedium) + } + else -> GitHubPage(flow, model::finishGitHubFlow) + } + } + } + } +} + +// GitHub's pages need scripts. Nothing is exposed to them: there are no JavaScript interfaces and no file access. +@SuppressLint("SetJavaScriptEnabled") +@Composable +private fun GitHubPage(flow: GitHubFlow, onReturn: (String) -> Unit) { + AndroidView( + modifier = Modifier.fillMaxSize(), + factory = { context -> + WebView(context).apply { + layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) + settings.javaScriptEnabled = true + settings.domStorageEnabled = true + settings.allowFileAccess = false + settings.allowContentAccess = false + webViewClient = object : WebViewClient() { + override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { + val url = request.url.toString() + if (!request.isForMainFrame) return false + if (isGitHubReturn(url, flow.step)) { + onReturn(url) + return true + } + return !isWebLink(url) + } + + // The redirect out of GitHub's App form follows a POST, which skips the check above. + override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) { + if (isGitHubReturn(url, flow.step)) { + view.stopLoading() + onReturn(url) + } + } + } + val manifest = flow.manifest + if (manifest != null) { + postUrl(flow.url, "manifest=${URLEncoder.encode(manifest, StandardCharsets.UTF_8.name())}".toByteArray()) + } else { + loadUrl(flow.url) + } + } + }, + onRelease = { it.destroy() }, + ) +} + +/** The sheets for connections, hosted once at the app's root. */ +@Composable +fun ConnectionDialogs(model: AppModel) { + model.pluginForm?.let { PluginSecretDialog(model, it) } + model.createAppForm?.let { CreateAppDialog(model, it) } + model.githubAppForm?.let { form -> + model.githubApps.value?.firstOrNull { it.id == form.appID }?.let { AppDialog(model, form, it) } + } + model.addAccountForm?.let { AddAccountDialog(model, it) } + model.githubAccountForm?.let { form -> + model.githubAccounts.value?.firstOrNull { it.id == form.accountID }?.let { AccountDialog(model, form, it) } + } + model.serverSettingsForm?.let { ServerSettingsDialog(model, it) } + model.inviteSheet?.let { InviteDialog(model, it) } + model.githubFlow?.let { GitHubFlowDialog(model, it) } +} diff --git a/app/src/main/java/dev/crumble/android/ui/CrumbleAppScreen.kt b/app/src/main/java/dev/crumble/android/ui/CrumbleAppScreen.kt index 7d3ad63..6970f4b 100644 --- a/app/src/main/java/dev/crumble/android/ui/CrumbleAppScreen.kt +++ b/app/src/main/java/dev/crumble/android/ui/CrumbleAppScreen.kt @@ -1,5 +1,18 @@ package dev.crumble.android.ui +import androidx.compose.material.icons.filled.GroupAdd +import androidx.compose.ui.graphics.RectangleShape +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.layout.union +import androidx.compose.foundation.layout.navigationBars +import androidx.compose.foundation.layout.ime +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.material.icons.filled.Person +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.material.icons.filled.Tune +import androidx.activity.compose.BackHandler +import dev.crumble.android.model.WORKSPACE_PAGES import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.background import androidx.compose.foundation.clickable @@ -23,19 +36,36 @@ import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.automirrored.filled.Login import androidx.compose.material.icons.automirrored.filled.MenuBook +import androidx.compose.material.icons.automirrored.filled.Message import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.AutoAwesome +import androidx.compose.material.icons.filled.Balance +import androidx.compose.material.icons.filled.Build import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Code import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.Extension +import androidx.compose.material.icons.filled.Group +import androidx.compose.material.icons.filled.Face +import androidx.compose.material.icons.filled.History +import androidx.compose.material.icons.filled.Home +import androidx.compose.material.icons.filled.Key +import androidx.compose.material.icons.filled.Language +import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.Psychology import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Schedule +import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Settings +import androidx.compose.material.icons.filled.Shield import androidx.compose.material.icons.filled.Timeline +import androidx.compose.material.icons.filled.Visibility import androidx.compose.material.icons.filled.Warning +import androidx.compose.material.icons.filled.Webhook import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.DrawerValue @@ -54,18 +84,22 @@ import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import dev.crumble.android.model.Agent +import dev.crumble.android.model.botListLine import dev.crumble.android.model.AppModel import dev.crumble.android.model.Route +import dev.crumble.android.model.SKILLS_SHARED import dev.crumble.android.model.nilIfEmpty import dev.crumble.android.model.preview import kotlinx.coroutines.launch @@ -73,48 +107,36 @@ import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun CrumbleAppScreen(model: AppModel) { - val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed) - val scope = rememberCoroutineScope() + val inChat = model.route is Route.AgentChat || model.route is Route.GroupChat - ModalNavigationDrawer( - drawerState = drawerState, - drawerContent = { - ModalDrawerSheet(modifier = Modifier.width(310.dp)) { - SidebarView( - model = model, - onSelectRoute = { route -> - model.navigate(route) - scope.launch { drawerState.close() } - }, - onOpenSettings = { - model.showingSettings = true - scope.launch { drawerState.close() } - }, - onCreateAgent = { - model.createAgent() - scope.launch { drawerState.close() } - }, - ) - } + Scaffold( + containerColor = pageColor, + topBar = { + CrumbleTopBar(model = model) }, - ) { - Scaffold( - topBar = { - CrumbleTopBar( - model = model, - onOpenDrawer = { scope.launch { drawerState.open() } }, - ) - }, - ) { innerPadding -> + ) { innerPadding -> + // The chat sheet runs under the gesture bar, so only the top inset comes off here. + val top = PaddingValues(top = innerPadding.calculateTopPadding()) + Surface( + color = if (inChat) sheetColor else Color.Transparent, + shape = if (inChat) RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp) else RectangleShape, + modifier = Modifier.fillMaxSize().padding(top).consumeWindowInsets(top), + ) { Box( modifier = Modifier .fillMaxSize() - .padding(innerPadding) - .consumeWindowInsets(innerPadding) - .imePadding(), + .then( + if (inChat) { + Modifier.windowInsetsPadding(WindowInsets.ime.union(WindowInsets.navigationBars)) + } else { + Modifier.imePadding() + }, + ), ) { when (val currentRoute = model.route) { - is Route.AgentChat, null -> { + is Route.GroupChat -> GroupChatView(model = model) + null -> HomeView(model = model) + is Route.AgentChat -> { val agent = model.selectedAgent if (agent != null) { ChatView(model = model, agent = agent) @@ -139,6 +161,7 @@ fun CrumbleAppScreen(model: AppModel) { } } + BackHandler(enabled = inChat) { model.navigate(null) } model.agentDraft?.let { draft -> AgentEditorDialog(model = model, draft = draft) } @@ -148,41 +171,94 @@ fun CrumbleAppScreen(model: AppModel) { model.taskDraft?.let { draft -> TaskFormDialog(model = model, draft = draft) } + model.eventSourceDraft?.let { draft -> + EventSourceDialog(model = model, draft = draft) + } model.mcpDraft?.let { draft -> MCPFormDialog(model = model, draft = draft) } model.skillDraft?.let { draft -> SkillFormDialog(model = model, draft = draft) } - if (model.showingSettings) { - SettingsDialog(model = model) + model.groupDraft?.let { draft -> + GroupFormDialog(model = model, draft = draft) + } + model.skillInstall?.let { form -> + InstallSkillsDialog(model = model, form = form) + } + model.installedSkill?.let { view -> + InstalledSkillDialog(model = model, view = view) + } + model.skillUpdate?.let { view -> + SkillUpdateDialog(model = model, view = view) + } + model.credentialForm?.let { form -> + CredentialFormDialog(model = model, form = form) + } + model.loginForm?.let { form -> + LoginFormDialog(model = model, form = form) + } + model.tokenForm?.let { form -> + ManagerTokenDialog(model = model, form = form) + } + model.providerKeyForm?.let { form -> + ProviderKeyDialog(model = model, form = form) + } + model.providerLogin?.let { view -> + ProviderLoginDialog(model = model, view = view) + } + model.secretUses?.let { view -> + SecretUsesDialog(model = model, view = view) + } + ConnectionDialogs(model) + if (model.showingChanges) { + ChangeHistoryDialog(model = model) + } + if (model.showingPalette) { + CommandPaletteDialog(model = model) + } + if (model.showingBotDetails) { + model.selectedAgent?.let { BotDetailsDialog(model = model, bot = it) } + } + if (model.showingJobs) { + JobListDialog(model = model) + } + model.jobPanel?.let { panel -> + JobPanelDialog(model = model, panel = panel) + } + model.botDesktop?.let { desktop -> + BotDesktopDialog(model = model, desktop = desktop) } } @OptIn(ExperimentalMaterial3Api::class) @Composable -private fun CrumbleTopBar( - model: AppModel, - onOpenDrawer: () -> Unit, -) { +private fun CrumbleTopBar(model: AppModel) { val currentRoute = model.route val selectedAgent = model.selectedAgent TopAppBar( + colors = TopAppBarDefaults.topAppBarColors(containerColor = pageColor, scrolledContainerColor = pageColor), navigationIcon = { - IconButton(onClick = onOpenDrawer) { - Icon(Icons.Default.Menu, contentDescription = "Open Navigation") + if (currentRoute != null && currentRoute != Route.Account) { + val parent = currentRoute.parent + IconButton(onClick = { model.navigate(parent) }) { + Icon( + Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = parent?.let { "Back to ${it.title.lowercase()}" } ?: "Back", + ) + } } }, title = { - if ((currentRoute is Route.AgentChat || currentRoute == null) && selectedAgent != null) { + if (currentRoute is Route.AgentChat && selectedAgent != null) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), ) { BotAvatarView( agent = selectedAgent, - size = 30.dp, + size = 40.dp, state = model.botState(selectedAgent), live = true, ) @@ -191,8 +267,8 @@ private fun CrumbleTopBar( .heightIn(min = 48.dp) .clickable( role = Role.Button, - onClickLabel = "Open ${selectedAgent.name} profile", - onClick = { model.openEditor() }, + onClickLabel = "Show details", + onClick = { model.openBotDetails() }, ), verticalArrangement = Arrangement.Center, ) { @@ -218,17 +294,51 @@ private fun CrumbleTopBar( } } } + } else if (currentRoute is Route.GroupChat) { + GroupTitle(model = model, groupID = currentRoute.id) + } else if (currentRoute is Route.MessageGateway) { + Text(model.gateways.value?.firstOrNull { it.id == currentRoute.id }?.label ?: currentRoute.title) } else { Text(currentRoute?.title ?: "Crumble") } }, actions = { when (currentRoute) { - is Route.AgentChat, null -> Unit + null -> { + IconButton(onClick = { model.showingPalette = true }) { + Icon(Icons.Default.Search, contentDescription = "Search") + } + AccountButton(model) + } + Route.Account -> { + IconButton(onClick = { model.navigate(null) }) { + Icon(Icons.Default.Close, contentDescription = "Close") + } + } + is Route.AgentChat -> { + if (model.jobs.isNotEmpty() || selectedAgent?.tools.orEmpty().any { it == "coding" || it == "desktop" }) { + IconButton(onClick = { model.openJobList() }) { + Icon(Icons.Default.Build, contentDescription = "Jobs") + } + } + ChatMenu { + item("Details") { model.openBotDetails() } + item("Bot settings") { model.openEditor() } + } + } + is Route.GroupChat -> { + ChatMenu { + item("Group settings") { model.openGroupEditor(currentRoute.id) } + } + } + Route.Settings, Route.General, Route.NewChat, Route.NewGroup -> Unit Route.Memory -> { - IconButton(onClick = { model.openMemoryForm("", agentID = null) }) { + IconButton(onClick = { model.openMemoryForm("", agentID = model.memoryScope?.takeIf { it != SKILLS_SHARED }) }) { Icon(Icons.Default.Add, contentDescription = "New Shared Memory") } + IconButton(onClick = { model.openChanges() }) { + Icon(Icons.Default.History, contentDescription = "Change history") + } IconButton(onClick = { model.openPanel(Route.Memory) }) { Icon(Icons.Default.Refresh, contentDescription = "Refresh") } @@ -237,6 +347,9 @@ private fun CrumbleTopBar( IconButton(onClick = { model.openSkillForm("") }) { Icon(Icons.Default.Add, contentDescription = "New Shared Skill") } + IconButton(onClick = { model.openChanges() }) { + Icon(Icons.Default.History, contentDescription = "Change history") + } IconButton(onClick = { model.openPanel(Route.Skills) }) { Icon(Icons.Default.Refresh, contentDescription = "Refresh") } @@ -265,184 +378,75 @@ private fun CrumbleTopBar( Icon(Icons.Default.Refresh, contentDescription = "Refresh") } } - } - }, - ) -} - -@Composable -private fun SidebarView( - model: AppModel, - onSelectRoute: (Route) -> Unit, - onOpenSettings: () -> Unit, - onCreateAgent: () -> Unit, -) { - val workspaceItems = listOf( - Triple(Route.Memory, "Memory", Icons.Default.Psychology), - Triple(Route.Skills, "Skills", Icons.AutoMirrored.Filled.MenuBook), - Triple(Route.Tasks, "Tasks", Icons.Default.Schedule), - Triple(Route.Activity, "Activity", Icons.Default.Timeline), - Triple(Route.Integrations, "Integrations", Icons.Default.Extension), - ) - - Column(modifier = Modifier.fillMaxHeight()) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 20.dp, vertical = 14.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, - ) { - Text( - text = "Crumble", - style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold), - ) - Row { - IconButton(onClick = onCreateAgent) { - Icon(Icons.Default.Edit, contentDescription = "New Agent") + Route.Avatars, Route.WebSearch, Route.JudgeModel, Route.VisionModel -> Unit + is Route.MessageGateway -> { + IconButton(onClick = { model.loadGateways() }) { + Icon(Icons.Default.Refresh, contentDescription = "Refresh") + } } - IconButton(onClick = onOpenSettings) { - Icon(Icons.Default.Settings, contentDescription = "Settings") + Route.Providers, Route.PasswordManagers, Route.Coding, Route.Users, Route.MessageGateways, Route.EventRelay -> { + IconButton(onClick = { model.openPanel(currentRoute) }) { + Icon(Icons.Default.Refresh, contentDescription = "Refresh") + } } - } - } - - HorizontalDivider() - - LazyColumn( - modifier = Modifier.weight(1f), - contentPadding = PaddingValues(vertical = 8.dp), - ) { - item { - Text( - text = "Agents", - style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.primary, - modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp), - ) - } - if (model.agents.isEmpty()) { - item { - Text( - text = "No agents yet", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp), - ) + Route.Credentials -> { + IconButton(onClick = { model.openCredentialForm(null) }, enabled = model.agents.isNotEmpty()) { + Icon(Icons.Default.Add, contentDescription = "New credential") + } + IconButton(onClick = { model.openPanel(Route.Credentials) }) { + Icon(Icons.Default.Refresh, contentDescription = "Refresh") + } } - } else { - items(model.agents, key = { it.id }) { agent -> - SidebarAgentRow( - model = model, - agent = agent, - selected = model.route == Route.AgentChat(agent.id), - onClick = { onSelectRoute(Route.AgentChat(agent.id)) }, - ) + Route.Logins -> { + IconButton(onClick = { model.openLoginForm(null) }, enabled = model.agents.isNotEmpty()) { + Icon(Icons.Default.Add, contentDescription = "New login") + } + IconButton(onClick = { model.openPanel(Route.Logins) }) { + Icon(Icons.Default.Refresh, contentDescription = "Refresh") + } } } - - item { - HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp)) - Text( - text = "Workspace", - style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.primary, - modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp), - ) - } - - items(workspaceItems, key = { it.second }) { (route, title, icon) -> - NavigationDrawerItem( - label = { Text(title) }, - icon = { Icon(icon, contentDescription = null) }, - selected = model.route == route, - onClick = { onSelectRoute(route) }, - modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding), - ) - } - } - - HorizontalDivider() - ConnectionStatus(model = model) - } + }, + ) } -@Composable -private fun SidebarAgentRow( - model: AppModel, - agent: Agent, - selected: Boolean, - onClick: () -> Unit, -) { - val isPending = model.pendingMutations.contains("agent:${agent.id}") - val bgColor = if (selected) { - MaterialTheme.colorScheme.secondaryContainer - } else { - Color.Transparent - } - Surface( - color = bgColor, - shape = RoundedCornerShape(14.dp), - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 12.dp, vertical = 2.dp) - .clickable(enabled = !isPending, onClick = onClick), - ) { - Row( - modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - BotAvatarView( - agent = agent, - size = 44.dp, - state = model.botState(agent), - ) - Column( - modifier = Modifier.weight(1f), - verticalArrangement = Arrangement.spacedBy(2.dp), - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(6.dp), - ) { - Text( - text = agent.name, - style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.SemiBold), - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - if (!agent.enabled) { - Text( - text = "Paused", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - Text( - text = preview(agent.lastMessage ?: "").nilIfEmpty ?: "No messages yet", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 2, - overflow = TextOverflow.Ellipsis, - ) - } - } - } +/** A page's icon. Chats have avatars instead. */ +fun routeIcon(route: Route): ImageVector = when (route) { + Route.Memory -> Icons.Default.Psychology + Route.Skills -> Icons.AutoMirrored.Filled.MenuBook + Route.Tasks -> Icons.Default.Schedule + Route.Activity -> Icons.Default.Timeline + Route.Integrations -> Icons.Default.Extension + Route.Avatars -> Icons.Default.Face + Route.Providers -> Icons.Default.Key + Route.PasswordManagers -> Icons.Default.Shield + Route.WebSearch -> Icons.Default.Language + Route.Credentials -> Icons.Default.Lock + Route.Logins -> Icons.AutoMirrored.Filled.Login + Route.JudgeModel -> Icons.Default.Balance + Route.VisionModel -> Icons.Default.Visibility + Route.Coding -> Icons.Default.Code + Route.Users -> Icons.Default.Group + Route.MessageGateways, is Route.MessageGateway -> Icons.AutoMirrored.Filled.Message + Route.EventRelay -> Icons.Default.Webhook + Route.Settings -> Icons.Default.Settings + Route.General -> Icons.Default.Tune + Route.Account -> Icons.Default.Person + Route.NewChat -> Icons.Default.Add + Route.NewGroup -> Icons.Default.GroupAdd + is Route.AgentChat, is Route.GroupChat -> Icons.AutoMirrored.Filled.Message } @Composable fun ConnectionStatus(model: AppModel) { val (status, color) = when { - model.streamStatus.isNotEmpty() -> model.streamStatus to MaterialTheme.colorScheme.error + model.liveStatus.isNotEmpty() -> model.liveStatus to MaterialTheme.colorScheme.error model.loading -> "Syncing…" to MaterialTheme.colorScheme.onSurfaceVariant else -> "Connected" to Color(0xFF16A34A) } Row( modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 20.dp, vertical = 14.dp), + .padding(top = 2.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), ) { @@ -501,7 +505,7 @@ fun WelcomeView(model: AppModel) { Button(onClick = { model.createAgent() }) { Text("Create an Agent") } - Button(onClick = { model.showingSettings = true }) { + Button(onClick = { model.navigate(Route.General) }) { Text("Server Settings") } } @@ -520,7 +524,8 @@ fun ErrorBanner( model.taskDraft == null && model.mcpDraft == null && model.skillDraft == null && - !model.showingSettings + model.groupDraft == null && + model.route != Route.General AnimatedVisibility( visible = model.errorText.isNotEmpty() && noSheetOpen, diff --git a/app/src/main/java/dev/crumble/android/ui/DecisionCards.kt b/app/src/main/java/dev/crumble/android/ui/DecisionCards.kt new file mode 100644 index 0000000..6c9d908 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/DecisionCards.kt @@ -0,0 +1,427 @@ +package dev.crumble.android.ui + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.clickable +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.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.Login +import androidx.compose.material.icons.automirrored.filled.Send +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.Group +import androidx.compose.material.icons.filled.Key +import androidx.compose.material.icons.filled.PanTool +import androidx.compose.material.icons.filled.QuestionAnswer +import androidx.compose.material3.Button +import androidx.compose.material3.Checkbox +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +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.graphics.vector.ImageVector +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import dev.crumble.android.generated.BotRequest +import dev.crumble.android.generated.CodingJobQuestion +import dev.crumble.android.generated.CredentialRequest +import dev.crumble.android.generated.HeldAction +import dev.crumble.android.generated.LoginRequest +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.BotRequestRef +import dev.crumble.android.model.HeldActionRef +import dev.crumble.android.model.JobQuestionRef +import dev.crumble.android.model.SecretRequestRef +import dev.crumble.android.model.SecretRequestState +import dev.crumble.android.model.credentialReadKey +import dev.crumble.android.model.loginReadKey +import dev.crumble.android.model.secretKey +import dev.crumble.android.model.secretRequestState + +private val HELD_OUTCOMES = mapOf("approved" to "Approved", "declined" to "Declined", "expired" to "Expired") + +@Composable +private fun DecisionSurface(content: @Composable () -> Unit) { + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(12.dp), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant), + color = MaterialTheme.colorScheme.surface, + ) { + Column(modifier = Modifier.padding(14.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { + content() + } + } +} + +@Composable +private fun DecisionHeader(icon: ImageVector, caption: String, title: String, detail: String? = null) { + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Icon(icon, contentDescription = null, modifier = Modifier.size(18.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant) + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(caption, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(title, style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Medium)) + if (!detail.isNullOrEmpty()) { + Text(detail, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + } +} + +@Composable +private fun SettledCard(icon: ImageVector, title: String, outcome: String, action: (@Composable () -> Unit)? = null) { + DecisionSurface { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Icon(icon, contentDescription = null, modifier = Modifier.size(18.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant) + Column(modifier = Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.bodyMedium, maxLines = 2, overflow = TextOverflow.Ellipsis) + Text(outcome, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + action?.invoke() + } + } +} + +@Composable +private fun DecisionError(model: AppModel, id: String) { + val error = model.decisionErrors[id] ?: return + Text(error, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) +} + +@Composable +private fun DecisionPending(model: AppModel, id: String) { + if (id in model.decidingIDs) { + CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp) + } +} + +private fun AppModel.unresolvedOutcome() = if (decisionsLoaded || decisionsFailed) "Unavailable" else "Loading…" + +@Composable +fun HeldActionCard(model: AppModel, held: HeldActionRef, title: String) { + val action = model.heldActions.firstOrNull { it.id == held.id } + when { + action == null -> SettledCard(Icons.Default.PanTool, title, model.unresolvedOutcome()) + action.status != "pending" -> SettledCard(Icons.Default.PanTool, title, HELD_OUTCOMES[action.status] ?: action.status) + else -> HeldActionPending(model, action) + } +} + +@Composable +private fun HeldActionPending(model: AppModel, action: HeldAction) { + var declining by remember(action.id) { mutableStateOf(false) } + var reason by remember(action.id) { mutableStateOf("") } + var checked by remember(action.id) { mutableStateOf(false) } + val busy = action.id in model.decidingIDs + DecisionSurface { + DecisionHeader(Icons.Default.PanTool, "${action.job} is waiting for your approval", action.action, action.page) + Text(action.reason, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text( + text = if (checked) "Hide your messages" else "Checked against your messages", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.clickable { checked = !checked }, + ) + if (checked) { + if (action.ownerMessages.isEmpty()) { + Text("None: the job had no message from you.", style = MaterialTheme.typography.bodySmall) + } + for (message in action.ownerMessages) { + Text( + text = (if (message.from == "automation") "Automation: " else "") + message.text, + style = MaterialTheme.typography.bodySmall, + ) + } + } + DecisionError(model, action.id) + if (declining) { + OutlinedTextField( + value = reason, + onValueChange = { reason = it }, + label = { Text("Reason (optional)") }, + modifier = Modifier.fillMaxWidth(), + ) + } + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), + ) { + DecisionPending(model, action.id) + TextButton( + enabled = !busy, + onClick = { if (declining) model.decideHeldAction(action.id, approve = false, reason = reason) else declining = true }, + ) { Text("Decline") } + if (!declining) { + Button(enabled = !busy, onClick = { model.decideHeldAction(action.id, approve = true) }) { Text("Approve") } + } + } + } +} + +@Composable +fun JobQuestionCard(model: AppModel, ref: JobQuestionRef, title: String) { + val waiting = model.codingJobs.firstOrNull { it.question?.id == ref.id }?.question + if (waiting != null) { + JobQuestionAnswer(model, ref.job, waiting) + } else { + val outcome = if (model.decisionsFailed) "Unavailable" else if (model.decisionsLoaded) "Answered" else "Loading…" + SettledCard(Icons.Default.QuestionAnswer, title, outcome) + } +} + +@Composable +fun JobQuestionAnswer(model: AppModel, job: String, question: CodingJobQuestion) { + var text by remember(question.id) { mutableStateOf("") } + var picked by remember(question.id) { mutableStateOf>(emptySet()) } + val multiple = question.multiple == true + val options = question.options.orEmpty() + val busy = question.id in model.decidingIDs + // A multiple-choice answer lists the picked options, then anything written. + val reply = listOf(options.filter { it in picked }.joinToString(", "), text.trim()).filter { it.isNotEmpty() }.joinToString("\n") + DecisionSurface { + DecisionHeader(Icons.Default.QuestionAnswer, "$job asks" + if (multiple) " · pick any" else "", question.text) + for (option in options) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(enabled = !busy) { + when { + !multiple -> model.answerJobQuestion(job, question.id, option) + option in picked -> picked = picked - option + else -> picked = picked + option + } + }, + verticalAlignment = Alignment.CenterVertically, + ) { + if (multiple) { + Checkbox(checked = option in picked, onCheckedChange = null, modifier = Modifier.padding(10.dp)) + } else { + RadioButton(selected = false, onClick = null, modifier = Modifier.padding(10.dp)) + } + Text(option, style = MaterialTheme.typography.bodyMedium) + } + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + OutlinedTextField( + value = text, + onValueChange = { text = it }, + enabled = !busy, + label = { Text(if (options.isEmpty()) "Your answer…" else "Something else…") }, + modifier = Modifier.weight(1f), + ) + if (busy) { + DecisionPending(model, question.id) + } else { + IconButton(enabled = reply.isNotEmpty(), onClick = { model.answerJobQuestion(job, question.id, reply) }) { + Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Answer") + } + } + } + DecisionError(model, question.id) + } +} + +@Composable +fun BotRequestCard(model: AppModel, ref: BotRequestRef) { + val request = model.botRequests.firstOrNull { it.id == ref.id } + when { + request == null -> SettledCard(Icons.Default.Group, ref.name, model.unresolvedOutcome()) + request.status == "pending" -> BotRequestPending(model, request) + else -> SettledCard( + icon = Icons.Default.Group, + title = request.proposal.name, + outcome = if (request.status == "approved") "Approved" else "Declined", + action = request.createdAgentId?.let { created -> + { OutlinedButton(onClick = { model.selectAgent(created) }) { Text("Open Chat") } } + }, + ) + } +} + +@Composable +private fun BotRequestPending(model: AppModel, request: BotRequest) { + val busy = request.id in model.decidingIDs + val proposal = request.proposal + var open by remember(request.id) { mutableStateOf(false) } + DecisionSurface { + Row(verticalAlignment = Alignment.Top) { + Column(modifier = Modifier.weight(1f)) { + DecisionHeader(Icons.Default.Group, "Wants to create a bot", proposal.name, proposal.description) + } + IconButton(enabled = !busy, onClick = { model.openBotRequestEditor(request.id) }) { + Icon(Icons.Default.Edit, contentDescription = "Edit") + } + } + Text(request.reason, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text( + text = if (open) "Hide details" else "Show details", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.clickable { open = !open }, + ) + if (open) { + val summary = listOfNotNull(proposal.provider, proposal.model).joinToString(" · ") + if (summary.isNotEmpty()) Text(summary, style = MaterialTheme.typography.bodySmall) + if (!proposal.tools.isNullOrEmpty()) Text("Tools: " + proposal.tools.joinToString(", "), style = MaterialTheme.typography.bodySmall) + if (!proposal.instructions.isNullOrEmpty()) Text(proposal.instructions, style = MaterialTheme.typography.bodySmall) + } + DecisionError(model, request.id) + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), + ) { + DecisionPending(model, request.id) + TextButton(enabled = !busy, onClick = { model.decideBotRequest(request.id, approve = false) }) { Text("Decline") } + Button(enabled = !busy, onClick = { model.decideBotRequest(request.id, approve = true) }) { Text("Approve") } + } + } +} + +@Composable +private fun RequestHosts(hosts: List) { + var expanded by remember(hosts) { mutableStateOf(false) } + val more = hosts.size - 1 + Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Text( + text = (if (expanded) hosts else hosts.take(1)).joinToString(" "), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + if (more > 0) { + Text( + text = if (expanded) "Show less" else "$more more", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.clickable { expanded = !expanded }, + ) + } + } +} + +@Composable +private fun SecretRequestSettled(icon: ImageVector, title: String, state: SecretRequestState<*>) { + val outcome = when (state) { + SecretRequestState.Unavailable -> "Unavailable" + SecretRequestState.Saved -> "Saved" + SecretRequestState.Declined -> "Declined" + else -> "Loading…" + } + SettledCard(icon, title, outcome) +} + +@Composable +fun CredentialRequestCard(model: AppModel, ref: SecretRequestRef) { + val botID = model.selectedAgentID + val list = model.botCredentials[botID] + val request = list?.requests?.firstOrNull { ref.answers(it.name, it.requestedAt) } + val state = secretRequestState( + request = request, + listed = list != null, + saved = list?.credentials?.any { it.name == ref.name } == true, + fresh = credentialReadKey(ref) in model.freshSecretRequests, + failed = model.decisionsFailed, + ) + if (state is SecretRequestState.Waiting) { + CredentialRequestPending(model, botID, state.request) + } else { + SecretRequestSettled(Icons.Default.Key, ref.name, state) + } +} + +@Composable +private fun CredentialRequestPending(model: AppModel, botID: String, request: CredentialRequest) { + SecretRequestPending( + model = model, + key = secretKey("credential", botID, request.name), + icon = Icons.Default.Key, + caption = "Credential", + name = request.name, + hosts = request.hosts, + addLabel = "Add credential", + onDecline = { model.declineCredentialRequest(botID, request.name) }, + onAdd = { model.openCredentialForm(botID, request = request) }, + ) +} + +@Composable +fun LoginRequestCard(model: AppModel, ref: SecretRequestRef) { + val botID = model.selectedAgentID + val list = model.botLogins[botID] + val request = list?.requests?.firstOrNull { ref.answers(it.name, it.requestedAt) } + val state = secretRequestState( + request = request, + listed = list != null, + saved = list?.logins?.any { it.name == ref.name } == true, + fresh = loginReadKey(ref) in model.freshSecretRequests, + failed = model.decisionsFailed, + ) + if (state is SecretRequestState.Waiting) { + LoginRequestPending(model, botID, state.request) + } else { + SecretRequestSettled(Icons.AutoMirrored.Filled.Login, ref.name, state) + } +} + +@Composable +private fun LoginRequestPending(model: AppModel, botID: String, request: LoginRequest) { + SecretRequestPending( + model = model, + key = secretKey("login", botID, request.name), + icon = Icons.AutoMirrored.Filled.Login, + caption = "Login", + name = request.name, + hosts = request.hosts, + addLabel = "Add login", + onDecline = { model.declineLoginRequest(botID, request.name) }, + onAdd = { model.openLoginForm(botID, request = request) }, + ) +} + +@Composable +private fun SecretRequestPending( + model: AppModel, + key: String, + icon: ImageVector, + caption: String, + name: String, + hosts: List, + addLabel: String, + onDecline: () -> Unit, + onAdd: () -> Unit, +) { + val busy = key in model.pendingMutations + DecisionSurface { + DecisionHeader(icon, caption, name) + RequestHosts(hosts) + DecisionError(model, key) + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), + ) { + if (busy) CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp) + TextButton(enabled = !busy, onClick = onDecline) { Text("Decline") } + Button(enabled = !busy, onClick = onAdd) { Text(addLabel) } + } + } +} diff --git a/app/src/main/java/dev/crumble/android/ui/DisplayCards.kt b/app/src/main/java/dev/crumble/android/ui/DisplayCards.kt new file mode 100644 index 0000000..61c4c4e --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/DisplayCards.kt @@ -0,0 +1,425 @@ +package dev.crumble.android.ui + +import android.graphics.BitmapFactory +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.horizontalScroll +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.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.aspectRatio +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.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ArrowDownward +import androidx.compose.material.icons.filled.ArrowForward +import androidx.compose.material.icons.filled.ArrowUpward +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +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.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.luminance +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.PathEffect +import androidx.compose.ui.graphics.PathFillType +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.StrokeJoin +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.Fill +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.drawscope.clipRect +import androidx.compose.ui.graphics.drawscope.rotate +import androidx.compose.ui.graphics.drawscope.scale +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.layout.layout +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.TextMeasurer +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.drawText +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.rememberTextMeasurer +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.Constraints +import androidx.compose.ui.unit.dp +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.ChartInk +import dev.crumble.android.model.ChartLayout +import dev.crumble.android.model.ChartNode +import dev.crumble.android.model.ChartPoint +import dev.crumble.android.model.ChartShape +import dev.crumble.android.model.DisplayCard +import dev.crumble.android.model.DisplayCell +import dev.crumble.android.model.DisplayStat +import dev.crumble.android.model.Message +import dev.crumble.android.model.chartLayoutFor +import dev.crumble.android.model.chartLayouts +import dev.crumble.android.model.fitColumns +import dev.crumble.android.model.nearestChartPoint +import dev.crumble.android.model.numericColumns +import java.text.NumberFormat +import kotlinx.serialization.json.JsonArray + +private val CARD_SHAPE = RoundedCornerShape(12.dp) + +@Composable +internal fun DisplayCardView(card: DisplayCard) { + Column( + modifier = Modifier + .fillMaxWidth() + .border(1.dp, MaterialTheme.colorScheme.outlineVariant, CARD_SHAPE) + .padding(12.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + card.title?.takeIf { it.isNotEmpty() }?.let { + Text(it, style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Medium)) + } + when (card) { + is DisplayCard.Stats -> StatGrid(card.items) + is DisplayCard.Table -> DisplayTable(card.columns, card.rows) + is DisplayCard.Chart -> DisplayChart(card.layouts, card.title) + } + } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun StatGrid(items: List) { + FlowRow( + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + for (item in items) StatCell(item) + } +} + +@Composable +private fun StatCell(item: DisplayStat) { + val muted = MaterialTheme.colorScheme.onSurfaceVariant + Column(modifier = Modifier.widthIn(min = 126.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(item.label, style = MaterialTheme.typography.labelSmall, color = muted) + Text(item.value, style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.SemiBold)) + item.change?.let { change -> + val color = when (item.trend) { + "up" -> if (MaterialTheme.colorScheme.surface.luminance() < 0.5f) Color(0xFF34D399) else Color(0xFF059669) + "down" -> MaterialTheme.colorScheme.error + else -> muted + } + val icon = when (item.trend) { + "up" -> Icons.Default.ArrowUpward + "down" -> Icons.Default.ArrowDownward + "flat" -> Icons.Default.ArrowForward + else -> null + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + icon?.let { Icon(it, contentDescription = null, tint = color, modifier = Modifier.size(12.dp)) } + Text(change, style = MaterialTheme.typography.labelSmall, color = color) + } + } + item.caption?.let { Text(it, style = MaterialTheme.typography.labelSmall, color = muted) } + } +} + +private fun cellText(cell: DisplayCell, format: NumberFormat) = + cell.number?.let(format::format) ?: cell.text + +@Composable +private fun DisplayTable(columns: List, rows: List>) { + val measurer = rememberTextMeasurer() + val style = MaterialTheme.typography.bodySmall + val density = LocalDensity.current + val cellPadding = 8.dp + val format = remember { NumberFormat.getInstance() } + val texts = remember(rows, format) { rows.map { row -> row.map { cellText(it, format) } } } + val count = maxOf(columns.size, rows.maxOfOrNull { it.size } ?: 0) + val numeric = remember(columns, rows, count) { numericColumns(count, rows) } + val natural = remember(columns, texts, count, style) { + List(count) { index -> + val cells = listOfNotNull(columns.getOrNull(index)) + texts.mapNotNull { it.getOrNull(index) } + val widest = cells.maxOfOrNull { measurer.measure(it, style, maxLines = 1, softWrap = false).size.width } ?: 0 + with(density) { widest.toDp() + cellPadding * 2 + 1.dp } + } + } + BoxWithConstraints(modifier = Modifier.fillMaxWidth()) { + val widths = remember(natural, maxWidth) { fitColumns(natural.map { it.value }, maxWidth.value).map { it.dp } } + Column(modifier = Modifier.horizontalScroll(rememberScrollState())) { + @Composable + fun TableRow(cells: List, color: Color) { + Row { + cells.forEachIndexed { index, text -> + Text( + text = text, + style = style, + color = color, + maxLines = 1, + softWrap = false, + textAlign = if (numeric.getOrElse(index) { false }) TextAlign.End else TextAlign.Start, + modifier = Modifier + .width(widths[index]) + .padding(horizontal = cellPadding, vertical = 6.dp), + ) + } + } + } + val divider = Modifier.width(widths.fold(0.dp) { sum, each -> sum + each }) + TableRow(columns, MaterialTheme.colorScheme.onSurfaceVariant) + HorizontalDivider(modifier = divider) + texts.forEachIndexed { index, row -> + TableRow(row, MaterialTheme.colorScheme.onSurface) + if (index != texts.lastIndex) HorizontalDivider(modifier = divider) + } + } + } +} + +private fun ChartInk.color(foreground: Color, background: Color): Color? = when (this) { + ChartInk.None -> null + ChartInk.Foreground -> foreground + ChartInk.Background -> background + is ChartInk.Literal -> Color(argb) +} + +private fun curveOf(shape: ChartShape.Curve) = Path().apply { + fillType = if (shape.evenOdd) PathFillType.EvenOdd else PathFillType.NonZero + for (command in shape.commands) { + val a = command.args + when (command.op) { + "M" -> moveTo(a[0], a[1]) + "L" -> lineTo(a[0], a[1]) + "Q" -> quadraticTo(a[0], a[1], a[2], a[3]) + "C" -> cubicTo(a[0], a[1], a[2], a[3], a[4], a[5]) + "Z" -> close() + } + } +} + +private fun strokeOf(node: ChartNode): Stroke { + // SVG repeats an odd dash list; Android needs pairs and fails on an all-zero pattern. + val dash = node.dash.takeIf { list -> list.isNotEmpty() && list.none { it < 0f } && list.sum() > 0f } + ?.let { if (it.size % 2 == 0) it else it + it } + return Stroke( + width = node.strokeWidth, + cap = when (node.lineCap) { + "round" -> StrokeCap.Round + "square" -> StrokeCap.Square + else -> StrokeCap.Butt + }, + join = when (node.lineJoin) { + "round" -> StrokeJoin.Round + "bevel" -> StrokeJoin.Bevel + else -> StrokeJoin.Miter + }, + pathEffect = dash?.let { PathEffect.dashPathEffect(it.toFloatArray()) }, + ) +} + +private fun DrawScope.drawLabel(shape: ChartShape.Label, color: Color, measurer: TextMeasurer) { + val style = TextStyle( + color = color, + fontSize = shape.size.toSp(), + fontWeight = FontWeight(shape.weight.coerceIn(1, 1000)), + ) + val measured = measurer.measure(shape.text, style, softWrap = false, maxLines = 1) + val left = when (shape.anchor) { + "middle" -> shape.x - measured.size.width / 2f + "end" -> shape.x - measured.size.width + else -> shape.x + } + val top = when (shape.baseline) { + "middle" -> shape.y - measured.size.height / 2f + "hanging" -> shape.y + else -> shape.y - measured.firstBaseline + } + rotate(shape.rotate, pivot = Offset(shape.x, shape.y)) { + drawText(measured, topLeft = Offset(left, top)) + } +} + +private fun DrawScope.drawShape(node: ChartNode, foreground: Color, background: Color, measurer: TextMeasurer) { + val fill = node.fill.color(foreground, background)?.let { it.copy(alpha = it.alpha * node.fillOpacity * node.opacity) } + // Android draws a hairline for width 0, where SVG draws nothing. + val stroke = node.stroke.color(foreground, background) + ?.takeIf { node.strokeWidth > 0f } + ?.let { it.copy(alpha = it.alpha * node.strokeOpacity * node.opacity) } + val style = strokeOf(node) + when (val shape = node.shape) { + is ChartShape.Line -> stroke?.let { + drawLine( + color = it, + start = Offset(shape.x1, shape.y1), + end = Offset(shape.x2, shape.y2), + strokeWidth = style.width, + cap = style.cap, + pathEffect = style.pathEffect, + ) + } + is ChartShape.Curve -> { + val path = curveOf(shape) + fill?.let { drawPath(path, it, style = Fill) } + stroke?.let { drawPath(path, it, style = style) } + } + is ChartShape.Circle -> { + val center = Offset(shape.x, shape.y) + fill?.let { drawCircle(it, shape.radius, center, style = Fill) } + stroke?.let { drawCircle(it, shape.radius, center, style = style) } + } + is ChartShape.Box -> { + val corner = CornerRadius(shape.radius) + val topLeft = Offset(shape.x, shape.y) + val size = Size(shape.width, shape.height) + fill?.let { drawRoundRect(it, topLeft, size, corner, style = Fill) } + stroke?.let { drawRoundRect(it, topLeft, size, corner, style = style) } + } + is ChartShape.Label -> fill?.let { drawLabel(shape, it, measurer) } + } +} + +private fun DrawScope.drawNode(node: ChartNode, foreground: Color, background: Color, measurer: TextMeasurer) { + val clip = node.clip + if (clip == null) { + drawShape(node, foreground, background, measurer) + } else { + clipRect(clip.x, clip.y, clip.x + clip.width, clip.y + clip.height) { + drawShape(node, foreground, background, measurer) + } + } +} + +@Composable +private fun DisplayChart(layouts: JsonArray, title: String?) { + val parsed = remember(layouts) { chartLayouts(layouts) } + BoxWithConstraints(modifier = Modifier.fillMaxWidth()) { + val layout = chartLayoutFor(parsed, maxWidth.value) ?: return@BoxWithConstraints + val shown = minOf(maxWidth, parsed.last().width.dp) + ChartCanvas(layout, shown.value, title) + } +} + +@Composable +private fun ChartCanvas(layout: ChartLayout, widthDp: Float, title: String?) { + val foreground = MaterialTheme.colorScheme.onSurface + val background = MaterialTheme.colorScheme.surface + val measurer = rememberTextMeasurer() + val density = LocalDensity.current + var selected by remember(layout) { mutableStateOf(null) } + val scaleUnits = layout.width / with(density) { widthDp.dp.toPx() } + + Box(modifier = Modifier.width(widthDp.dp).aspectRatio(layout.width / layout.height)) { + Canvas( + modifier = Modifier + .matchParentSize() + .semantics { contentDescription = title ?: "Chart" } + .pointerInput(layout, scaleUnits) { + detectTapGestures { touch -> + selected = nearestChartPoint( + layout.points, + touch.x * scaleUnits, + touch.y * scaleUnits, + with(density) { 32.dp.toPx() } * scaleUnits, + ) + } + }, + ) { + scale(size.width / layout.width, pivot = Offset.Zero) { + layout.nodes.forEach { drawNode(it, foreground, background, measurer) } + selected?.let { point -> + drawCircle(foreground, 5f, Offset(point.x, point.y), style = Stroke(width = 2f)) + } + } + } + selected?.let { point -> + ChartTooltip( + point = point, + modifier = Modifier.layout { measurable, constraints -> + val parentWidth = constraints.maxWidth + val tooltip = measurable.measure(Constraints(maxWidth = parentWidth)) + val anchorX = (point.x / scaleUnits).toInt() + val anchorY = (point.y / scaleUnits).toInt() + val x = (anchorX - tooltip.width / 2).coerceIn(0, maxOf(0, parentWidth - tooltip.width)) + val y = maxOf(0, anchorY - tooltip.height - 10.dp.roundToPx()) + layout(tooltip.width, tooltip.height) { tooltip.place(x, y) } + }, + ) + } + } +} + +@Composable +private fun ChartTooltip(point: ChartPoint, modifier: Modifier) { + val small = MaterialTheme.typography.labelSmall + Surface(modifier = modifier, shape = RoundedCornerShape(6.dp), tonalElevation = 3.dp, shadowElevation = 3.dp) { + Column(modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)) { + point.title?.takeIf { it.isNotEmpty() }?.let { + Text(it, style = small.copy(fontWeight = FontWeight.Medium)) + } + point.text?.let { Text(it, style = small) } + for (row in point.rows) { + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Text(row.label, style = small, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(row.value, style = small) + } + } + } + } +} + +/** The picture a `desktop_screenshot` call took, stored as the result's first attachment. */ +@Composable +internal fun DesktopScreenshotCard(model: AppModel, message: Message) { + val entryID = message.entryId ?: return + LaunchedEffect(entryID) { model.loadAttachmentImage(entryID = entryID, index = 0) } + val bytes = model.attachmentImageBytes(message, 0) + val bitmap = remember(bytes) { bytes?.let { BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() } } + if (bitmap != null) { + Image( + bitmap = bitmap, + contentDescription = "Desktop screenshot", + contentScale = ContentScale.Fit, + modifier = Modifier + .fillMaxWidth() + .heightIn(max = 512.dp) + .clip(CARD_SHAPE), + ) + } else { + Box( + modifier = Modifier + .fillMaxWidth() + .aspectRatio(16f / 9f) + .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.6f), CARD_SHAPE), + contentAlignment = Alignment.Center, + ) { + CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp) + } + } +} diff --git a/app/src/main/java/dev/crumble/android/ui/GroupChatScreen.kt b/app/src/main/java/dev/crumble/android/ui/GroupChatScreen.kt new file mode 100644 index 0000000..56da58b --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/GroupChatScreen.kt @@ -0,0 +1,523 @@ +package dev.crumble.android.ui + +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable +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.PaddingValues +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.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +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.runtime.snapshotFlow +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import dev.crumble.android.generated.GroupActivity +import dev.crumble.android.generated.GroupChat +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.ChatRow +import dev.crumble.android.model.GROUP_NAME_LIMIT +import dev.crumble.android.model.GroupConversation +import dev.crumble.android.model.GroupDraft +import dev.crumble.android.model.MAX_GROUP_MEMBERS +import dev.crumble.android.model.Message +import dev.crumble.android.model.groupReactions +import dev.crumble.android.model.groupReplyLabel +import dev.crumble.android.model.groupSourcesOf +import dev.crumble.android.model.groupStatusLine +import dev.crumble.android.model.isGroupRunning +import dev.crumble.android.model.isNotice +import dev.crumble.android.model.isValidGroup +import dev.crumble.android.model.memberStatusLabel +import dev.crumble.android.model.membersOf +import dev.crumble.android.model.shownInGroup +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.distinctUntilChanged + +@Composable +fun GroupChatView( + model: AppModel, + modifier: Modifier = Modifier, +) { + val conversation = model.groupConversation + val group = conversation?.group + if (conversation == null || group == null) { + Box(modifier = modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) { + val error = conversation?.loadError + if (error != null) SheetErrorBanner(error) else CircularProgressIndicator() + } + return + } + val outgoing = model.groupOutgoing[group.id].orEmpty() + val composer = model.groupComposer(group.id) + val transcript = conversation.messages + val rows = remember(transcript, outgoing, conversation.hasMore) { + ChatRow.rows(transcript + outgoing, null, conversation.hasMore && conversation.oldestEntryID != null, ::shownInGroup) + } + val reactions = remember(transcript) { groupReactions(transcript) } + val members = remember(group, model.agents) { membersOf(group, model.agents) } + val listState = remember(group.id) { LazyListState() } + var wasNearBottom by remember(group.id) { mutableStateOf(true) } + + LaunchedEffect(listState) { + snapshotFlow { listState.firstVisibleItemIndex == 0 && listState.firstVisibleItemScrollOffset <= 48 } + .distinctUntilChanged() + .collectLatest { wasNearBottom = it } + } + LaunchedEffect(rows.size) { + if (rows.isNotEmpty() && wasNearBottom) listState.animateScrollToItem(0) + } + + Column(modifier = modifier.fillMaxSize()) { + Box(modifier = Modifier.weight(1f).fillMaxWidth()) { + if (rows.none { it is ChatRow.MessageRow }) { + GroupEmpty(modifier = Modifier.align(Alignment.Center)) + } + LazyColumn( + state = listState, + modifier = Modifier.fillMaxSize(), + reverseLayout = true, + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(10.dp, Alignment.Bottom), + ) { + groupActivityRows(conversation.activity, model.agents) + items(rows.asReversed(), key = { it.id }) { row -> + when (row) { + is ChatRow.Older -> OlderRow(conversation.loadingOlder) { model.loadEarlierGroupMessages() } + is ChatRow.Time -> TimeRow(row.label) + is ChatRow.MessageRow -> if (isNotice(row.message)) { + NoticeRow(model, row.message) + } else { + GroupMessageView( + model = model, + conversation = conversation, + message = row.message, + reactions = reactions[row.message.entryId].orEmpty(), + ) + } + else -> Unit + } + } + } + } + conversation.sendError?.let { + Text( + text = it, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp), + ) + } + val reply = composer.replyTo + ComposerBar( + draft = composer.draft, + onDraftChange = { text -> model.updateGroupComposer(group.id) { it.copy(draft = text) } }, + attachments = composer.attachments, + onAddAttachment = { model.addGroupAttachment(group.id, it) }, + onRemoveAttachment = { id -> + model.updateGroupComposer(group.id) { current -> current.copy(attachments = current.attachments.filterNot { it.id == id }) } + }, + onAttachmentError = { model.errorText = it }, + replyTitle = reply?.let { "Replying to ${groupReplyLabel(it)}" }, + replyPreview = reply?.text.orEmpty(), + onCancelReply = { model.updateGroupComposer(group.id) { it.copy(replyTo = null) } }, + mentionable = members.filter { it.enabled }, + enabled = true, + placeholder = "Message ${group.name}", + running = isGroupRunning(conversation.activity), + stopEnabled = "group-stop:${group.id}" !in model.pendingMutations, + onStop = { model.stopGroupChat() }, + onSend = { model.sendGroupMessage() }, + ) + } +} + +@Composable +private fun GroupEmpty(modifier: Modifier = Modifier) { + Column( + modifier = modifier.padding(horizontal = 32.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + Text( + text = "Start the conversation", + style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), + ) + Text( + text = "Everyone here reads every message. Mention a bot with @ to ask only it.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + } +} + +/** In a reversed list the first items sit lowest, so these rows follow the newest message. */ +private fun androidx.compose.foundation.lazy.LazyListScope.groupActivityRows(activity: GroupActivity?, agents: List) { + val members = activity?.members.orEmpty() + if (activity?.paused == true) { + item(key = "paused") { + Text( + text = "The bots are waiting for you. Your next message lets them continue.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth(), + ) + } + } + items(members.filter { it.error != null }, key = { "failure-${it.agentId}" }) { member -> + GroupFailure(name = agents.firstOrNull { it.id == member.agentId }?.name ?: "A bot", error = member.error.orEmpty()) + } + val working = members.filter { it.status == "running" }.mapNotNull { member -> agents.firstOrNull { it.id == member.agentId } } + if (members.any { it.status == "running" }) { + item(key = "working") { + Row( + modifier = Modifier.semantics { contentDescription = "Working…" }, + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + AvatarStack(working, size = 24.dp) { BotState.working } + Text( + text = "Working…", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } +} + +@Composable +private fun GroupFailure(name: String, error: String) { + Surface( + color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.5f), + shape = RoundedCornerShape(12.dp), + modifier = Modifier.fillMaxWidth(), + ) { + Column(modifier = Modifier.padding(14.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text( + text = "$name couldn't finish", + style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.SemiBold), + ) + Text( + text = error, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } + } +} + +@Composable +internal fun AvatarStack( + bots: List, + size: Dp, + modifier: Modifier = Modifier, + label: (Agent) -> String? = { null }, + state: (Agent) -> BotState, +) { + val step = size * 3 / 4 + Box(modifier = modifier.width(size + step * maxOf(0, bots.size - 1))) { + bots.forEachIndexed { index, bot -> + val text = label(bot) + BotAvatarView( + agent = bot, + size = size, + state = state(bot), + modifier = Modifier + .offset(x = step * index) + .then(if (text != null) Modifier.semantics { contentDescription = text } else Modifier), + ) + } + } +} + +/** The top bar's title for a group chat: its members, its name, and who is doing what. */ +@Composable +fun GroupTitle(model: AppModel, groupID: String) { + val conversation = model.groupConversation?.takeIf { it.groupID == groupID } + val group = conversation?.group ?: model.groupChats.firstOrNull { it.id == groupID } + val activity = conversation?.activity + val members = group?.let { membersOf(it, model.agents) }.orEmpty() + fun status(id: String) = activity?.members?.firstOrNull { it.agentId == id }?.status + Row( + modifier = Modifier.clickable(enabled = group != null) { model.openGroupEditor(groupID) }, + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + AvatarStack( + bots = members, + size = 26.dp, + label = { memberStatusLabel(it, status(it.id)) }, + ) { + when (status(it.id)) { + "running" -> BotState.working + "disabled" -> BotState.sleeping + else -> BotState.idle + } + } + Column(modifier = Modifier.heightIn(min = 48.dp), verticalArrangement = Arrangement.Center) { + Text( + text = group?.name ?: "Group chat", + style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + val subtitle = groupStatusLine(members, activity) + if (subtitle.isNotEmpty()) { + Text( + text = subtitle, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + } +} + +@Composable +internal fun Reactions(labels: List) { + if (labels.isEmpty()) return + Row( + modifier = Modifier.horizontalScroll(rememberScrollState()), + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + for (label in labels) { + Surface(color = MaterialTheme.colorScheme.surfaceVariant, shape = CircleShape) { + Text( + text = label, + style = MaterialTheme.typography.labelSmall, + modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp), + ) + } + } + } +} + +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun GroupMessageView( + model: AppModel, + conversation: GroupConversation, + message: Message, + reactions: List, +) { + val replyable = !message.entryId.isNullOrEmpty() + val owner = message.role == "user" + var menuExpanded by remember { mutableStateOf(false) } + val clipboard = LocalClipboardManager.current + val reply = { model.updateGroupComposer(conversation.groupID) { it.copy(replyTo = message) } } + val bubble: @Composable () -> Unit = { + Box { + ChatBubble( + owner = owner, + modifier = Modifier + .widthIn(max = 310.dp) + .combinedClickable(onClick = {}, onLongClick = { menuExpanded = true }), + ) { + if (owner) { + Text( + text = message.text, + style = MaterialTheme.typography.bodyMedium, + color = LocalContentColor.current, + ) + } else { + ReplyContent(message.text, groupSourcesOf(message)) + } + } + MessageContextMenu( + expanded = menuExpanded, + onDismiss = { menuExpanded = false }, + replyable = replyable, + onReply = { + reply() + menuExpanded = false + }, + onCopy = { + clipboard.setText(AnnotatedString(message.text)) + menuExpanded = false + }, + ) + } + } + + if (owner) { + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + Spacer(modifier = Modifier.width(40.dp)) + Column(horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(4.dp)) { + ReplyQuote(message = message, transcript = conversation.messages) + SentAttachments( + message = message, + imageBytes = { model.groupAttachmentImageBytes(message, it) }, + loadImage = { entryID, index -> model.loadGroupAttachmentImage(entryID, index) }, + ) + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + if (replyable) ReplyButton(onClick = { reply() }) + if (message.text.isNotEmpty()) bubble() + } + Reactions(reactions) + DeliveryStatus(message = message, onRetry = { model.retryGroupMessage(message) }) + } + } + } else { + val bot = model.agents.firstOrNull { it.id == message.origin?.agentId } + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text( + text = message.origin?.name ?: bot?.name ?: "Bot", + style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.SemiBold), + color = bot?.avatar?.let { avatarColor(it.color) } ?: MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 6.dp), + ) + Row(verticalAlignment = Alignment.CenterVertically) { + bubble() + if (replyable) ReplyButton(onClick = { reply() }) + } + Reactions(reactions) + } + } +} + +@Composable +fun GroupFormDialog( + model: AppModel, + draft: GroupDraft, +) { + val isNew = draft.groupID.isEmpty() + val savedName = model.groupChats.firstOrNull { it.id == draft.groupID }?.name ?: draft.name + val pending = "group:${draft.groupID}" in model.pendingMutations + var confirmingDelete by remember(draft.id) { mutableStateOf(false) } + val close = { + model.errorText = "" + model.groupDraft = null + } + AlertDialog( + onDismissRequest = close, + title = { Text(if (isNew) "New group chat" else "Edit $savedName") }, + text = { + Column( + modifier = Modifier.verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + SheetErrorBanner(model.errorText) + OutlinedTextField( + value = draft.name, + onValueChange = { model.groupDraft = draft.copy(name = it.take(GROUP_NAME_LIMIT)) }, + label = { Text("Name") }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + if (!isNew) { + GroupLabel("Members") + Text( + text = "Choose two to six bots. A bot added later gets a summary of the conversation so far.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + GroupedRows { + for (bot in model.agents.filterNot { it.id.startsWith("pending:") }) { + val on = bot.id in draft.memberIDs + row { shape -> + GroupedItem( + shape = shape, + leading = { BotAvatarView(agent = bot, size = 44.dp) }, + trailing = { + Switch( + checked = on, + enabled = on || draft.memberIDs.size < MAX_GROUP_MEMBERS, + onCheckedChange = { model.toggleGroupMember(bot.id, it) }, + ) + }, + ) { + RowTitle(bot.name, maxLines = 1) + if (!bot.enabled) RowSubtitle("Disabled") + } + } + } + } + TextButton(enabled = !pending, onClick = { confirmingDelete = true }) { + Text("Delete", color = MaterialTheme.colorScheme.error) + } + } + } + }, + confirmButton = { + Button( + enabled = !pending && isValidGroup(draft.name, draft.memberIDs), + onClick = { model.saveGroup() }, + ) { + Text(if (isNew) "Create group chat" else "Save") + } + }, + dismissButton = { + TextButton(onClick = close) { + Text("Cancel") + } + }, + ) + if (confirmingDelete) { + AlertDialog( + onDismissRequest = { confirmingDelete = false }, + title = { Text("Delete $savedName?") }, + text = { Text("The group chat and its messages will be removed. The bots stay. This cannot be undone.") }, + confirmButton = { + TextButton(onClick = { model.deleteGroup(draft.groupID) }) { + Text("Delete", color = MaterialTheme.colorScheme.error) + } + }, + dismissButton = { + TextButton(onClick = { confirmingDelete = false }) { + Text("Cancel") + } + }, + ) + } +} diff --git a/app/src/main/java/dev/crumble/android/ui/HomeScreen.kt b/app/src/main/java/dev/crumble/android/ui/HomeScreen.kt new file mode 100644 index 0000000..40b44a2 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/HomeScreen.kt @@ -0,0 +1,175 @@ +package dev.crumble.android.ui + +import androidx.compose.foundation.layout.navigationBarsPadding +import dev.crumble.android.model.MIN_GROUP_MEMBERS +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material.icons.filled.GroupAdd +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.ExtendedFloatingActionButton +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.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.material.icons.automirrored.filled.ArrowForward +import androidx.compose.material.icons.automirrored.filled.Message +import androidx.compose.material3.Checkbox +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import dev.crumble.android.model.MAX_GROUP_MEMBERS +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.unit.dp +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.Route +import dev.crumble.android.model.botStatusLine +import dev.crumble.android.model.membersOf + +/** A conversation list, like Messages: a flat list on a rounded sheet, with New chat in reach. */ +@Composable +fun HomeView(model: AppModel) { + LaunchedEffect(model.agents.map { it.id }) { model.followBotStatuses() } + if (model.agents.isEmpty()) { + WelcomeView(model = model) + return + } + + Box(modifier = Modifier.fillMaxSize()) { + ConversationSheet { + items(model.agents, key = { it.id }) { bot -> BotConversation(model, bot) } + items(model.groupChats, key = { it.id }) { group -> + val members = membersOf(group, model.agents) + ConversationRow( + title = group.name, + preview = members.joinToString(", ") { it.name }, + enabled = !group.id.startsWith("pending:"), + onClick = { model.navigate(Route.GroupChat(group.id)) }, + leading = { AvatarStack(members.take(2), size = 32.dp) { BotState.idle } }, + ) + } + if (model.groupsFailed) { + item { + ConversationRow( + title = "Couldn't load group chats", + onClick = { model.loadGroupChats() }, + leading = { IconTile(Icons.Default.Refresh, Tone.Orange) }, + ) + } + } + } + ExtendedFloatingActionButton( + onClick = { model.navigate(Route.NewChat) }, + icon = { Icon(Icons.AutoMirrored.Filled.Message, contentDescription = null) }, + text = { Text("New chat") }, + modifier = Modifier.align(Alignment.BottomEnd).navigationBarsPadding().padding(16.dp), + ) + } +} + +/** Starts a chat: a new bot, a group, or a bot that already exists. */ +@Composable +fun NewChatPanel(model: AppModel) { + val bots = model.agents.filterNot { it.id.startsWith("pending:") } + ConversationSheet { + item { + ConversationRow( + title = "New bot", + onClick = { model.createAgent() }, + leading = { IconTile(Icons.Default.Add, Tone.Blue) }, + ) + } + if (bots.size >= MIN_GROUP_MEMBERS) { + item { + ConversationRow( + title = "New group chat", + onClick = { model.navigate(Route.NewGroup) }, + leading = { IconTile(Icons.Default.GroupAdd, Tone.Lavender) }, + ) + } + } + if (bots.isNotEmpty()) item { GroupLabel("Bots") } + items(bots, key = { it.id }) { bot -> BotConversation(model, bot) } + } +} + +/** Picks a group's bots; the form that follows names it. */ +@Composable +fun NewGroupPanel(model: AppModel) { + var members by remember { mutableStateOf(emptyList()) } + val bots = model.agents.filterNot { it.id.startsWith("pending:") } + Box(modifier = Modifier.fillMaxSize()) { + ConversationSheet { + item { GroupLabel("Choose two to six bots") } + items(bots, key = { it.id }) { bot -> + val on = bot.id in members + ConversationRow( + title = bot.name, + preview = "Disabled".takeIf { !bot.enabled }, + enabled = on || members.size < MAX_GROUP_MEMBERS, + onClick = { members = if (on) members - bot.id else members + bot.id }, + trailing = { Checkbox(checked = on, onCheckedChange = null) }, + leading = { BotAvatarView(agent = bot, size = 52.dp, live = false) }, + ) + } + } + if (members.size >= MIN_GROUP_MEMBERS) { + ExtendedFloatingActionButton( + onClick = { model.openNewGroup(members) }, + icon = { Icon(Icons.AutoMirrored.Filled.ArrowForward, contentDescription = null) }, + text = { Text("Next") }, + modifier = Modifier.align(Alignment.BottomEnd).navigationBarsPadding().padding(16.dp), + ) + } + } +} + +@Composable +private fun BotConversation(model: AppModel, agent: Agent) { + val working = model.isWorking(agent.id) + ConversationRow( + title = agent.name, + preview = agent.lastMessage?.takeIf { !working && it.isNotBlank() } ?: botStatusLine(agent, working), + enabled = !model.pendingMutations.contains("agent:${agent.id}"), + onClick = { model.navigate(Route.AgentChat(agent.id)) }, + leading = { + Box(contentAlignment = Alignment.BottomEnd) { + BotAvatarView(agent = agent, size = 52.dp, state = model.botState(agent), live = false) + if (working) WorkingDot() + } + }, + ) +} + +@Composable +private fun WorkingDot() { + val pulse by rememberInfiniteTransition(label = "working").animateFloat( + initialValue = 1f, + targetValue = 0.35f, + animationSpec = infiniteRepeatable(tween(800), RepeatMode.Reverse), + label = "working dot", + ) + Box( + modifier = Modifier + .size(10.dp) + .alpha(pulse) + .background(MaterialTheme.colorScheme.primary, CircleShape), + ) +} diff --git a/app/src/main/java/dev/crumble/android/ui/JobScreen.kt b/app/src/main/java/dev/crumble/android/ui/JobScreen.kt new file mode 100644 index 0000000..f4398ab --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/JobScreen.kt @@ -0,0 +1,365 @@ +package dev.crumble.android.ui + +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +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.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.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Build +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Description +import androidx.compose.material.icons.filled.DesktopWindows +import androidx.compose.material.icons.filled.Download +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.ExpandLess +import androidx.compose.material.icons.filled.ExpandMore +import androidx.compose.material.icons.filled.Terminal +import androidx.compose.material.icons.filled.TouchApp +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +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.graphics.Shape +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.JobItem +import dev.crumble.android.model.JobKind +import dev.crumble.android.model.JobPanel +import dev.crumble.android.model.JobRef +import dev.crumble.android.model.JobSummary +import dev.crumble.android.model.jobItems +import dev.crumble.android.model.jobStepVerb +import dev.crumble.android.model.jobWorking +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +private fun JobKind.icon(): ImageVector = if (this == JobKind.coding) Icons.Default.Build else Icons.Default.DesktopWindows + +private fun stepIcon(tool: String): ImageVector = when (tool) { + "bash" -> Icons.Default.Terminal + "read" -> Icons.Default.Description + "write", "edit" -> Icons.Default.Edit + "computer_use" -> Icons.Default.TouchApp + else -> Icons.Default.Build +} + +/** Whether a job works, as its card and panel show it. */ +@Composable +private fun JobStatusLabel(working: Boolean) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + if (working) CircularProgressIndicator(modifier = Modifier.size(12.dp), strokeWidth = 1.5.dp) + Text( + text = if (working) "Working" else "Idle", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} + +@Composable +private fun JobRow(kind: JobKind, name: String, subtitle: String, working: Boolean, shape: Shape, onClick: () -> Unit) { + GroupedItem( + shape = shape, + onClick = onClick, + leading = { IconTile(kind.icon(), Tone.Lavender) }, + trailing = { JobStatusLabel(working) }, + ) { + RowTitle(name, maxLines = 1) + RowSubtitle(subtitle, maxLines = 1) + } +} + +/** A job in the chat; the job list's status wins over the one its tool result reported. */ +@Composable +fun JobCard(model: AppModel, job: JobRef) { + val status = model.jobs.firstOrNull { it.name == job.name }?.status ?: job.status + JobRow(job.kind, job.name, job.kind.label, jobWorking(status), groupedShape(0, 1)) { model.openJob(job) } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun JobDialog( + onClose: () -> Unit, + title: @Composable () -> Unit, + actions: @Composable () -> Unit = {}, + content: @Composable (PaddingValues) -> Unit, +) { + Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false)) { + Scaffold( + containerColor = pageColor, + topBar = { + TopAppBar( + colors = TopAppBarDefaults.topAppBarColors(containerColor = pageColor, scrolledContainerColor = pageColor), + title = title, + navigationIcon = { + IconButton(onClick = onClose) { Icon(Icons.Default.Close, contentDescription = "Close") } + }, + actions = { actions() }, + ) + }, + content = content, + ) + } +} + +@Composable +private fun JobLoadError(text: String, onRetry: () -> Unit) { + Surface(color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.5f), shape = RoundedCornerShape(12.dp), modifier = Modifier.fillMaxWidth()) { + Row( + modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text(text, style = MaterialTheme.typography.bodySmall, modifier = Modifier.weight(1f)) + OutlinedButton(onClick = onRetry) { Text("Try again") } + } + } +} + +@Composable +fun JobListDialog(model: AppModel) { + val onClose = { model.closeJobList() } + JobDialog(onClose = onClose, title = { Text("Jobs") }) { padding -> + Column(modifier = Modifier.fillMaxSize().padding(padding)) { + model.selectedAgent?.takeIf { "desktop" in it.tools.orEmpty() }?.let { bot -> + DesktopPreviewSection(model, bot.id) + } + LazyColumn( + modifier = Modifier.fillMaxWidth().weight(1f), + contentPadding = PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(ROW_GAP), + ) { + if (model.jobsFailed) { + item { JobLoadError("Couldn't load jobs.", onRetry = { model.openJobList() }) } + } + if (!model.jobsLoaded && !model.jobsFailed) { + item { + Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp) } + } + } + if (model.jobsLoaded && model.jobs.isEmpty()) { + item { Text("Nothing here yet.", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } + } + itemsIndexed(model.jobs, key = { _, job -> "${job.kind}:${job.name}" }) { index, job -> + JobRow( + job.kind, + job.name, + listOf(job.kind.label, job.subtitle).filter { it.isNotEmpty() }.joinToString(" · "), + jobWorking(job.status), + groupedShape(index, model.jobs.size), + ) { + model.openJob(job.ref) + } + } + } + } + } +} + +@Composable +private fun JobTitle(job: JobRef, current: JobSummary?) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Icon(job.kind.icon(), contentDescription = null, modifier = Modifier.size(18.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant) + Column { + Text(job.name, style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.SemiBold), maxLines = 1, overflow = TextOverflow.Ellipsis) + val subtitle = current?.subtitle.orEmpty() + if (subtitle.isNotEmpty()) { + Text(subtitle, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + } +} + +@Composable +private fun JobDownloadButton(model: AppModel, panel: JobPanel) { + val context = LocalContext.current + val save = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("text/markdown")) { uri -> + if (uri != null) { + model.downloadJobTranscript { markdown -> + withContext(Dispatchers.IO) { + val stream = checkNotNull(context.contentResolver.openOutputStream(uri)) { "The file could not be opened." } + stream.use { it.write(markdown.toByteArray()) } + } + } + } + } + if (panel.downloading) { + CircularProgressIndicator(modifier = Modifier.padding(12.dp).size(20.dp), strokeWidth = 2.dp) + } else { + IconButton(onClick = { save.launch("${panel.job.name}.md") }) { + Icon(Icons.Default.Download, contentDescription = "Download transcript") + } + } +} + +@Composable +private fun JobStep(step: JobItem.Step, shape: Shape) { + var open by remember(step.id) { mutableStateOf(false) } + val result = step.result + GroupedItem( + shape = shape, + onClick = { open = !open }, + enabled = result != null, + leading = { + ToneTile(Tone.Lavender) { + if (result == null) { + CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp, color = LocalContentColor.current) + } else { + Icon(stepIcon(step.tool), contentDescription = null) + } + } + }, + trailing = { + if (result?.isError == true) { + Text("Failed", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.error) + } + if (result != null) { + Icon(if (open) Icons.Default.ExpandLess else Icons.Default.ExpandMore, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant) + } + }, + below = if (open && result != null) { + { + Box( + modifier = Modifier + .fillMaxWidth() + .background(sheetColor, RoundedCornerShape(8.dp)) + .horizontalScroll(rememberScrollState()) + .padding(8.dp), + ) { + Text( + text = result.text.trimEnd('\n').ifEmpty { "No output." }, + style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace), + ) + } + } + } else { + null + }, + ) { + RowTitle(jobStepVerb(step.tool), maxLines = 1) + step.subject?.takeIf { it.isNotEmpty() }?.let { RowSubtitle(it, maxLines = 1, fontFamily = FontFamily.Monospace) } + } +} + +@Composable +private fun JobItemView(item: JobItem, shape: Shape) { + when (item) { + is JobItem.Task -> Column(verticalArrangement = Arrangement.spacedBy(ROW_GAP)) { + GroupLabel("Task") + GroupCard { Text(item.text, style = MaterialTheme.typography.bodyMedium) } + } + is JobItem.Reply -> MarkdownText(text = item.text) + is JobItem.Step -> JobStep(item, shape) + } +} + +// With the list's ROW_GAP, this keeps 16dp between blocks; consecutive steps stay one group. +private val BLOCK_GAP = 13.dp + +/** A job's task, replies and tool steps, read-only, over the chat. */ +@Composable +fun JobPanelDialog(model: AppModel, panel: JobPanel) { + val job = panel.job + val current = model.jobs.firstOrNull { it.ref == job } + val working = jobWorking(current?.status) + val items = remember(panel.messages) { jobItems(panel.messages) } + JobDialog( + onClose = { model.closeJob() }, + title = { JobTitle(job, current) }, + actions = { + JobStatusLabel(working) + if (job.kind == JobKind.desktop) { + IconButton(onClick = { model.openBotDesktop() }) { + Icon(Icons.Default.DesktopWindows, contentDescription = "Bot desktop") + } + } + JobDownloadButton(model, panel) + }, + ) { padding -> + Column(modifier = Modifier.fillMaxSize().padding(padding)) { + if (panel.downloadFailed) { + Text( + text = "Couldn't download the transcript. Try again.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = 16.dp), + ) + } + current?.question?.let { question -> + Box(modifier = Modifier.padding(16.dp)) { JobQuestionAnswer(model, job.name, question) } + } + // Reverse layout keeps the newest step in view as the job works. + LazyColumn( + modifier = Modifier.weight(1f).fillMaxWidth(), + reverseLayout = true, + contentPadding = PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(ROW_GAP, Alignment.Bottom), + ) { + if (working) { + item(key = "working") { Text("Working…", style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(top = BLOCK_GAP)) } + } + itemsIndexed(items.asReversed(), key = { _, item -> item.id }) { reversedIndex, item -> + val index = items.lastIndex - reversedIndex + val afterStep = item is JobItem.Step && items.getOrNull(index - 1) is JobItem.Step + val beforeStep = item is JobItem.Step && items.getOrNull(index + 1) is JobItem.Step + val position = if (afterStep) 1 else 0 + Box(modifier = Modifier.fillMaxWidth().padding(top = if (afterStep) 0.dp else BLOCK_GAP)) { + JobItemView(item, groupedShape(position, position + if (beforeStep) 2 else 1)) + } + } + if (panel.loaded && items.isEmpty()) { + item(key = "empty") { Text("Nothing here yet.", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } + } + if (panel.failed) { + item(key = "failed") { JobLoadError("Couldn't load this ${job.kind.label.lowercase()}.", onRetry = { model.retryJobHistory() }) } + } + if (!panel.loaded && !panel.failed) { + item(key = "loading") { + Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp) } + } + } + if (panel.hasMore) { + item(key = "earlier") { + TextButton(enabled = !panel.loadingEarlier, onClick = { model.loadEarlierJobActivity() }) { Text("Load earlier activity") } + } + } + } + } + } +} diff --git a/app/src/main/java/dev/crumble/android/ui/MarkdownText.kt b/app/src/main/java/dev/crumble/android/ui/MarkdownText.kt index a80748b..a6936ff 100644 --- a/app/src/main/java/dev/crumble/android/ui/MarkdownText.kt +++ b/app/src/main/java/dev/crumble/android/ui/MarkdownText.kt @@ -1,6 +1,7 @@ package dev.crumble.android.ui 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 @@ -21,17 +22,35 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.Layout +import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.LinkAnnotation +import androidx.compose.ui.text.LinkInteractionListener import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextLinkStyles 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.TextAlign +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.text.withLink import androidx.compose.ui.text.withStyle +import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.dp +import dev.crumble.android.model.isWebLink + +private val MAX_CELL_WIDTH = 240.dp +private val BARE_URL = Regex("https?://[^\\s<>\"]+") +private val ANGLE_URL = Regex("<(https?://[^\\s<>\"]+)>") +private val LINK_TARGET = Regex("(?:<([^<>\\n]*)>|([^<>\\s]*?))(?:\\s+(?:\"[^\"]*\"|'[^']*'|\\([^)]*\\)))?") +private val TABLE_DELIMITER_CELL = Regex(":?-+:?") +private const val ESCAPABLE = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" +private const val URL_END_PUNCTUATION = ".,:;!?'*_~" /** - * Renders agent replies: headings, lists, quotes, and code blocks, with inline Markdown inside them. + * Renders agent replies: headings, lists, quotes, tables, and code blocks, with inline Markdown inside them. * Unfinished streaming text renders too; an open code fence simply runs to the end. */ @Composable @@ -41,6 +60,9 @@ fun MarkdownText( ) { val blocks = remember(text) { MarkdownBlock.parse(text) } val contentColor = LocalContentColor.current + val uriHandler = LocalUriHandler.current + val linkStyles = TextLinkStyles(SpanStyle(color = MaterialTheme.colorScheme.primary, textDecoration = TextDecoration.Underline)) + val inline = { source: String -> inlineMarkdown(source, linkStyles) { url -> runCatching { uriHandler.openUri(url) } } } Column( modifier = modifier, verticalArrangement = Arrangement.spacedBy(6.dp), @@ -49,7 +71,7 @@ fun MarkdownText( when (block) { is MarkdownBlock.Paragraph -> { Text( - text = inlineMarkdown(block.text), + text = inline(block.text), color = contentColor, style = MaterialTheme.typography.bodyMedium, ) @@ -61,7 +83,7 @@ fun MarkdownText( else -> MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Bold) } Text( - text = inlineMarkdown(block.text), + text = inline(block.text), color = contentColor, style = style, ) @@ -80,7 +102,7 @@ fun MarkdownText( style = MaterialTheme.typography.bodyMedium, ) Text( - text = inlineMarkdown(item.text), + text = inline(item.text), color = contentColor, style = MaterialTheme.typography.bodyMedium, ) @@ -100,12 +122,13 @@ fun MarkdownText( .background(contentColor.copy(alpha = 0.35f), CircleShape), ) Text( - text = inlineMarkdown(block.text), + text = inline(block.text), color = contentColor.copy(alpha = 0.78f), style = MaterialTheme.typography.bodyMedium, ) } } + is MarkdownBlock.Table -> MarkdownTable(block, inline) is MarkdownBlock.Code -> { Box( modifier = Modifier @@ -128,10 +151,80 @@ fun MarkdownText( } } -fun inlineMarkdown(text: String): AnnotatedString = buildAnnotatedString { +/** Cells wrap at a capped width and rows line up across columns, so a wide table scrolls sideways. */ +@Composable +private fun MarkdownTable(table: MarkdownBlock.Table, inline: (String) -> AnnotatedString) { + val contentColor = LocalContentColor.current + val columns = table.header.size + + @Composable + fun Cell(text: String, column: Int, weight: FontWeight?) { + Text( + text = inline(text), + color = contentColor, + style = MaterialTheme.typography.bodySmall, + fontWeight = weight, + textAlign = table.align[column], + modifier = Modifier + .border(0.5.dp, contentColor.copy(alpha = 0.25f)) + .padding(horizontal = 8.dp, vertical = 4.dp), + ) + } + Layout( + modifier = Modifier.horizontalScroll(rememberScrollState()), + content = { + table.header.forEachIndexed { column, text -> Cell(text, column, FontWeight.SemiBold) } + for (row in table.rows) row.forEachIndexed { column, text -> Cell(text, column, null) } + }, + ) { measurables, _ -> + val rows = measurables.chunked(columns) + val cap = MAX_CELL_WIDTH.roundToPx() + val widths = List(columns) { column -> rows.maxOf { minOf(it[column].maxIntrinsicWidth(Constraints.Infinity), cap) } } + val heights = rows.map { row -> row.indices.maxOf { row[it].minIntrinsicHeight(widths[it]) } } + val cells = rows.mapIndexed { y, row -> + row.mapIndexed { x, cell -> cell.measure(Constraints.fixed(widths[x], heights[y])) } + } + layout(widths.sum(), heights.sum()) { + var top = 0 + cells.forEachIndexed { y, row -> + var left = 0 + row.forEachIndexed { x, cell -> + cell.place(left, top) + left += widths[x] + } + top += heights[y] + } + } + } +} + +/** `onLink` handles a tap; without it Compose opens the link itself. Only web links become tappable. */ +fun inlineMarkdown( + text: String, + linkStyles: TextLinkStyles? = null, + onLink: ((String) -> Unit)? = null, +): AnnotatedString = buildAnnotatedString { + appendInline(text, inLink = false) { url -> + LinkAnnotation.Url(url, linkStyles, onLink?.let { open -> LinkInteractionListener { open(url) } }) + } +} + +private fun AnnotatedString.Builder.appendInline(text: String, inLink: Boolean, linkTo: (String) -> LinkAnnotation) { + fun marked(style: SpanStyle, inner: String) = withStyle(style) { appendInline(inner, inLink, linkTo) } + + fun linked(url: String, label: String) = when { + inLink || !isWebLink(url) -> appendInline(label, inLink, linkTo) + else -> withLink(linkTo(url)) { appendInline(label, inLink = true, linkTo) } + } + var i = 0 val n = text.length while (i < n) { + if (text[i] == '\\' && i + 1 < n && text[i + 1] in ESCAPABLE) { + append(text[i + 1]) + i += 2 + continue + } if (text.startsWith("`", i)) { val end = text.indexOf('`', i + 1) if (end > i) { @@ -142,13 +235,51 @@ fun inlineMarkdown(text: String): AnnotatedString = buildAnnotatedString { continue } } + if (text[i] == '[' || text.startsWith("![", i)) { + // Replies show no remote images, so an image reads as a link to it. + val link = inlineLink(text, if (text[i] == '!') i + 1 else i) + if (link != null) { + linked(link.target, link.label.ifEmpty { link.target }) + i = link.end + continue + } + } + if (text[i] == '<' && !inLink) { + val url = ANGLE_URL.matchAt(text, i) + if (url != null) { + linked(url.groupValues[1], url.groupValues[1]) + i = url.range.last + 1 + continue + } + } + if (text[i] == 'h' && !inLink && text.getOrNull(i - 1)?.isLetterOrDigit() != true) { + val url = BARE_URL.matchAt(text, i)?.value?.let(::trimUrl) + if (url != null && url.length > "https://".length) { + linked(url, url) + i += url.length + continue + } + } + if (text.startsWith("~~~", i)) { + val run = text.drop(i).takeWhile { it == '~' } + append(run) + i += run.length + continue + } + if (text[i] == '~') { + val size = if (text.startsWith("~~", i)) 2 else 1 + val end = strikeEnd(text, i + size, size) + if (end > i) { + marked(SpanStyle(textDecoration = TextDecoration.LineThrough), text.substring(i + size, end)) + i = end + size + continue + } + } if (text.startsWith("**", i) || text.startsWith("__", i)) { val delim = text.substring(i, i + 2) val end = text.indexOf(delim, i + 2) if (end > i) { - withStyle(SpanStyle(fontWeight = FontWeight.Bold)) { - append(text.substring(i + 2, end)) - } + marked(SpanStyle(fontWeight = FontWeight.Bold), text.substring(i + 2, end)) i = end + 2 continue } @@ -156,9 +287,7 @@ fun inlineMarkdown(text: String): AnnotatedString = buildAnnotatedString { if (text.startsWith("*", i) && !text.startsWith("**", i)) { val end = text.indexOf('*', i + 1) if (end > i) { - withStyle(SpanStyle(fontStyle = FontStyle.Italic)) { - append(text.substring(i + 1, end)) - } + marked(SpanStyle(fontStyle = FontStyle.Italic), text.substring(i + 1, end)) i = end + 1 continue } @@ -168,6 +297,57 @@ fun inlineMarkdown(text: String): AnnotatedString = buildAnnotatedString { } } +private class InlineLink(val label: String, val target: String, val end: Int) + +private fun inlineLink(text: String, open: Int): InlineLink? { + val close = balancedEnd(text, open, '[', ']') + if (close < 0 || text.getOrNull(close + 1) != '(') return null + val end = balancedEnd(text, close + 1, '(', ')') + if (end < 0) return null + val target = LINK_TARGET.matchEntire(text.substring(close + 2, end).trim()) ?: return null + return InlineLink(text.substring(open + 1, close), target.groupValues[1].ifEmpty { target.groupValues[2] }, end + 1) +} + +private fun balancedEnd(text: String, open: Int, opening: Char, closing: Char): Int { + var depth = 0 + var i = open + while (i < text.length) { + when (text[i]) { + '\\' -> i++ + opening -> depth++ + closing -> if (--depth == 0) return i + } + i++ + } + return -1 +} + +/** Drops what GitHub drops from a bare URL's end: sentence punctuation, and closing brackets it didn't open. */ +private fun trimUrl(url: String): String { + var end = url.length + while (end > 0) { + val kept = url.substring(0, end) + val unopened = kept.last() == ')' && kept.count { it == ')' } > kept.count { it == '(' } + if (kept.last() !in URL_END_PUNCTUATION && !unopened) break + end-- + } + return url.substring(0, end) +} + +/** One tilde must hug its text, so "~5 min" and "~ 6" stay as written. */ +private fun strikeEnd(text: String, start: Int, size: Int): Int { + if (size == 1 && text.getOrNull(start)?.let { it.isWhitespace() || it.isDigit() } != false) return -1 + val delimiter = "~".repeat(size) + var index = text.indexOf(delimiter, start) + while (index >= 0) { + if (text[index - 1] != '~' && text.getOrNull(index + size) != '~') { + return if (size == 1 && text[index - 1].isWhitespace()) -1 else index + } + index = text.indexOf(delimiter, index + 1) + } + return -1 +} + sealed class MarkdownBlock { data class Item( val marker: String, @@ -181,6 +361,13 @@ sealed class MarkdownBlock { data class Quote(val text: String) : MarkdownBlock() data class Code(val code: String) : MarkdownBlock() + /** Every row has as many cells as `header`, and `align` holds one alignment per column. */ + data class Table( + val header: List, + val align: List, + val rows: List>, + ) : MarkdownBlock() + companion object { fun parse(text: String): List { val blocks = mutableListOf() @@ -198,7 +385,10 @@ sealed class MarkdownBlock { quote = mutableListOf() } - for (line in text.split("\n")) { + val lines = text.split("\n") + var index = -1 + while (++index < lines.size) { + val line = lines[index] val trimmed = line.trim() val codeLines = code if (codeLines != null) { @@ -236,6 +426,19 @@ sealed class MarkdownBlock { if (paragraph.isNotEmpty() || items.isNotEmpty()) flush() quote.add(trimmed.drop(1).trim()) } + isTableHeader(line, lines.getOrNull(index + 1)) -> { + flush() + val header = tableCells(line) + val align = tableCells(lines[index + 1]).map(::columnAlign) + val rows = mutableListOf>() + index += 1 + while (index + 1 < lines.size && !endsTable(lines[index + 1], lines.getOrNull(index + 2))) { + index += 1 + val cells = tableCells(lines[index]) + rows.add(header.indices.map { cells.getOrElse(it) { "" } }) + } + blocks.add(Table(header, align, rows)) + } items.isNotEmpty() && line.startsWith(" ") -> { val last = items.last() items[items.lastIndex] = last.copy(text = "${last.text} $trimmed") @@ -252,6 +455,47 @@ sealed class MarkdownBlock { return blocks } + private fun isTableHeader(header: String, delimiter: String?): Boolean { + if (delimiter == null || '|' !in header) return false + val cells = tableCells(delimiter) + return cells.size == tableCells(header).size && cells.all(TABLE_DELIMITER_CELL::matches) + } + + private fun endsTable(line: String, next: String?): Boolean { + val trimmed = line.trim() + return trimmed.isEmpty() || trimmed.startsWith("```") || trimmed.startsWith(">") || + headingLevel(trimmed) != null || listItem(line) != null || isTableHeader(line, next) + } + + private fun tableCells(line: String): List { + val row = line.trim() + val cells = mutableListOf() + val current = StringBuilder() + var i = if (row.startsWith("|")) 1 else 0 + while (i < row.length) { + when { + row.startsWith("\\|", i) -> { + current.append('|') + i++ + } + row[i] == '|' -> { + cells.add(current.toString().trim()) + current.clear() + } + else -> current.append(row[i]) + } + i++ + } + if (current.isNotEmpty() || !row.endsWith("|") || cells.isEmpty()) cells.add(current.toString().trim()) + return cells + } + + private fun columnAlign(delimiter: String): TextAlign = when { + delimiter.startsWith(":") && delimiter.endsWith(":") -> TextAlign.Center + delimiter.endsWith(":") -> TextAlign.End + else -> TextAlign.Start + } + private fun headingLevel(line: String): Int? { val hashes = line.takeWhile { it == '#' }.length if (hashes !in 1..6) return null diff --git a/app/src/main/java/dev/crumble/android/ui/NativeLook.kt b/app/src/main/java/dev/crumble/android/ui/NativeLook.kt new file mode 100644 index 0000000..b60b6bb --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/NativeLook.kt @@ -0,0 +1,330 @@ +package dev.crumble.android.ui + +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.material3.LocalContentColor +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.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +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.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +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.graphics.Shape +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp + +private val OUTER_CORNER = 24.dp +private val INNER_CORNER = 6.dp +val ROW_GAP = 3.dp + +/** Android's page color; cards sit on it with `cardColor`. */ +val pageColor: Color @Composable get() = MaterialTheme.colorScheme.surfaceContainer +val cardColor: Color @Composable get() = MaterialTheme.colorScheme.surfaceContainerHighest + +/** The darker sheet under Messages' conversation list, and its chats. */ +val sheetColor: Color @Composable get() = MaterialTheme.colorScheme.surfaceContainerLowest + +/** Rows in a group share one rounded outline, like the system Settings app. */ +fun groupedShape(index: Int, count: Int): Shape = RoundedCornerShape( + topStart = if (index == 0) OUTER_CORNER else INNER_CORNER, + topEnd = if (index == 0) OUTER_CORNER else INNER_CORNER, + bottomStart = if (index == count - 1) OUTER_CORNER else INNER_CORNER, + bottomEnd = if (index == count - 1) OUTER_CORNER else INNER_CORNER, +) + +/** Fixed hues, as in the system Settings app, so tiles stay colored on a neutral wallpaper. */ +enum class Tone(val container: Color, val content: Color) { + Blue(Color(0xFF7BD3FF), Color(0xFF00405A)), + Lavender(Color(0xFFB4C8FF), Color(0xFF12337A)), + Pink(Color(0xFFFFB0E6), Color(0xFF6E0052)), + Orange(Color(0xFFFFB877), Color(0xFF5A2A00)), + Green(Color(0xFF9FE3B0), Color(0xFF0B4A24)), +} + +@Composable +fun ToneTile(tone: Tone, content: @Composable () -> Unit) { + Box( + modifier = Modifier.size(44.dp).background(tone.container, CircleShape), + contentAlignment = Alignment.Center, + ) { + CompositionLocalProvider(LocalContentColor provides tone.content) { content() } + } +} + +@Composable +fun IconTile(icon: ImageVector, tone: Tone) { + ToneTile(tone) { Icon(icon, contentDescription = null) } +} + +/** A tile with a name's first letter, for rows that have no avatar or icon of their own. */ +@Composable +fun LetterTile(name: String, tone: Tone = Tone.Lavender) { + ToneTile(tone) { + Text(name.take(1).uppercase(), style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold)) + } +} + +@Composable +fun GroupedRow( + title: String, + shape: Shape, + onClick: () -> Unit, + subtitle: String? = null, + enabled: Boolean = true, + titleColor: Color = Color.Unspecified, + leading: @Composable (() -> Unit)? = null, +) { + Surface( + onClick = onClick, + enabled = enabled, + shape = shape, + color = cardColor, + modifier = Modifier.fillMaxWidth(), + ) { + Row( + modifier = Modifier.heightIn(min = 72.dp).padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(16.dp), + ) { + leading?.invoke() + Column(modifier = Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.titleMedium, color = titleColor, maxLines = 1, overflow = TextOverflow.Ellipsis) + subtitle?.takeIf { it.isNotBlank() }?.let { + Text( + text = it, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + } + } +} + +@Composable +fun RowTitle(text: String, modifier: Modifier = Modifier, maxLines: Int = 2, fontFamily: FontFamily? = null, fontWeight: FontWeight? = null) { + Text( + text, + style = MaterialTheme.typography.titleMedium, + fontFamily = fontFamily, + fontWeight = fontWeight, + maxLines = maxLines, + overflow = TextOverflow.Ellipsis, + modifier = modifier, + ) +} + +@Composable +fun RowSubtitle( + text: String, + color: Color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines: Int = Int.MAX_VALUE, + overflow: TextOverflow = TextOverflow.Ellipsis, + fontFamily: FontFamily? = null, +) { + Text(text, style = MaterialTheme.typography.bodyMedium, color = color, fontFamily = fontFamily, maxLines = maxLines, overflow = overflow) +} + +/** + * A grouped row for what GroupedRow can't hold: trailing controls, extra lines, and content below. + * `onClick` covers the head of the row, and the content below as well with `clickBelow`. + */ +@Composable +fun GroupedItem( + shape: Shape, + onClick: (() -> Unit)? = null, + enabled: Boolean = true, + clickBelow: Boolean = false, + leading: (@Composable () -> Unit)? = null, + trailing: @Composable RowScope.() -> Unit = {}, + below: (@Composable ColumnScope.() -> Unit)? = null, + content: @Composable ColumnScope.() -> Unit, +) { + val click = if (onClick != null) Modifier.clickable(enabled = enabled, onClick = onClick) else Modifier + Surface(shape = shape, color = cardColor, modifier = Modifier.fillMaxWidth()) { + Column(modifier = if (clickBelow) click else Modifier) { + Row( + modifier = Modifier + .fillMaxWidth() + .then(if (clickBelow) Modifier else click) + .heightIn(min = 72.dp) + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(16.dp), + ) { + leading?.invoke() + Column(modifier = Modifier.weight(1f), content = content) + trailing() + } + if (below != null) { + Column( + modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, bottom = 12.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + content = below, + ) + } + } + } +} + +/** A line of text in a group: an empty state, a note, or an error. */ +@Composable +fun GroupedNote(text: String, shape: Shape, isError: Boolean = false, fontFamily: FontFamily? = null) { + Surface(shape = shape, color = cardColor, modifier = Modifier.fillMaxWidth()) { + Text( + text, + style = MaterialTheme.typography.bodyMedium, + color = if (isError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, + fontFamily = fontFamily, + modifier = Modifier.padding(16.dp), + ) + } +} + +/** Collects a group's rows, so each gets its groupedShape whichever rows are showing. */ +class GroupScope { + internal val rows = mutableListOf<@Composable (Shape) -> Unit>() + + fun row(content: @Composable (Shape) -> Unit) { + rows += content + } + + fun note(text: String, isError: Boolean = false, fontFamily: FontFamily? = null) { + row { shape -> GroupedNote(text, shape, isError, fontFamily) } + } + + /** The row that adds to a group, like New group chat on Home. */ + fun add(title: String, enabled: Boolean = true, onClick: () -> Unit) { + row { shape -> + GroupedRow(title = title, shape = shape, onClick = onClick, enabled = enabled, leading = { IconTile(Icons.Default.Add, Tone.Lavender) }) + } + } +} + +@Composable +fun GroupedRows(build: GroupScope.() -> Unit) { + val rows = GroupScope().apply(build).rows + Column(verticalArrangement = Arrangement.spacedBy(ROW_GAP)) { + rows.forEachIndexed { index, row -> row(groupedShape(index, rows.size)) } + } +} + +/** A flat row on the sheet, like a conversation in Messages. */ +@Composable +fun ConversationRow( + title: String, + onClick: () -> Unit, + preview: String? = null, + enabled: Boolean = true, + trailing: @Composable () -> Unit = {}, + leading: @Composable () -> Unit, +) { + Surface(onClick = onClick, enabled = enabled, color = Color.Transparent, modifier = Modifier.fillMaxWidth()) { + Row( + modifier = Modifier.heightIn(min = 84.dp).padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(16.dp), + ) { + leading() + Column(modifier = Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.titleLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) + preview?.takeIf { it.isNotBlank() }?.let { + Text( + text = it, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + trailing() + } + } +} + +/** A flat conversation list on a rounded sheet, with room below it for a floating button. */ +@Composable +fun ConversationSheet(content: LazyListScope.() -> Unit) { + Surface( + color = sheetColor, + shape = RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp), + modifier = Modifier.fillMaxSize(), + ) { + LazyColumn(contentPadding = PaddingValues(top = 8.dp, bottom = 96.dp), content = content) + } +} + +/** A plain card of content, for forms and switches. */ +@Composable +fun GroupCard(shape: Shape = RoundedCornerShape(OUTER_CORNER), content: @Composable () -> Unit) { + Surface(shape = shape, color = cardColor, modifier = Modifier.fillMaxWidth()) { + Column( + modifier = Modifier.padding(16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + content() + } + } +} + +@Composable +fun GroupLabel(text: String) { + Text( + text = text, + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = 16.dp, top = 8.dp, bottom = 2.dp), + ) +} + +/** The search pill at the top of Messages and Settings. */ +@Composable +fun SearchPill( + hint: String, + onClick: () -> Unit, + modifier: Modifier = Modifier, + leading: @Composable () -> Unit, +) { + Surface( + onClick = onClick, + shape = CircleShape, + color = MaterialTheme.colorScheme.surfaceContainerLowest, + modifier = modifier.fillMaxWidth().heightIn(min = 56.dp), + ) { + Row( + modifier = Modifier.heightIn(min = 56.dp).padding(horizontal = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + leading() + Text(hint, style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } +} diff --git a/app/src/main/java/dev/crumble/android/ui/PanelScreen.kt b/app/src/main/java/dev/crumble/android/ui/PanelScreen.kt index 001077e..0fde6bf 100644 --- a/app/src/main/java/dev/crumble/android/ui/PanelScreen.kt +++ b/app/src/main/java/dev/crumble/android/ui/PanelScreen.kt @@ -1,5 +1,9 @@ package dev.crumble.android.ui +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.CardDefaults +import androidx.activity.compose.BackHandler +import android.content.Context import android.content.Intent import android.net.Uri import androidx.compose.animation.AnimatedVisibility @@ -8,9 +12,9 @@ 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.ColumnScope import androidx.compose.foundation.layout.PaddingValues 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 @@ -26,8 +30,6 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.ExpandLess import androidx.compose.material.icons.filled.ExpandMore -import androidx.compose.material.icons.filled.Schedule -import androidx.compose.material.icons.filled.Timeline import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults @@ -54,7 +56,12 @@ 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.Color +import androidx.compose.ui.graphics.Shape import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.style.TextAlign @@ -68,17 +75,12 @@ import dev.crumble.android.model.MCPServer import dev.crumble.android.model.Memory import dev.crumble.android.model.MemoryDraft import dev.crumble.android.model.Route -import dev.crumble.android.model.Schedule import dev.crumble.android.model.SkillDraft -import dev.crumble.android.model.TaskDraft +import dev.crumble.android.model.SKILLS_SHARED import dev.crumble.android.model.activityTime -import dev.crumble.android.model.timeLabel -import dev.crumble.android.model.displayLabel +import dev.crumble.android.model.matchesMCP +import dev.crumble.android.model.memoryLine import java.time.Instant -import java.time.LocalDateTime -import java.time.ZoneId -import java.time.ZonedDateTime -import java.time.format.DateTimeFormatter @Composable fun PanelView( @@ -86,6 +88,7 @@ fun PanelView( panel: Route, modifier: Modifier = Modifier, ) { + BackHandler { model.navigate(panel.parent) } Box(modifier = modifier.fillMaxSize()) { when (panel) { Route.Memory -> MemoryPanel(model) @@ -93,22 +96,53 @@ fun PanelView( Route.Tasks -> TasksPanel(model) Route.Activity -> ActivityPanel(model) Route.Integrations -> IntegrationsPanel(model) - is Route.AgentChat -> Unit + Route.Avatars -> AvatarsPanel(model) + Route.Providers -> ProvidersPanel(model) + Route.PasswordManagers -> PasswordManagersPanel(model) + Route.Credentials -> CredentialsPanel(model) + Route.Logins -> LoginsPanel(model) + Route.WebSearch -> WebSearchPanel(model) + Route.JudgeModel -> JudgeModelPanel(model) + Route.VisionModel -> VisionModelPanel(model) + Route.Coding -> CodingPanel(model) + Route.Users -> UsersPanel(model) + Route.MessageGateways -> MessageGatewaysPanel(model) + is Route.MessageGateway -> MessageGatewayPanel(model, panel.id) + Route.EventRelay -> EventRelayPanel(model) + Route.Settings -> SettingsPanel(model) + Route.General -> GeneralPanel(model) + Route.Account -> AccountPanel(model) + Route.NewChat -> NewChatPanel(model) + Route.NewGroup -> NewGroupPanel(model) + is Route.AgentChat, is Route.GroupChat -> Unit } } } +/** The text with every occurrence of `needle`, already lowercased, marked. */ +internal fun highlighted(text: String, needle: String, mark: Color): AnnotatedString = buildAnnotatedString { + append(text) + if (needle.isEmpty()) return@buildAnnotatedString + val lower = text.lowercase() + if (lower.length != text.length) return@buildAnnotatedString + var at = lower.indexOf(needle) + while (at >= 0) { + addStyle(SpanStyle(background = mark), at, at + needle.length) + at = lower.indexOf(needle, at + needle.length) + } +} + @Composable private fun MemoryPanel(model: AppModel) { var query by remember { mutableStateOf("") } - var scope by remember { mutableStateOf(null) } + val scope = model.memoryScope val normalizedQuery = query.trim().lowercase() val matches: (Memory) -> Boolean = { memory -> normalizedQuery.isEmpty() || memory.content.lowercase().contains(normalizedQuery) } val shared = model.sharedMemories.filter(matches) val scopedAgents = model.agents .filter { scope == null || scope == it.id } .filter { agent -> - scope != null || model.agentMemories[agent.id].orEmpty().any(matches) + scope != null || agent.id in model.memoryErrors || model.agentMemories[agent.id].orEmpty().any(matches) } val sharedEnabledBots = model.agents.filter { it.sharedMemory == true }.map { it.name } val sharedFooter = if (sharedEnabledBots.isEmpty()) { @@ -116,6 +150,8 @@ private fun MemoryPanel(model: AppModel) { } else { "Used by: ${sharedEnabledBots.joinToString(", ")}" } + val total = model.sharedMemories.size + model.agents.sumOf { model.agentMemories[it.id].orEmpty().size } + val now = Instant.now() LazyColumn( modifier = Modifier.fillMaxSize(), @@ -127,6 +163,7 @@ private fun MemoryPanel(model: AppModel) { value = query, onValueChange = { query = it }, label = { Text("Search memories") }, + shape = CircleShape, singleLine = true, modifier = Modifier.fillMaxWidth(), ) @@ -136,49 +173,48 @@ private fun MemoryPanel(model: AppModel) { .padding(top = 8.dp) .horizontalScroll(rememberScrollState()), ) { - FilterChip(selected = scope == null, onClick = { scope = null }, label = { Text("All") }) - FilterChip(selected = scope == "shared", onClick = { scope = "shared" }, label = { Text("Shared") }) + FilterChip(selected = scope == null, onClick = { model.memoryScope = null }, label = { Text("All · $total") }) + FilterChip(selected = scope == SKILLS_SHARED, onClick = { model.memoryScope = SKILLS_SHARED }, label = { Text("Shared · ${model.sharedMemories.size}") }) for (agent in model.agents) { - FilterChip(selected = scope == agent.id, onClick = { scope = agent.id }, label = { Text(agent.name) }) + FilterChip( + selected = scope == agent.id, + onClick = { model.memoryScope = agent.id }, + label = { Text("${agent.name} · ${model.agentMemories[agent.id].orEmpty().size}") }, + leadingIcon = { BotAvatarView(agent = agent, size = 18.dp) }, + ) } } } item { - if (scope != null && scope != "shared") return@item - SectionCard( + if (scope != null && scope != SKILLS_SHARED) return@item + RowsSection( title = "Shared · ${model.sharedMemories.size}", footer = sharedFooter, expandable = true, ) { - if (shared.isEmpty()) { - Text( - text = if (normalizedQuery.isEmpty()) "No shared memories yet." else "No matching shared memories.", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) + model.memoryErrors[SKILLS_SHARED]?.let { note(it, isError = true) } + if (shared.isEmpty() && SKILLS_SHARED !in model.memoryErrors) { + note(if (normalizedQuery.isEmpty()) "No shared memories yet." else "No matching shared memories.") } for (memory in shared) { - MemoryRow(model = model, memory = memory, agentID = null) + row { shape -> MemoryRow(model = model, memory = memory, agentID = null, needle = normalizedQuery, now = now, shape = shape) } } } } - items(scopedAgents.filter { scope != "shared" }, key = { it.id }) { agent -> + items(scopedAgents.filter { scope != SKILLS_SHARED }, key = { it.id }) { agent -> val memories = model.agentMemories[agent.id].orEmpty().filter(matches) val totalMemories = model.agentMemories[agent.id].orEmpty().size - SectionCard( + RowsSection( title = "${agent.name} · $totalMemories", expandable = true, ) { - if (memories.isEmpty()) { - Text( - text = if (normalizedQuery.isEmpty()) "No memories yet." else "No matching memories.", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) + model.memoryErrors[agent.id]?.let { note(it, isError = true) } + if (memories.isEmpty() && agent.id !in model.memoryErrors) { + note(if (normalizedQuery.isEmpty()) "No memories yet." else "No matching memories.") } for (memory in memories) { - MemoryRow(model = model, memory = memory, agentID = agent.id) + row { shape -> MemoryRow(model = model, memory = memory, agentID = agent.id, needle = normalizedQuery, now = now, shape = shape) } } } } @@ -190,29 +226,30 @@ private fun MemoryRow( model: AppModel, memory: Memory, agentID: String?, + needle: String, + now: Instant, + shape: Shape, ) { val isPending = memory.id.startsWith("pending-") var confirmingDelete by remember(memory.id) { mutableStateOf(false) } - Column(modifier = Modifier.fillMaxWidth()) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(vertical = 4.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text( - text = memory.content, - style = MaterialTheme.typography.bodyMedium, - modifier = Modifier.weight(1f), - ) - TextButton(onClick = { model.openMemoryForm(memory.id, agentID = agentID) }, enabled = !isPending) { Text("Edit") } - TextButton( - onClick = { confirmingDelete = true }, - enabled = !isPending, - colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error), - ) { Text("Delete") } - } + val mark = MaterialTheme.colorScheme.tertiaryContainer + val line = memoryLine(memory, now) + GroupedItem( + shape = shape, + leading = { IconTile(routeIcon(Route.Memory), Tone.Lavender) }, + below = { + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = { model.openMemoryForm(memory.id, agentID = agentID) }, enabled = !isPending) { Text("Edit") } + TextButton( + onClick = { confirmingDelete = true }, + enabled = !isPending, + colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error), + ) { Text("Delete") } + } + }, + ) { + Text(text = highlighted(memory.content, needle, mark), style = MaterialTheme.typography.titleMedium) + if (line.isNotEmpty()) RowSubtitle(line) } if (confirmingDelete) { AlertDialog( @@ -233,430 +270,52 @@ private fun MemoryRow( } @Composable -private fun SkillsPanel(model: AppModel) { +private fun IntegrationsPanel(model: AppModel) { + val appContext = LocalContext.current.applicationContext + var search by remember { mutableStateOf("") } + val needle = search.trim().lowercase() + val listed = model.mcpServers.filter { matchesMCP(it, needle) } LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp), ) { item { - SectionCard( - title = "Shared skills", - footer = "Optional shared skills can be assigned to individual bots. Built-in defaults apply to every bot.", - ) { - if (model.sharedSkills.isEmpty()) { - Text( - text = "No shared skills yet.", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - for (skill in model.sharedSkills.filter { !it.isDefault }) { - var expanded by remember(skill.id) { mutableStateOf(false) } - val isPending = skill.id.startsWith("pending-") - Column(modifier = Modifier.fillMaxWidth()) { - Row( - modifier = Modifier - .fillMaxWidth() - .clickable { expanded = !expanded } - .padding(vertical = 4.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Column(modifier = Modifier.weight(1f)) { - Text( - text = skill.name, - style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.SemiBold), - ) - val sub = if (skill.isDefault) { - "Default · Every bot" - } else { - val enabled = model.agents - .filter { it.sharedSkills?.contains(skill.id) == true } - .map { it.name } - if (enabled.isEmpty()) "No bots enabled" else "Enabled for: ${enabled.joinToString(", ")}" - } - Text( - text = sub, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - if (!skill.isDefault) { - val pending = model.pendingMutations.contains("skill:${skill.id}") - TextButton( - onClick = { model.openSkillForm(skill.id) }, - enabled = !isPending && !pending, - ) { - Text("Edit") - } - TextButton( - onClick = { model.deleteSharedSkill(skill.id) }, - enabled = !isPending && !pending, - ) { - Text("Delete", color = MaterialTheme.colorScheme.error) - } - } - Icon( - imageVector = if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore, - contentDescription = null, - ) - } - AnimatedVisibility(visible = expanded) { - Column( - modifier = Modifier.padding(top = 4.dp, bottom = 8.dp), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - Text( - text = skill.instructions, - style = MaterialTheme.typography.bodySmall, - ) - if (!skill.path.isNullOrEmpty()) { - Text( - text = "Source: ${skill.path}", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - if (!skill.isDefault) { - Text( - text = "Assign to bots", - style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.SemiBold), - modifier = Modifier.padding(top = 6.dp), - ) - for (agent in model.agents) { - val enabled = agent.sharedSkills?.contains(skill.id) == true - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, - ) { - Text(agent.name, style = MaterialTheme.typography.bodySmall) - Switch( - checked = enabled, - enabled = !model.pendingMutations.contains("agent-shared-skills:${agent.id}"), - onCheckedChange = { model.setSharedSkillEnabled(agent.id, skill.id, it) }, - ) - } - } - } - } - } - } - } - val builtIns = model.sharedSkills.filter { it.isDefault } - if (builtIns.isNotEmpty()) { - Text( - text = "Built-in skills", - style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.SemiBold), - modifier = Modifier.padding(top = 8.dp), - ) - for (skill in builtIns) { - var expanded by remember(skill.id) { mutableStateOf(false) } - Column(modifier = Modifier.fillMaxWidth()) { - Row( - modifier = Modifier - .fillMaxWidth() - .clickable { expanded = !expanded } - .padding(vertical = 4.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text(skill.name, modifier = Modifier.weight(1f)) - Text("Every bot", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - Icon(if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore, contentDescription = null) - } - AnimatedVisibility(expanded) { - Text(skill.instructions, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(bottom = 6.dp)) - } - } - } - } - TextButton(onClick = { model.openSkillForm("") }) { - Icon(Icons.Default.Add, contentDescription = null, modifier = Modifier.size(18.dp)) - Spacer(Modifier.size(4.dp)) - Text("Add shared skill") - } - } - } - - items(model.agents, key = { it.id }) { agent -> - val skills = agent.skills.orEmpty() - SectionCard( - title = agent.name, - footer = "Personal skills only ${agent.name} follows.", - ) { - if (skills.isEmpty()) { - Text( - text = "No personal skills yet.", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - for (skill in skills) { - var expanded by remember(skill.id) { mutableStateOf(false) } - Column(modifier = Modifier.fillMaxWidth()) { - Row( - modifier = Modifier - .fillMaxWidth() - .clickable { expanded = !expanded } - .padding(vertical = 4.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - text = skill.name, - style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.SemiBold), - modifier = Modifier.weight(1f), - ) - val pending = model.pendingMutations.contains("agent-skills:${agent.id}") - TextButton(enabled = !pending, onClick = { model.openSkillForm(skill.id, agent.id) }) { Text("Edit") } - TextButton(enabled = !pending, onClick = { model.deleteAgentSkill(agent.id, skill.id) }) { Text("Delete", color = MaterialTheme.colorScheme.error) } - Icon( - imageVector = if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore, - contentDescription = null, - ) - } - AnimatedVisibility(visible = expanded) { - Text( - text = skill.instructions, - style = MaterialTheme.typography.bodySmall, - modifier = Modifier.padding(bottom = 6.dp), - ) - } - } - } - TextButton(enabled = !model.pendingMutations.contains("agent-skills:${agent.id}"), onClick = { model.openSkillForm("", agent.id) }) { - Icon(Icons.Default.Add, contentDescription = null, modifier = Modifier.size(18.dp)) - Spacer(Modifier.size(4.dp)) - Text("Add personal skill") - } - } - } - } -} - -@Composable -private fun TasksPanel(model: AppModel) { - if (model.agents.isEmpty()) { - EmptyWorkspacePlaceholder( - icon = Icons.Default.Schedule, - title = "No Tasks", - description = "Create an agent, then give it a task to run once or on a schedule.", - ) - } else { - LazyColumn( - modifier = Modifier.fillMaxSize(), - contentPadding = PaddingValues(16.dp), - verticalArrangement = Arrangement.spacedBy(16.dp), - ) { - items(model.agents, key = { it.id }) { agent -> - val tasks = model.schedules.filter { it.agentId == agent.id } - SectionCard( - title = agent.name, - footer = "Runs in ${agent.name}’s chat, once or on a schedule.", - ) { - if (tasks.isEmpty()) { - Text( - text = "No tasks yet.", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - for (schedule in tasks) { - val isPending = schedule.id.startsWith("pending-") - Column( - modifier = Modifier - .fillMaxWidth() - .padding(vertical = 4.dp), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - Text( - text = schedule.name, - style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.SemiBold), - ) - Text( - text = schedule.prompt, - style = MaterialTheme.typography.bodySmall, - maxLines = 2, - overflow = TextOverflow.Ellipsis, - ) - Text( - text = scheduleTiming(schedule), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - val creator = schedule.createdByAgentId - if (creator != null && creator != agent.id) { - val creatorName = model.agents.firstOrNull { it.id == creator }?.name - if (creatorName != null) { - Text( - text = "Scheduled by $creatorName", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - OutlinedButton( - onClick = { model.runSchedule(schedule.id) }, - enabled = schedule.enabled && !isPending, - ) { - Text("Run Now") - } - TextButton( - onClick = { model.openTaskForm(schedule.id) }, - enabled = !isPending, - ) { - Text("Edit") - } - TextButton( - onClick = { model.deleteSchedule(schedule.id) }, - enabled = !isPending, - ) { - Text("Delete", color = MaterialTheme.colorScheme.error) - } - } - } - } - TextButton(onClick = { model.openTaskForm("", agentID = agent.id) }) { - Icon(Icons.Default.Add, contentDescription = null, modifier = Modifier.size(18.dp)) - Spacer(Modifier.size(4.dp)) - Text("New Task") - } - } - } - } - } -} - -private fun scheduleTiming(schedule: Schedule): String { - var timing = schedule.runAt ?: "" - if (!schedule.cron.isNullOrEmpty()) { - timing = "${schedule.cron} · ${schedule.timezone ?: ""}" - } - return if (schedule.enabled) timing else "Paused · $timing" -} - -@Composable -private fun ActivityPanel(model: AppModel) { - if (model.activities.isEmpty()) { - EmptyWorkspacePlaceholder( - icon = Icons.Default.Timeline, - title = "No Activity", - description = "Tool calls and bot messages will appear here.", - ) - } else { - LazyColumn( - modifier = Modifier.fillMaxSize(), - contentPadding = PaddingValues(16.dp), - verticalArrangement = Arrangement.spacedBy(12.dp), - ) { - items(model.activities, key = { it.id }) { activity -> - var expanded by remember(activity.id) { mutableStateOf(false) } - Card(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier - .fillMaxWidth() - .clickable { expanded = !expanded } - .padding(14.dp), - verticalArrangement = Arrangement.spacedBy(6.dp), - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - Surface(color = MaterialTheme.colorScheme.secondaryContainer, shape = RoundedCornerShape(50)) { - Text( - text = activity.kind.replace('-', ' ').replaceFirstChar { it.uppercase() }, - style = MaterialTheme.typography.labelSmall, - modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp), - ) - } - Text(activity.displayLabel(), style = MaterialTheme.typography.titleSmall) - if (activity.agentName.isNotEmpty()) Text(activity.agentName, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - Text(activity.timestamp?.let { timeLabel(Instant.ofEpochMilli(it)) } ?: "", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - Spacer(Modifier.weight(1f)) - Icon(if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore, contentDescription = null) - } - if (expanded) { - Text( - activity.details?.toString()?.replace(",\"", ",\n\"") ?: "No details", - style = MaterialTheme.typography.bodySmall, - ) - if (activity.agentId.isNotEmpty()) { - OutlinedButton(onClick = { model.selectAgent(activity.agentId) }) { Text("Open Chat") } - } - } - } - } - } + OutlinedTextField( + value = search, + onValueChange = { search = it }, + label = { Text("Search MCP servers") }, + shape = CircleShape, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) } - } -} -@Composable -private fun IntegrationsPanel(model: AppModel) { - val context = LocalContext.current - LazyColumn( - modifier = Modifier.fillMaxSize(), - contentPadding = PaddingValues(16.dp), - verticalArrangement = Arrangement.spacedBy(16.dp), - ) { item { - val shared = model.mcpServers.filter { it.agentId == null } - SectionCard( + val shared = listed.filter { it.agentId == null } + RowsSection( title = "Shared", footer = "Every bot can use these. Turn one on for a bot in its profile.", ) { - if (shared.isEmpty()) { - Text( - text = "No shared MCP servers yet.", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } + if (shared.isEmpty()) note("No shared MCP servers yet.") for (server in shared) { - MCPServerRow( - model = model, - server = server, - onOpenBrowser = { url -> - context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) - }, - ) - } - TextButton(onClick = { model.openMCPForm("", agentID = null) }) { - Icon(Icons.Default.Add, contentDescription = null, modifier = Modifier.size(18.dp)) - Spacer(Modifier.size(4.dp)) - Text("Add Shared MCP Server") + row { shape -> MCPServerRow(model = model, server = server, shape = shape, onOpenBrowser = { url -> openSignInPage(appContext, url) }) } } + add("Add Shared MCP Server") { model.openMCPForm("", agentID = null) } } } - items(model.agents, key = { it.id }) { agent -> - val own = model.mcpServers.filter { it.agentId == agent.id } - SectionCard( + items(model.agents.filter { agent -> needle.isEmpty() || listed.any { it.agentId == agent.id } }, key = { it.id }) { agent -> + val own = listed.filter { it.agentId == agent.id } + RowsSection( title = agent.name, footer = "Only ${agent.name} can use these, with their own sign-in.", ) { - if (own.isEmpty()) { - Text( - text = "No MCP servers of its own.", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } + if (own.isEmpty()) note("No MCP servers of its own.") for (server in own) { - MCPServerRow( - model = model, - server = server, - onOpenBrowser = { url -> - context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) - }, - ) - } - TextButton(onClick = { model.openMCPForm("", agentID = agent.id) }) { - Icon(Icons.Default.Add, contentDescription = null, modifier = Modifier.size(18.dp)) - Spacer(Modifier.size(4.dp)) - Text("Add MCP Server") + row { shape -> MCPServerRow(model = model, server = server, shape = shape, onOpenBrowser = { url -> openSignInPage(appContext, url) }) } } + add("Add MCP Server") { model.openMCPForm("", agentID = agent.id) } } } } @@ -666,29 +325,20 @@ private fun IntegrationsPanel(model: AppModel) { private fun MCPServerRow( model: AppModel, server: MCPServer, + shape: Shape, onOpenBrowser: (String) -> Unit, ) { val isPending = server.id.startsWith("pending-") + var confirmingDelete by remember { mutableStateOf(false) } val statusText = when (server.auth) { "oauth" -> "Signed in with OAuth" "token" -> "Uses a token" else -> "No sign-in" } - Column( - modifier = Modifier - .fillMaxWidth() - .padding(vertical = 4.dp), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, - ) { - Text( - text = server.name, - style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.SemiBold), - ) + GroupedItem( + shape = shape, + leading = { LetterTile(server.name) }, + trailing = { if (!server.enabled) { Text( text = "Disabled", @@ -696,62 +346,112 @@ private fun MCPServerRow( color = MaterialTheme.colorScheme.onSurfaceVariant, ) } - } - Text( - text = server.url, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.MiddleEllipsis, - ) - Text( - text = statusText, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - if (model.signingIn == server.id) { - CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp) - } else if (server.auth == "oauth") { - OutlinedButton(onClick = { model.signOutOfMCP(server.id) }) { - Text("Sign Out") + }, + below = { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + if (model.signingIn == server.id) { + CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp) + } else if (server.auth == "oauth") { + OutlinedButton(onClick = { model.signOutOfMCP(server.id) }) { + Text("Sign Out") + } + } else { + OutlinedButton( + onClick = { model.beginMCPSignIn(server.id, onOpenBrowser) }, + enabled = model.signingIn == null && !isPending, + ) { + Text("Sign In…") + } } - } else { - OutlinedButton( - onClick = { model.beginMCPSignIn(server.id, onOpenBrowser) }, - enabled = model.signingIn == null && !isPending, + TextButton( + onClick = { model.openMCPForm(server.id) }, + enabled = !isPending, ) { - Text("Sign In…") + Text("Edit") + } + TextButton( + onClick = { confirmingDelete = true }, + enabled = !isPending, + ) { + Text("Delete", color = MaterialTheme.colorScheme.error) } } - TextButton( - onClick = { model.openMCPForm(server.id) }, - enabled = !isPending, - ) { - Text("Edit") - } - TextButton( - onClick = { model.deleteMCP(server.id) }, - enabled = !isPending, + }, + ) { + RowTitle(server.name) + RowSubtitle(server.url, maxLines = 1, overflow = TextOverflow.MiddleEllipsis) + RowSubtitle(statusText) + server.error?.let { RowSubtitle(it, color = MaterialTheme.colorScheme.error) } + } + if (confirmingDelete) { + AlertDialog( + onDismissRequest = { confirmingDelete = false }, + title = { Text("Delete ${server.name}?") }, + text = { Text("Bots lose its tools and its sign-in is removed. This cannot be undone.") }, + confirmButton = { + TextButton( + onClick = { + confirmingDelete = false + model.deleteMCP(server.id) + }, + ) { + Text("Delete", color = MaterialTheme.colorScheme.error) + } + }, + dismissButton = { TextButton(onClick = { confirmingDelete = false }) { Text("Cancel") } }, + ) + } +} + +@Composable +fun SectionCard( + title: String, + footer: String? = null, + expandable: Boolean = false, + content: @Composable () -> Unit, +) { + SectionFrame(title, footer, expandable) { + Card( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(24.dp), + colors = CardDefaults.cardColors(containerColor = cardColor), + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(14.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), ) { - Text("Delete", color = MaterialTheme.colorScheme.error) + content() } } } } +/** A SectionCard for a list: each row is its own surface in a group. */ @Composable -fun SectionCard( +fun RowsSection( title: String, footer: String? = null, expandable: Boolean = false, - content: @Composable () -> Unit, + build: GroupScope.() -> Unit, +) { + SectionFrame(title, footer, expandable) { GroupedRows(build) } +} + +/** A section's heading and footer around its content, which an expandable heading hides. */ +@Composable +internal fun SectionFrame( + title: String, + footer: String? = null, + expandable: Boolean = false, + content: @Composable ColumnScope.() -> Unit, ) { var expanded by remember(title) { mutableStateOf(true) } - Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + Column(verticalArrangement = Arrangement.spacedBy(ROW_GAP)) { if (expandable) { Row( modifier = Modifier @@ -759,54 +459,38 @@ fun SectionCard( .clickable { expanded = !expanded } .semantics { stateDescription = if (expanded) "Expanded" else "Collapsed" } .heightIn(min = 48.dp) - .padding(horizontal = 4.dp), + .padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically, ) { Text( text = title, - style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.primary, + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f), ) Icon( imageVector = if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore, contentDescription = if (expanded) "Collapse $title" else "Expand $title", - tint = MaterialTheme.colorScheme.primary, + tint = MaterialTheme.colorScheme.onSurfaceVariant, ) } } else { - Text( - text = title, - style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.primary, - modifier = Modifier.padding(horizontal = 4.dp), - ) - } - if (!expandable || expanded) { - Card(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier - .fillMaxWidth() - .padding(14.dp), - verticalArrangement = Arrangement.spacedBy(10.dp), - ) { - content() - } - } + GroupLabel(title) } + if (!expandable || expanded) content() if (!footer.isNullOrEmpty()) { Text( text = footer, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(horizontal = 4.dp), + modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 4.dp), ) } } } @Composable -private fun EmptyWorkspacePlaceholder( +internal fun EmptyWorkspacePlaceholder( icon: androidx.compose.ui.graphics.vector.ImageVector, title: String, description: String, @@ -901,7 +585,7 @@ fun MemoryFormDialog( } OutlinedTextField( value = draft.content, - onValueChange = { model.memoryDraft = draft.copy(content = it) }, + onValueChange = { model.memoryDraft = draft.copy(content = it.take(32_000)) }, label = { Text("Memory Entry") }, minLines = 4, modifier = Modifier.fillMaxWidth(), @@ -929,160 +613,6 @@ fun MemoryFormDialog( ) } -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun TaskFormDialog( - model: AppModel, - draft: TaskDraft, -) { - var botMenuExpanded by remember { mutableStateOf(false) } - val selectedBotName = model.agents.firstOrNull { it.id == draft.agentID }?.name ?: "" - val zone = remember(draft.timezone) { - try { - ZoneId.of(draft.timezone) - } catch (_: Exception) { - ZoneId.systemDefault() - } - } - val localFormatter = remember { DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") } - var runDateText by remember(draft.id, zone) { - mutableStateOf(ZonedDateTime.ofInstant(draft.runDate, zone).format(localFormatter)) - } - - AlertDialog( - onDismissRequest = { - model.errorText = "" - model.taskDraft = null - }, - title = { Text(if (draft.scheduleID.isEmpty()) "New Task" else "Edit Task") }, - text = { - Column( - modifier = Modifier.verticalScroll(rememberScrollState()), - verticalArrangement = Arrangement.spacedBy(10.dp), - ) { - SheetErrorBanner(model.errorText) - ExposedDropdownMenuBox( - expanded = botMenuExpanded, - onExpandedChange = { botMenuExpanded = it }, - ) { - OutlinedTextField( - value = selectedBotName, - onValueChange = {}, - readOnly = true, - label = { Text("Runs on") }, - trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = botMenuExpanded) }, - modifier = Modifier - .menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable) - .fillMaxWidth(), - ) - ExposedDropdownMenu( - expanded = botMenuExpanded, - onDismissRequest = { botMenuExpanded = false }, - ) { - for (agent in model.agents) { - DropdownMenuItem( - text = { Text(agent.name) }, - onClick = { - model.taskDraft = draft.copy(agentID = agent.id) - botMenuExpanded = false - }, - ) - } - } - } - OutlinedTextField( - value = draft.name, - onValueChange = { model.taskDraft = draft.copy(name = it) }, - label = { Text("Name") }, - singleLine = true, - modifier = Modifier.fillMaxWidth(), - ) - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, - ) { - Text("Enabled") - Switch( - checked = draft.enabled, - onCheckedChange = { model.taskDraft = draft.copy(enabled = it) }, - ) - } - OutlinedTextField( - value = draft.prompt, - onValueChange = { model.taskDraft = draft.copy(prompt = it) }, - label = { Text("Prompt") }, - minLines = 3, - modifier = Modifier.fillMaxWidth(), - ) - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - FilterChip( - selected = !draft.repeats, - onClick = { model.taskDraft = draft.copy(repeats = false) }, - label = { Text("Run once") }, - ) - FilterChip( - selected = draft.repeats, - onClick = { model.taskDraft = draft.copy(repeats = true) }, - label = { Text("Repeat") }, - ) - } - if (draft.repeats) { - OutlinedTextField( - value = draft.cron, - onValueChange = { model.taskDraft = draft.copy(cron = it) }, - label = { Text("Cron expression") }, - placeholder = { Text("0 9 * * 1-5") }, - singleLine = true, - modifier = Modifier.fillMaxWidth(), - ) - } else { - OutlinedTextField( - value = runDateText, - onValueChange = { text -> - runDateText = text - try { - val ldt = LocalDateTime.parse(text.trim(), localFormatter) - val instant = ldt.atZone(zone).toInstant() - model.taskDraft = draft.copy(runDate = instant) - } catch (_: Exception) { - } - }, - label = { Text("Run at (YYYY-MM-DD HH:mm)") }, - singleLine = true, - modifier = Modifier.fillMaxWidth(), - ) - } - OutlinedTextField( - value = draft.timezone, - onValueChange = { model.taskDraft = draft.copy(timezone = it) }, - label = { Text("Time zone") }, - singleLine = true, - modifier = Modifier.fillMaxWidth(), - ) - } - }, - confirmButton = { - Button( - onClick = { model.saveTask() }, - enabled = !model.loading, - ) { - Text("Save") - } - }, - dismissButton = { - TextButton( - onClick = { - model.errorText = "" - model.taskDraft = null - }, - ) { - Text("Cancel") - } - }, - ) -} - @OptIn(ExperimentalMaterial3Api::class) @Composable fun MCPFormDialog( @@ -1090,6 +620,7 @@ fun MCPFormDialog( draft: MCPDraft, ) { var ownerMenuExpanded by remember { mutableStateOf(false) } + val server = model.mcpServers.firstOrNull { it.id == draft.serverID } val selectedOwnerName = if (draft.agentID == null) { "Every bot (shared)" } else { @@ -1161,14 +692,40 @@ fun MCPFormDialog( singleLine = true, modifier = Modifier.fillMaxWidth(), ) + SecretSourceField( + model = model, + label = "Token (Optional)", + draft = draft.token, + onChange = { model.mcpDraft = model.mcpDraft?.copy(token = it) }, + valueDescription = "Leave the token empty for servers that use OAuth, then choose Sign In in the list after saving.", + valuePlaceholder = server?.takeIf { it.auth == "token" && it.token?.reference == null }?.let { "Replace the saved token" }, + ) + Text( + text = "OAuth app", + style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.SemiBold), + ) + Text( + text = "Only for servers whose sign-in can't register Crumble, such as GitHub's. Register an OAuth app there with the callback URL ${AppModel.oauthRedirectURI} and enter its client ID and secret.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) OutlinedTextField( - value = draft.token, - onValueChange = { model.mcpDraft = draft.copy(token = it) }, - label = { Text("Token (Optional)") }, - visualTransformation = PasswordVisualTransformation(), + value = draft.clientID, + onValueChange = { model.mcpDraft = model.mcpDraft?.copy(clientID = it) }, + label = { Text("Client ID") }, + placeholder = { Text("Optional") }, singleLine = true, modifier = Modifier.fillMaxWidth(), ) + SecretSourceField( + model = model, + label = "Client secret", + draft = draft.clientSecret, + onChange = { model.mcpDraft = model.mcpDraft?.copy(clientSecret = it) }, + valueDescription = "Stored encrypted and never shown again. Changing the app signs the server out.", + valuePlaceholder = if (server?.oauthClientSecret?.configured == true) "Replace the saved secret" else "Optional", + enabled = draft.clientID.isNotBlank(), + ) Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, @@ -1180,17 +737,12 @@ fun MCPFormDialog( onCheckedChange = { model.mcpDraft = draft.copy(enabled = it) }, ) } - Text( - text = "Leave the token empty for servers that use OAuth, then choose Sign In in the list after saving.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) } }, confirmButton = { Button( onClick = { model.saveMCP() }, - enabled = !model.loading, + enabled = !model.loading && !draft.saving, ) { Text("Save") } @@ -1265,23 +817,27 @@ fun SkillFormDialog( } OutlinedTextField( value = draft.name, - onValueChange = { model.skillDraft = draft.copy(name = it) }, + onValueChange = { model.skillDraft = draft.copy(name = it.take(100)) }, label = { Text("Name") }, singleLine = true, modifier = Modifier.fillMaxWidth(), ) OutlinedTextField( value = draft.instructions, - onValueChange = { model.skillDraft = draft.copy(instructions = it) }, + onValueChange = { model.skillDraft = draft.copy(instructions = it.take(32_000)) }, label = { Text("Instructions") }, minLines = 4, modifier = Modifier.fillMaxWidth(), ) - Text( - text = if (draft.agentID == null) "Assign this shared skill to bots from its expanded row." else "Only this bot follows this personal skill.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) + if (draft.agentID == null) { + SkillUsedByField(model.agents, draft.usedBy) { model.skillDraft = draft.copy(usedBy = it) } + } else { + Text( + text = "Only this bot follows this personal skill.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } } }, confirmButton = { @@ -1322,3 +878,8 @@ fun SheetErrorBanner(errorText: String) { } } } + +/** The sign-in outlives the activity that started it, so this can't go through that activity. */ +private fun openSignInPage(context: Context, url: String) { + context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) +} diff --git a/app/src/main/java/dev/crumble/android/ui/ProvidersScreen.kt b/app/src/main/java/dev/crumble/android/ui/ProvidersScreen.kt new file mode 100644 index 0000000..9576a45 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/ProvidersScreen.kt @@ -0,0 +1,358 @@ +package dev.crumble.android.ui + +import androidx.compose.ui.graphics.Shape +import androidx.compose.foundation.shape.CircleShape +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.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +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.platform.LocalClipboardManager +import androidx.compose.ui.platform.LocalUriHandler +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.input.VisualTransformation +import androidx.compose.ui.unit.dp +import dev.crumble.android.generated.Provider +import dev.crumble.android.generated.ProviderLoginEvent +import dev.crumble.android.generated.ProviderLoginSession +import dev.crumble.android.generated.ProviderLoginSessionPrompt +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.ProviderKeyForm +import dev.crumble.android.model.ProviderLoginView +import dev.crumble.android.model.isWebLink +import dev.crumble.android.model.keyAvailable +import dev.crumble.android.model.matchingProviders +import dev.crumble.android.model.providerStatus +import dev.crumble.android.model.signInAvailable + +@Composable +private fun ProviderSection(model: AppModel, title: String, description: String?, providers: List) { + Column(verticalArrangement = Arrangement.spacedBy(ROW_GAP)) { + GroupLabel(title) + if (description != null) { + Text( + description, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 6.dp), + ) + } + providers.forEachIndexed { index, provider -> ProviderRow(model, provider, groupedShape(index, providers.size)) } + } +} + +@Composable +private fun ProviderRow(model: AppModel, provider: Provider, shape: Shape) { + val label = providerStatus(provider, model.passwordManagers) + val oauth = provider.authMethods.firstOrNull { it.type == "oauth" } + val busy = "provider:${provider.provider}" in model.pendingMutations + val external = provider.externalAuth + Surface(shape = shape, color = cardColor, modifier = Modifier.fillMaxWidth()) { + Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp)) { + ToneTile(if (provider.configured) Tone.Green else Tone.Lavender) { + Text(provider.name.take(1).uppercase(), style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold)) + } + Column(modifier = Modifier.weight(1f)) { + Text(provider.name, style = MaterialTheme.typography.titleMedium) + if (label != null) { + Text( + label, + style = MaterialTheme.typography.bodyMedium, + color = if (provider.configured) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (oauth != null) { + Text(oauth.label, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + when { + busy -> CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) + external != null -> ExternalMenu(model, provider) + else -> ProviderActions(model, provider) + } + } + external?.message?.takeIf { external.status == "cli_missing" || external.status == "error" }?.let { + Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + } +} + +@Composable +private fun ProviderActions(model: AppModel, provider: Provider) { + val signIn = provider.signInAvailable() + val addKey = provider.keyAvailable() + val signInLabel = if (provider.activeLoginId != null) "Continue sign-in" else "Sign in" + if (provider.credentialType == null) { + Row(verticalAlignment = Alignment.CenterVertically) { + if (addKey) TextButton(onClick = { model.openProviderKey(provider) }) { Text("Add key") } + if (signIn) OutlinedButton(onClick = { model.openProviderLogin(provider) }) { Text(signInLabel) } + } + return + } + SecretOverflowMenu { close -> + if (signIn) { + DropdownMenuItem(text = { Text(signInLabel) }, onClick = { + close() + model.openProviderLogin(provider) + }) + } + if (addKey) { + DropdownMenuItem(text = { Text(if (provider.credentialType == "api_key") "Replace key" else "Use a key") }, onClick = { + close() + model.openProviderKey(provider) + }) + } + DropdownMenuItem( + text = { Text(if (provider.credentialType == "oauth") "Sign out" else "Remove key", color = MaterialTheme.colorScheme.error) }, + onClick = { + close() + model.removeProviderCredential(provider) + }, + ) + } +} + +/** A provider that signs in outside Crumble: its menu copies the command to run on the server. */ +@Composable +private fun ExternalMenu(model: AppModel, provider: Provider) { + val external = provider.externalAuth ?: return + val signedIn = external.status == "signed_in" + val command = (if (signedIn) external.signOutCommand else external.signInCommand) ?: return + if (external.status == "cli_missing") return + val clipboard = LocalClipboardManager.current + SecretOverflowMenu { close -> + DropdownMenuItem(text = { Text(if (signedIn) "Copy sign-out command" else "Copy sign-in command") }, onClick = { + close() + clipboard.setText(AnnotatedString(command)) + model.showNotice("Copied") + }) + } +} + +@Composable +fun ProvidersPanel(model: AppModel) { + var search by remember { mutableStateOf("") } + val shown = matchingProviders(model.providerAccounts, search.trim().lowercase()) + val ready = shown.filter { it.configured } + val rest = shown.filter { !it.configured } + LazyColumn(modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) { + item { + OutlinedTextField( + value = search, + onValueChange = { search = it }, + label = { Text("Search providers") }, + shape = CircleShape, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + } + if (model.providerAccounts.isNotEmpty() && shown.isEmpty()) { + item { + Column(modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { + Text("No providers match", style = MaterialTheme.typography.titleSmall) + Text("Try another name.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + } + if (ready.isNotEmpty()) { + item { + ProviderSection(model, "Set up", "Bots use these providers' models. Keys and sign-ins are stored encrypted on the server and shared by every bot.", ready) + } + } + if (rest.isNotEmpty()) { + item { ProviderSection(model, if (ready.isNotEmpty()) "Available" else "Providers", null, rest) } + } + } +} + +@Composable +fun ProviderKeyDialog(model: AppModel, form: ProviderKeyForm) { + val provider = form.provider + AlertDialog( + onDismissRequest = { model.closeProviderKey() }, + title = { Text("${if (provider.credentialType == "api_key") "Replace" else "Add"} ${provider.name} API key") }, + text = { + Column(modifier = Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) { + SheetErrorBanner(form.error) + SecretSourceField( + model = model, + label = "API key", + draft = form.key, + onChange = { next -> model.providerKeyForm?.let { model.providerKeyForm = it.copy(key = next) } }, + valueDescription = "Stored encrypted and never shown again.", + valuePlaceholder = "API key", + enabled = !form.saving, + ) + } + }, + confirmButton = { + Button(enabled = form.key.changed && !form.saving, onClick = { model.saveProviderAccountKey() }) { + if (form.saving) { + CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) + } else { + Text("Save") + } + } + }, + dismissButton = { TextButton(onClick = { model.closeProviderKey() }) { Text("Cancel") } }, + ) +} + +/** Runs a provider's account sign-in; closing keeps it going on the server so it can be continued. */ +@Composable +fun ProviderLoginDialog(model: AppModel, view: ProviderLoginView) { + val status = view.session?.status + AlertDialog( + onDismissRequest = { model.hideProviderLogin() }, + title = { Text("Sign in to ${view.provider.name}") }, + text = { + Column(modifier = Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text( + "The server keeps this sign-in. Bots that use ${view.provider.name} share it.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + ProviderLoginBody(model, view) + SheetErrorBanner(view.error) + } + }, + confirmButton = { + OutlinedButton(onClick = { model.hideProviderLogin() }) { Text(if (status == "pending") "Hide" else "Close") } + }, + dismissButton = { + if (view.sessionID != null && status == "pending") { + TextButton(enabled = !view.cancelling, onClick = { model.cancelProviderLogin() }) { Text("Cancel sign-in") } + } + }, + ) +} + +@Composable +private fun ProviderLoginBody(model: AppModel, view: ProviderLoginView) { + val session = view.session + when { + view.sessionID == null -> Button(enabled = !view.starting, onClick = { model.startProviderLogin() }) { + if (view.starting) { + CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) + } else { + Text("Start sign-in") + } + } + view.gone -> Text("This sign-in ended or was lost on restart. Close this and start again.", style = MaterialTheme.typography.bodySmall) + session == null -> CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp) + session.status == "succeeded" -> Text("Signed in.", style = MaterialTheme.typography.bodyMedium) + session.status != "pending" -> SheetErrorBanner(session.failure?.message ?: "Sign-in ${session.status}.") + else -> ProviderLoginSteps(model, view, session) + } +} + +@Composable +private fun ProviderLoginSteps(model: AppModel, view: ProviderLoginView, session: ProviderLoginSession) { + session.events.forEachIndexed { index, event -> + ProviderLoginEventView(event, last = index == session.events.lastIndex) + } + val prompt = session.prompt + when { + prompt != null -> ProviderLoginPrompt(model, view, prompt) + session.events.lastOrNull() !is ProviderLoginEvent.Variant4 -> Text("Waiting for the provider…", style = MaterialTheme.typography.bodySmall) + } +} + +@Composable +private fun ProviderLoginEventView(event: ProviderLoginEvent, last: Boolean) { + val uriHandler = LocalUriHandler.current + val open = { url: String -> if (isWebLink(url)) runCatching { uriHandler.openUri(url) } } + when (event) { + is ProviderLoginEvent.Variant1 -> Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(event.value.message, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + for (link in event.value.links.orEmpty()) { + TextButton(onClick = { open(link.url) }) { Text(link.label ?: link.url) } + } + } + is ProviderLoginEvent.Variant2 -> Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + event.value.instructions?.let { Text(it, style = MaterialTheme.typography.bodySmall) } + Button(onClick = { open(event.value.url) }) { Text("Open sign-in page") } + } + is ProviderLoginEvent.Variant3 -> Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text("Enter this code at", style = MaterialTheme.typography.bodySmall) + TextButton(onClick = { open(event.value.verificationUri) }) { Text(event.value.verificationUri) } + SelectionContainer { + Text(event.value.userCode, style = MaterialTheme.typography.titleLarge, fontFamily = FontFamily.Monospace) + } + } + is ProviderLoginEvent.Variant4 -> if (last) Text(event.value.message, style = MaterialTheme.typography.bodySmall) + } +} + +@Composable +private fun ProviderLoginPrompt(model: AppModel, view: ProviderLoginView, prompt: ProviderLoginSessionPrompt) { + val error = view.answerError + if (prompt.type == "select") { + Text(prompt.message, style = MaterialTheme.typography.bodyMedium) + for (option in prompt.options.orEmpty()) { + OutlinedButton(enabled = !view.answering, onClick = { model.answerProviderLogin(option.id) }, modifier = Modifier.fillMaxWidth()) { + Column(modifier = Modifier.fillMaxWidth()) { + Text(option.label) + option.description?.let { Text(it, style = MaterialTheme.typography.labelSmall) } + } + } + } + SheetErrorBanner(error) + return + } + val concealed = prompt.type == "secret" + val value = view.answer.text.trim() + OutlinedTextField( + value = view.answer.text, + onValueChange = { text -> model.providerLogin?.let { model.providerLogin = it.copy(answer = it.answer.copy(text = text)) } }, + label = { Text(prompt.message) }, + placeholder = prompt.placeholder?.let { { Text(it) } }, + enabled = !view.answering, + singleLine = true, + isError = error.isNotEmpty(), + visualTransformation = if (concealed) PasswordVisualTransformation() else VisualTransformation.None, + keyboardOptions = SECRET_KEYBOARD, + modifier = Modifier.fillMaxWidth(), + ) + SheetErrorBanner(error) + Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd) { + Button(enabled = value.isNotEmpty() && !view.answering, onClick = { model.answerProviderLogin(value) }) { + if (view.answering) { + CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) + } else { + Text("Continue") + } + } + } +} diff --git a/app/src/main/java/dev/crumble/android/ui/SecretsScreen.kt b/app/src/main/java/dev/crumble/android/ui/SecretsScreen.kt new file mode 100644 index 0000000..61d1f3b --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/SecretsScreen.kt @@ -0,0 +1,723 @@ +package dev.crumble.android.ui + +import androidx.compose.foundation.shape.CircleShape +import android.text.format.DateUtils +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.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.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.FilterChip +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +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.graphics.Shape +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +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 dev.crumble.android.generated.PasswordManager +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.CredentialForm +import dev.crumble.android.model.LoginForm +import dev.crumble.android.model.LoginMode +import dev.crumble.android.model.ManagerTokenForm +import dev.crumble.android.model.ONE_PASSWORD +import dev.crumble.android.model.Route +import dev.crumble.android.model.SKILLS_ALL +import dev.crumble.android.model.SecretAsk +import dev.crumble.android.model.SecretDraft +import dev.crumble.android.model.SecretKind +import dev.crumble.android.model.SecretRow +import dev.crumble.android.model.SecretUsesView +import dev.crumble.android.model.activityTime +import dev.crumble.android.model.keepPlaceholder +import dev.crumble.android.model.matchesSecret +import dev.crumble.android.model.secretBotsShown +import dev.crumble.android.model.secretKey +import dev.crumble.android.model.taskRunDate + +// The password keyboard turns off suggestions and learning, so typed secrets stay out of its dictionary. +internal val SECRET_KEYBOARD = KeyboardOptions( + capitalization = KeyboardCapitalization.None, + autoCorrectEnabled = false, + keyboardType = KeyboardType.Password, +) + +private val PLAIN_KEYBOARD = KeyboardOptions( + capitalization = KeyboardCapitalization.None, + autoCorrectEnabled = false, + keyboardType = KeyboardType.Ascii, +) + +private val REFERENCE_PLACEHOLDERS = mapOf(ONE_PASSWORD to "op://vault/item/field", "bitwarden" to "Secret ID") + +private val TOKEN_LABELS = mapOf(ONE_PASSWORD to "Service account token", "bitwarden" to "Access token") + +/** One kind of secret on its page: credentials and logins differ only in copy and data. */ +private class SecretPage( + val kind: SecretKind, + val searchLabel: String, + val empty: String, + val noMatch: String, + val note: String, + val usedVerb: String, + val neverUsed: String, + val usesLabel: String, + val deleteText: String, + val mono: Boolean, + val scope: String, + val onScope: (String) -> Unit, + val rowsOf: (String) -> List?, + val asksOf: (String) -> List, + val failures: Map, + val onAdd: (String, SecretAsk) -> Unit, + val onDecline: (String, String) -> Unit, + val onEdit: (String, String) -> Unit, + val onDelete: (String, String) -> Unit, +) + +@Composable +fun CredentialsPanel(model: AppModel) { + SecretPageView( + model, + SecretPage( + kind = SecretKind.credential, + searchLabel = "Search credentials", + empty = "None yet. The bot asks for one when a coding job needs it.", + noMatch = "No credentials match your search.", + note = "Coding jobs get a placeholder for each credential; the value only goes to its hosts. Uses are kept for 90 days.", + usedVerb = "Used", + neverUsed = "Never used", + usesLabel = "Uses", + deleteText = "Requests with its placeholder stop working at once, and its uses are deleted. This cannot be undone.", + mono = true, + scope = model.credentialScope, + onScope = { model.credentialScope = it }, + rowsOf = { id -> model.botCredentials[id]?.credentials?.map { SecretRow(it.name, it.hosts, it.lastUsedAt, it.lastError, it.github) } }, + asksOf = { id -> model.botCredentials[id]?.requests.orEmpty().map { SecretAsk(it.name, it.hosts, it.reason) } }, + failures = model.credentialLoadErrors, + onAdd = { id, ask -> model.openCredentialForm(id, request = model.botCredentials[id]?.requests?.firstOrNull { it.name == ask.name }) }, + onDecline = model::declineCredentialRequest, + onEdit = { id, name -> model.openCredentialForm(id, existing = model.botCredentials[id]?.credentials?.firstOrNull { it.name == name }) }, + onDelete = model::deleteCredential, + ), + ) +} + +@Composable +fun LoginsPanel(model: AppModel) { + SecretPageView( + model, + SecretPage( + kind = SecretKind.login, + searchLabel = "Search logins", + empty = "None yet. The bot asks for one when a desktop job needs to sign in.", + noMatch = "No logins match your search.", + note = "Desktop jobs fill a login only into https pages on its hosts, and never see its password. Fills are kept for 90 days.", + usedVerb = "Filled", + neverUsed = "Never filled", + usesLabel = "Fills", + deleteText = "Desktop jobs can no longer fill it, and its fills are deleted. This cannot be undone.", + mono = false, + scope = model.loginScope, + onScope = { model.loginScope = it }, + rowsOf = { id -> model.botLogins[id]?.logins?.map { SecretRow(it.name, it.hosts, it.lastUsedAt, it.lastError) } }, + asksOf = { id -> model.botLogins[id]?.requests.orEmpty().map { SecretAsk(it.name, it.hosts, it.reason) } }, + failures = model.loginLoadErrors, + onAdd = { id, ask -> model.openLoginForm(id, request = model.botLogins[id]?.requests?.firstOrNull { it.name == ask.name }) }, + onDecline = model::declineLoginRequest, + onEdit = { id, name -> model.openLoginForm(id, existing = model.botLogins[id]?.logins?.firstOrNull { it.name == name }) }, + onDelete = model::deleteLogin, + ), + ) +} + +@Composable +private fun OverflowMenu(content: @Composable (close: () -> Unit) -> Unit) { + var open by remember { mutableStateOf(false) } + Box { + IconButton(onClick = { open = true }) { Icon(Icons.Default.MoreVert, contentDescription = "More") } + DropdownMenu(expanded = open, onDismissRequest = { open = false }) { content { open = false } } + } +} + +@Composable +internal fun SecretOverflowMenu(content: @Composable (close: () -> Unit) -> Unit) = OverflowMenu(content) + +@Composable +internal fun SecretNote(text: String) { + Text(text, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) +} + +@Composable +private fun SecretPageView(model: AppModel, page: SecretPage) { + var search by remember { mutableStateOf("") } + var deleting by remember { mutableStateOf?>(null) } + val needle = search.trim().lowercase() + val bots = model.agents + val inScope = bots.filter { page.scope == SKILLS_ALL || it.id == page.scope } + val waiting = inScope.flatMap { bot -> + page.asksOf(bot.id).filter { matchesSecret(it.name, it.hosts, needle) }.map { bot to it } + } + val shown = secretBotsShown(bots.map { it.id }, page.scope, needle, { page.rowsOf(it).orEmpty() }, { it in page.failures }) + + LazyColumn(modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) { + item { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField( + value = search, + onValueChange = { search = it }, + label = { Text(page.searchLabel) }, + shape = CircleShape, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) { + fun count(id: String) = page.rowsOf(id).orEmpty().size + page.asksOf(id).size + FilterChip(page.scope == SKILLS_ALL, { page.onScope(SKILLS_ALL) }, { Text("All · ${bots.sumOf { count(it.id) }}") }) + for (bot in bots) { + FilterChip( + selected = page.scope == bot.id, + onClick = { page.onScope(bot.id) }, + label = { Text("${bot.name} · ${count(bot.id)}") }, + leadingIcon = { BotAvatarView(agent = bot, size = 18.dp) }, + ) + } + } + } + } + if (waiting.isNotEmpty()) { + item { + RowsSection(title = "Waiting for you") { + for ((bot, ask) in waiting) row { shape -> AskRow(model, page, bot, ask, shape) } + } + } + } + for (id in shown) { + val bot = bots.first { it.id == id } + item(key = id) { BotSecrets(model, page, bot, needle) { deleting = id to it } } + } + item { SecretNote(page.note) } + } + deleting?.let { (id, name) -> + ConfirmDialog( + title = "Delete $name?", + text = page.deleteText, + confirmLabel = "Delete", + onConfirm = { page.onDelete(id, name) }, + onDismiss = { deleting = null }, + ) + } +} + +@Composable +private fun AskRow(model: AppModel, page: SecretPage, bot: Agent, ask: SecretAsk, shape: Shape) { + val busy = secretKey(page.kind.name, bot.id, ask.name) in model.pendingMutations + GroupedItem( + shape = shape, + leading = { BotAvatarView(agent = bot, size = 44.dp) }, + below = { + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) { + TextButton(enabled = !busy, onClick = { page.onDecline(bot.id, ask.name) }) { Text("Decline") } + Button(enabled = !busy, onClick = { page.onAdd(bot.id, ask) }) { Text("Add") } + } + }, + ) { + RowTitle("${bot.name} asks for ${ask.name}") + RowSubtitle("${ask.reason} · ${ask.hosts.joinToString(", ")}", maxLines = 2) + } +} + +@Composable +private fun BotSecrets(model: AppModel, page: SecretPage, bot: Agent, needle: String, onDelete: (String) -> Unit) { + val all = page.rowsOf(bot.id) + val rows = all.orEmpty().filter { matchesSecret(it.name, it.hosts, needle) } + val error = page.failures[bot.id] + RowsSection(title = bot.name) { + when { + error != null -> note(error) + all != null && rows.isEmpty() -> note(if (all.isNotEmpty()) page.noMatch else page.empty) + } + for (row in rows) row { shape -> SecretRowView(model, page, bot, row, shape) { onDelete(row.name) } } + } +} + +private fun agoLabel(iso: String): String { + val at = taskRunDate(iso) ?: return iso + return DateUtils.getRelativeTimeSpanString(at.toEpochMilli(), System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS).toString() +} + +@Composable +private fun SecretRowView(model: AppModel, page: SecretPage, bot: Agent, row: SecretRow, shape: Shape, onDelete: () -> Unit) { + val busy = secretKey(page.kind.name, bot.id, row.name) in model.pendingMutations + GroupedItem( + shape = shape, + onClick = { page.onEdit(bot.id, row.name) }, + enabled = !busy && !row.managed, + leading = { IconTile(routeIcon(if (page.kind == SecretKind.credential) Route.Credentials else Route.Logins), Tone.Lavender) }, + trailing = { + if (busy) { + CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) + } else { + OverflowMenu { close -> + DropdownMenuItem(text = { Text(page.usesLabel) }, onClick = { + close() + model.openSecretUses(page.kind, bot.id, row.name) + }) + if (!row.managed) { + DropdownMenuItem(text = { Text("Edit") }, onClick = { + close() + page.onEdit(bot.id, row.name) + }) + DropdownMenuItem( + text = { Text("Delete", color = MaterialTheme.colorScheme.error) }, + onClick = { + close() + onDelete() + }, + ) + } + } + } + }, + ) { + RowTitle(row.name, fontFamily = if (page.mono) FontFamily.Monospace else null) + RowSubtitle(row.hosts.joinToString(", "), maxLines = 1) + RowSubtitle( + row.lastError ?: row.lastUsedAt?.let { "${page.usedVerb} ${agoLabel(it)}" } ?: page.neverUsed, + color = if (row.lastError != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + ) + } +} + +@Composable +fun SecretUsesDialog(model: AppModel, view: SecretUsesView) { + val credential = view.kind == SecretKind.credential + AlertDialog( + onDismissRequest = { model.closeSecretUses() }, + title = { Text(if (credential) "Uses of ${view.name}" else "Fills of ${view.name}") }, + text = { + Column(modifier = Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) { + SecretNote( + if (credential) "Requests sent with the value in the last 90 days, newest first." + else "Fields desktop jobs filled in the last 90 days, newest first.", + ) + SheetErrorBanner(view.error) + when { + view.loading -> CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp) + view.rows.isEmpty() && view.error.isEmpty() -> SecretNote(if (credential) "Not used yet." else "Not filled yet.") + } + for (use in view.rows) { + Column { + Text(activityTime(use.at), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(use.detail, style = MaterialTheme.typography.bodySmall, fontFamily = if (credential) FontFamily.Monospace else null) + use.note?.let { + Text( + it, + style = MaterialTheme.typography.labelSmall, + color = if (use.failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + if (view.hasMore) { + OutlinedButton(enabled = !view.loadingMore, onClick = { model.loadMoreSecretUses() }) { Text("Load More") } + } + } + }, + confirmButton = { TextButton(onClick = { model.closeSecretUses() }) { Text("Done") } }, + ) +} + +/** A secret's value, or a password manager reference once one is connected. */ +@Composable +internal fun SecretSourceField( + model: AppModel, + label: String, + draft: SecretDraft, + onChange: (SecretDraft) -> Unit, + valueDescription: String, + valuePlaceholder: String? = null, + concealed: Boolean = true, + enabled: Boolean = true, +) { + val connected = model.connectedManagers + val manager = connected.firstOrNull { it.id == draft.manager } + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + if (connected.isNotEmpty()) { + Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) { + FilterChip(draft.manager == null, { onChange(draft.source(null)) }, { Text("Crumble") }, enabled = enabled) + for (item in connected) { + FilterChip(draft.manager == item.id, { onChange(draft.source(item.id)) }, { Text(item.name) }, enabled = enabled) + } + } + } + OutlinedTextField( + value = draft.text, + onValueChange = { onChange(draft.copy(text = it)) }, + label = { Text(label) }, + placeholder = (if (draft.manager != null) REFERENCE_PLACEHOLDERS[draft.manager] else valuePlaceholder)?.let { { Text(it) } }, + singleLine = true, + enabled = enabled, + visualTransformation = if (draft.manager == null && concealed) PasswordVisualTransformation() else VisualTransformation.None, + keyboardOptions = if (draft.manager == null) SECRET_KEYBOARD else PLAIN_KEYBOARD, + textStyle = if (draft.manager == null) MaterialTheme.typography.bodyLarge else MaterialTheme.typography.bodyLarge.copy(fontFamily = FontFamily.Monospace), + modifier = Modifier.fillMaxWidth(), + ) + when { + draft.manager != null -> SecretNote("Read from ${manager?.name ?: "the password manager"} when it's used. Crumble checks it can read it when you save.") + connected.isNotEmpty() -> SecretNote(valueDescription) + else -> { + SecretNote(valueDescription) + Text( + "Connect a password manager to read it from there instead.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.clickable { model.navigate(Route.PasswordManagers) }, + ) + } + } + } +} + +@Composable +private fun OwnerField(model: AppModel, owner: String, onOwner: (String) -> Unit) { + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text("For bot", style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.SemiBold)) + BotPills(model.agents, { it.id == owner }, { bot, _ -> onOwner(bot.id) }) + } +} + +@Composable +private fun SecretSheet( + noun: String, + existing: String?, + reason: String?, + error: String, + ready: Boolean, + saving: Boolean, + onSubmit: () -> Unit, + onClose: () -> Unit, + content: @Composable () -> Unit, +) { + AlertDialog( + onDismissRequest = onClose, + title = { Text(if (existing != null) "Edit $existing" else "New $noun") }, + text = { + Column(modifier = Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) { + if (!reason.isNullOrEmpty()) SecretNote(reason) + SheetErrorBanner(error) + content() + } + }, + confirmButton = { + Button(enabled = ready, onClick = onSubmit) { + if (saving) { + CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) + } else { + Text(if (existing != null) "Save" else "Add") + } + } + }, + dismissButton = { TextButton(onClick = onClose) { Text("Cancel") } }, + ) +} + +@Composable +private fun NameAndHosts( + name: String, + hosts: String, + locked: Boolean, + invalid: Boolean, + enabled: Boolean, + placeholder: String, + nameNote: String, + hostsPlaceholder: String, + hostsNote: String, + mono: Boolean, + onName: (String) -> Unit, + onHosts: (String) -> Unit, +) { + OutlinedTextField( + value = name, + onValueChange = onName, + label = { Text("Name") }, + placeholder = { Text(placeholder) }, + singleLine = true, + enabled = !locked && enabled, + isError = invalid, + keyboardOptions = PLAIN_KEYBOARD, + textStyle = if (mono) MaterialTheme.typography.bodyLarge.copy(fontFamily = FontFamily.Monospace) else MaterialTheme.typography.bodyLarge, + supportingText = { Text(nameNote) }, + modifier = Modifier.fillMaxWidth(), + ) + OutlinedTextField( + value = hosts, + onValueChange = onHosts, + label = { Text("Hosts") }, + placeholder = { Text(hostsPlaceholder) }, + singleLine = true, + enabled = enabled, + keyboardOptions = PLAIN_KEYBOARD, + supportingText = { Text(hostsNote) }, + modifier = Modifier.fillMaxWidth(), + ) +} + +@Composable +fun CredentialFormDialog(model: AppModel, form: CredentialForm) { + val update = { next: CredentialForm -> if (model.credentialForm != null) model.credentialForm = next } + SecretSheet( + noun = "Credential", + existing = form.existing?.name, + reason = form.request?.reason, + error = form.error, + ready = form.ready, + saving = form.saving, + onSubmit = { model.saveCredential() }, + onClose = { model.closeCredentialForm() }, + ) { + if (form.botID == null) OwnerField(model, form.owner) { update(form.copy(owner = it)) } + NameAndHosts( + name = form.name, + hosts = form.hosts, + locked = form.locked, + invalid = form.nameInvalid, + enabled = !form.saving, + placeholder = "ACME_TOKEN", + nameNote = "The environment variable coding jobs see.", + hostsPlaceholder = "api.example.com, *.example.com", + hostsNote = if (form.request != null) { + "The bot proposed these. The value goes only to them, so check they belong to the service." + } else { + "The value goes only to these hosts. *.example.com covers every subdomain." + }, + mono = true, + onName = { update(form.copy(name = it.uppercase())) }, + onHosts = { update(form.copy(hosts = it)) }, + ) + SecretSourceField( + model = model, + label = "Value", + draft = form.secret, + onChange = { update(form.copy(secret = it)) }, + valueDescription = "Stored encrypted and never shown again.", + valuePlaceholder = keepPlaceholder(form.existing), + enabled = !form.saving, + ) + } +} + +@Composable +fun LoginFormDialog(model: AppModel, form: LoginForm) { + val update = { next: LoginForm -> if (model.loginForm != null) model.loginForm = next } + val fields = form.existing?.fields + SecretSheet( + noun = "Login", + existing = form.existing?.name, + reason = form.request?.reason, + error = form.error, + ready = form.ready, + saving = form.saving, + onSubmit = { model.saveLogin() }, + onClose = { model.closeLoginForm() }, + ) { + if (form.botID == null) OwnerField(model, form.owner) { update(form.copy(owner = it)) } + NameAndHosts( + name = form.name, + hosts = form.hosts, + locked = form.locked, + invalid = form.nameInvalid, + enabled = !form.saving, + placeholder = "github", + nameNote = "How desktop jobs refer to it.", + hostsPlaceholder = "github.com, *.github.com", + hostsNote = if (form.request != null) { + "The bot proposed these. The login is filled only into https pages on them, so check they belong to the site." + } else { + "Filled only into https pages on these hosts. *.example.com covers every subdomain." + }, + mono = false, + onName = { update(form.copy(name = it.lowercase())) }, + onHosts = { update(form.copy(hosts = it)) }, + ) + if (model.connectedManagers.any { it.id == ONE_PASSWORD }) { + Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + FilterChip(form.mode == LoginMode.fields, { update(form.copy(mode = LoginMode.fields)) }, { Text("Fields") }, enabled = !form.saving) + FilterChip(form.mode == LoginMode.item, { update(form.copy(mode = LoginMode.item)) }, { Text("1Password item") }, enabled = !form.saving) + } + } + if (form.mode == LoginMode.item) { + OutlinedTextField( + value = form.item, + onValueChange = { update(form.copy(item = it)) }, + label = { Text("Item") }, + placeholder = { Text("op://vault/item") }, + singleLine = true, + enabled = !form.saving, + keyboardOptions = PLAIN_KEYBOARD, + textStyle = MaterialTheme.typography.bodyLarge.copy(fontFamily = FontFamily.Monospace), + supportingText = { Text("Fills the item's username, password, and one-time code, if it has one. Crumble checks it can read them when you save.") }, + modifier = Modifier.fillMaxWidth(), + ) + } else { + SecretSourceField( + model = model, + label = "Username", + draft = form.username, + onChange = { update(form.copy(username = it)) }, + valueDescription = "Stored encrypted and never shown again.", + valuePlaceholder = keepPlaceholder(fields?.username), + concealed = false, + enabled = !form.saving, + ) + SecretSourceField( + model = model, + label = "Password", + draft = form.password, + onChange = { update(form.copy(password = it)) }, + valueDescription = "Stored encrypted and never shown again. Desktop jobs fill it without seeing it.", + valuePlaceholder = keepPlaceholder(fields?.password), + enabled = !form.saving, + ) + Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween) { + Text("One-time code", style = MaterialTheme.typography.bodyMedium) + Switch(checked = form.hasCode, enabled = !form.saving, onCheckedChange = { update(form.copy(hasCode = it)) }) + } + if (form.hasCode) { + SecretSourceField( + model = model, + label = "One-time code secret", + draft = form.code, + onChange = { update(form.copy(code = it)) }, + valueDescription = "The setup key or otpauth:// URI from the site's two-factor setup. Crumble computes each code from it.", + valuePlaceholder = keepPlaceholder(fields?.one_time_code), + enabled = !form.saving, + ) + } + } + } +} + +@Composable +private fun ManagerRow(model: AppModel, manager: PasswordManager, shape: Shape) { + val inUse = manager.usedBy.isNotEmpty() + val busy = "password-manager:${manager.id}" in model.pendingMutations + GroupedItem( + shape = shape, + leading = { LetterTile(manager.name) }, + trailing = { + when { + busy -> CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) + manager.connected -> OverflowMenu { close -> + DropdownMenuItem(text = { Text("Replace token") }, onClick = { + close() + model.openManagerToken(manager) + }) + DropdownMenuItem( + text = { Text(if (inUse) "Disconnect (in use)" else "Disconnect") }, + enabled = !inUse, + onClick = { + close() + model.disconnectManager(manager) + }, + ) + } + else -> OutlinedButton(onClick = { model.openManagerToken(manager) }) { Text("Connect") } + } + }, + ) { + RowTitle(manager.name + if (inUse) " (used by ${manager.usedBy.size})" else "") + } +} + +@Composable +fun PasswordManagersPanel(model: AppModel) { + Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 24.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + SecretNote("Credentials, provider API keys, and MCP server tokens can be read from a connected password manager instead of being stored in Crumble.") + SheetErrorBanner(model.passwordManagersError) + if (!model.passwordManagersLoaded && model.passwordManagersError.isEmpty()) SecretNote("Loading…") + Column(verticalArrangement = Arrangement.spacedBy(ROW_GAP)) { + model.passwordManagers.forEachIndexed { index, manager -> + ManagerRow(model, manager, groupedShape(index, model.passwordManagers.size)) + } + } + } +} + +@Composable +fun ManagerTokenDialog(model: AppModel, form: ManagerTokenForm) { + val manager = form.manager + AlertDialog( + onDismissRequest = { model.closeManagerToken() }, + title = { Text(if (manager.connected) "Replace ${manager.name} token" else "Connect ${manager.name}") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + SecretNote("Crumble signs in once to check the token and stores it encrypted. It only reads secrets you point it at.") + SheetErrorBanner(form.error) + OutlinedTextField( + value = form.token.text, + onValueChange = { text -> model.tokenForm?.let { model.tokenForm = it.copy(token = it.token.copy(text = text)) } }, + label = { Text(TOKEN_LABELS[manager.id] ?: "Token") }, + singleLine = true, + enabled = !form.saving, + visualTransformation = PasswordVisualTransformation(), + keyboardOptions = SECRET_KEYBOARD, + modifier = Modifier.fillMaxWidth(), + ) + if (manager.connected) SecretNote("Values read with the old token are dropped.") + } + }, + confirmButton = { + Button(enabled = form.ready, onClick = { model.saveManagerToken() }) { + if (form.saving) { + CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) + } else { + Text(if (manager.connected) "Save" else "Connect") + } + } + }, + dismissButton = { TextButton(onClick = { model.closeManagerToken() }) { Text("Cancel") } }, + ) +} diff --git a/app/src/main/java/dev/crumble/android/ui/SettingsSheet.kt b/app/src/main/java/dev/crumble/android/ui/SettingsSheet.kt index 944fcd9..b289eca 100644 --- a/app/src/main/java/dev/crumble/android/ui/SettingsSheet.kt +++ b/app/src/main/java/dev/crumble/android/ui/SettingsSheet.kt @@ -1,5 +1,18 @@ package dev.crumble.android.ui +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.Icons +import androidx.compose.material3.SingleChoiceSegmentedButtonRow +import androidx.compose.material3.SegmentedButtonDefaults +import androidx.compose.material3.SegmentedButton +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.foundation.layout.padding +import dev.crumble.android.model.SETTINGS_GROUPS +import dev.crumble.android.model.Route +import androidx.compose.material3.Icon +import androidx.compose.foundation.layout.fillMaxSize +import android.content.Intent +import android.provider.Settings import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -9,200 +22,274 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button -import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExposedDropdownMenuBox -import androidx.compose.material3.ExposedDropdownMenuDefaults import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.ExposedDropdownMenuAnchorType -import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextButton 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.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.unit.dp +import dev.crumble.android.model.AccountMode import dev.crumble.android.model.AppModel +import dev.crumble.android.model.ThemeChoice +import dev.crumble.android.model.canCreateAccount +import dev.crumble.android.model.isExposedHttp +import dev.crumble.android.model.replyNotificationsDescription -@OptIn(ExperimentalMaterial3Api::class) @Composable -fun SettingsDialog(model: AppModel) { - var providerMenuExpanded by remember { mutableStateOf(false) } - val configured = model.providers.filter { it.configured }.map { it.provider } - - LaunchedEffect(Unit) { - model.loadProviders() +private fun SwitchRow( + title: String, + checked: Boolean, + onCheckedChange: (Boolean) -> Unit, + enabled: Boolean = true, + description: String? = null, +) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Column(modifier = Modifier.weight(1f)) { + Text(title, style = MaterialTheme.typography.bodyLarge) + description?.let { + Text( + text = it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + Switch(checked = checked, onCheckedChange = onCheckedChange, enabled = enabled) } +} - AlertDialog( - onDismissRequest = { - model.errorText = "" - model.showingSettings = false - }, - title = { Text("Settings") }, - text = { - Column( - modifier = Modifier.verticalScroll(rememberScrollState()), - verticalArrangement = Arrangement.spacedBy(16.dp), - ) { - SheetErrorBanner(model.errorText) +@Composable +private fun NotificationSettingsSection(model: AppModel) { + val context = LocalContext.current + val on = model.replyNotifications && model.notificationsAllowed - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - Text( - text = "Server", - style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.primary, - ) - OutlinedTextField( - value = model.serverURL, - onValueChange = { model.serverURL = it }, - label = { Text("Server URL") }, - placeholder = { Text("http://10.0.2.2:7337") }, - singleLine = true, - modifier = Modifier.fillMaxWidth(), - ) - OutlinedTextField( - value = model.token, - onValueChange = { model.token = it }, - label = { Text("Server token") }, - placeholder = { Text("Required") }, - visualTransformation = PasswordVisualTransformation(), - singleLine = true, - modifier = Modifier.fillMaxWidth(), + GroupLabel("Notifications") + GroupCard { + SwitchRow( + title = "Bot replies", + description = replyNotificationsDescription(model.replyNotifications, model.notificationsAllowed), + checked = on, + onCheckedChange = model::changeReplyNotifications, + ) + if (!model.notificationsAllowed) { + TextButton( + onClick = { + context.startActivity( + Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS) + .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName), ) - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(10.dp), - ) { - Button( - onClick = { model.saveSettings() }, - enabled = !model.savingConnection, - ) { - Text("Save Connection") - } - if (model.savingConnection) { - CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp) - Text( - text = "Connecting…", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - Text( - text = "The token stays encrypted in the Android Keystore. On the Android emulator, use http://10.0.2.2:7337 to reach a server running on your computer.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, + }, + ) { + Text("Open Android settings") + } + } + SwitchRow( + title = "Sound", + checked = model.notificationSound, + onCheckedChange = model::changeNotificationSound, + enabled = on, + ) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun ThemeSection(model: AppModel) { + GroupLabel("Theme") + SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { + ThemeChoice.entries.forEachIndexed { index, choice -> + SegmentedButton( + selected = model.theme == choice, + onClick = { model.chooseTheme(choice) }, + shape = SegmentedButtonDefaults.itemShape(index, ThemeChoice.entries.size), + label = { Text(choice.label) }, + ) + } + } +} + +private fun settingsSubtitle(page: Route): String? = when (page) { + Route.General -> "Notifications, theme, and account" + Route.Providers -> "API keys and account sign-in" + Route.JudgeModel -> "Checks what desktop jobs do" + Route.VisionModel -> "Describes images" + Route.WebSearch -> "Search provider" + Route.Credentials -> "Secrets your bots can use" + Route.Logins -> "Sites your bots can sign in to" + Route.PasswordManagers -> "1Password and Bitwarden" + Route.Integrations -> "MCP servers" + Route.Coding -> "GitHub and workspaces" + Route.MessageGateways -> "Talk to bots from other apps" + Route.EventRelay -> "Events from outside" + Route.Skills -> "Skills your bots follow" + Route.Avatars -> "Gallery and previews" + Route.Users -> "Accounts and invites" + else -> null +} + +/** Everything the website keeps under Settings, laid out like the system Settings app. */ +@Composable +fun SettingsPanel(model: AppModel) { + val tones = Tone.entries + Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 24.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + SearchPill(hint = "Search settings", onClick = { model.showingPalette = true }) { + Icon( + Icons.Default.Search, + contentDescription = null, + modifier = Modifier.padding(start = 8.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + SETTINGS_GROUPS.forEachIndexed { groupIndex, group -> + val pages = group.filter { it != Route.Users || model.isAdmin == true } + Column(verticalArrangement = Arrangement.spacedBy(ROW_GAP)) { + pages.forEachIndexed { index, page -> + GroupedRow( + title = page.title, + subtitle = settingsSubtitle(page), + shape = groupedShape(index, pages.size), + onClick = { model.navigate(page) }, + leading = { IconTile(routeIcon(page), tones[groupIndex % tones.size]) }, ) } + } + } + } +} - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - Text( - text = "Provider API Keys", - style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.primary, - ) - if (model.providers.isEmpty()) { - OutlinedTextField( - value = model.provider, - onValueChange = { model.provider = it }, - label = { Text("Provider") }, - placeholder = { Text("melious") }, - singleLine = true, - modifier = Modifier.fillMaxWidth(), - ) - } else { - ExposedDropdownMenuBox( - expanded = providerMenuExpanded, - onExpandedChange = { providerMenuExpanded = it }, - ) { - OutlinedTextField( - value = model.provider, - onValueChange = {}, - readOnly = true, - label = { Text("Provider") }, - trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = providerMenuExpanded) }, - modifier = Modifier - .menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable) - .fillMaxWidth(), - ) - ExposedDropdownMenu( - expanded = providerMenuExpanded, - onDismissRequest = { providerMenuExpanded = false }, - ) { - for (item in model.providers) { - DropdownMenuItem( - text = { Text(item.provider) }, - onClick = { - model.provider = item.provider - providerMenuExpanded = false - }, - ) - } - } - } - } - OutlinedTextField( - value = model.providerKey, - onValueChange = { model.providerKey = it }, - label = { Text("API key") }, - placeholder = { Text("Paste a key") }, - visualTransformation = PasswordVisualTransformation(), - singleLine = true, - modifier = Modifier.fillMaxWidth(), - ) - val isMutatingKey = model.pendingMutations.contains("provider:${model.provider}") - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - Button( - onClick = { model.saveProviderKey() }, - enabled = !isMutatingKey, - ) { - Text("Save Key") - } - OutlinedButton( - onClick = { model.removeProviderKey() }, - enabled = !isMutatingKey, - colors = ButtonDefaults.outlinedButtonColors( - contentColor = MaterialTheme.colorScheme.error, - ), - ) { - Text("Remove Key") - } - if (isMutatingKey) { - CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) - } - } - val prefix = if (configured.isEmpty()) "" else "Configured: ${configured.joinToString(", ")}. " +@Composable +fun GeneralPanel(model: AppModel) { + val signingUp = model.accountMode == AccountMode.SignUp + + Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 24.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + SheetErrorBanner(model.errorText) + + if (model.token.isNotEmpty()) { + NotificationSettingsSection(model) + ThemeSection(model) + } + + GroupLabel("Server") + GroupCard { + model.client?.baseURL?.takeIf { model.token.isNotEmpty() }?.let { CopyField("Address", it) } + OutlinedTextField( + value = model.serverURL, + onValueChange = { model.serverURL = it }, + label = { Text("Server URL") }, + placeholder = { Text("http://10.0.2.2:7337") }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + if (isExposedHttp(model.serverURL)) { + Text( + text = "This server uses http, so your password and messages can be read on the network.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } + if (signingUp) { + OutlinedTextField( + value = model.accountName, + onValueChange = { model.accountName = it }, + label = { Text("Name") }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + } + OutlinedTextField( + value = model.email, + onValueChange = { model.email = it }, + label = { Text("Email") }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + OutlinedTextField( + value = model.password, + onValueChange = { model.password = it }, + label = { Text("Password") }, + placeholder = { Text(if (model.token.isEmpty() || signingUp) "Required" else "Signed in") }, + visualTransformation = PasswordVisualTransformation(), + keyboardOptions = SECRET_KEYBOARD, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + if (signingUp) { + OutlinedTextField( + value = model.inviteCode, + onValueChange = { model.inviteCode = it }, + label = { Text("Invite code") }, + placeholder = { Text("Optional") }, + supportingText = { Text("Paste the invite link or its code.") }, + keyboardOptions = SECRET_KEYBOARD, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + } + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Button( + onClick = { model.saveSettings() }, + enabled = !model.savingConnection && + (!signingUp || canCreateAccount(model.accountName, model.email, model.password)), + ) { + Text(if (signingUp) "Create account" else "Save Connection") + } + if (model.savingConnection) { + CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp) Text( - text = "${prefix}Keys are stored encrypted on your server.", + text = "Connecting…", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) } } - }, - confirmButton = { TextButton( - onClick = { - model.errorText = "" - model.showingSettings = false - }, + onClick = { model.switchAccountMode() }, + enabled = !model.savingConnection, ) { - Text("Done") + Text(if (signingUp) "Already have an account? Sign in" else "Create an account") } - }, - ) + Text( + text = "Your session stays encrypted in the Android Keystore; the password is not stored. On the Android emulator, use http://10.0.2.2:7337 to reach a server running on your computer.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (model.token.isNotEmpty() && !signingUp) { + GroupLabel("Account") + GroupedRow( + title = if (model.signingOut) "Signing out…" else "Sign out", + subtitle = model.email.ifEmpty { null }, + titleColor = MaterialTheme.colorScheme.error, + shape = groupedShape(0, 1), + enabled = !model.signingOut && !model.savingConnection, + onClick = { model.signOut() }, + ) + } + } } diff --git a/app/src/main/java/dev/crumble/android/ui/SkillsScreen.kt b/app/src/main/java/dev/crumble/android/ui/SkillsScreen.kt new file mode 100644 index 0000000..02ffa3b --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/SkillsScreen.kt @@ -0,0 +1,756 @@ +package dev.crumble.android.ui + +import androidx.compose.foundation.shape.CircleShape +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.ColumnScope +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.PaddingValues +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.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.ExpandLess +import androidx.compose.material.icons.filled.ExpandMore +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Checkbox +import androidx.compose.material3.CheckboxColors +import androidx.compose.material3.CheckboxDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.FilterChip +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TriStateCheckbox +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.graphics.Shape +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.state.ToggleableState +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import dev.crumble.android.generated.SkillCandidate +import dev.crumble.android.generated.SkillListing +import dev.crumble.android.generated.SkillOrigin +import dev.crumble.android.generated.SkillPackage +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.BulkAction +import dev.crumble.android.model.InstalledSkillView +import dev.crumble.android.model.SKILLS_ALL +import dev.crumble.android.model.SKILLS_DEFAULT +import dev.crumble.android.model.SKILLS_SHARED +import dev.crumble.android.model.SelectableSkill +import dev.crumble.android.model.SharedSkill +import dev.crumble.android.model.SkillInstallForm +import dev.crumble.android.model.SkillUpdateView +import dev.crumble.android.model.installLabel +import dev.crumble.android.model.label +import dev.crumble.android.model.lineDiff +import dev.crumble.android.model.matchesSkill +import dev.crumble.android.model.selectionCatalog +import dev.crumble.android.model.skillGlimpse +import dev.crumble.android.model.skillLines +import dev.crumble.android.model.skillSummary +import dev.crumble.android.model.skippedNote +import dev.crumble.android.model.visibleIn + +private fun SkillOrigin.folder() = "$repository${if (path.isEmpty()) "" else "/$path"}" + +private val STATUS_LABELS = mapOf("installed" to "Installed", "update" to "Update available") + +@Composable +private fun Muted(text: String, maxLines: Int = Int.MAX_VALUE) { + Text( + text, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = maxLines, + overflow = TextOverflow.Ellipsis, + ) +} + +@Composable +internal fun Pill(text: String) { + Surface(color = MaterialTheme.colorScheme.secondaryContainer, shape = RoundedCornerShape(50)) { + Text(text, style = MaterialTheme.typography.labelSmall, modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp)) + } +} + +@Composable +fun ConfirmDialog(title: String, text: String, confirmLabel: String, onConfirm: () -> Unit, onDismiss: () -> Unit, destructive: Boolean = true) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title) }, + text = { Text(text) }, + confirmButton = { + TextButton( + onClick = { + onDismiss() + onConfirm() + }, + colors = if (destructive) ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error) else ButtonDefaults.textButtonColors(), + ) { Text(confirmLabel) } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +fun BotPills(bots: List, isOn: (Agent) -> Boolean, onToggle: (Agent, Boolean) -> Unit, enabled: (Agent) -> Boolean = { true }) { + FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + for (bot in bots) { + val on = isOn(bot) + FilterChip( + selected = on, + enabled = enabled(bot), + onClick = { onToggle(bot, !on) }, + label = { Text(bot.name) }, + leadingIcon = { BotAvatarView(agent = bot, size = 16.dp) }, + ) + } + } +} + +@Composable +private fun UsedByField(bots: List, isOn: (Agent) -> Boolean, onToggle: (Agent, Boolean) -> Unit, enabled: (Agent) -> Boolean = { true }) { + if (bots.isEmpty()) return + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text("Used by", style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.SemiBold)) + BotPills(bots, isOn, onToggle, enabled) + } +} + +/** A form field choosing which bots use a shared skill. */ +@Composable +fun SkillUsedByField(bots: List, selected: Set, onChange: (Set) -> Unit) { + UsedByField(bots, { it.id in selected }, { bot, on -> onChange(if (on) selected + bot.id else selected - bot.id) }) +} + +@Composable +private fun SelectionBox(model: AppModel, ids: List, label: String, busy: Boolean, colors: CheckboxColors = CheckboxDefaults.colors()) { + if (ids.isEmpty()) return + val count = ids.count { it in model.selectedSkills } + val state = when (count) { + 0 -> ToggleableState.Off + ids.size -> ToggleableState.On + else -> ToggleableState.Indeterminate + } + TriStateCheckbox( + state = state, + enabled = !busy, + onClick = { model.toggleSkillSelection(ids, count != ids.size) }, + colors = colors, + modifier = Modifier.semantics { contentDescription = label }, + ) +} + +@Composable +private fun SelectAll(model: AppModel, ids: List, label: String, busy: Boolean) { + if (ids.isEmpty()) return + Row(verticalAlignment = Alignment.CenterVertically) { + SelectionBox(model, ids, label, busy) + Muted("Select all") + } +} + +@Composable +private fun RowMenu(content: @Composable (close: () -> Unit) -> Unit) { + var open by remember { mutableStateOf(false) } + Box { + IconButton(onClick = { open = true }) { Icon(Icons.Default.MoreVert, contentDescription = "More") } + DropdownMenu(expanded = open, onDismissRequest = { open = false }) { content { open = false } } + } +} + +/** The checkbox takes the tile's place on a selectable row, so the name keeps its width on a phone. */ +@Composable +private fun TileSelectionBox(model: AppModel, id: String, label: String, busy: Boolean) { + val tone = Tone.Lavender + SelectionBox( + model, + listOf(id), + label, + busy, + CheckboxDefaults.colors(checkedColor = tone.content, uncheckedColor = tone.content, checkmarkColor = tone.container), + ) +} + +/** A skill row: its name and first line, and what follows on the right. */ +@Composable +private fun SkillRow( + name: String, + line: String, + onOpen: () -> Unit, + shape: Shape, + selection: (@Composable () -> Unit)? = null, + badge: String? = null, + usage: String? = null, + actions: @Composable () -> Unit = {}, + below: (@Composable ColumnScope.() -> Unit)? = null, +) { + GroupedItem( + shape = shape, + onClick = onOpen, + leading = { + if (selection != null) ToneTile(Tone.Lavender) { selection() } else LetterTile(name) + }, + trailing = { actions() }, + below = below, + ) { + RowTitle(name, maxLines = 1) + RowSubtitle(line, maxLines = 1) + if (usage != null) RowSubtitle(usage) + if (badge != null) Pill(badge) + } +} + +private fun usedByLine(model: AppModel, skillID: String): String? = + model.agents.count { it.sharedSkills?.contains(skillID) == true }.takeIf { it > 0 }?.let { "(used by $it)" } + +@Composable +private fun SharedSkillRow(model: AppModel, skill: SharedSkill, busy: Boolean, shape: Shape) { + var deleting by remember(skill.id) { mutableStateOf(false) } + var expanded by remember(skill.id) { mutableStateOf(false) } + val pending = skill.id.startsWith("pending-") || "skill:${skill.id}" in model.pendingMutations + val origin = skill.origin + val update = skill.update + SkillRow( + name = skill.name, + line = skillSummary(skill.description, skill.instructions), + shape = shape, + selection = if (pending) null else { + { TileSelectionBox(model, skill.id, "Select ${skill.name} (Shared)", busy) } + }, + badge = update?.let { if (it.removed) "Removed upstream" else "Update available" }, + usage = usedByLine(model, skill.id), + onOpen = { if (origin != null) model.openInstalledSkill(skill.id) else expanded = !expanded }, + actions = { + RowMenu { close -> + if (origin != null) { + DropdownMenuItem(text = { Text("View") }, onClick = { close(); model.openInstalledSkill(skill.id) }) + if (update != null && !update.removed) { + DropdownMenuItem(text = { Text("Update") }, onClick = { close(); model.openSkillUpdate(skill.id) }) + } + DropdownMenuItem(text = { Text("Make a copy") }, enabled = !pending, onClick = { close(); model.copySkill(skill.id) }) + } else { + DropdownMenuItem(text = { Text("Edit") }, enabled = !pending, onClick = { close(); model.openSkillForm(skill.id) }) + } + HorizontalDivider() + DropdownMenuItem( + text = { Text(if (origin != null) "Uninstall" else "Delete", color = MaterialTheme.colorScheme.error) }, + enabled = !pending, + onClick = { close(); deleting = true }, + ) + } + }, + below = if (!expanded) null else { + { + Text(skill.instructions, style = MaterialTheme.typography.bodyMedium) + Text( + "Assign to bots", + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 6.dp), + ) + for (agent in model.agents) { + Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween) { + Text(agent.name, style = MaterialTheme.typography.bodyMedium) + Switch( + checked = agent.sharedSkills?.contains(skill.id) == true, + enabled = "agent-shared-skills:${agent.id}" !in model.pendingMutations, + onCheckedChange = { model.setSharedSkillEnabled(agent.id, skill.id, it) }, + ) + } + } + } + }, + ) + if (deleting) { + ConfirmDialog( + title = if (origin != null) "Uninstall ${skill.name}?" else "Delete ${skill.name}?", + text = if (origin != null) "Every bot that uses it loses it. You can install it again from GitHub." else "Every bot that uses it loses it. This cannot be undone.", + confirmLabel = if (origin != null) "Uninstall" else "Delete", + onConfirm = { model.deleteSharedSkill(skill.id) }, + onDismiss = { deleting = false }, + ) + } +} + +@Composable +private fun PersonalSkillRow(model: AppModel, agent: Agent, skill: SkillPackage, busy: Boolean, shape: Shape) { + var deleting by remember(skill.id) { mutableStateOf(false) } + val pending = skill.id.startsWith("pending-") || "agent-skill:${skill.id}" in model.pendingMutations + SkillRow( + name = skill.name, + line = skillGlimpse(skill.instructions), + shape = shape, + selection = if (pending) null else { + { TileSelectionBox(model, skill.id, "Select ${skill.name} (${agent.name})", busy) } + }, + badge = if (skill.pinned) "Pinned" else null, + onOpen = { if (!pending) model.openSkillForm(skill.id, agent.id) }, + actions = { + RowMenu { close -> + DropdownMenuItem(text = { Text("Edit") }, enabled = !pending, onClick = { close(); model.openSkillForm(skill.id, agent.id) }) + DropdownMenuItem(text = { Text(if (skill.pinned) "Unpin" else "Pin") }, enabled = !pending, onClick = { close(); model.toggleSkillPin(agent.id, skill.id) }) + HorizontalDivider() + DropdownMenuItem( + text = { Text("Delete", color = MaterialTheme.colorScheme.error) }, + enabled = !pending, + onClick = { close(); deleting = true }, + ) + } + }, + ) + if (deleting) { + ConfirmDialog( + title = "Delete ${skill.name}?", + text = "${agent.name} loses this skill. This cannot be undone.", + confirmLabel = "Delete", + onConfirm = { model.deleteAgentSkill(agent.id, skill.id) }, + onDismiss = { deleting = false }, + ) + } +} + +@Composable +private fun BundledRow(skill: SharedSkill, shape: Shape) { + var expanded by remember(skill.id) { mutableStateOf(false) } + GroupedItem( + shape = shape, + onClick = { expanded = !expanded }, + leading = { LetterTile(skill.name) }, + trailing = { Icon(if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore, contentDescription = null) }, + below = if (!expanded) null else { + { + Text(skill.instructions.ifEmpty { "No instructions." }, style = MaterialTheme.typography.bodyMedium) + skill.path?.let { Text(it, style = MaterialTheme.typography.labelSmall, fontFamily = FontFamily.Monospace, color = MaterialTheme.colorScheme.onSurfaceVariant) } + } + }, + ) { + RowTitle(skill.name, maxLines = 1) + RowSubtitle(skillSummary(skill.description, skill.instructions), maxLines = 1) + } +} + +@Composable +private fun ScopeChips(model: AppModel, scope: String, onScope: (String) -> Unit) { + val shared = model.sharedSkills.count { !it.isDefault } + val bundled = model.sharedSkills.count { it.isDefault } + val own = model.agents.sumOf { model.agentSkills[it.id].orEmpty().size } + val partial = model.agentSkillErrors.isNotEmpty() + fun counted(label: String, count: Int?) = if (count == null) label else "$label · $count" + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) { + FilterChip(scope == SKILLS_ALL, { onScope(SKILLS_ALL) }, { Text(counted("All", if (partial) null else shared + own + bundled)) }) + FilterChip(scope == SKILLS_SHARED, { onScope(SKILLS_SHARED) }, { Text(counted("Shared", shared)) }) + for (bot in model.agents) { + val count = if (bot.id in model.agentSkillErrors) null else model.agentSkills[bot.id].orEmpty().size + FilterChip( + selected = scope == bot.id, + onClick = { onScope(bot.id) }, + label = { Text(counted(bot.name, count)) }, + leadingIcon = { BotAvatarView(agent = bot, size = 18.dp) }, + ) + } + FilterChip(scope == SKILLS_DEFAULT, { onScope(SKILLS_DEFAULT) }, { Text(counted("Default", bundled)) }) + } +} + +@Composable +private fun ErrorLine(text: String) { + Text(text, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) +} + +@Composable +fun SkillsPanel(model: AppModel) { + var search by remember { mutableStateOf("") } + var scope by remember { mutableStateOf(SKILLS_ALL) } + var dialog by remember { mutableStateOf(null) } + val needle = search.trim().lowercase() + val catalog = selectionCatalog(model.sharedSkills, model.agents, model.agentSkills) + val picked = catalog.filter { it.id in model.selectedSkills } + val busy = "skills:bulk" in model.pendingMutations + val shared = model.sharedSkills.filter { !it.isDefault && matchesSkill(it.name, it.instructions, needle) } + val bundled = model.sharedSkills.filter { it.isDefault && matchesSkill(it.name, it.instructions, needle) } + val ownScope = scope != SKILLS_SHARED && scope != SKILLS_DEFAULT + val owners = model.agents.filter { it.id !in model.agentSkillErrors }.filter { bot -> + if (scope == SKILLS_ALL) model.agentSkills[bot.id].orEmpty().any { matchesSkill(it.name, it.instructions, needle) } else bot.id == scope + } + + Column(modifier = Modifier.fillMaxSize()) { + LazyColumn( + modifier = Modifier.weight(1f), + contentPadding = PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + item { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField( + value = search, + onValueChange = { search = it }, + label = { Text("Search skills") }, + shape = CircleShape, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) { + if (model.sharedSkills.any { it.origin != null }) { + OutlinedButton(enabled = !model.checkingSkillUpdates, onClick = { model.checkSkillUpdates() }) { + if (model.checkingSkillUpdates) { + CircularProgressIndicator(modifier = Modifier.size(14.dp), strokeWidth = 2.dp) + Spacer(Modifier.size(6.dp)) + } + Text("Check for updates") + } + } + OutlinedButton(onClick = { model.openSkillInstall() }) { Text("Install from GitHub") } + } + ScopeChips(model, scope) { scope = it } + } + } + if (model.skillCheckFailures.isNotEmpty()) { + item { ErrorLine(model.skillCheckFailures.joinToString(" ")) } + } + if (model.bulkReport.isNotEmpty()) { + item { + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + for (line in model.bulkReport) Text(line.text, style = MaterialTheme.typography.bodySmall) + } + } + } + items(model.agents.filter { it.id in model.agentSkillErrors }, key = { "error-${it.id}" }) { bot -> + ErrorLine("Could not load ${bot.name}'s skills: ${model.agentSkillErrors[bot.id]}") + } + item { SelectAll(model, catalog.visibleIn(scope, needle).map { it.id }, "Select all results", busy) } + if (scope == SKILLS_ALL || scope == SKILLS_SHARED) { + item { + SectionFrame(title = "Shared", footer = "Turn a shared skill on for the bots that should have it.") { + SelectAll(model, shared.filterNot { it.id.startsWith("pending-") }.map { it.id }, "Select all shared skills", busy) + GroupedRows { + if (shared.isEmpty()) note("No shared skills yet.") + for (skill in shared) row { shape -> SharedSkillRow(model, skill, busy, shape) } + add("Add shared skill") { model.openSkillForm("") } + } + } + } + } + if (ownScope) { + items(owners, key = { it.id }) { agent -> + val skills = model.agentSkills[agent.id].orEmpty() + val shown = skills.filter { matchesSkill(it.name, it.instructions, needle) } + SectionFrame(title = agent.name, footer = "Personal skills only ${agent.name} follows.") { + SelectAll(model, shown.filterNot { it.id.startsWith("pending-") }.map { it.id }, "Select all ${agent.name} skills", busy) + GroupedRows { + if (shown.isEmpty()) note(if (skills.isEmpty()) "No personal skills yet." else "No skills match your search.") + for (skill in shown) row { shape -> PersonalSkillRow(model, agent, skill, busy, shape) } + add("Add personal skill") { model.openSkillForm("", agent.id) } + } + } + } + } + if (scope == SKILLS_ALL || scope == SKILLS_DEFAULT) { + item { + RowsSection(title = "Default", footer = "Every bot has these. They're files on the server: edit them there and restart it.") { + if (bundled.isEmpty()) note("No default skills.") + for (skill in bundled) row { shape -> BundledRow(skill, shape) } + } + } + } + } + if (picked.isNotEmpty()) { + BulkBar(model, picked, busy) { action -> if (action == BulkAction.update) model.runBulkAction(action) else dialog = action } + } + } + + when (val action = dialog) { + BulkAction.delete -> ConfirmDialog( + title = "Delete ${picked.size} skills?", + text = "Delete: ${picked.joinToString(", ") { it.label }}. Shared skills are removed from every bot. Existing bot-specific copies are kept. This cannot be undone here.", + confirmLabel = "Delete", + onConfirm = { model.runBulkAction(BulkAction.delete) }, + onDismiss = { dialog = null }, + ) + BulkAction.assign, BulkAction.remove -> BotTargetsDialog( + action = action, + bots = model.agents, + picked = picked, + onSubmit = { targets -> + dialog = null + model.runBulkAction(action, targets) + }, + onClose = { dialog = null }, + ) + BulkAction.update, null -> Unit + } +} + +private val BULK_ACTIONS = listOf( + BulkAction.update to "Update", + BulkAction.assign to "Assign to bots", + BulkAction.remove to "Remove from bots", + BulkAction.delete to "Delete", +) + +@Composable +private fun BulkBar(model: AppModel, picked: List, busy: Boolean, onAction: (BulkAction) -> Unit) { + val notInstalled = picked.filter { !it.installed } + Surface( + color = cardColor, + shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp), + modifier = Modifier.fillMaxWidth(), + ) { + Column(modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.horizontalScroll(rememberScrollState())) { + IconButton(enabled = !busy, onClick = { model.selectedSkills = emptySet() }) { + Icon(Icons.Default.Close, contentDescription = "Clear selection") + } + Text("${picked.size} selected", style = MaterialTheme.typography.labelLarge) + for ((action, label) in BULK_ACTIONS) { + val disabled = when (action) { + BulkAction.update -> notInstalled.size == picked.size + BulkAction.assign, BulkAction.remove -> model.agents.isEmpty() + BulkAction.delete -> false + } + TextButton(enabled = !busy && !disabled, onClick = { onAction(action) }) { + Text(label, color = if (action == BulkAction.delete && !busy) MaterialTheme.colorScheme.error else androidx.compose.ui.graphics.Color.Unspecified) + } + } + } + if (notInstalled.isNotEmpty()) { + Muted("Update skips skills not installed from GitHub: ${notInstalled.joinToString(", ") { it.label }}.") + } + if (busy) Muted("Applying action…") + } + } +} + +@Composable +private fun BotTargetsDialog(action: BulkAction, bots: List, picked: List, onSubmit: (Set) -> Unit, onClose: () -> Unit) { + val assign = action == BulkAction.assign + var targets by remember { mutableStateOf(emptySet()) } + AlertDialog( + onDismissRequest = onClose, + title = { Text(if (assign) "Assign to bots" else "Remove from bots") }, + text = { + Column(modifier = Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text( + if (assign) { + "Shared skills are enabled. Bot-specific skills are copied; existing linked copies and their edits are kept." + } else { + "Shared skills are disabled. Only linked bot-specific copies are deleted, including edited copies; same-name skills and the original are kept." + }, + style = MaterialTheme.typography.bodyMedium, + ) + Text(picked.joinToString(", ") { it.label }, style = MaterialTheme.typography.bodyMedium) + BotPills(bots, { it.id in targets }, { bot, on -> targets = if (on) targets + bot.id else targets - bot.id }) + } + }, + confirmButton = { Button(enabled = targets.isNotEmpty(), onClick = { onSubmit(targets) }) { Text(if (assign) "Assign" else "Remove") } }, + dismissButton = { TextButton(onClick = onClose) { Text("Cancel") } }, + ) +} + +@Composable +private fun CandidateRow(candidate: SkillCandidate, checked: Boolean, enabled: Boolean, onChange: (Boolean) -> Unit) { + val selectable = candidate.status == "new" + val note = candidate.problem ?: skippedNote(candidate.skipped) + Row(verticalAlignment = Alignment.Top) { + Checkbox(checked = checked, enabled = selectable && enabled, onCheckedChange = onChange) + Column(modifier = Modifier.padding(top = 10.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Text(candidate.name, style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Medium)) + STATUS_LABELS[candidate.status]?.let { Pill(it) } + } + if (candidate.description.isNotEmpty()) Muted(candidate.description) + if (note != null) { + if (candidate.problem != null) ErrorLine(note) else Muted(note) + } + } + } +} + +@Composable +private fun CandidateList(listing: SkillListing, form: SkillInstallForm, onToggle: (String, Boolean) -> Unit) { + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text("Skills in ${listing.repository} (${listing.branch})", style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.SemiBold)) + if (listing.skills.isEmpty()) Muted("No folder here has a SKILL.md.") + for (candidate in listing.skills) { + CandidateRow(candidate, candidate.path in form.picked, !form.installing) { onToggle(candidate.path, it) } + } + if (listing.omitted > 0) Muted("${listing.omitted} more aren't listed. Link to a folder to see them.") + } +} + +/** Finds the skills in a GitHub repository and installs the checked ones as shared skills. */ +@Composable +fun InstallSkillsDialog(model: AppModel, form: SkillInstallForm) { + val listing = form.listing + val idle = !form.browsing && !form.installing + AlertDialog( + onDismissRequest = { if (!form.installing) model.closeSkillInstall() }, + title = { Text("Install from GitHub") }, + text = { + Column(modifier = Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Muted("Installed skills are shared and read-only. You can update them when the repository changes.") + SheetErrorBanner(form.error) + OutlinedTextField( + value = form.location, + onValueChange = { model.changeSkillLocation(it) }, + enabled = !form.installing, + label = { Text("Repository") }, + placeholder = { Text("owner/repo") }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + Muted("A public repository, or a github.com link to a folder in one.") + if (form.browsing) CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp) + if (listing != null) { + OutlinedButton(enabled = idle, onClick = { model.findSkills() }) { Text("Find") } + CandidateList(listing, form) { path, on -> model.toggleSkillCandidate(path, on) } + UsedByField(model.agents, { it.id in form.botIDs }, { bot, on -> model.toggleInstallBot(bot.id, on) }, { !form.installing }) + } + if (form.installing) Muted("Installing…") + } + }, + confirmButton = { + if (listing != null) { + Button(enabled = idle && form.picked.isNotEmpty(), onClick = { model.installSkills() }) { Text(installLabel(form.picked.size)) } + } else { + Button(enabled = idle && form.location.isNotBlank(), onClick = { model.findSkills() }) { Text("Find skills") } + } + }, + dismissButton = { TextButton(enabled = !form.installing, onClick = { model.closeSkillInstall() }) { Text("Cancel") } }, + ) +} + +@Composable +private fun SkillContent(skill: SkillPackage) { + if (skill.description.isNotEmpty()) Text(skill.description, style = MaterialTheme.typography.bodyMedium) + Surface(color = sheetColor, shape = RoundedCornerShape(8.dp), modifier = Modifier.fillMaxWidth()) { + Text(skill.instructions, style = MaterialTheme.typography.bodySmall, fontFamily = FontFamily.Monospace, modifier = Modifier.padding(10.dp)) + } + if (skill.documents.isNotEmpty()) { + Text("Reference documents", style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.SemiBold)) + for (document in skill.documents) { + Text(document.path, style = MaterialTheme.typography.labelSmall, fontFamily = FontFamily.Monospace, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } +} + +/** An installed skill, read-only: its source, who uses it, its content, and a pending update. */ +@Composable +fun InstalledSkillDialog(model: AppModel, view: InstalledSkillView) { + val skill = model.sharedSkills.firstOrNull { it.id == view.skillID } ?: return + val close = { model.installedSkill = null } + AlertDialog( + onDismissRequest = close, + title = { Text(skill.name) }, + text = { + Column(modifier = Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Muted("Installed skills are read-only. Make a copy to change one.") + SheetErrorBanner(view.error) + skill.origin?.let { origin -> + Muted("From ${origin.folder()} on ${origin.branch}, commit ${origin.commit.take(7)}.") + } + UsedByField( + bots = model.agents, + isOn = { it.sharedSkills?.contains(skill.id) == true }, + onToggle = { bot, on -> model.setSharedSkillEnabled(bot.id, skill.id, on) }, + enabled = { "agent-shared-skills:${it.id}" !in model.pendingMutations }, + ) + skill.update?.let { update -> + Surface(color = MaterialTheme.colorScheme.secondaryContainer, shape = RoundedCornerShape(8.dp), modifier = Modifier.fillMaxWidth()) { + Row(modifier = Modifier.padding(10.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + if (update.removed) "This skill is no longer in the repository." else "A newer version is available.", + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.weight(1f), + ) + if (!update.removed) Button(onClick = { model.openSkillUpdate(skill.id) }) { Text("Review update") } + } + } + } + val full = view.full + if (full != null) { + SkillContent(full) + } else if (view.error.isEmpty()) { + CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp) + } + } + }, + confirmButton = { Button(onClick = close) { Text("Done") } }, + dismissButton = { + OutlinedButton(onClick = { + model.copySkill(skill.id) + close() + }) { Text("Make a copy") } + }, + ) +} + +/** The changes an update brings, and applying it. */ +@Composable +fun SkillUpdateDialog(model: AppModel, view: SkillUpdateView) { + val skill = model.sharedSkills.firstOrNull { it.id == view.skillID } + val current = view.current + val pending = view.pending + AlertDialog( + onDismissRequest = { if (!view.applying) model.skillUpdate = null }, + title = { Text("Update ${skill?.name.orEmpty()}") }, + text = { + Column(modifier = Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Muted("The update is recorded in the change log, so you can revert it.") + SheetErrorBanner(view.error) + if (current != null && pending != null) { + val lines = remember(current, pending) { + lineDiff(skillLines(current), skillLines(pending.name, pending.description, pending.instructions, pending.documents)) + } + DiffView(lines) + skippedNote(pending.skipped)?.let { Muted(it) } + } else if (view.error.isEmpty()) { + CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp) + } + if (view.applying) Muted("Updating…") + } + }, + confirmButton = { + Button(enabled = pending != null && !view.applying, onClick = { model.applySkillUpdate() }) { Text("Update") } + }, + dismissButton = { TextButton(enabled = !view.applying, onClick = { model.skillUpdate = null }) { Text("Cancel") } }, + ) +} diff --git a/app/src/main/java/dev/crumble/android/ui/TaskTiming.kt b/app/src/main/java/dev/crumble/android/ui/TaskTiming.kt new file mode 100644 index 0000000..b938f3f --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/TaskTiming.kt @@ -0,0 +1,286 @@ +package dev.crumble.android.ui + +import android.text.format.DateFormat +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.DatePicker +import androidx.compose.material3.DatePickerDialog +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ExposedDropdownMenuAnchorType +import androidx.compose.material3.ExposedDropdownMenuBox +import androidx.compose.material3.ExposedDropdownMenuDefaults +import androidx.compose.material3.FilterChip +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TimePicker +import androidx.compose.material3.rememberDatePickerState +import androidx.compose.material3.rememberTimePickerState +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.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import dev.crumble.android.model.MAX_CRON_CHARS +import dev.crumble.android.model.NextRun +import dev.crumble.android.model.Recurrence +import dev.crumble.android.model.TaskDraft +import dev.crumble.android.model.TaskWhen +import dev.crumble.android.model.WEEK +import dev.crumble.android.model.choice +import dev.crumble.android.model.choosing +import dev.crumble.android.model.describeCron +import dev.crumble.android.model.inTimezone +import dev.crumble.android.model.minuteChoices +import dev.crumble.android.model.nextRunOf +import dev.crumble.android.model.recurrenceOf +import dev.crumble.android.model.recurring +import dev.crumble.android.model.runningAt +import dev.crumble.android.model.timezoneChoices +import dev.crumble.android.model.wallClock +import dev.crumble.android.model.weekdayName +import java.time.Instant +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.ZoneOffset +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle +import java.time.format.TextStyle as DateTextStyle + +private val MONTH_DAYS = (1..31).toList() + +@Composable +internal fun TaskTimeFields(draft: TaskDraft, onChange: (TaskDraft) -> Unit) { + val choice = draft.choice + val recurrence = recurrenceOf(draft.cron) + Choice( + label = "When", + value = choice.label, + options = TaskWhen.entries, + optionLabel = { it.label }, + onPick = { onChange(draft.choosing(it)) }, + ) + when { + choice == TaskWhen.Once -> RunDateFields(draft, onChange) + choice == TaskWhen.Custom || recurrence == null -> CronField(draft, onChange) + else -> RecurrenceFields(recurrence) { onChange(draft.recurring(it)) } + } + TimezoneField(draft.timezone) { onChange(draft.inTimezone(it)) } + NextRunLine(draft) +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun Choice(label: String, value: String, options: List, optionLabel: (T) -> String, onPick: (T) -> Unit) { + var expanded by remember { mutableStateOf(false) } + ExposedDropdownMenuBox(expanded = expanded, onExpandedChange = { expanded = it }) { + OutlinedTextField( + value = value, + onValueChange = {}, + readOnly = true, + label = { Text(label) }, + trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) }, + modifier = Modifier.menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable).fillMaxWidth(), + ) + ExposedDropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { + for (option in options) { + DropdownMenuItem( + text = { Text(optionLabel(option)) }, + onClick = { + expanded = false + onPick(option) + }, + ) + } + } + } +} + +@Composable +private fun PickerRow(label: String, value: String, onClick: () -> Unit) { + GroupedRow(title = label, subtitle = value, shape = groupedShape(0, 1), onClick = onClick) +} + +@Composable +private fun RunDateFields(draft: TaskDraft, onChange: (TaskDraft) -> Unit) { + val local = draft.wallClock + var pickingDate by remember { mutableStateOf(false) } + var pickingTime by remember { mutableStateOf(false) } + PickerRow("Date", local.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM))) { pickingDate = true } + PickerRow("Time", timeText(local.toLocalTime())) { pickingTime = true } + if (pickingDate) { + RunDatePicker(local.toLocalDate(), onDismiss = { pickingDate = false }) { onChange(draft.runningAt(LocalDateTime.of(it, local.toLocalTime()))) } + } + if (pickingTime) { + ClockPicker(local.toLocalTime(), onDismiss = { pickingTime = false }) { onChange(draft.runningAt(LocalDateTime.of(local.toLocalDate(), it))) } + } +} + +private fun timeText(time: LocalTime) = time.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)) + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun RunDatePicker(initial: LocalDate, onDismiss: () -> Unit, onPick: (LocalDate) -> Unit) { + // The Material picker reads and writes midnight UTC, whatever zone the task runs in. + val state = rememberDatePickerState(initialSelectedDateMillis = initial.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()) + DatePickerDialog( + onDismissRequest = onDismiss, + confirmButton = { + TextButton( + onClick = { + state.selectedDateMillis?.let { onPick(Instant.ofEpochMilli(it).atZone(ZoneOffset.UTC).toLocalDate()) } + onDismiss() + }, + ) { Text("OK") } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) { DatePicker(state = state) } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun ClockPicker(initial: LocalTime, onDismiss: () -> Unit, onPick: (LocalTime) -> Unit) { + val state = rememberTimePickerState(initial.hour, initial.minute, DateFormat.is24HourFormat(LocalContext.current)) + AlertDialog( + onDismissRequest = onDismiss, + text = { TimePicker(state = state) }, + confirmButton = { + TextButton( + onClick = { + onPick(LocalTime.of(state.hour, state.minute)) + onDismiss() + }, + ) { Text("OK") } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} + +@Composable +private fun RecurrenceFields(recurrence: Recurrence, onChange: (Recurrence) -> Unit) { + if (recurrence.kind == TaskWhen.Hourly) { + Choice( + label = "Minute", + value = ":%02d".format(recurrence.minute), + options = minuteChoices(recurrence.minute), + optionLabel = { ":%02d".format(it) }, + onPick = { onChange(recurrence.copy(minute = it)) }, + ) + return + } + if (recurrence.kind == TaskWhen.Weekly) WeekdayToggles(recurrence.days) { onChange(recurrence.copy(days = it)) } + if (recurrence.kind == TaskWhen.Monthly) { + Choice( + label = "Day of the month", + value = recurrence.day.toString(), + options = MONTH_DAYS, + optionLabel = { it.toString() }, + onPick = { onChange(recurrence.copy(day = it)) }, + ) + } + var picking by remember { mutableStateOf(false) } + val time = LocalTime.of(recurrence.hour, recurrence.minute) + PickerRow("Time", timeText(time)) { picking = true } + if (picking) ClockPicker(time, onDismiss = { picking = false }) { onChange(recurrence.copy(hour = it.hour, minute = it.minute)) } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun WeekdayToggles(days: List, onChange: (List) -> Unit) { + FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + for (day in WEEK) { + val on = day in days + FilterChip( + selected = on, + enabled = !(on && days.size == 1), + onClick = { onChange(if (on) days - day else days + day) }, + label = { Text(weekdayName(day, DateTextStyle.SHORT)) }, + ) + } + } +} + +@Composable +private fun CronField(draft: TaskDraft, onChange: (TaskDraft) -> Unit) { + OutlinedTextField( + value = draft.cron, + onValueChange = { onChange(draft.copy(cron = it.take(MAX_CRON_CHARS))) }, + label = { Text("Cron expression") }, + placeholder = { Text("0 9 * * 1-5") }, + supportingText = { Text(describeCron(draft.cron, draft.timezone.trim())) }, + textStyle = TextStyle(fontFamily = FontFamily.Monospace), + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) +} + +@Composable +private fun TimezoneField(timezone: String, onPick: (String) -> Unit) { + var picking by remember { mutableStateOf(false) } + PickerRow("Time zone", timezone) { picking = true } + if (picking) TimezoneDialog(timezone, onDismiss = { picking = false }, onPick = onPick) +} + +@Composable +private fun TimezoneDialog(current: String, onDismiss: () -> Unit, onPick: (String) -> Unit) { + var query by remember { mutableStateOf("") } + val zones = remember(query, current) { timezoneChoices(query, current) } + Dialog(onDismissRequest = onDismiss) { + Surface(shape = MaterialTheme.shapes.extraLarge, color = pageColor) { + Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField( + value = query, + onValueChange = { query = it }, + label = { Text("Time zone") }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + LazyColumn(modifier = Modifier.fillMaxWidth().height(320.dp), verticalArrangement = Arrangement.spacedBy(ROW_GAP)) { + itemsIndexed(zones, key = { _, zone -> zone }) { index, zone -> + GroupedItem( + shape = groupedShape(index, zones.size), + onClick = { + onPick(zone) + onDismiss() + }, + ) { + RowTitle(zone, maxLines = 1, fontWeight = if (zone == current) FontWeight.SemiBold else null) + } + } + } + TextButton(onClick = onDismiss) { Text("Cancel") } + } + } + } +} + +@Composable +private fun NextRunLine(draft: TaskDraft) { + val muted = MaterialTheme.colorScheme.onSurfaceVariant + val error = MaterialTheme.colorScheme.error + when (val run = nextRunOf(draft)) { + NextRun.Never -> Text("This schedule never runs.", style = MaterialTheme.typography.bodySmall, color = error) + NextRun.Passed -> Text("This time has passed.", style = MaterialTheme.typography.bodySmall, color = error) + NextRun.Unknown -> Unit + is NextRun.At -> Text("${run.label} ${run.time} (${run.zone})", style = MaterialTheme.typography.bodySmall, color = muted) + } +} diff --git a/app/src/main/java/dev/crumble/android/ui/TasksScreen.kt b/app/src/main/java/dev/crumble/android/ui/TasksScreen.kt new file mode 100644 index 0000000..e038378 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/TasksScreen.kt @@ -0,0 +1,652 @@ +package dev.crumble.android.ui + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +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.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Cancel +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.Schedule +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ExposedDropdownMenuAnchorType +import androidx.compose.material3.ExposedDropdownMenuBox +import androidx.compose.material3.ExposedDropdownMenuDefaults +import androidx.compose.material3.FilterChip +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.PrimaryTabRow +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Tab +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +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.graphics.Color +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import dev.crumble.android.generated.ScriptRun +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.EventSource +import dev.crumble.android.model.EventSourceDraft +import dev.crumble.android.model.MAX_COMMAND_CHARS +import dev.crumble.android.model.MAX_EVENT_SOURCE_NAME_CHARS +import dev.crumble.android.model.Route +import dev.crumble.android.model.Schedule +import dev.crumble.android.model.ScheduleStatus +import dev.crumble.android.model.TaskDraft +import dev.crumble.android.model.TaskRun +import dev.crumble.android.model.TaskTab +import dev.crumble.android.model.activityTime +import dev.crumble.android.model.canRunScripts +import dev.crumble.android.model.describeTiming +import dev.crumble.android.model.finished +import dev.crumble.android.model.listedSchedules +import dev.crumble.android.model.scriptRunDuration +import dev.crumble.android.model.status +import dev.crumble.android.model.taskRuns + +private val SUCCESS = Color(0xFF059669) + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun TasksPanel(model: AppModel) { + Column(modifier = Modifier.fillMaxSize()) { + PrimaryTabRow(selectedTabIndex = model.taskTab.ordinal, containerColor = Color.Transparent) { + for (tab in TaskTab.entries) { + Tab( + selected = model.taskTab == tab, + onClick = { model.selectTaskTab(tab) }, + text = { Text(tab.label, maxLines = 1) }, + ) + } + } + when (model.taskTab) { + TaskTab.Tasks -> TaskList(model) + TaskTab.Runs -> RunList(model) + TaskTab.EventSources -> EventSourceList(model) + } + } +} + +@Composable +private fun TaskList(model: AppModel) { + if (model.agents.isEmpty()) { + EmptyWorkspacePlaceholder( + icon = Icons.Default.Schedule, + title = "No Tasks", + description = "Create an agent, then give it a task to run once or on a schedule.", + ) + return + } + val listed = listedSchedules(model.schedules) + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + items(model.agents, key = { it.id }) { agent -> + val tasks = listed.filter { it.agentId == agent.id } + RowsSection( + title = agent.name, + footer = "Runs in ${agent.name}’s chat, once or on a schedule.", + ) { + if (tasks.isEmpty()) note("No tasks yet.") + for (schedule in tasks) { + row { shape -> TaskRow(model, schedule, agent, shape) } + } + add("New Task") { model.openTaskForm("", agentID = agent.id) } + } + } + } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun TaskRow(model: AppModel, schedule: Schedule, agent: Agent, shape: Shape) { + val isPending = model.schedulePending(schedule.id) + var confirmingDelete by remember(schedule.id) { mutableStateOf(false) } + if (confirmingDelete) { + ConfirmDialog( + title = "Delete ${schedule.name}?", + text = "The task stops running. This cannot be undone.", + confirmLabel = "Delete", + onConfirm = { model.deleteSchedule(schedule.id) }, + onDismiss = { confirmingDelete = false }, + ) + } + GroupedItem( + shape = shape, + leading = { IconTile(routeIcon(Route.Tasks), Tone.Lavender) }, + below = { + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedButton( + onClick = { model.runSchedule(schedule.id) }, + enabled = schedule.enabled && !isPending && !model.pendingMutations.contains("schedule-run:${schedule.id}"), + ) { + Text("Run Now") + } + if (!schedule.finished) { + TextButton(onClick = { model.toggleSchedule(schedule.id) }, enabled = !isPending) { + Text(if (schedule.enabled) "Pause" else "Resume") + } + } + TextButton(onClick = { model.openTaskForm(schedule.id) }, enabled = !isPending) { + Text("Edit") + } + TextButton(onClick = { confirmingDelete = true }, enabled = !isPending) { + Text("Delete", color = MaterialTheme.colorScheme.error) + } + } + }, + ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + RowTitle(schedule.name, modifier = Modifier.weight(1f, fill = false)) + if (schedule.kind == "script") Pill("Script") + } + RowSubtitle( + text = if (schedule.kind == "script") schedule.command.orEmpty() else schedule.prompt, + maxLines = 2, + fontFamily = if (schedule.kind == "script") FontFamily.Monospace else null, + ) + RowSubtitle("${schedule.status.label} · ${describeTiming(schedule, model.eventSources)}") + val nextRun = schedule.nextRunAt + if (schedule.status == ScheduleStatus.Active && nextRun != null) { + RowSubtitle("Next run ${activityTime(nextRun)}") + } + val creator = schedule.createdByAgentId + if (creator != null && creator != agent.id) { + val creatorName = model.agents.firstOrNull { it.id == creator }?.name + if (creatorName != null) RowSubtitle("Scheduled by $creatorName") + } + } +} + +@Composable +private fun RunList(model: AppModel) { + val runs = taskRuns(model.schedules, model.executions, model.scriptRuns) + var open by remember { mutableStateOf(null) } + Column(modifier = Modifier.fillMaxSize()) { + if (model.taskRunsError.isNotEmpty()) { + Box(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) { + SheetErrorBanner(model.taskRunsError) + } + } + when { + runs.isNotEmpty() -> LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(ROW_GAP), + ) { + itemsIndexed(runs, key = { _, run -> run.id }) { index, run -> + val bot = model.agents.firstOrNull { it.id == run.agentId } + RunRow(run, bot, groupedShape(index, runs.size)) { + when { + run.script != null -> open = run + bot != null -> model.selectAgent(bot.id) + } + } + } + } + model.taskRunsLoading -> Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + CircularProgressIndicator() + } + model.taskRunsError.isEmpty() -> EmptyWorkspacePlaceholder( + icon = Icons.Default.Schedule, + title = "No runs yet", + description = "Each time a task runs, it shows up here.", + ) + } + } + open?.let { run -> + val script = run.script + if (script != null) RunDetailsDialog(run, script) { open = null } + } +} + +@Composable +private fun RunRow(run: TaskRun, bot: Agent?, shape: Shape, onOpen: () -> Unit) { + GroupedItem( + shape = shape, + onClick = onOpen, + leading = { if (bot != null) BotAvatarView(bot, size = 44.dp) else IconTile(routeIcon(Route.Tasks), Tone.Lavender) }, + trailing = { RunStatus(run) }, + ) { + RowTitle(run.schedule?.name ?: "Deleted task", maxLines = 1) + RowSubtitle( + text = listOfNotNull( + bot?.name ?: "Deleted bot", + activityTime(run.startedAt), + run.script?.let(::scriptRunDuration), + ).joinToString(" · "), + maxLines = 1, + ) + } +} + +@Composable +private fun RunStatus(run: TaskRun) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + when { + run.running -> CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) + run.failed -> Icon(Icons.Default.Cancel, null, Modifier.size(16.dp), tint = MaterialTheme.colorScheme.error) + else -> Icon(Icons.Default.CheckCircle, null, Modifier.size(16.dp), tint = SUCCESS) + } + Text(run.label, style = MaterialTheme.typography.labelMedium) + } +} + +@Composable +private fun RunDetailsDialog(run: TaskRun, script: ScriptRun, onClose: () -> Unit) { + AlertDialog( + onDismissRequest = onClose, + title = { Text(run.schedule?.name ?: "Deleted task") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + text = listOf( + script.status.replace("_", " "), + "Exit code: ${script.exitCode ?: "—"}", + activityTime(script.startedAt), + "Duration: ${scriptRunDuration(script)}", + ).joinToString(" · "), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + script.error?.takeIf { it.isNotEmpty() }?.let { + Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) + } + if (script.droppedBytes > 0) { + Text( + text = "${script.droppedBytes} bytes omitted", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Surface(shape = RoundedCornerShape(8.dp), color = sheetColor) { + Text( + text = script.output.ifEmpty { "No output" }, + style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace), + modifier = Modifier + .fillMaxWidth() + .heightIn(max = 320.dp) + .verticalScroll(rememberScrollState()) + .padding(12.dp), + ) + } + } + }, + confirmButton = { TextButton(onClick = onClose) { Text("Close") } }, + ) +} + +@Composable +private fun EventSourceList(model: AppModel) { + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(16.dp), + ) { + item { + RowsSection( + title = "Event sources", + footer = "Each source is one webhook address. Tasks that use a source run when an event arrives there.", + ) { + if (model.eventSourcesError.isNotEmpty()) note(model.eventSourcesError, isError = true) + if (model.eventSourcesLoaded && model.eventSources.isEmpty()) note("No event sources yet.") + for (source in model.eventSources) { + row { shape -> EventSourceRow(model, source, shape) } + } + add("Add source") { model.openEventSourceForm() } + } + } + } +} + +@Composable +internal fun EventSourceRow(model: AppModel, source: EventSource, shape: Shape) { + val deleting = model.deletingEventSources.contains(source.id) + var confirming by remember { mutableStateOf(false) } + GroupedItem( + shape = shape, + leading = { LetterTile(source.name) }, + trailing = { + if (deleting) { + CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp) + } else { + IconButton(onClick = { confirming = true }, enabled = source.usedBy == 0L) { + Icon(Icons.Default.Delete, contentDescription = "Delete") + } + } + }, + ) { + RowTitle("${source.name} (used by ${source.usedBy})", maxLines = 1) + if (source.usedBy > 0) RowSubtitle("Remove the tasks that use it first") + model.eventSourceErrors[source.id]?.let { RowSubtitle(it, color = MaterialTheme.colorScheme.error) } + } + if (confirming) { + AlertDialog( + onDismissRequest = { confirming = false }, + title = { Text("Delete ${source.name}?") }, + text = { Text("Its webhook address stops working. Events that already arrived are kept.") }, + confirmButton = { + TextButton( + onClick = { + confirming = false + model.deleteEventSource(source.id) + }, + ) { + Text("Delete", color = MaterialTheme.colorScheme.error) + } + }, + dismissButton = { TextButton(onClick = { confirming = false }) { Text("Cancel") } }, + ) + } +} + +@Composable +fun EventSourceDialog(model: AppModel, draft: EventSourceDraft) { + val created = draft.created + if (created != null) { + AlertDialog( + onDismissRequest = {}, + title = { Text("${created.name} address") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + CopyField("Webhook address", created.address, sensitive = true) + Text( + text = "Shown once. Paste it into the provider's webhook settings.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + }, + confirmButton = { Button(onClick = { model.closeEventSourceForm() }) { Text("Done") } }, + ) + return + } + AlertDialog( + onDismissRequest = { model.closeEventSourceForm() }, + title = { Text("Add event source") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + text = "Crumble creates the source on the relay and shows its webhook address once.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + SheetErrorBanner(draft.error) + OutlinedTextField( + value = draft.name, + onValueChange = { model.eventSourceDraft = draft.copy(name = it.take(MAX_EVENT_SOURCE_NAME_CHARS)) }, + label = { Text("Name") }, + placeholder = { Text("GitHub issues") }, + singleLine = true, + enabled = !draft.saving, + modifier = Modifier.fillMaxWidth(), + ) + } + }, + confirmButton = { + Button(onClick = { model.saveEventSource() }, enabled = draft.name.isNotBlank() && !draft.saving) { + if (draft.saving) { + CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp) + } else { + Text("Add") + } + } + }, + dismissButton = { + TextButton(onClick = { model.closeEventSourceForm() }, enabled = !draft.saving) { Text("Cancel") } + }, + ) +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun TaskFormDialog( + model: AppModel, + draft: TaskDraft, +) { + var botMenuExpanded by remember { mutableStateOf(false) } + val selectedBotName = model.agents.firstOrNull { it.id == draft.agentID }?.name ?: "" + val canScript = canRunScripts(model.capabilities, model.agents.firstOrNull { it.id == draft.agentID }) + val editingScript = model.schedules.firstOrNull { it.id == draft.scheduleID }?.kind == "script" + + AlertDialog( + onDismissRequest = { + model.errorText = "" + model.taskDraft = null + }, + title = { Text(if (draft.scheduleID.isEmpty()) "New Task" else "Edit Task") }, + text = { + Column( + modifier = Modifier.verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + SheetErrorBanner(model.errorText) + ExposedDropdownMenuBox( + expanded = botMenuExpanded, + onExpandedChange = { botMenuExpanded = it }, + ) { + OutlinedTextField( + value = selectedBotName, + onValueChange = {}, + readOnly = true, + label = { Text("Runs on") }, + trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = botMenuExpanded) }, + modifier = Modifier + .menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable) + .fillMaxWidth(), + ) + ExposedDropdownMenu( + expanded = botMenuExpanded, + onDismissRequest = { botMenuExpanded = false }, + ) { + for (agent in model.agents) { + DropdownMenuItem( + text = { Text(agent.name) }, + onClick = { + model.pickTaskBot(agent.id) + botMenuExpanded = false + }, + ) + } + } + } + OutlinedTextField( + value = draft.name, + onValueChange = { model.taskDraft = draft.copy(name = it) }, + label = { Text("Name") }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text("Enabled") + Switch( + checked = draft.enabled, + onCheckedChange = { model.taskDraft = draft.copy(enabled = it) }, + ) + } + if (canScript || editingScript) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + FilterChip( + selected = draft.kind == "prompt", + onClick = { model.taskDraft = draft.copy(kind = "prompt") }, + label = { Text("Prompt") }, + ) + FilterChip( + selected = draft.kind == "script", + onClick = { model.taskDraft = draft.copy(kind = "script") }, + enabled = canScript, + label = { Text("Script") }, + ) + } + } + if (draft.kind == "script") { + ScriptFields(model, draft) + } else { + OutlinedTextField( + value = draft.prompt, + onValueChange = { model.taskDraft = draft.copy(prompt = it) }, + label = { Text("Prompt") }, + minLines = 3, + modifier = Modifier.fillMaxWidth(), + ) + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + FilterChip( + selected = !draft.onEvent, + onClick = { model.taskDraft = draft.copy(onEvent = false) }, + label = { Text("Time") }, + ) + FilterChip( + selected = draft.onEvent, + onClick = { model.taskDraft = draft.copy(onEvent = true) }, + label = { Text("Event") }, + ) + } + if (draft.onEvent) { + EventSourcePicker(model, draft) + } else { + TaskTimeFields(draft) { model.taskDraft = it } + } + } + }, + confirmButton = { + Button( + onClick = { model.saveTask() }, + enabled = !model.loading, + ) { + Text("Save") + } + }, + dismissButton = { + TextButton( + onClick = { + model.errorText = "" + model.taskDraft = null + }, + ) { + Text("Cancel") + } + }, + ) +} + +@Composable +private fun ScriptFields(model: AppModel, draft: TaskDraft) { + OutlinedTextField( + value = draft.command, + onValueChange = { model.taskDraft = draft.copy(command = it.take(MAX_COMMAND_CHARS)) }, + label = { Text("Command") }, + placeholder = { Text("./scripts/backup.sh") }, + textStyle = TextStyle(fontFamily = FontFamily.Monospace), + minLines = 3, + modifier = Modifier.fillMaxWidth(), + ) + OutlinedTextField( + value = draft.timeoutSeconds, + onValueChange = { model.taskDraft = draft.copy(timeoutSeconds = it) }, + label = { Text("Timeout (seconds)") }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Column(modifier = Modifier.weight(1f)) { + Text("Send results to the chat") + Text( + text = "Each finished run posts its output to the bot's chat.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Switch( + checked = draft.notify, + onCheckedChange = { model.taskDraft = draft.copy(notify = it) }, + ) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun EventSourcePicker(model: AppModel, draft: TaskDraft) { + if (model.eventSources.isEmpty() && model.eventSourcesError.isNotEmpty()) { + SheetErrorBanner(model.eventSourcesError) + return + } + if (model.eventSourcesLoaded && model.eventSources.isEmpty()) { + Text( + text = "Add a source in Event sources first.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + return + } + var expanded by remember { mutableStateOf(false) } + ExposedDropdownMenuBox(expanded = expanded, onExpandedChange = { expanded = it }) { + OutlinedTextField( + value = model.eventSources.firstOrNull { it.id == draft.eventSourceID }?.name ?: "Choose a source", + onValueChange = {}, + readOnly = true, + label = { Text("Event source") }, + trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) }, + modifier = Modifier + .menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable) + .fillMaxWidth(), + ) + ExposedDropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { + for (source in model.eventSources) { + DropdownMenuItem( + text = { Text(source.name) }, + onClick = { + model.taskDraft = draft.copy(eventSourceID = source.id) + expanded = false + }, + ) + } + } + } +} diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml index 07d5da9..db15131 100644 --- a/app/src/main/res/drawable/ic_launcher_background.xml +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -5,166 +5,6 @@ android:viewportWidth="108" android:viewportHeight="108"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml index 2b068d1..5ad0ba2 100644 --- a/app/src/main/res/drawable/ic_launcher_foreground.xml +++ b/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -1,30 +1,22 @@ + - - - - - - - - - - \ No newline at end of file + + + + + + diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/app/src/main/res/mipmap-hdpi/ic_launcher.webp deleted file mode 100644 index c209e78..0000000 Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher.webp and /dev/null differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp deleted file mode 100644 index b2dfe3d..0000000 Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp and /dev/null differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/app/src/main/res/mipmap-mdpi/ic_launcher.webp deleted file mode 100644 index 4f0f1d6..0000000 Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher.webp and /dev/null differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp deleted file mode 100644 index 62b611d..0000000 Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp and /dev/null differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp deleted file mode 100644 index 948a307..0000000 Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp and /dev/null differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp deleted file mode 100644 index 1b9a695..0000000 Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp and /dev/null differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp deleted file mode 100644 index 28d4b77..0000000 Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp and /dev/null differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp deleted file mode 100644 index 9287f50..0000000 Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp and /dev/null differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp deleted file mode 100644 index aa7d642..0000000 Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp and /dev/null differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp deleted file mode 100644 index 9126ae3..0000000 Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp and /dev/null differ diff --git a/app/src/main/res/raw/generate_avatar_prompt.txt b/app/src/main/res/raw/generate_avatar_prompt.txt new file mode 100644 index 0000000..90895bd --- /dev/null +++ b/app/src/main/res/raw/generate_avatar_prompt.txt @@ -0,0 +1,117 @@ +# Avatar geometry designer + +You design one avatar for a small vector character engine: a soft, chunky object silhouette with two eyes, given as compact JSON. The user describes the avatar in their own words (a hobby, a role or an object). You write **geometry only**. The engine adds color, an implied 3D volume, gaze, blinking and motion, so never output any of those. + +## Task + +1. Infer everything from the description; there are no other fields. Decide the object (the description may name one, or only a role or hobby: then pick the single most iconic object for it), the view, which part carries the face, the parts and proportions, and an `id` slug and a `name` (see *Naming*). Explicit details in the description (a part's side, size or count, a tilt, a name) win over the defaults below. Do not ask follow-up questions unless the description is empty or unusable. +2. Design the path and eyes (see *Face first*, *Visual hierarchy* and *Structure*). Think privately; do not narrate. +3. Check the result against every rule below before answering. +4. Reply with **only** the JSON on one line: no prose, no explanation, no code fence. + +## Output schema + +``` +{"version":1,"id":"slug","name":"Name","body":{"path":"M… Z"},"eyes":{"x":50,"y":46,"spacing":15,"scale":1}} +``` + +Exactly these fields. No colors, styles, transforms, markup, animation or extra keys at any level. + +## Hard rules + +The engine validates every definition and rejects any that breaks these. + +- Canvas is a fixed `0 0 100 100` viewBox, y pointing down. Keep all geometry within **8..92** (rejected outside 6..94); the renderer needs the margin for turning, tilt and hop. +- `body.path` uses only `M L H V C S Q T A Z`, absolute or relative. Numbers only, arc flags as separate `0`/`1` tokens. At most 16 subpaths, 400 segments, 6000 characters. Aim for well under 1500 characters. +- Fill rule is **nonzero**. Wind every outline clockwise on screen (travel left→right along the top edge). Overlapping clockwise parts merge into one shape. A hole is a subpath wound counter-clockwise inside an outline. + - Every hole is a **see-through cut-out** that stays open as the object turns: use them for loops and handles (mug handle, ring, scissor loops), not for decoration. + - For a circle hole: `M cx-r cy A r r 0 1 0 cx+r cy A r r 0 1 0 cx-r cy Z` (sweep `0`); the outline version uses sweep `1`. +- Body must be at least 40 units on its long side, 14 on its short side, with ≥ 600 units² of fill. +- `eyes`: `x`,`y` is the center of the pair, `spacing` center-to-center, `scale` 0.6..1.8. At scale 1 each eye is a 4 × 11 vertical pill. Spacing ≥ 7 × scale. +- Both eyes plus a 1.2 unit margin must lie on solid fill, not in a hole. That is only the floor: see *Face first* for the room the drawn eyes actually need. +- `version` is `1`. `id`: lowercase slug of 1–40 characters (`a-z`, `0-9`, inner `-`). `name`: ≤ 40 printable characters. + +## Naming + +The `name` labels the avatar in a small gallery and for screen readers. Use the **shortest conventional name that still identifies the object unambiguously**: usually a single noun, with qualifiers the drawing already shows (material, color, size, cuteness, the contents) dropped. Keep a compound noun whole when its head word alone names a different or vaguer thing; clarity beats brevity. Title-case it. A name the user gives always wins. The `id` is a slug of the full object name. + +## Face first + +The renderer draws the eyes bigger than the contract size: up to **1.45×** (a 5.8 × 16 pill at scale 1), the happy-mood arcs are about **2× as wide** as a pill (±5.9 units around each eye center at scale 1), and the gaze nudges them ~1.5 units. If that does not fit, eyes look pasted on and touch the background. So: + +- **The part that carries the face is the main mass.** Exaggerate it beyond the real object's proportions as far as the face needs, and no further: once the eyes have their room, extra bulk only crowds out the parts that make the object recognizable. +- **Grow the face part in place.** Find the room by thickening or widening the part the face naturally sits on, along the structure it belongs to, and scale its neighbors with it. Never insert a separate block for the face that the rest of the object merely hangs off. +- **Room around the drawn eyes.** At scale `s` and spacing `p` the face area needs roughly `(p + 12·s + 9)` × `(16·s + 9)` units of calm solid fill (scale 1, spacing 15: about 36 × 25). The engine's strict check draws the eyes at the full 1.45× and wants at least 4.5 units of clearance from the outline at rest, for both pill and happy arcs, plus full gaze travel. +- Fix a short face by **enlarging the face part**, never by shrinking `scale` below 1 or squeezing `spacing`. + +## Visual hierarchy + +Size is judged by **outline extent**, not filled area. A thin loop or frame has little fill, but the eye reads the whole region it encloses, and in 3D it turns as big as its outline. Judge every secondary part by its outer envelope, negative space included: + +- **The face mass reads first.** At 28 px the face part should be the first shape seen, then the feature that names the object. +- **Secondary parts stay compact and close.** Size each one by its envelope, not its fill: clearly smaller than the face part, spanning well under its height and width, and reaching out past it only as far as recognition needs. Where a part *is* the object's identity, it may overtop the face part moderately, but stays slimmer so the face part keeps the weight. +- **Keep the defining relations.** Whatever makes the object recognizable as a whole (which parts are bigger, thicker or longer than which, what lines up with what) survives the exaggeration. When you enlarge the face part, rescale the parts that define the object with it instead of leaving them behind. +- **Judge the whole.** Look at the finished silhouette as one object at thumbnail size, resting and turned: if it reads as a different or broken object, rebalance the parts (or change the view) even when every individual rule is met. No local rule outranks overall recognition. +- These are judgments, not quotas: fit them to the object, and follow explicit wishes in the description over them. + +## Structure + +Simplify the object, but do not break how it reads. + +- **Keep attachments.** A part joined to the body at two points stays joined at both, however small it gets; a part that grows out of the body still grows out of it. Run each joint a few units into the part it meets so it stays solid when the parts turn and separate in depth. +- **Keep continuity as a simple cue.** Where something runs through or past other parts, let it show as a soft, chunky continuation of the same shape, long and thick enough to read as more than a bump, without spelling out mechanical detail. +- **Keep the characteristic steps.** Simplifying must not erase the few silhouette transitions that make the object recognizable (a stepped profile, a tier, a neck, a lip): keep a small number of them, rounded and chunky, rather than collapsing them into one blob or multiplying them into detail. +- **Every join is a clear step or a smooth flow, never in between.** Where parts meet on the outline, either step decisively (about 3 units or more, where the object really changes part or tier) or let one outline run on into the next at the same width and direction, with the inner part's rounded corners buried inside the outer part. Edges that nearly line up, or a rounded corner left on the outline right at the joint, make a thin ledge, sliver or notch: it reads as a flaw and grows on a large stage. Widen or narrow the step until it is unmistakable, or match the edges exactly. +- **Keep openings visible.** An opening that defines the object sits where it stays see-through as the object turns, beside the main mass rather than against an edge the turned surface covers. + +## How the engine builds volume + +Design for this; the silhouette is all you control. + +- **Decide flat or round first**, per part, from the real object. Flat things (boards, books, phones, tablets, cards, envelopes, boxes, signs, screens, clipboards, tickets) must not turn as cylinders: draw a flat object's body as **one merged outline**, with its small features (a clip, a tab, a lid, a notch) rising out of that outline as clear, rounded steps rather than as separate subpaths. Give it extra subpaths only for features that should turn on their own and are not mirror-symmetric (a handle, a strap). A clipboard drawn as a board, a clip and a tab in three symmetric subpaths turns as three stacked cylinders. +- Each clockwise outline subpath becomes its **own part**, all centered on one mid-plane, so separate subpaths turn and parallax independently. A body drawn as one merged outline turns as one rounded slab (pebble). +- In a body of two or more parts, **every** part that is **mirror-symmetric about its own vertical center line** (and has no hole) becomes round about that line, whether you mean it or not. Use that for objects that really are round: draw a mug's cup, a pot, a bottle, a can or a bulb as its own symmetric subpath and it turns as a cylinder, cone or sphere. Keep handles, spouts and leaves as separate, asymmetric subpaths. +- A side view of **two or more parts that is mirror-symmetric about a horizontal line**, with every part centered on it, turns about that line instead: bars become cylinders, plates become discs. Draw turned objects (rods, rockets, pencils) that way; break the symmetry if the object is not round. +- The eyes are painted on the front surface of the part under them, drawn up to 1.45× the validated size where there is room, so leave space around them. + +## Craft + +The look: a simple, rounded character first and an object second. Think of a soft, chunky blob made of a few rounded lobes, in one saturated flat color with two plain dark pill eyes, that carries just enough of the object's silhouette to be named at 28 px. Avoid realism and mechanical construction: no thin rods, elaborate handles or fine parts. The renderer draws one flat color with no shading, so the silhouette alone must carry recognition. + +- **Pick the iconic view**: the one whose outline alone names the object at thumbnail size (often the side profile for vessels, tools and turned objects, the front for devices and faces). If it would not, change the view or exaggerate the signature feature. +- **Toy proportions.** Chunky and slightly squat; parts at least 5 units thick; corner radii 3+ units; no hairlines or thin spikes, and tapering parts end in a softly rounded tip rather than a sharp point. Prefer `C` curves and arcs over polygons for anything organic. +- **Simplify detail, keep character.** Drop small and accidental detail, but keep each part's distinctive shape and gesture: an organic part (leaf, flame, tail, petal) keeps its characteristic outline and direction, such as a blade that curves and tapers, instead of turning into a generic oval or capsule. +- **One face region** on the dominant part (see *Face first*). Place eyes a little above that area's center; it reads friendlier. Keep details and part seams out of it. +- **Few parts, unified.** Build from 1–7 soft primitives (rounded rects, capsules, blobs) that overlap into one unified silhouette; for a flat object, trace them as one outline (see *How the engine builds volume*). No buttons, slots or decorative cut-outs: detail that disappears at 28 px is noise. +- **Balance.** Center the visual mass near x 50, sit the object on a flat or gently rounded base near y 80–88 so it looks grounded. +- **Eyes.** Default scale 1–1.15 and spacing 15–18; up to 1.25 on large round bodies. Two eyes only; no mouth, brows or pupils (the engine expresses mood). + +Common failures and fixes: eyes outside the body or too little face room → enlarge the face part or move `eyes` to its calm center; a secondary part that reads as big as the main mass → shrink its envelope while keeping its joints (see *Structure*); safe-area overflow → shrink the secondary parts first, then scale the drawing toward 50,50; unexpected hole → an overlapping part was wound counter-clockwise, reverse it; a small ledge or notch where two parts meet → make the step clearly bigger, or match the edges and bury the corners (see *Structure*). + +## Reference examples + +Illustrations of the format and of the principles above, not templates to copy. + +Controller (front view; one squat outline, so it turns as one flat, rounded slab; the face on the wide center): + +```json +{"version":1,"id":"controller","name":"Controller","body":{"path":"M28 22C38 20 44 23 50 23C56 23 62 20 72 22C84 24 90 34 91 48C92 62 91 76 82 80C75 83 69 78 66 72C63 67 58 66 50 66C42 66 37 67 34 72C31 78 25 83 18 80C9 76 8 62 9 48C10 34 16 24 28 22Z"},"eyes":{"x":50,"y":42,"spacing":16,"scale":1.05}} +``` + +Barbell (side view, symmetric about a horizontal line so it turns as a bar with round plates; soft overlapping capsules keep its stepped profile): + +```json +{"version":1,"id":"barbell","name":"Barbell","body":{"path":"M12 41H12A4 4 0 0 1 16 45V55A4 4 0 0 1 12 59H12A4 4 0 0 1 8 55V45A4 4 0 0 1 12 41ZM18 29H18A4 4 0 0 1 22 33V67A4 4 0 0 1 18 71H18A4 4 0 0 1 14 67V33A4 4 0 0 1 18 29ZM26 17H26A5 5 0 0 1 31 22V78A5 5 0 0 1 26 83H26A5 5 0 0 1 21 78V22A5 5 0 0 1 26 17ZM38 33H62A10 10 0 0 1 72 43V57A10 10 0 0 1 62 67H38A10 10 0 0 1 28 57V43A10 10 0 0 1 38 33ZM74 17H74A5 5 0 0 1 79 22V78A5 5 0 0 1 74 83H74A5 5 0 0 1 69 78V22A5 5 0 0 1 74 17ZM82 29H82A4 4 0 0 1 86 33V67A4 4 0 0 1 82 71H82A4 4 0 0 1 78 67V33A4 4 0 0 1 82 29ZM88 41H88A4 4 0 0 1 92 45V55A4 4 0 0 1 88 59H88A4 4 0 0 1 84 55V45A4 4 0 0 1 88 41Z"},"eyes":{"x":50,"y":50,"spacing":15,"scale":1.05}} +``` + +Mug (side view; a symmetric cup subpath turns as a cylinder and carries the face; the handle is a separate outline with a counter-clockwise hole): + +```json +{"version":1,"id":"mug","name":"Mug","body":{"path":"M22 20H62C67 20 70 23 70 28V72C70 80 64 86 56 86H28C20 86 14 80 14 72V28C14 23 17 20 22 20ZM68 36C80 34 87 42 87 53C87 64 80 72 68 70ZM69 45L69 61C75.5 62 79 58.5 79 53C79 47.5 76 44 69 45Z"},"eyes":{"x":42,"y":49,"spacing":16,"scale":1.15}} +``` + +Watering Can (side view; the can body carries the face; handle loop and spout are separate outlines that run into the body): + +```json +{"version":1,"id":"watering-can","name":"Watering Can","body":{"path":"M32 38H62C68 38 71 41 72 47L74 76C74.5 82 70 86 64 86H30C24 86 19.5 82 20 76L22 47C23 41 26 38 32 38ZM23 63C14 63 8.5 57 8.5 48C8.5 37 13 30.5 19 30.5C25 30.5 28.5 34 30 39.5L26 52ZM23.5 42C22 38 20 36 17.5 36C15 36 14 41 14 48C14 54 16 57.5 22 58L23.5 47ZM69 66C75 61 78 55 80 46.5L88 49.5C85 62 80 73 72 81ZM78.7 43A7 4.5 25 0 1 91.3 49A7 4.5 25 0 1 78.7 43Z"},"eyes":{"x":47,"y":61,"spacing":16,"scale":1.15}} +``` diff --git a/app/src/main/res/xml/backup_rules.xml b/app/src/main/res/xml/backup_rules.xml index 4df9255..652f953 100644 --- a/app/src/main/res/xml/backup_rules.xml +++ b/app/src/main/res/xml/backup_rules.xml @@ -1,13 +1,5 @@ - + + - - \ No newline at end of file + + diff --git a/app/src/main/res/xml/data_extraction_rules.xml b/app/src/main/res/xml/data_extraction_rules.xml index 9ee9997..bc77908 100644 --- a/app/src/main/res/xml/data_extraction_rules.xml +++ b/app/src/main/res/xml/data_extraction_rules.xml @@ -1,19 +1,10 @@ - + + - + - - \ No newline at end of file + diff --git a/app/src/test/java/dev/crumble/android/ActivityTests.kt b/app/src/test/java/dev/crumble/android/ActivityTests.kt new file mode 100644 index 0000000..42e7c8d --- /dev/null +++ b/app/src/test/java/dev/crumble/android/ActivityTests.kt @@ -0,0 +1,333 @@ +package dev.crumble.android + +import dev.crumble.android.model.ACTIVITY_PAGE_SIZE +import dev.crumble.android.model.ActivityFeedResponse +import dev.crumble.android.model.ActivityFeedState +import dev.crumble.android.model.ActivityRecord +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.CrumbleJson +import dev.crumble.android.model.Route +import dev.crumble.android.model.activityDays +import dev.crumble.android.model.clock +import dev.crumble.android.model.detailText +import dev.crumble.android.model.failed +import dev.crumble.android.model.headline +import dev.crumble.android.model.preview +import dev.crumble.android.model.withFirstPage +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import java.nio.charset.StandardCharsets +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import java.time.ZoneOffset +import java.util.Locale +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +private fun event(id: String, kind: String = "tool-call", details: String = "{}", timestamp: Long = 1_720_000_000_000) = + """{"id":"$id","agentId":"a1","agentName":"Atlas","entryId":"r-$id","timestamp":$timestamp,"kind":"$kind","details":$details}""" + +private fun feed(vararg events: String, cursor: String? = null) = + """{"activities":[${events.joinToString(",")}],"nextCursor":${cursor?.let { "\"$it\"" } ?: "null"},"hasMore":${cursor != null}}""" + +private fun record(kind: String, details: String, agentName: String = "Atlas", timestamp: Long? = 1_720_000_000_000) = + ActivityRecord(id = "e", agentId = "a1", agentName = agentName, kind = kind, timestamp = timestamp, details = CrumbleJson.parseToJsonElement(details)) + +private class FeedTransport(private val handler: (String) -> Pair) : HttpTransport { + val paths = mutableListOf() + val held = mutableMapOf>() + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + paths.add(request.pathWithQuery) + held[request.pathWithQuery]?.await() + val (status, body) = handler(request.pathWithQuery) + return HttpResponseData(status, body.toByteArray(StandardCharsets.UTF_8)) + } + + override suspend fun openStream(request: HttpRequestData): HttpStreamResponse = + throw UnsupportedOperationException("streams are not used here") +} + +private const val FIRST = "/v1/activity/feed?limit=50" +private const val SECOND = "/v1/activity/feed?limit=50&cursor=c1" +private const val TOOLS = "/v1/activity/feed?limit=50&kind=tool-call" + +@OptIn(ExperimentalCoroutinesApi::class) +class ActivityTests { + private fun modelWith(transport: FeedTransport, scope: CoroutineScope) = + AppModel(client = APIClient(baseURL = "https://example.test", token = "secret", transport = transport), scope = scope) + + @Test + fun signingOutDropsTheOldServersActivity() = runTest { + val transport = FeedTransport { 200 to feed(event("e1")) } + val model = modelWith(transport, this) + model.openPanel(Route.Activity) + runCurrent() + assertEquals(1, model.activities.size) + model.signOut() + runCurrent() + assertTrue(model.activities.isEmpty()) + } + + @Test + fun showsLoadingThenThePageAndItsCursor() = runTest { + val transport = FeedTransport { 200 to feed(event("e1"), cursor = "c1") } + val gate = CompletableDeferred() + transport.held[FIRST] = gate + val model = modelWith(transport, this) + model.openPanel(Route.Activity) + runCurrent() + assertTrue(model.activityFeed.loading) + gate.complete(Unit) + runCurrent() + assertFalse(model.activityFeed.loading) + assertEquals("c1", model.activityFeed.nextCursor) + assertEquals(listOf(FIRST), transport.paths) + assertEquals(50L, ACTIVITY_PAGE_SIZE) + } + + @Test + fun filtersGoToTheServerAndAResponseForTheOldFilterIsDropped() = runTest { + val transport = FeedTransport { path -> + 200 to when { + "kind=tool-call" in path && "agentId=a2" in path -> feed(event("bot-tool")) + "kind=tool-call" in path -> feed(event("tool")) + else -> feed(event("everything")) + } + } + val slow = CompletableDeferred() + transport.held[FIRST] = slow + val model = modelWith(transport, this) + model.openPanel(Route.Activity) + runCurrent() + + model.filterActivity(kind = "tool-call") + runCurrent() + assertEquals(listOf("tool"), model.activities.map { it.id }) + slow.complete(Unit) + runCurrent() + assertEquals(listOf("tool"), model.activities.map { it.id }) + + model.filterActivity(botID = "a2") + assertTrue("A new filter must not show the old filter's rows", model.activities.isEmpty()) + runCurrent() + assertEquals("/v1/activity/feed?agentId=a2&limit=50&kind=tool-call", transport.paths.last()) + assertEquals(listOf("bot-tool"), model.activities.map { it.id }) + } + + @Test + fun refreshKeepsFiltersAndLeavingThePageClearsThem() = runTest { + val transport = FeedTransport { 200 to feed(event("e1")) } + val model = modelWith(transport, this) + model.openPanel(Route.Activity) + runCurrent() + model.filterActivity(kind = "tool-call") + runCurrent() + + model.openPanel(Route.Activity) + runCurrent() + assertEquals(TOOLS, transport.paths.last()) + + model.openPanel(Route.Memory) + model.openPanel(Route.Activity) + runCurrent() + assertEquals(FIRST, transport.paths.last()) + assertNull(model.activityFeed.kind) + } + + @Test + fun olderPagesAppendWithoutDuplicatesAndFilterCarriesOver() = runTest { + val transport = FeedTransport { path -> + 200 to when (path) { + FIRST -> feed(event("e1"), event("e2"), cursor = "c1") + else -> feed(event("e2"), event("e3")) + } + } + val model = modelWith(transport, this) + model.openPanel(Route.Activity) + runCurrent() + model.loadOlderActivity() + runCurrent() + assertEquals(SECOND, transport.paths.last()) + assertEquals(listOf("e1", "e2", "e3"), model.activities.map { it.id }) + assertNull(model.activityFeed.nextCursor) + model.loadOlderActivity() + runCurrent() + assertEquals(2, transport.paths.size) + } + + @Test + fun aFailedOlderPageKeepsTheListAndCanBeRetried() = runTest { + var failing = true + val transport = FeedTransport { path -> + when { + path == FIRST -> 200 to feed(event("e1"), cursor = "c1") + failing -> 500 to """{"error":"down"}""" + else -> 200 to feed(event("e2")) + } + } + val model = modelWith(transport, this) + model.openPanel(Route.Activity) + runCurrent() + model.loadOlderActivity() + assertTrue(model.activityFeed.loadingOlder) + runCurrent() + assertFalse(model.activityFeed.loadingOlder) + assertTrue(model.activityFeed.olderError.isNotEmpty()) + assertEquals(listOf("e1"), model.activities.map { it.id }) + assertEquals("c1", model.activityFeed.nextCursor) + + failing = false + model.loadOlderActivity() + runCurrent() + assertEquals(listOf("e1", "e2"), model.activities.map { it.id }) + assertEquals("", model.activityFeed.olderError) + } + + @Test + fun aFailedFirstLoadStaysOnThePageAndRefreshRecovers() = runTest { + var failing = true + val transport = FeedTransport { if (failing) 500 to """{"error":"down"}""" else 200 to feed(event("e1")) } + val model = modelWith(transport, this) + model.openPanel(Route.Activity) + runCurrent() + assertTrue(model.activityFeed.error.isNotEmpty()) + assertFalse(model.activityFeed.loading) + + failing = false + model.openPanel(Route.Activity) + runCurrent() + assertEquals("", model.activityFeed.error) + assertEquals(listOf("e1"), model.activities.map { it.id }) + } + + @Test + fun aLateOlderPageNeverLandsInANewFilter() = runTest { + val transport = FeedTransport { path -> 200 to if (path == SECOND) feed(event("old")) else feed(event("e1"), cursor = "c1") } + val gate = CompletableDeferred() + transport.held[SECOND] = gate + val model = modelWith(transport, this) + model.openPanel(Route.Activity) + runCurrent() + model.loadOlderActivity() + runCurrent() + model.filterActivity(kind = "tool-call") + runCurrent() + gate.complete(Unit) + runCurrent() + assertEquals(listOf("e1"), model.activities.map { it.id }) + assertFalse(model.activityFeed.loadingOlder) + } + + @Test + fun aRefreshAfterARevertKeepsOlderPagesWhenTheFirstPageStillJoinsThem() { + fun records(vararg ids: String) = ids.map { ActivityRecord(id = it) } + val state = ActivityFeedState(items = records("e2", "e3", "e4"), nextCursor = "older") + val joined = state.withFirstPage(ActivityFeedResponse(records("e1", "e2"), nextCursor = "c1"), keepOlder = true) + assertEquals(listOf("e1", "e2", "e3", "e4"), joined.items.map { it.id }) + assertEquals("older", joined.nextCursor) + + val apart = state.withFirstPage(ActivityFeedResponse(records("x1"), nextCursor = "c1"), keepOlder = true) + assertEquals(listOf("x1"), apart.items.map { it.id }) + assertEquals("c1", apart.nextCursor) + } + + @Test + fun sentencesMatchTheWeb() { + fun line(record: ActivityRecord) = record.headline().run { listOf(lead, verb, target).joinToString(" ") } + assertEquals("Atlas used search", line(record("tool-call", """{"toolName":"search","name":"ignored"}"""))) + assertEquals("Atlas used a tool", line(record("tool-call", "{}"))) + assertEquals("Atlas got a result from search", line(record("tool-result", """{"name":"search"}"""))) + assertEquals("Atlas got an error from search", line(record("tool-result", """{"toolName":"search","isError":true}"""))) + assertEquals("Atlas called linear_find", line(record("mcp-call", """{"name":"linear_find"}"""))) + assertEquals("Atlas called an MCP tool", line(record("mcp-call", "{}"))) + assertEquals("Scout messaged Kev", line(record("bot-message", """{"communication":{"fromName":"Scout","toName":"Kev"}}"""))) + assertEquals("Atlas messaged a bot", line(record("bot-message", "{}"))) + assertTrue(record("tool-call", "{}").headline().code) + assertFalse(record("bot-message", "{}").headline().code) + } + + @Test + fun previewsAreReadableAndNeverRawDetails() { + assertEquals("a b c", record("bot-message", """{"content":"a\n b\tc"}""").preview()) + assertEquals("x".repeat(240), record("tool-result", """{"content":"${"x".repeat(300)}"}""").preview()) + assertEquals("""[{"type":"text"}]""", record("tool-result", """{"content":[{"type":"text"}]}""").preview()) + assertEquals("boom", record("tool-call", """{"error":"boom","args":"a","arguments":{"q":1}}""").preview()) + assertEquals("a", record("tool-call", """{"args":"a","arguments":{"q":1}}""").preview()) + assertEquals("""{"q":1}""", record("mcp-call", """{"arguments":{"q":1}}""").preview()) + assertEquals("", record("tool-call", """{"content":"hidden"}""").preview()) + assertEquals("", record("change", """{"content":"hidden"}""").preview()) + } + + @Test + fun detailsShowMessagesAsTextAndEverythingElseAsIndentedJson() { + assertEquals("Hello", record("bot-message", """{"content":"Hello"}""").detailText()) + assertEquals("{\n \"toolName\": \"search\"\n}", record("tool-call", """{"toolName":"search"}""").detailText()) + assertEquals("{\n \"content\": \"\"\n}", record("bot-message", """{"content":""}""").detailText()) + assertEquals("No details", ActivityRecord(kind = "tool-call").detailText()) + } + + @Test + fun failuresAreFlagged() { + assertTrue(record("tool-result", """{"isError":true}""").failed) + assertTrue(record("mcp-call", """{"error":"boom"}""").failed) + assertFalse(record("tool-result", """{"isError":false,"error":""}""").failed) + assertFalse(record("change", """{"isError":true}""").failed) + } + + @Test + fun rowsGroupByTheViewersLocalDay() { + val zone = ZoneId.of("Europe/Berlin") + val today = LocalDate.of(2026, 11, 5) + fun at(date: LocalDate, hour: Int) = date.atTime(hour, 0).atZone(zone).toInstant().toEpochMilli() + val rows = listOf( + ActivityRecord(id = "late", timestamp = at(today, 23)), + ActivityRecord(id = "early", timestamp = at(today, 0)), + ActivityRecord(id = "yesterday", timestamp = at(today.minusDays(1), 12)), + ActivityRecord(id = "week", timestamp = at(today.minusDays(3), 12)), + ActivityRecord(id = "lastYear", timestamp = at(LocalDate.of(2025, 12, 31), 12)), + ActivityRecord(id = "undated"), + ) + val days = activityDays(rows, today, zone, Locale.US) + assertEquals( + listOf("Today", "Yesterday", "Monday, November 2", "Wednesday, December 31, 2025", "Earlier"), + days.map { it.label }, + ) + assertEquals(listOf("late", "early"), days[0].items.map { it.id }) + } + + @Test + fun rowsShowTheLocalClockTime() { + val stamp = Instant.parse("2026-11-05T08:30:00Z").toEpochMilli() + assertEquals("08:30", ActivityRecord(timestamp = stamp).clock(ZoneOffset.UTC, Locale.UK)) + assertEquals("", ActivityRecord().clock(ZoneOffset.UTC, Locale.UK)) + } + + @Test + fun theBotFilterListsConnectedBots() = runTest { + val transport = FeedTransport { 200 to feed() } + val model = modelWith(transport, this) + model.agents = listOf(Agent(id = "a1", name = "Atlas")) + model.openPanel(Route.Activity) + runCurrent() + model.filterActivity(botID = "a1") + runCurrent() + assertEquals("/v1/activity/feed?agentId=a1&limit=50", transport.paths.last()) + model.filterActivity(botID = null) + runCurrent() + assertEquals(FIRST, transport.paths.last()) + } +} diff --git a/app/src/test/java/dev/crumble/android/AdminTests.kt b/app/src/test/java/dev/crumble/android/AdminTests.kt new file mode 100644 index 0000000..4f068ca --- /dev/null +++ b/app/src/test/java/dev/crumble/android/AdminTests.kt @@ -0,0 +1,619 @@ +package dev.crumble.android + +import dev.crumble.android.generated.AdminUser +import dev.crumble.android.generated.Invite +import dev.crumble.android.generated.ListOutdatedWorkspacesResponseWorkspacesItem +import dev.crumble.android.model.AccountMode +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.OutdatedWorkspaceRow +import dev.crumble.android.model.Route +import dev.crumble.android.model.WorkspaceField +import dev.crumble.android.model.canCreateAccount +import dev.crumble.android.model.dateOnly +import dev.crumble.android.model.inviteToken +import dev.crumble.android.model.outdatedWorkspaceRows +import dev.crumble.android.model.userRowTitle +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import dev.crumble.android.network.INVITE_HEADER +import dev.crumble.android.network.friendlyError +import dev.crumble.android.storage.InMemoryCredentialStore +import java.nio.charset.StandardCharsets +import java.time.ZoneOffset +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +private const val SERVER = "https://crumble.example" +private const val ME = "user-me" +private const val OTHER = "user-other" +private const val SIGN_UP = "POST /api/auth/sign-up/email" +private const val SIGN_IN = "POST /api/auth/sign-in/email" +private const val SESSION = "GET /api/auth/get-session" +private const val USERS = "GET /v1/admin/users" +private const val INVITES = "GET /v1/admin/invites" +private const val MINT = "POST /v1/admin/invites" +private const val SETTINGS = "GET /v1/admin/settings" +private const val PATCH_SETTINGS = "PATCH /v1/admin/settings" +private const val OUTDATED = "GET /v1/admin/workspaces/outdated" + +private class AdminTransport : HttpTransport { + val requests = mutableListOf() + val held = mutableMapOf>() + val responses = mutableMapOf>() + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + requests.add(request) + val key = "${request.method} ${request.pathWithQuery}" + held[key]?.await() + val (status, body) = responses[key] ?: (503 to """{"error":"unscripted $key"}""") + return HttpResponseData(status, body.toByteArray(StandardCharsets.UTF_8)) + } + + override suspend fun openStream(request: HttpRequestData): HttpStreamResponse = + throw UnsupportedOperationException("streams are not used here") + + fun sent(key: String) = requests.filter { "${it.method} ${it.pathWithQuery}" == key } + fun hold(key: String) = CompletableDeferred().also { held[key] = it } + fun answer(key: String, status: Int = 200, body: String) { + responses[key] = status to body + } +} + +private fun userJson(id: String, name: String = id, role: String = "user", createdAt: String = "2026-01-01T00:00:00.000Z") = + """{"id":"$id","email":"$id@example.com","name":"$name","role":"$role","createdAt":"$createdAt"}""" + +private fun inviteJson(id: String, createdAt: String = "2026-03-01T00:00:00.000Z") = """{"id":"$id","createdAt":"$createdAt"}""" + +private fun settingsJson(open: Boolean = false, image: String = "img") = + """{"signUpOpen":$open,"workspaceCpus":2,"workspaceMemoryMib":4096,"codingImage":"$image","questionGraceMinutes":30}""" + +private fun sessionJson(role: String = "admin") = """{"session":{"id":"s","userId":"$ME"},"user":{"id":"$ME","role":"$role"}}""" + +@OptIn(ExperimentalCoroutinesApi::class) +class AdminTests { + private fun scripted() = AdminTransport().apply { + answer(SESSION, body = sessionJson()) + answer(USERS, body = """{"users":[${userJson(ME, "Me", "admin")},${userJson(OTHER, "Kev", createdAt = "2026-02-01T00:00:00.000Z")},${userJson("user-third", "Ada", createdAt = "2026-02-02T00:00:00.000Z")}]}""") + answer(INVITES, body = """{"invites":[${inviteJson("new", "2026-04-01T00:00:00.000Z")},${inviteJson("old")}]}""") + answer(SETTINGS, body = settingsJson()) + answer("GET /v1/agents", body = "[]") + answer("GET /v1/group-chats", body = """{"groups":[]}""") + answer("GET /v1/password-managers", body = """{"passwordManagers":[]}""") + answer("GET /v1/github-apps", body = """{"apps":[]}""") + answer("GET /v1/github-accounts", body = """{"accounts":[]}""") + answer(OUTDATED, body = """{"workspaces":[]}""") + } + + private fun TestScope.usersPage(transport: AdminTransport): AppModel { + val client = APIClient(baseURL = SERVER, token = "session", transport = transport) + val model = AppModel(client = client, scope = this) + model.navigate(Route.Users) + runCurrent() + return model + } + + private fun TestScope.signedOut(transport: AdminTransport, store: InMemoryCredentialStore = InMemoryCredentialStore()): AppModel = + // The activity stream retries forever once connected, so the model can't live in the test's own scope. + AppModel(credentials = store, scope = backgroundScope, loadCredentials = false, transport = transport).also { + it.serverURL = SERVER + it.email = " new@example.com " + it.password = "hunter2hunter2" + it.accountName = " New Person " + it.accountMode = AccountMode.SignUp + } + + private fun AppModel.user(id: String) = adminUsers.value!!.first { it.id == id } + + // MARK: Creating an account + + @Test + fun signUpSendsTheInviteHeaderAndWaitsForTheServer() = runTest { + val transport = scripted() + transport.answer(SIGN_UP, body = """{"token":"new-session","user":{"id":"u"}}""") + val gate = transport.hold(SIGN_UP) + val store = InMemoryCredentialStore() + val model = signedOut(transport, store) + model.inviteCode = "$SERVER/connect?invite=abc-_123" + + model.saveSettings() + runCurrent() + assertTrue(model.savingConnection) + assertEquals("", model.token) + assertEquals("", model.notice) + + gate.complete(Unit) + runCurrent() + val request = transport.sent(SIGN_UP).single() + assertEquals("abc-_123", request.headers[INVITE_HEADER]) + assertFalse(request.headers.containsKey("Authorization")) + assertEquals( + """{"email":"new@example.com","password":"hunter2hunter2","name":"New Person"}""", + request.body?.toString(StandardCharsets.UTF_8), + ) + assertEquals("new-session", model.token) + assertEquals("new-session", store.read("server-token")) + assertEquals("", model.password) + assertEquals(AccountMode.SignIn, model.accountMode) + assertEquals("", model.inviteCode) + assertEquals("", model.accountName) + assertEquals("Connected", model.notice) + } + + @Test + fun signUpWithoutAnInviteOmitsTheHeader() = runTest { + val transport = scripted() + transport.answer(SIGN_UP, body = """{"token":"new-session"}""") + val model = signedOut(transport) + model.inviteCode = " " + + model.saveSettings() + runCurrent() + assertFalse(transport.sent(SIGN_UP).single().headers.containsKey(INVITE_HEADER)) + } + + @Test + fun closedSignUpShowsTheServersReasonAndKeepsTheForm() = runTest { + val transport = scripted() + transport.answer(SIGN_UP, 403, """{"code":"FORBIDDEN","message":"Sign-up is closed. Ask an admin for an invite link."}""") + val model = signedOut(transport) + model.inviteCode = "spent" + + model.saveSettings() + runCurrent() + assertEquals("Sign-up is closed. Ask an admin for an invite link.", model.errorText) + assertEquals(AccountMode.SignUp, model.accountMode) + assertEquals("hunter2hunter2", model.password) + assertEquals("spent", model.inviteCode) + assertEquals("", model.token) + assertFalse(model.savingConnection) + } + + @Test + fun aRetryAfterACreatedAccountFailedToConnectSignsIn() = runTest { + val transport = scripted() + transport.answer(SIGN_UP, body = """{"token":"new-session"}""") + transport.answer("GET /v1/agents", 500, """{"error":"Starting up"}""") + val model = signedOut(transport) + model.inviteCode = "once" + + model.saveSettings() + runCurrent() + assertEquals("Your account was created, but connecting failed: Starting up", model.errorText) + assertEquals(AccountMode.SignIn, model.accountMode) + assertEquals("hunter2hunter2", model.password) + assertEquals("", model.token) + + transport.answer("GET /v1/agents", body = "[]") + transport.answer(SIGN_IN, body = """{"token":"signed-in"}""") + model.saveSettings() + runCurrent() + assertEquals(1, transport.sent(SIGN_UP).size) + assertEquals("signed-in", model.token) + } + + @Test + fun anIncompleteSignUpStaysLocal() = runTest { + val transport = scripted() + val model = signedOut(transport) + model.accountName = " " + + model.saveSettings() + runCurrent() + assertEquals("Enter your name, email, and password.", model.errorText) + assertTrue(transport.requests.isEmpty()) + } + + @Test + fun switchingModesClearsTheError() { + val model = AppModel(loadCredentials = false) + model.errorText = "old" + model.switchAccountMode() + assertEquals(AccountMode.SignUp, model.accountMode) + assertEquals("", model.errorText) + model.switchAccountMode() + assertEquals(AccountMode.SignIn, model.accountMode) + } + + @Test + fun inviteTokensComeFromLinksOrBareCodes() { + assertEquals("tok-_en", inviteToken(" https://bots.example/connect?invite=tok-_en\n")) + assertEquals("a b", inviteToken("https://bots.example/connect?x=1&invite=a%20b")) + assertEquals("tok-_en", inviteToken(" tok-_en ")) + assertEquals("", inviteToken(" ")) + assertEquals("not a link", inviteToken("not a link")) + } + + @Test + fun anAccountNeedsANameEmailAndPassword() { + assertTrue(canCreateAccount("A", "a@b", "pw")) + assertFalse(canCreateAccount(" ", "a@b", "pw")) + assertFalse(canCreateAccount("A", " ", "pw")) + assertFalse(canCreateAccount("A", "a@b", "")) + } + + // MARK: Session + + @Test + fun anEmptySessionReadsAsSignedOut() = runTest { + val transport = scripted() + transport.answer(SESSION, body = "null") + val client = APIClient(baseURL = SERVER, token = "stale", transport = transport) + val failure = runCatching { client.accountSession() }.exceptionOrNull() + assertEquals("Authentication failed. Sign in again in Settings.", friendlyError(failure!!)) + } + + @Test + fun refreshingLearnsTheRoleForTheSidebar() = runTest { + val transport = scripted() + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + model.refresh() + runCurrent() + assertEquals(true, model.isAdmin) + assertEquals(ME, model.accountID) + assertEquals("Bearer session", transport.sent(SESSION).single().headers["Authorization"]) + assertTrue(transport.sent(USERS).isEmpty()) + } + + @Test + fun aRegularUserLoadsNoAdminData() = runTest { + val transport = scripted() + transport.answer(SESSION, body = sessionJson(role = "user")) + val model = usersPage(transport) + assertEquals(false, model.isAdmin) + assertTrue(transport.sent(USERS).isEmpty()) + assertTrue(transport.sent(INVITES).isEmpty()) + assertTrue(transport.sent(SETTINGS).isEmpty()) + } + + @Test + fun aFailedSessionReadShowsOnThePage() = runTest { + val transport = scripted() + transport.answer(SESSION, 500, """{"error":"Down"}""") + val model = usersPage(transport) + assertNull(model.isAdmin) + assertEquals("Down", model.adminUsers.error) + } + + // MARK: Users + + @Test + fun theUsersPageLoadsUsersInvitesAndSettings() = runTest { + val model = usersPage(scripted()) + assertEquals(listOf(ME, OTHER, "user-third"), model.adminUsers.value?.map { it.id }) + assertEquals(listOf("new", "old"), model.invites.value?.map { it.id }) + assertEquals(false, model.serverSettings.value?.signUpOpen) + assertEquals(ME, model.accountID) + } + + @Test + fun aRoleChangeAppliesAtOnceAndSurvivesADelayedRefresh() = runTest { + val transport = scripted() + val model = usersPage(transport) + val path = "PATCH /v1/admin/users/$OTHER" + transport.answer(path, body = userJson(OTHER, "Kev Renamed", "admin")) + val gate = transport.hold(path) + + model.setUserRole(model.user(OTHER), "admin") + assertEquals("admin", model.user(OTHER).role) + assertTrue("admin-user:$OTHER" in model.pendingMutations) + + model.navigate(Route.Users) + runCurrent() + assertEquals("admin", model.user(OTHER).role) + assertEquals("""{"role":"admin"}""", transport.sent(path).single().body?.toString(StandardCharsets.UTF_8)) + + gate.complete(Unit) + runCurrent() + assertEquals("Kev Renamed", model.user(OTHER).name) + assertFalse("admin-user:$OTHER" in model.pendingMutations) + } + + @Test + fun aRefusedRoleChangeRollsBackAndSaysWhy() = runTest { + val transport = scripted() + val model = usersPage(transport) + transport.answer("PATCH /v1/admin/users/$OTHER", 409, """{"error":"The server needs at least one admin"}""") + + model.setUserRole(model.user(OTHER), "admin") + runCurrent() + assertEquals("user", model.user(OTHER).role) + assertEquals("The server needs at least one admin", model.adminUsers.failure) + } + + @Test + fun aRemovedAccountLeavesAtOnceAndReturnsInPlaceOnFailure() = runTest { + val transport = scripted() + val model = usersPage(transport) + val path = "DELETE /v1/admin/users/$OTHER" + transport.answer(path, 500, """{"error":"Busy"}""") + val gate = transport.hold(path) + + model.removeUser(model.user(OTHER)) + assertEquals(listOf(ME, "user-third"), model.adminUsers.value?.map { it.id }) + runCurrent() + + transport.responses.remove(USERS) + gate.complete(Unit) + runCurrent() + assertEquals(listOf(ME, OTHER, "user-third"), model.adminUsers.value?.map { it.id }) + assertEquals("Busy", model.adminUsers.failure) + } + + @Test + fun aConfirmedRemovalStaysGone() = runTest { + val transport = scripted() + val model = usersPage(transport) + transport.answer("DELETE /v1/admin/users/$OTHER", 204, "") + + model.removeUser(model.user(OTHER)) + runCurrent() + assertEquals(listOf(ME, "user-third"), model.adminUsers.value?.map { it.id }) + assertEquals("", model.adminUsers.failure) + } + + @Test + fun usersShowTheirNameOrEmailAndRole() { + assertEquals("Kev (admin)", userRowTitle(AdminUser("1", "k@x", "Kev", "admin", "t"))) + assertEquals("k@x", userRowTitle(AdminUser("1", "k@x", "", "user", "t"))) + } + + // MARK: Invites + + @Test + fun anInviteIsMintedOnceAndShownWhenTheServerConfirms() = runTest { + val transport = scripted() + val model = usersPage(transport) + transport.answer(MINT, body = """{"id":"i1","createdAt":"t","url":"$SERVER/connect?invite=tok"}""") + val gate = transport.hold(MINT) + + model.createInvite() + assertNotNull(model.inviteSheet) + assertNull(model.inviteSheet?.url) + runCurrent() + assertNull(model.inviteSheet?.url) + + gate.complete(Unit) + runCurrent() + assertEquals("$SERVER/connect?invite=tok", model.inviteSheet?.url) + assertEquals(1, transport.sent(MINT).size) + + model.closeInviteSheet() + runCurrent() + assertNull(model.inviteSheet) + assertEquals(1, transport.sent(MINT).size) + } + + @Test + fun aFailedInviteOffersARetry() = runTest { + val transport = scripted() + val model = usersPage(transport) + transport.answer(MINT, 500, """{"error":"Busy"}""") + + model.createInvite() + runCurrent() + assertEquals("Busy", model.inviteSheet?.error) + assertNull(model.inviteSheet?.url) + + transport.answer(MINT, body = """{"id":"i1","createdAt":"t","url":"link"}""") + model.createInvite() + assertEquals("", model.inviteSheet?.error) + runCurrent() + assertEquals("link", model.inviteSheet?.url) + } + + @Test + fun aLateInviteNeitherReopensTheSheetNorLeavesTheListStale() = runTest { + val transport = scripted() + val model = usersPage(transport) + transport.answer(MINT, body = """{"id":"late","createdAt":"t","url":"link"}""") + val gate = transport.hold(MINT) + + model.createInvite() + runCurrent() + model.closeInviteSheet() + runCurrent() + transport.answer(INVITES, body = """{"invites":[${inviteJson("late", "2026-05-01T00:00:00.000Z")}]}""") + + gate.complete(Unit) + runCurrent() + assertNull(model.inviteSheet) + assertEquals(listOf("late"), model.invites.value?.map { it.id }) + } + + @Test + fun anEarlierInviteCannotFillANewerSheet() = runTest { + val transport = scripted() + val model = usersPage(transport) + transport.answer(MINT, body = """{"id":"first","createdAt":"t","url":"first-link"}""") + val first = transport.hold(MINT) + + model.createInvite() + runCurrent() + model.closeInviteSheet() + val second = CompletableDeferred() + transport.held[MINT] = second + model.createInvite() + runCurrent() + + first.complete(Unit) + runCurrent() + assertNull(model.inviteSheet?.url) + + transport.answer(MINT, body = """{"id":"second","createdAt":"t","url":"second-link"}""") + second.complete(Unit) + runCurrent() + assertEquals("second-link", model.inviteSheet?.url) + } + + @Test + fun leavingThePageDropsTheShownLink() = runTest { + val transport = scripted() + val model = usersPage(transport) + transport.answer(MINT, body = """{"id":"i1","createdAt":"t","url":"link"}""") + model.createInvite() + runCurrent() + assertEquals("link", model.inviteSheet?.url) + + model.navigate(Route.Coding) + assertNull(model.inviteSheet) + } + + @Test + fun revokingAnInviteAppliesAtOnceAndRollsBackInPlace() = runTest { + val transport = scripted() + val model = usersPage(transport) + val path = "DELETE /v1/admin/invites/new" + transport.answer(path, 404, """{"error":"No such invite"}""") + val gate = transport.hold(path) + val invite: Invite = model.invites.value!!.first() + + model.revokeInvite(invite) + assertEquals(listOf("old"), model.invites.value?.map { it.id }) + runCurrent() + + transport.responses.remove(INVITES) + gate.complete(Unit) + runCurrent() + assertEquals(listOf("new", "old"), model.invites.value?.map { it.id }) + assertEquals("No such invite", model.invites.failure) + } + + @Test + fun invitesShowTheirDate() { + assertTrue(dateOnly("2026-03-01T12:00:00.000Z", ZoneOffset.UTC).contains("26")) + assertEquals("not a date", dateOnly("not a date", ZoneOffset.UTC)) + } + + // MARK: Server settings + + @Test + fun openingSignUpAppliesAtOnceAndRollsBackOnFailure() = runTest { + val transport = scripted() + val model = usersPage(transport) + transport.answer(PATCH_SETTINGS, 500, """{"error":"Busy"}""") + val gate = transport.hold(PATCH_SETTINGS) + + model.setSignUpOpen(true) + assertEquals(true, model.serverSettings.value?.signUpOpen) + runCurrent() + assertEquals("""{"signUpOpen":true}""", transport.sent(PATCH_SETTINGS).single().body?.toString(StandardCharsets.UTF_8)) + + gate.complete(Unit) + runCurrent() + assertEquals(false, model.serverSettings.value?.signUpOpen) + assertEquals("Busy", model.serverSettings.failure) + } + + @Test + fun aSlowSignUpChangeIsNotOverwrittenByARefresh() = runTest { + val transport = scripted() + val model = usersPage(transport) + transport.answer(PATCH_SETTINGS, body = settingsJson(open = true)) + val gate = transport.hold(PATCH_SETTINGS) + + model.setSignUpOpen(true) + model.navigate(Route.Users) + runCurrent() + assertEquals(true, model.serverSettings.value?.signUpOpen) + + model.setSignUpOpen(false) + runCurrent() + assertEquals(1, transport.sent(PATCH_SETTINGS).size) + + gate.complete(Unit) + runCurrent() + assertEquals(true, model.serverSettings.value?.signUpOpen) + } + + @Test + fun workspaceAndSignUpChangesWaitForEachOther() = runTest { + val transport = scripted() + val model = usersPage(transport) + transport.answer(PATCH_SETTINGS, body = settingsJson(open = true)) + val gate = transport.hold(PATCH_SETTINGS) + model.setSignUpOpen(true) + model.openServerSettings(WorkspaceField.grace) + model.serverSettingsForm = model.serverSettingsForm?.copy(grace = "5") + + model.saveServerSettings() + runCurrent() + assertEquals(1, transport.sent(PATCH_SETTINGS).size) + assertNotNull(model.serverSettingsForm) + gate.complete(Unit) + } + + // MARK: Outdated workspaces + + @Test + fun theCodingPageNamesOutdatedWorkspaces() = runTest { + val transport = scripted() + transport.answer(OUTDATED, body = """{"workspaces":[{"userId":"$OTHER","agentId":"bot-1"}]}""") + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + model.navigate(Route.Coding) + runCurrent() + assertEquals(listOf("bot-1"), model.outdatedWorkspaces.value?.map { it.agentId }) + assertEquals("Kev", model.adminUsers.value?.first { it.id == OTHER }?.name) + } + + @Test + fun aRegularUserNeverAsksForOutdatedWorkspaces() = runTest { + val transport = scripted() + transport.answer(SETTINGS, 403, """{"error":"Only admins can do this"}""") + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + model.navigate(Route.Coding) + runCurrent() + assertEquals(false, model.isAdmin) + assertTrue(transport.sent(OUTDATED).isEmpty()) + } + + @Test + fun savingAnImageRechecksOutdatedWorkspaces() = runTest { + val transport = scripted() + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + model.navigate(Route.Coding) + runCurrent() + assertEquals(emptyList(), model.outdatedWorkspaces.value) + transport.answer(PATCH_SETTINGS, body = settingsJson(image = "next")) + transport.answer(OUTDATED, body = """{"workspaces":[{"userId":"$ME","agentId":"bot-1"}]}""") + + model.openServerSettings(WorkspaceField.image) + model.serverSettingsForm = model.serverSettingsForm?.copy(image = "next") + model.saveServerSettings() + runCurrent() + assertEquals(1, model.outdatedWorkspaces.value?.size) + } + + @Test + fun outdatedRowsFallBackToIDsForOtherAccounts() { + val workspaces = listOf( + ListOutdatedWorkspacesResponseWorkspacesItem(userId = ME, agentId = "mine"), + ListOutdatedWorkspacesResponseWorkspacesItem(userId = "gone", agentId = "theirs"), + ) + val rows = outdatedWorkspaceRows( + workspaces, + listOf(Agent(id = "mine", name = "Atlas")), + listOf(AdminUser(ME, "me@x", "", "admin", "t")), + ) + assertEquals(listOf(OutdatedWorkspaceRow("Atlas", "me@x"), OutdatedWorkspaceRow("theirs", "gone")), rows) + } + + @Test + fun disconnectedScreensDoNotProbeTheSession() { + val model = AppModel(loadCredentials = false) + model.refresh() + assertNull(model.isAdmin) + } +} diff --git a/app/src/test/java/dev/crumble/android/AgentSaveTests.kt b/app/src/test/java/dev/crumble/android/AgentSaveTests.kt new file mode 100644 index 0000000..c6cc1b1 --- /dev/null +++ b/app/src/test/java/dev/crumble/android/AgentSaveTests.kt @@ -0,0 +1,100 @@ +package dev.crumble.android + +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.Skill +import dev.crumble.android.network.APIClient +import dev.crumble.android.model.CrumbleJson +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import java.nio.charset.StandardCharsets +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +private const val SERVER = "https://crumble.example" + +private class RecordingTransport : HttpTransport { + val requests = mutableListOf() + var status = 200 + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + requests.add(request) + return HttpResponseData(status, (if (request.method == "PATCH") agentFixture("a1") else "[]").toByteArray(StandardCharsets.UTF_8)) + } + + override suspend fun openStream(request: HttpRequestData): HttpStreamResponse = + throw UnsupportedOperationException("streams are not used here") + + fun patch(): JsonObject { + val body = requests.single { it.method == "PATCH" }.body ?: ByteArray(0) + return CrumbleJson.parseToJsonElement(String(body, StandardCharsets.UTF_8)).jsonObject + } +} + +@OptIn(ExperimentalCoroutinesApi::class) +class AgentSaveTests { + private val bot = Agent( + id = "a1", + name = "Kev", + provider = "openai", + model = "gpt", + tools = listOf("memory", "web", "coding", "desktop", "create_bots"), + skills = listOf(Skill(name = "Triage", instructions = "Sort it")), + sharedSkills = listOf("shared-1"), + ) + + @Test + fun savingAnEditKeepsToolsTheEditorDoesNotShow() = runTest { + val transport = RecordingTransport() + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + model.agents = listOf(bot) + model.openEditor("a1") + model.agentDraft = model.agentDraft!!.copy(name = "Kevin") + model.saveAgentEditor() + runCurrent() + + val tools = transport.patch().getValue("tools").jsonArray.map { it.jsonPrimitive.content } + assertEquals(bot.tools!!.toSet(), tools.toSet()) + } + + @Test + fun savingAnEditNeverSubmitsSkillLists() = runTest { + val transport = RecordingTransport() + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + model.agents = listOf(bot) + model.openEditor("a1") + model.saveAgentEditor() + + assertEquals(bot.skills, model.agents.single().skills) + assertEquals(bot.sharedSkills, model.agents.single().sharedSkills) + runCurrent() + + val patch = transport.patch() + assertFalse(patch.containsKey("skills")) + assertFalse(patch.containsKey("sharedSkills")) + } + + @Test + fun aSavedSessionNeverGoesToAChangedServerURL() = runTest { + val transport = RecordingTransport() + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + model.token = "session" + model.serverURL = "http://other.example" + model.saveSettings() + runCurrent() + + assertTrue(transport.requests.isEmpty()) + assertEquals("Enter your password to connect to this server.", model.errorText) + } +} diff --git a/app/src/test/java/dev/crumble/android/AndroidRegexTests.kt b/app/src/test/java/dev/crumble/android/AndroidRegexTests.kt new file mode 100644 index 0000000..379e576 --- /dev/null +++ b/app/src/test/java/dev/crumble/android/AndroidRegexTests.kt @@ -0,0 +1,19 @@ +package dev.crumble.android + +import java.io.File +import org.junit.Assert.assertEquals +import org.junit.Test + +class AndroidRegexTests { + // Android's ICU regex engine throws on these flags, while the JVM running this suite accepts them. + @Test + fun appRegexesAvoidFlagsThatCrashOnAndroid() { + val unsupported = Regex("""\(\?[a-zA-Z]*U|UNICODE_CHARACTER_CLASS""") + val offenders = File("src/main/java").walkTopDown() + .filter { it.extension == "kt" } + .filter { unsupported.containsMatchIn(it.readText()) } + .map { it.name } + .toList() + assertEquals(emptyList(), offenders) + } +} diff --git a/app/src/test/java/dev/crumble/android/AutomationsTests.kt b/app/src/test/java/dev/crumble/android/AutomationsTests.kt new file mode 100644 index 0000000..cfc27be --- /dev/null +++ b/app/src/test/java/dev/crumble/android/AutomationsTests.kt @@ -0,0 +1,581 @@ +package dev.crumble.android + +import dev.crumble.android.generated.Capabilities +import dev.crumble.android.generated.ScriptRun +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.CrumbleJson +import dev.crumble.android.model.EventSource +import dev.crumble.android.model.EventSourceDraft +import dev.crumble.android.model.Execution +import dev.crumble.android.model.Route +import dev.crumble.android.model.Schedule +import dev.crumble.android.model.ScheduleStatus +import dev.crumble.android.model.TaskDraft +import dev.crumble.android.model.TaskTab +import dev.crumble.android.model.TaskWhen +import dev.crumble.android.model.choice +import dev.crumble.android.model.choosing +import dev.crumble.android.model.inTimezone +import dev.crumble.android.model.recurrenceOf +import dev.crumble.android.model.recurring +import dev.crumble.android.model.runningAt +import dev.crumble.android.model.canRunScripts +import dev.crumble.android.model.describeTiming +import dev.crumble.android.model.finished +import dev.crumble.android.model.listedSchedules +import dev.crumble.android.model.scriptRunDuration +import dev.crumble.android.model.status +import dev.crumble.android.model.taskRuns +import dev.crumble.android.model.validateTask +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import java.nio.charset.StandardCharsets +import java.time.Instant +import java.time.LocalDateTime +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +private class HeldTransport( + private val handler: (HttpRequestData) -> Pair, +) : HttpTransport { + val requests = mutableListOf() + val held = mutableMapOf>() + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + requests.add(request) + held["${request.method} ${request.pathWithQuery}"]?.await() + val (status, body) = handler(request) + return HttpResponseData(status, body.toByteArray(StandardCharsets.UTF_8)) + } + + override suspend fun openStream(request: HttpRequestData): HttpStreamResponse = + throw UnsupportedOperationException("streams are not used here") +} + +private fun bodyOf(request: HttpRequestData): JsonObject = + CrumbleJson.parseToJsonElement(String(request.body!!, StandardCharsets.UTF_8)).jsonObject + +private fun scheduleJson( + id: String = "s1", + kind: String = "script", + cron: String? = null, + runAt: String? = null, + eventSourceId: String? = "e1", + enabled: Boolean = true, + nextRunAt: String? = null, +): String { + fun quoted(value: String?) = value?.let { "\"$it\"" } ?: "null" + val command = if (kind == "script") "\"./backup.sh\"" else "null" + val prompt = if (kind == "script") "" else "Say hi" + return """{"id":"$id","agentId":"a1","name":"Backup","kind":"$kind","prompt":"$prompt","command":$command,"timeoutSeconds":120,"notify":false,"eventSourceId":${quoted(eventSourceId)},"enabled":$enabled,"timezone":"UTC","runAt":${quoted(runAt)},"cron":${quoted(cron)},"nextRunAt":${quoted(nextRunAt)},"createdAt":"2026-11-05T10:00:00Z","createdByAgentId":null}""" +} + +private fun schedule(json: String = scheduleJson()) = CrumbleJson.decodeFromString(Schedule.serializer(), json) + +private fun scriptRun(id: String, scheduleId: String = "s1", status: String = "succeeded", startedAt: String = "2026-11-05T10:00:00Z") = + ScriptRun(id, scheduleId, "a1", "./backup.sh", status, 0, "done", 0, null, startedAt, "2026-11-05T10:00:01.500Z") + +private const val SOURCES = """{"sources":[{"id":"e1","name":"GitHub","createdAt":"2026-11-05T10:00:00Z","usedBy":0}]}""" +private const val CREATED_SOURCE = """{"id":"e2","name":"Linear","createdAt":"2026-11-05T10:00:00Z","usedBy":0,"address":"https://relay.example/e2"}""" +private val CODING = Capabilities(coding = true, desktop = false, jobKinds = listOf("coding")) +private val SOURCE = EventSource("e1", "GitHub", "2026-11-05T10:00:00Z", 0) + +@OptIn(ExperimentalCoroutinesApi::class) +class AutomationsTests { + private fun modelWith(transport: HeldTransport, scope: TestScope): AppModel { + val client = APIClient(baseURL = "https://example.test", token = "secret", transport = transport) + return AppModel(client = client, scope = scope).also { + it.agents = listOf(Agent(id = "a1", name = "Atlas", tools = listOf("coding")), Agent(id = "a2", name = "Scout")) + it.capabilities = CODING + } + } + + @Test + fun scriptTaskOnAnEventAppearsAtOnceAndReconcilesWithoutDuplicates() = runTest { + val transport = HeldTransport { 201 to scheduleJson() } + val gate = CompletableDeferred() + transport.held["POST /v1/schedules"] = gate + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.taskDraft = TaskDraft( + scheduleID = "", agentID = "a1", name = "Backup", kind = "script", command = "./backup.sh", + timeoutSeconds = "120", notify = false, onEvent = true, eventSourceID = "e1", + ) + + model.saveTask() + testScheduler.runCurrent() + + val provisional = model.schedules.single() + assertTrue(provisional.id.startsWith("pending-")) + assertEquals(listOf(provisional), listedSchedules(model.schedules)) + assertTrue(model.schedulePending(provisional.id)) + val body = bodyOf(transport.requests.single()) + assertEquals(JsonPrimitive("script"), body["kind"]) + assertEquals(JsonPrimitive("./backup.sh"), body["command"]) + assertEquals(JsonPrimitive(120L), body["timeoutSeconds"]) + assertEquals(JsonPrimitive(false), body["notify"]) + assertEquals(JsonPrimitive("e1"), body["eventSourceId"]) + assertEquals(JsonPrimitive(""), body["prompt"]) + assertFalse(body.containsKey("cron")) + assertFalse(body.containsKey("runAt")) + + gate.complete(Unit) + testScheduler.advanceUntilIdle() + assertEquals(listOf("s1"), model.schedules.map { it.id }) + assertEquals(120L, model.schedules.single().timeoutSeconds) + } + + @Test + fun aNewOneOffStaysListedWhileItSaves() = runTest { + val transport = HeldTransport { 500 to """{"error":"down"}""" } + transport.held["POST /v1/schedules"] = CompletableDeferred() + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.taskDraft = TaskDraft(scheduleID = "", agentID = "a1", name = "Once", prompt = "Hi") + + model.saveTask() + testScheduler.runCurrent() + + assertEquals(1, listedSchedules(model.schedules).size) + } + + @Test + fun aFailedScriptSaveDropsTheRowAndRestoresTheDraft() = runTest { + val transport = HeldTransport { 500 to """{"error":"down"}""" } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.openPanel(Route.Tasks) + testScheduler.advanceUntilIdle() + val form = TaskDraft(scheduleID = "", agentID = "a1", name = "Backup", kind = "script", command = "./b.sh", timeoutSeconds = "90", notify = false) + model.taskDraft = form + + model.saveTask() + testScheduler.advanceUntilIdle() + + assertTrue(model.schedules.isEmpty()) + assertEquals(form, model.taskDraft) + assertTrue(model.errorText.isNotEmpty()) + } + + @Test + fun movingATaskOntoAnEventClearsItsOtherTriggersAndAPromptSendsNoCommand() = runTest { + val transport = HeldTransport { 200 to scheduleJson(kind = "prompt") } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.schedules = listOf(schedule(scheduleJson(kind = "prompt", cron = "0 9 * * *", eventSourceId = null))) + model.openTaskForm("s1") + assertTrue(model.taskDraft!!.repeats) + + model.taskDraft = model.taskDraft!!.copy(onEvent = true, eventSourceID = "e1") + model.saveTask() + testScheduler.advanceUntilIdle() + + val body = bodyOf(transport.requests.single { it.method == "PATCH" }) + assertEquals(JsonPrimitive("e1"), body["eventSourceId"]) + assertEquals(JsonNull, body["cron"]) + assertEquals(JsonNull, body["runAt"]) + assertEquals(JsonNull, body["command"]) + assertEquals(JsonPrimitive(600L), body["timeoutSeconds"]) + } + + @Test + fun aFormOpensWithTheScriptFieldsOfItsTask() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(HeldTransport { 200 to "[]" }, scope) + model.schedules = listOf(schedule()) + + model.openTaskForm("s1") + + val draft = model.taskDraft!! + assertEquals("script", draft.kind) + assertEquals("./backup.sh", draft.command) + assertEquals("120", draft.timeoutSeconds) + assertFalse(draft.notify) + assertTrue(draft.onEvent) + assertEquals("e1", draft.eventSourceID) + } + + @Test + fun pickingABotWithoutCodingJobsFallsBackToAPrompt() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(HeldTransport { 200 to "[]" }, scope) + model.taskDraft = TaskDraft(scheduleID = "", agentID = "a1", kind = "script") + + model.pickTaskBot("a1") + assertEquals("script", model.taskDraft!!.kind) + model.pickTaskBot("a2") + assertEquals("prompt", model.taskDraft!!.kind) + assertEquals("a2", model.taskDraft!!.agentID) + } + + @Test + fun pausingAppliesAtOnceAndRollsBack() = runTest { + val transport = HeldTransport { 500 to """{"error":"down"}""" } + val gate = CompletableDeferred() + transport.held["PATCH /v1/schedules/s1"] = gate + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.schedules = listOf(schedule()) + + model.toggleSchedule("s1") + testScheduler.runCurrent() + + assertFalse(model.schedules.single().enabled) + assertTrue(model.schedulePending("s1")) + assertEquals(setOf("enabled"), bodyOf(transport.requests.single()).keys) + + gate.complete(Unit) + testScheduler.advanceUntilIdle() + assertTrue(model.schedules.single().enabled) + assertFalse(model.schedulePending("s1")) + assertTrue(model.errorText.isNotEmpty()) + } + + @Test + fun runningAScriptOpensItsBotThoughAdmissionNamesOnlyTheRun() = runTest { + val transport = HeldTransport { 202 to """{"admitted":true,"result":{"id":"r1","status":"running"}}""" } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.schedules = listOf(schedule()) + model.route = Route.Tasks + + model.runSchedule("s1") + testScheduler.advanceUntilIdle() + + assertEquals(Route.AgentChat("a1"), model.route) + } + + @Test + fun aRefreshDuringASaveKeepsTheProvisionalRow() = runTest { + val transport = HeldTransport { request -> + when { + request.method == "POST" -> 201 to scheduleJson() + request.pathWithQuery == "/v1/schedules" -> 200 to "[]" + request.pathWithQuery == "/v1/capabilities" -> 200 to """{"coding":true,"desktop":false,"jobKinds":[]}""" + else -> 200 to SOURCES + } + } + val gate = CompletableDeferred() + transport.held["POST /v1/schedules"] = gate + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.taskDraft = TaskDraft(scheduleID = "", agentID = "a1", name = "Backup", prompt = "Hi") + model.saveTask() + testScheduler.runCurrent() + + model.openPanel(Route.Tasks) + testScheduler.advanceUntilIdle() + + assertEquals(1, model.schedules.size) + assertEquals("GitHub", model.eventSources.single().name) + gate.complete(Unit) + testScheduler.advanceUntilIdle() + assertEquals(listOf("s1"), model.schedules.map { it.id }) + } + + @Test + fun anEventSourceStaysPendingUntilTheRelayConfirmsAndShowsItsAddress() = runTest { + val transport = HeldTransport { request -> + if (request.method == "POST") { + 201 to CREATED_SOURCE + } else { + 200 to """{"sources":[{"id":"e2","name":"Linear","createdAt":"2026-11-05T10:00:00Z","usedBy":0}]}""" + } + } + val gate = CompletableDeferred() + transport.held["POST /v1/event-sources"] = gate + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.eventSourceDraft = EventSourceDraft(name = " Linear ") + + model.saveEventSource() + testScheduler.runCurrent() + + assertTrue(model.eventSourceDraft!!.saving) + assertTrue(model.eventSources.isEmpty()) + model.closeEventSourceForm() + assertNotNull("a pending sheet can't lose its one-time address", model.eventSourceDraft) + assertEquals(JsonPrimitive("Linear"), bodyOf(transport.requests.single())["name"]) + + gate.complete(Unit) + testScheduler.advanceUntilIdle() + assertEquals("https://relay.example/e2", model.eventSourceDraft!!.created!!.address) + assertEquals(listOf("e2"), model.eventSources.map { it.id }) + model.closeEventSourceForm() + assertNull(model.eventSourceDraft) + } + + @Test + fun aFailedEventSourceKeepsTheNameForRetry() = runTest { + val transport = HeldTransport { 502 to """{"error":"relay down"}""" } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.eventSourceDraft = EventSourceDraft(name = "Linear") + + model.saveEventSource() + testScheduler.advanceUntilIdle() + + val draft = model.eventSourceDraft!! + assertEquals("Linear", draft.name) + assertFalse(draft.saving) + assertTrue(draft.error.isNotEmpty()) + assertTrue(model.eventSources.isEmpty()) + } + + @Test + fun deletingAnEventSourceWaitsForTheRelayAndKeepsTheRowOnFailure() = runTest { + val transport = HeldTransport { 409 to """{"error":"Used by 1 automation"}""" } + val gate = CompletableDeferred() + transport.held["DELETE /v1/event-sources/e1"] = gate + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.eventSources = listOf(SOURCE) + + model.deleteEventSource("e1") + testScheduler.runCurrent() + + assertEquals(listOf(SOURCE), model.eventSources) + assertEquals(setOf("e1"), model.deletingEventSources) + + gate.complete(Unit) + testScheduler.advanceUntilIdle() + assertEquals(listOf(SOURCE), model.eventSources) + assertTrue(model.deletingEventSources.isEmpty()) + assertTrue(model.eventSourceErrors.getValue("e1").isNotEmpty()) + } + + @Test + fun aListThatStartedBeforeADeleteCannotBringTheSourceBack() = runTest { + // The held list answers last, with what it read before the delete. + var lists = 0 + val transport = HeldTransport { request -> + when { + request.method == "DELETE" -> 204 to "" + lists++ == 0 -> 200 to """{"sources":[]}""" + else -> 200 to SOURCES + } + } + val listGate = CompletableDeferred() + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.eventSources = listOf(SOURCE) + transport.held["GET /v1/event-sources"] = listGate + + model.selectTaskTab(TaskTab.EventSources) + testScheduler.runCurrent() + transport.held.clear() + model.deleteEventSource("e1") + testScheduler.runCurrent() + assertTrue(model.eventSources.isEmpty()) + + listGate.complete(Unit) + testScheduler.advanceUntilIdle() + assertTrue(model.eventSources.isEmpty()) + } + + @Test + fun runsTabLoadsScriptHistoryAndKeepsWhatAFailedScheduleHad() = runTest { + val runJson = """{"id":"r1","scheduleId":"s1","agentId":"a1","command":"./backup.sh","status":"succeeded","exitCode":0,"output":"done","droppedBytes":0,"error":null,"startedAt":"2026-11-05T10:00:00Z","finishedAt":"2026-11-05T10:00:01Z"}""" + var failing = false + val transport = HeldTransport { request -> + when (request.pathWithQuery) { + "/v1/schedules/s1/runs?limit=20" -> if (failing) 500 to """{"error":"down"}""" else 200 to "[$runJson]" + else -> 200 to "[]" + } + } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.schedules = listOf(schedule()) + + model.selectTaskTab(TaskTab.Runs) + testScheduler.advanceUntilIdle() + assertEquals(listOf("r1"), model.scriptRuns.getValue("s1").map { it.id }) + assertEquals("", model.taskRunsError) + + failing = true + model.selectTaskTab(TaskTab.Runs) + testScheduler.advanceUntilIdle() + assertEquals(listOf("r1"), model.scriptRuns.getValue("s1").map { it.id }) + assertEquals("Some script runs could not be loaded.", model.taskRunsError) + assertFalse(model.taskRunsLoading) + } + + @Test + fun runsMergeNewestFirstAndNameDeletedTasks() { + val runs = taskRuns( + schedules = listOf(schedule()), + executions = listOf( + Execution(id = "x1", agentId = "a1", status = "failed", createdAt = "2026-11-05T12:00:00Z", scheduleId = "gone"), + Execution(id = "x2", agentId = "a1", status = "done", createdAt = "2026-11-05T13:00:00Z"), + ), + scriptRuns = mapOf( + "s1" to listOf(scriptRun("r1", status = "timed_out"), scriptRun("r2", status = "running", startedAt = "2026-11-05T14:00:00Z")), + "deleted" to listOf(scriptRun("r3", scheduleId = "deleted")), + ), + ) + + assertEquals(listOf("r2", "x1", "r1"), runs.map { it.id }) + assertTrue(runs[0].running) + assertEquals("Failed", runs[1].label) + assertNull(runs[1].schedule) + assertEquals("Timed out", runs[2].label) + assertTrue(runs[2].failed) + } + + @Test + fun runsStopAtOneHundred() { + val many = (1..150).map { scriptRun("r$it") } + assertEquals(100, taskRuns(listOf(schedule()), emptyList(), mapOf("s1" to many)).size) + } + + @Test + fun aScriptRunReportsItsDuration() { + assertEquals("1.5 s", scriptRunDuration(scriptRun("r1"))) + val running = scriptRun("r2").copy(finishedAt = null) + assertEquals("2.0 s", scriptRunDuration(running, Instant.parse("2026-11-05T10:00:02Z"))) + } + + @Test + fun anEventTaskNamesItsSourceAndNeverCountsAsFinished() { + val task = schedule() + assertEquals("On event · GitHub", describeTiming(task, listOf(SOURCE))) + assertEquals("On event", describeTiming(task, emptyList())) + assertFalse(task.finished) + } + + @Test + fun aOneOffReadsRanOnlyAfterItFinished() { + val now = Instant.parse("2026-11-05T12:00:00Z") + val done = schedule(scheduleJson(kind = "prompt", runAt = "2026-11-05T10:00:00Z", eventSourceId = null)) + val waiting = schedule(scheduleJson(kind = "prompt", runAt = "2026-11-05T14:00:00Z", eventSourceId = null, nextRunAt = "2026-11-05T14:00:00Z")) + assertTrue(describeTiming(done, emptyList(), now).startsWith("Ran ")) + assertTrue(describeTiming(waiting, emptyList(), now).startsWith("Once, ")) + assertEquals(ScheduleStatus.Completed, done.status) + assertEquals(ScheduleStatus.Active, waiting.status) + } + + @Test + fun listingHidesFinishedPromptsAndOrdersByStatusThenNextRun() { + val finishedPrompt = schedule(scheduleJson(id = "p", kind = "prompt", runAt = "2026-11-05T10:00:00Z", eventSourceId = null)) + val finishedScript = schedule(scheduleJson(id = "f", runAt = "2026-11-05T10:00:00Z", eventSourceId = null)) + val paused = schedule(scheduleJson(id = "z", enabled = false)) + val later = schedule(scheduleJson(id = "l", cron = "0 9 * * *", eventSourceId = null, nextRunAt = "2026-11-06T09:00:00Z")) + val sooner = schedule(scheduleJson(id = "s", cron = "0 8 * * *", eventSourceId = null, nextRunAt = "2026-11-05T15:00:00Z")) + + val order = listedSchedules(listOf(finishedPrompt, finishedScript, paused, later, sooner)).map { it.id } + + assertEquals(listOf("s", "l", "z", "f"), order) + } + + @Test + fun scriptValidationMatchesTheWebsite() { + fun script(command: String = "./a.sh", timeout: String = "600", onEvent: Boolean = false, source: String = "") = validateTask( + name = "Task", prompt = "", cron = "0 9 * * *", runAt = "", kind = "script", + command = command, timeoutSeconds = timeout, onEvent = onEvent, eventSourceID = source, + ) + assertNull(script()) + assertEquals("Task name and command are required.", script(command = " ")) + assertEquals("Timeout must be between 1 and 3600 seconds.", script(timeout = "0")) + assertEquals("Timeout must be between 1 and 3600 seconds.", script(timeout = "3601")) + assertEquals("Timeout must be between 1 and 3600 seconds.", script(timeout = "1.5")) + assertEquals("Choose an event source.", script(onEvent = true)) + assertNull(script(onEvent = true, source = "e1")) + assertNull(validateTask(name = "T", prompt = "Hi", cron = "", runAt = "", onEvent = true, eventSourceID = "e1")) + } + + @Test + fun scriptsNeedBothAWorkspaceServerAndACodingBot() { + val coder = Agent(id = "a1", tools = listOf("coding")) + assertTrue(canRunScripts(CODING, coder)) + assertFalse(canRunScripts(CODING.copy(coding = false), coder)) + assertFalse(canRunScripts(null, coder)) + assertFalse(canRunScripts(CODING, Agent(id = "a2"))) + } + + @Test + fun aCronTaskShowsWordedTiming() { + val task = schedule(scheduleJson(kind = "prompt", cron = "0 9 * * 1-5", eventSourceId = null)) + assertEquals("At 09:00, Monday through Friday", describeTiming(task, emptyList(), localZone = "UTC")) + assertEquals("At 09:00, Monday through Friday (UTC)", describeTiming(task, emptyList(), localZone = "Europe/Berlin")) + } + + @Test + fun anExistingCronOpensInTheMatchingPickerAndAnOddOneAsCustom() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(HeldTransport { 200 to "{}" }, scope) + model.schedules = listOf( + schedule(scheduleJson(id = "weekly", kind = "prompt", cron = "30 8 * * 1,3", eventSourceId = null)), + schedule(scheduleJson(id = "odd", kind = "prompt", cron = "*/7 * * * *", eventSourceId = null)), + schedule(scheduleJson(id = "once", kind = "prompt", runAt = "2026-12-01T10:00:00Z", eventSourceId = null)), + ) + model.openTaskForm("weekly") + assertEquals(TaskWhen.Weekly, model.taskDraft!!.choice) + model.openTaskForm("odd") + assertEquals(TaskWhen.Custom, model.taskDraft!!.choice) + model.openTaskForm("once") + assertEquals(TaskWhen.Once, model.taskDraft!!.choice) + } + + @Test + fun aDraftFromThePickersSavesTheCronAndZoneItShows() = runTest { + val transport = HeldTransport { 201 to scheduleJson(kind = "prompt", cron = "15 7 * * 2,4", eventSourceId = null) } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + var draft = TaskDraft(scheduleID = "", agentID = "a1", name = "Standup", prompt = "Go", timezone = "UTC") + draft = draft.choosing(TaskWhen.Weekly) + draft = draft.recurring(recurrenceOf(draft.cron)!!.copy(days = listOf(2, 4), hour = 7, minute = 15)) + model.taskDraft = draft.inTimezone("Asia/Tokyo") + model.saveTask() + testScheduler.runCurrent() + val body = bodyOf(transport.requests.single()) + assertEquals("15 7 * * 2,4", body["cron"]?.jsonPrimitive?.content) + assertEquals("Asia/Tokyo", body["timezone"]?.jsonPrimitive?.content) + assertNull(body["runAt"]) + } + + @Test + fun aOneOffSavesTheWallClockInTheChosenZone() = runTest { + val transport = HeldTransport { 201 to scheduleJson(kind = "prompt", runAt = "2026-12-01T00:00:00Z", eventSourceId = null) } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + val draft = TaskDraft(scheduleID = "", agentID = "a1", name = "Once", prompt = "Go", timezone = "UTC") + .runningAt(LocalDateTime.of(2026, 12, 1, 9, 0)) + model.taskDraft = draft.inTimezone("Asia/Tokyo") + model.saveTask() + testScheduler.runCurrent() + assertEquals("2026-12-01T00:00:00Z", bodyOf(transport.requests.single())["runAt"]?.jsonPrimitive?.content) + } + + @Test + fun deletingATaskAppliesAtOnceAndRestoresItOnFailure() = runTest { + val transport = HeldTransport { 500 to """{"error":"down"}""" } + val gate = CompletableDeferred() + transport.held["DELETE /v1/schedules/s1"] = gate + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.schedules = listOf(schedule(), schedule(scheduleJson(id = "s2"))) + model.deleteSchedule("s1") + assertEquals(listOf("s2"), model.schedules.map { it.id }) + gate.complete(Unit) + testScheduler.runCurrent() + assertEquals(listOf("s1", "s2"), model.schedules.map { it.id }) + } +} diff --git a/app/src/test/java/dev/crumble/android/BotDesktopTests.kt b/app/src/test/java/dev/crumble/android/BotDesktopTests.kt new file mode 100644 index 0000000..173928e --- /dev/null +++ b/app/src/test/java/dev/crumble/android/BotDesktopTests.kt @@ -0,0 +1,490 @@ +package dev.crumble.android + +import dev.crumble.android.generated.DesktopControl +import dev.crumble.android.generated.DesktopViewer +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.DESKTOP_BOT +import dev.crumble.android.model.DESKTOP_HAND_BACK_FAILED +import dev.crumble.android.model.DESKTOP_OWNER +import dev.crumble.android.model.DESKTOP_UNAVAILABLE +import dev.crumble.android.model.DesktopKey +import dev.crumble.android.model.DesktopLink +import dev.crumble.android.model.DesktopPress +import dev.crumble.android.model.desktopKeyScript +import dev.crumble.android.model.desktopPresses +import dev.crumble.android.model.newerControl +import dev.crumble.android.model.press +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import java.io.ByteArrayInputStream +import java.nio.charset.StandardCharsets +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +private const val STATUS = "/v1/agents/a1/desktop/status" +private const val CONTROL = "/v1/agents/a1/desktop/control" +private const val VIEWER = "/v1/agents/a1/desktop/viewer" +private const val PASSIVE = "$VIEWER?passive=true" + +private fun control(holder: String, changes: Long) = + """event: control +data: {"holder":"$holder","changes":$changes,"updatedAt":"2026-11-05T10:00:00Z"} + +""" + +private fun controlBody(holder: String, changes: Long) = + """{"holder":"$holder","changes":$changes,"updatedAt":"2026-11-05T10:00:00Z"}""" + +/** Serves one desktop event stream per connection, and answers requests from the fields below. */ +private class DesktopTransport(streams: List = listOf(control(DESKTOP_BOT, 1))) : HttpTransport { + val requests = mutableListOf() + val held = mutableMapOf>() + var running = false + var statusCode = 200 + var controlCode = 200 + var viewerCode = 201 + private val remaining = streams.toMutableList() + private var tickets = 0 + var opened = 0 + + fun methods(path: String) = requests.filter { it.pathWithQuery == path }.map { it.method } + + fun holders() = requests.filter { it.pathWithQuery == CONTROL && it.method == "PUT" }.map { + it.body!!.toString(StandardCharsets.UTF_8).substringAfter("holder\":\"").substringBefore("\"") + } + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + requests.add(request) + held[request.pathWithQuery]?.await() + val body = when (request.pathWithQuery) { + STATUS -> statusCode to """{"running":$running}""" + CONTROL -> { + val holder = if (request.body!!.toString(StandardCharsets.UTF_8).contains(DESKTOP_OWNER)) DESKTOP_OWNER else DESKTOP_BOT + controlCode to controlBody(holder, requests.size.toLong() + 1) + } + VIEWER, PASSIVE -> { + tickets += 1 + viewerCode to """{"path":"/desktop-viewer/t$tickets","expiresAt":"2026-11-05T10:01:00Z"}""" + } + else -> 503 to "" + } + return HttpResponseData(body.first, body.second.toByteArray(StandardCharsets.UTF_8)) + } + + override suspend fun openStream(request: HttpRequestData): HttpStreamResponse { + val desktop = request.pathWithQuery == "/v1/agents/a1/desktop/events" + if (desktop) opened += 1 + val text = if (desktop && remaining.isNotEmpty()) remaining.removeAt(0) else "" + return HttpStreamResponse(200, ByteArrayInputStream(text.toByteArray())) + } +} + +@OptIn(ExperimentalCoroutinesApi::class) +class BotDesktopTests { + private fun modelWith(transport: DesktopTransport, scope: TestScope) = + AppModel(client = APIClient(baseURL = "http://crumble.test/", token = "", transport = transport), scope = scope) + + // The stream reads on the IO dispatcher, so events land off the test scheduler. + private fun TestScope.settle(condition: () -> Boolean) { + val deadline = System.currentTimeMillis() + 5_000 + while (!condition()) { + assertTrue("timed out", System.currentTimeMillis() < deadline) + testScheduler.runCurrent() + Thread.sleep(2) + } + } + + @Test + fun newerControlKeepsTheLatestChange() { + val first = DesktopControl(DESKTOP_OWNER, 4, "a") + val stale = DesktopControl(DESKTOP_BOT, 3, "b") + val same = DesktopControl(DESKTOP_BOT, 4, "c") + assertEquals(stale, newerControl(null, stale)) + assertEquals(first, newerControl(first, stale)) + assertEquals(same, newerControl(first, same)) + } + + @Test + fun viewerUrlIsResolvedAgainstTheServer() { + val api = APIClient("https://crumble.test/", "", DesktopTransport()) + assertEquals("https://crumble.test/desktop-viewer/a.b", api.desktopViewerURL(DesktopViewer("/desktop-viewer/a.b", "t"))) + } + + @Test + fun textBecomesKeyPresses() { + assertEquals( + listOf(DesktopPress("a"), DesktopKey.Enter.press(), DesktopKey.Tab.press(), DesktopPress("é")), + desktopPresses("a\r\n\té😀"), + ) + } + + @Test + fun keyScriptEscapesTextAndHoldsCtrlAroundThePresses() { + val script = desktopKeyScript(listOf(DesktopPress("\"'\\"), DesktopPress("c")), ctrl = true) + assertTrue(script, script.contains("""k('keydown',"\"'\\","")""")) + val down = script.indexOf("k('keydown','Control','ControlLeft')") + val press = script.indexOf("""k('keydown',"c","")""") + val up = script.indexOf("k('keyup','Control','ControlLeft')") + assertTrue(down in 0 until press && press < up) + assertFalse(desktopKeyScript(listOf(DesktopPress("c"))).contains("Control")) + } + + @Test + fun eventsSetControlAndAStaleOneIsIgnored() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = DesktopTransport(listOf(control(DESKTOP_OWNER, 5) + "event: heartbeat\ndata: {}\n\n" + control(DESKTOP_BOT, 2))) + val model = modelWith(transport, scope) + model.openBotDesktop("a1") + settle { transport.opened == 1 && model.botDesktop?.control != null } + testScheduler.runCurrent() + assertTrue(model.botDesktop!!.owner) + assertEquals(5L, model.botDesktop!!.control!!.changes) + model.closeBotDesktop() + } + + @Test + fun aDroppedEventStreamReconnectsAndCatchesUp() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = DesktopTransport(listOf(control(DESKTOP_BOT, 1), control(DESKTOP_OWNER, 2))) + val model = modelWith(transport, scope) + model.openBotDesktop("a1") + settle { model.botDesktop?.control != null } + testScheduler.advanceTimeBy(600) + settle { model.botDesktop?.owner == true } + assertEquals(2, transport.opened) + model.closeBotDesktop() + } + + @Test + fun takingControlStaysPendingUntilConfirmed() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = DesktopTransport() + val gate = CompletableDeferred().also { transport.held[CONTROL] = it } + val model = modelWith(transport, scope) + model.openBotDesktop("a1") + settle { model.botDesktop?.control != null } + + model.setDesktopHolder(DESKTOP_OWNER) + testScheduler.runCurrent() + assertEquals(DESKTOP_OWNER, model.botDesktop!!.taking) + assertFalse(model.botDesktop!!.owner) + + model.setDesktopHolder(DESKTOP_OWNER) + testScheduler.runCurrent() + assertEquals(listOf(DESKTOP_OWNER), transport.holders()) + + gate.complete(Unit) + testScheduler.runCurrent() + assertNull(model.botDesktop!!.taking) + assertTrue(model.botDesktop!!.owner) + + model.setDesktopHolder(DESKTOP_BOT) + testScheduler.runCurrent() + assertFalse(model.botDesktop!!.owner) + model.closeBotDesktop() + testScheduler.runCurrent() + assertEquals(listOf(DESKTOP_OWNER, DESKTOP_BOT), transport.holders()) + } + + @Test + fun aFailedTakeKeepsTheHolderAndCanBeRetried() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = DesktopTransport().also { it.controlCode = 500 } + val model = modelWith(transport, scope) + model.openBotDesktop("a1") + settle { model.botDesktop?.control != null } + + model.setDesktopHolder(DESKTOP_OWNER) + testScheduler.runCurrent() + assertFalse(model.botDesktop!!.owner) + assertNull(model.botDesktop!!.taking) + assertTrue(model.botDesktop!!.takeError.isNotEmpty()) + + transport.controlCode = 200 + model.setDesktopHolder(DESKTOP_OWNER) + testScheduler.runCurrent() + assertTrue(model.botDesktop!!.owner) + assertEquals("", model.botDesktop!!.takeError) + model.closeBotDesktop() + } + + @Test + fun takingControlWaitsForTheFirstEvent() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = DesktopTransport(emptyList()) + val model = modelWith(transport, scope) + model.openBotDesktop("a1") + model.setDesktopHolder(DESKTOP_OWNER) + testScheduler.runCurrent() + assertEquals(emptyList(), transport.holders()) + model.closeBotDesktop() + } + + @Test + fun leavingHandsControlBackOnlyWhenTheOwnerHoldsIt() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val watching = DesktopTransport() + val watcher = modelWith(watching, scope) + watcher.openBotDesktop("a1") + settle { watcher.botDesktop?.control != null } + watcher.closeBotDesktop() + testScheduler.runCurrent() + assertEquals(emptyList(), watching.holders()) + + val holding = DesktopTransport(listOf(control(DESKTOP_OWNER, 3))) + val holder = modelWith(holding, scope) + holder.openBotDesktop("a1") + settle { holder.botDesktop?.owner == true } + holder.closeBotDesktop() + testScheduler.runCurrent() + assertNull(holder.botDesktop) + assertEquals(listOf(DESKTOP_BOT), holding.holders()) + } + + @Test + fun leavingDuringATakeHandsBackAfterItLands() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = DesktopTransport() + val gate = CompletableDeferred().also { transport.held[CONTROL] = it } + val model = modelWith(transport, scope) + model.openBotDesktop("a1") + settle { model.botDesktop?.control != null } + model.setDesktopHolder(DESKTOP_OWNER) + testScheduler.runCurrent() + + model.closeBotDesktop() + testScheduler.runCurrent() + assertEquals(listOf(DESKTOP_OWNER), transport.holders()) + + gate.complete(Unit) + testScheduler.runCurrent() + assertEquals(listOf(DESKTOP_OWNER, DESKTOP_BOT), transport.holders()) + assertNull(model.botDesktop) + } + + @Test + fun aFailedHandBackRetriesThenSaysSo() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = DesktopTransport(listOf(control(DESKTOP_OWNER, 3))).also { it.controlCode = 503 } + val model = modelWith(transport, scope) + model.openBotDesktop("a1") + settle { model.botDesktop?.owner == true } + model.closeBotDesktop() + testScheduler.advanceUntilIdle() + assertEquals(3, transport.holders().size) + assertEquals(DESKTOP_HAND_BACK_FAILED, model.errorText) + } + + @Test + fun refreshingTheSameBotKeepsTheDesktopAndSwitchingBotsLeavesIt() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = DesktopTransport(listOf(control(DESKTOP_OWNER, 3))) + val model = modelWith(transport, scope) + model.openBotDesktop("a1") + settle { model.botDesktop?.owner == true } + + model.selectAgent("a1") + testScheduler.runCurrent() + assertTrue(model.botDesktop!!.owner) + assertEquals(emptyList(), transport.holders()) + + model.selectAgent("a2") + testScheduler.runCurrent() + assertNull(model.botDesktop) + assertEquals(listOf(DESKTOP_BOT), transport.holders()) + model.cancelStream() + } + + @Test + fun everyConnectionGetsAFreshLinkAndAFailureCanReconnect() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = DesktopTransport() + val model = modelWith(transport, scope) + model.openBotDesktop("a1") + assertTrue(model.botDesktop!!.viewer.connecting) + testScheduler.runCurrent() + assertEquals("http://crumble.test/desktop-viewer/t1", model.botDesktop!!.viewer.url) + + model.reconnectDesktopViewer() + assertEquals(DesktopLink(connecting = true), model.botDesktop!!.viewer) + testScheduler.runCurrent() + assertEquals("http://crumble.test/desktop-viewer/t2", model.botDesktop!!.viewer.url) + + transport.viewerCode = 409 + model.reconnectDesktopViewer() + testScheduler.runCurrent() + assertNull(model.botDesktop!!.viewer.url) + assertTrue(model.botDesktop!!.viewer.error.isNotEmpty()) + + transport.viewerCode = 201 + model.reconnectDesktopViewer() + testScheduler.runCurrent() + assertEquals("http://crumble.test/desktop-viewer/t4", model.botDesktop!!.viewer.url) + assertEquals(4, transport.methods(VIEWER).size) + model.closeBotDesktop() + } + + @Test + fun aLostPageAsksForReconnectUnlessItsLinkWasReplaced() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = DesktopTransport() + val model = modelWith(transport, scope) + model.openBotDesktop("a1") + testScheduler.runCurrent() + val first = model.botDesktop!!.viewer.url!! + model.reconnectDesktopViewer() + testScheduler.runCurrent() + + model.desktopViewerLost(first) + assertEquals("http://crumble.test/desktop-viewer/t2", model.botDesktop!!.viewer.url) + + model.desktopViewerLost(model.botDesktop!!.viewer.url!!) + assertEquals(DesktopLink(error = DESKTOP_UNAVAILABLE), model.botDesktop!!.viewer) + model.closeBotDesktop() + } + + @Test + fun aLateViewerResponseIsDroppedAfterLeaving() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = DesktopTransport() + val gate = CompletableDeferred().also { transport.held[VIEWER] = it } + val model = modelWith(transport, scope) + model.openBotDesktop("a1") + testScheduler.runCurrent() + model.closeBotDesktop() + transport.held.remove(VIEWER) + model.openBotDesktop("a1") + testScheduler.runCurrent() + assertEquals("http://crumble.test/desktop-viewer/t1", model.botDesktop!!.viewer.url) + + gate.complete(Unit) + testScheduler.runCurrent() + assertEquals("http://crumble.test/desktop-viewer/t1", model.botDesktop!!.viewer.url) + model.closeBotDesktop() + } + + @Test + fun aSleepingPreviewShowsNoViewerAndWakingBootsTheMachine() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = DesktopTransport() + val model = modelWith(transport, scope) + model.watchDesktopPreview("a1") + assertNull(model.desktopPreview!!.running) + testScheduler.runCurrent() + assertEquals(false, model.desktopPreview!!.running) + assertFalse(model.desktopPreview!!.awake) + assertEquals(emptyList(), transport.methods(VIEWER) + transport.methods(PASSIVE)) + + model.wakeDesktop() + testScheduler.runCurrent() + assertEquals(listOf("POST"), transport.methods(VIEWER)) + assertEquals("http://crumble.test/desktop-viewer/t1", model.desktopPreview!!.viewer.url) + model.stopDesktopPreview() + } + + @Test + fun aRunningMachineIsWatchedPassivelyAndStoppingEndsThePreview() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = DesktopTransport().also { it.running = true } + val model = modelWith(transport, scope) + model.watchDesktopPreview("a1") + testScheduler.runCurrent() + assertEquals(listOf("POST"), transport.methods(PASSIVE)) + assertEquals("http://crumble.test/desktop-viewer/t1", model.desktopPreview!!.viewer.url) + + testScheduler.advanceTimeBy(10_001) + assertEquals(listOf("POST"), transport.methods(PASSIVE)) + + transport.running = false + testScheduler.advanceTimeBy(10_001) + assertEquals(DesktopLink(), model.desktopPreview!!.viewer) + assertFalse(model.desktopPreview!!.awake) + + model.stopDesktopPreview() + val reads = transport.methods(STATUS).size + testScheduler.advanceTimeBy(30_000) + assertEquals(reads, transport.methods(STATUS).size) + } + + @Test + fun aFailedStatusReadKeepsTheLastAnswer() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = DesktopTransport().also { it.running = true } + val model = modelWith(transport, scope) + model.watchDesktopPreview("a1") + testScheduler.runCurrent() + transport.statusCode = 503 + testScheduler.advanceTimeBy(10_001) + assertEquals(true, model.desktopPreview!!.running) + assertEquals("http://crumble.test/desktop-viewer/t1", model.desktopPreview!!.viewer.url) + model.stopDesktopPreview() + } + + @Test + fun theOpenDesktopReplacesThePreviewUntilItCloses() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = DesktopTransport().also { it.running = true } + val model = modelWith(transport, scope) + model.watchDesktopPreview("a1") + testScheduler.runCurrent() + + model.openBotDesktop("a1") + testScheduler.runCurrent() + assertEquals(DesktopLink(), model.desktopPreview!!.viewer) + + model.closeBotDesktop() + testScheduler.runCurrent() + assertEquals(2, transport.methods(PASSIVE).size) + assertTrue(model.desktopPreview!!.viewer.url != null) + model.stopDesktopPreview() + } + + @Test + fun aLatePreviewLinkIsDroppedOnceStopped() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = DesktopTransport().also { it.running = true } + val gate = CompletableDeferred().also { transport.held[PASSIVE] = it } + val model = modelWith(transport, scope) + model.watchDesktopPreview("a1") + testScheduler.runCurrent() + model.stopDesktopPreview() + transport.held.remove(PASSIVE) + model.watchDesktopPreview("a1") + testScheduler.runCurrent() + assertEquals("http://crumble.test/desktop-viewer/t1", model.desktopPreview!!.viewer.url) + + gate.complete(Unit) + testScheduler.runCurrent() + assertEquals("http://crumble.test/desktop-viewer/t1", model.desktopPreview!!.viewer.url) + model.stopDesktopPreview() + } + + @Test + fun anExpiredSessionStopsFollowingEvents() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + var opened = 0 + val transport = object : HttpTransport by DesktopTransport() { + override suspend fun openStream(request: HttpRequestData): HttpStreamResponse { + opened += 1 + return HttpStreamResponse(401, ByteArrayInputStream(ByteArray(0))) + } + } + val model = AppModel(client = APIClient("http://crumble.test", "", transport), scope = scope) + model.openBotDesktop("a1") + settle { model.botDesktop?.takeError?.isNotEmpty() == true } + testScheduler.advanceTimeBy(30_000) + assertEquals(1, opened) + model.closeBotDesktop() + } +} diff --git a/app/src/test/java/dev/crumble/android/BotParityTests.kt b/app/src/test/java/dev/crumble/android/BotParityTests.kt new file mode 100644 index 0000000..14370c2 --- /dev/null +++ b/app/src/test/java/dev/crumble/android/BotParityTests.kt @@ -0,0 +1,706 @@ +package dev.crumble.android + +import dev.crumble.android.generated.BotRequest +import dev.crumble.android.generated.Capabilities +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.ChartInk +import dev.crumble.android.model.ChartShape +import dev.crumble.android.model.ChatRow +import dev.crumble.android.model.ChatSnapshot +import dev.crumble.android.model.CrumbleJson +import dev.crumble.android.model.DisplayCard +import dev.crumble.android.model.DisplayCell +import dev.crumble.android.model.Message +import dev.crumble.android.model.MessageOrigin +import dev.crumble.android.model.ModelChoice +import dev.crumble.android.model.ProviderStatus +import dev.crumble.android.model.Schedule +import dev.crumble.android.model.THINKING_LEVELS +import dev.crumble.android.model.WEB_SEARCH_OPTIONS +import dev.crumble.android.model.automationTiming +import dev.crumble.android.model.automationsOf +import dev.crumble.android.model.botListLine +import dev.crumble.android.model.botReactions +import dev.crumble.android.model.chartInk +import dev.crumble.android.model.chartLayoutFor +import dev.crumble.android.model.chartLayouts +import dev.crumble.android.model.desktopModelHint +import dev.crumble.android.model.desktopProviderOptions +import dev.crumble.android.model.displayOf +import dev.crumble.android.model.fitColumns +import dev.crumble.android.model.groupReactions +import dev.crumble.android.model.isDesktopScreenshot +import dev.crumble.android.model.loadAttachment +import dev.crumble.android.model.nearestChartPoint +import dev.crumble.android.model.numericColumns +import dev.crumble.android.model.shownCapabilities +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import dev.crumble.android.network.edited +import dev.crumble.android.network.wire +import dev.crumble.android.ui.BotState +import java.nio.charset.StandardCharsets +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.encodeToJsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +private const val SERVER = "https://crumble.example" + +private fun json(text: String) = CrumbleJson.parseToJsonElement(text) + +private fun chatJson(status: String) = snapshotFixture(ChatSnapshot(agentId = "a", status = status)) + +private class Replies( + private val handler: (HttpRequestData) -> Pair, +) : HttpTransport { + val requests = mutableListOf() + val held = mutableMapOf>() + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + requests.add(request) + held.entries.firstOrNull { request.pathWithQuery.startsWith(it.key) }?.value?.await() + val (status, body) = handler(request) + return HttpResponseData(status, body.toByteArray(StandardCharsets.UTF_8)) + } + + override suspend fun openStream(request: HttpRequestData): HttpStreamResponse = + throw UnsupportedOperationException("streams are not used here") + + fun patch(): JsonObject = + json(String(requests.single { it.method == "PATCH" }.body!!, StandardCharsets.UTF_8)).jsonObject + + fun post(): JsonObject = + json(String(requests.single { it.method == "POST" }.body!!, StandardCharsets.UTF_8)).jsonObject +} + +private fun show(details: String, isError: Boolean? = null) = + Message(id = "m", role = "toolResult", toolName = "show", isError = isError, toolDetails = json(details)) + +@OptIn(ExperimentalCoroutinesApi::class) +class BotParityTests { + // MARK: Attachments + + @Test + fun everyFileTheWebsitePickerOffersCanBeAttached() { + val extensions = listOf("json", "xml", "md", "csv", "ts", "tsx", "js", "py", "swift", "go", "rs", "java", "kt", "rb", "sh", "yaml", "yml", "toml") + for (extension in extensions) { + for (hint in listOf(null, "application/octet-stream")) { + val attachment = loadAttachment("file.$extension", hint, "hello".toByteArray()) + assertEquals("file.$extension", attachment.name) + } + } + } + + @Test + fun aRubyFileReportedUnderItsApplicationTypeCanBeAttached() { + assertEquals("text/plain", loadAttachment("build.rb", "application/x-ruby", "puts 1".toByteArray()).mimeType) + } + + @Test + fun aTypeScriptFileReportedAsVideoCanBeAttached() { + assertEquals("text/plain", loadAttachment("app.ts", "video/mp2t", "let a = 1".toByteArray()).mimeType) + } + + // MARK: Bot editor + + private val bot = Agent( + id = "a1", + name = "Kev", + provider = "openai", + model = "gpt", + tools = listOf("memory", "web", "desktop"), + webSearchProvider = "exa", + desktopModel = ModelChoice("openai", "gpt"), + ) + + @Test + fun codingAndDesktopShowOnlyWhenTheServerOffersThemOrTheBotHasThem() { + fun tools(server: Capabilities?, initial: Set = emptySet()) = + shownCapabilities(server, initial).map { it.tool } + + val always = listOf("memory", "web", "delegate", "create_bots") + assertEquals(always, tools(null)) + assertEquals(always, tools(Capabilities(coding = false, desktop = false, jobKinds = emptyList()))) + assertEquals( + listOf("memory", "web", "delegate", "coding", "desktop", "create_bots"), + tools(Capabilities(coding = true, desktop = true, jobKinds = emptyList())), + ) + assertEquals(listOf("memory", "web", "delegate", "desktop", "create_bots"), tools(null, setOf("desktop"))) + } + + @Test + fun theDesktopProviderListKeepsAChoiceThatLostItsKey() { + val providers = listOf(ProviderStatus("openai", "OpenAI", true), ProviderStatus("melious", "Melious", false)) + + assertEquals(listOf("", "openai"), desktopProviderOptions(providers, "").map { it.value }) + assertEquals("Same as the bot", desktopProviderOptions(providers, "")[0].label) + assertEquals( + listOf("Same as the bot", "Melious (not set up)", "OpenAI"), + desktopProviderOptions(providers, "melious").map { it.label }, + ) + assertEquals("Add an API key or sign in for this provider in Settings to load its models.", desktopModelHint(providers, "melious", 0)) + assertEquals("3 models available.", desktopModelHint(providers, "openai", 3)) + assertEquals("Type a model ID.", desktopModelHint(providers, "openai", 0)) + } + + @Test + fun webSearchChoicesMatchTheWebsite() { + assertEquals(listOf("Account default", "Mixed", "Exa"), WEB_SEARCH_OPTIONS.map { it.label }) + } + + @Test + fun aNewBotStartsWithTheWebsitesTools() { + val model = AppModel(client = null, scope = kotlinx.coroutines.test.TestScope()) + model.createAgent() + val draft = model.agentDraft!! + assertTrue(draft.toolsMemory) + assertTrue(draft.toolsDelegate) + assertEquals(setOf("web"), draft.otherTools) + } + + @Test + fun savingSendsTheWebSearchProviderAndDesktopModel() = runTest { + val transport = Replies { 200 to agentFixture("a1") } + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + model.agents = listOf(bot) + model.openEditor("a1") + val draft = model.agentDraft!! + assertEquals("exa", draft.webSearchProvider) + assertEquals("openai", draft.desktopProvider) + assertEquals("gpt", draft.desktopModel) + model.agentDraft = draft.copy(webSearchProvider = "mixed", desktopModel = " sonnet ") + model.saveAgentEditor() + assertEquals("mixed", model.agents.single().webSearchProvider) + assertEquals(ModelChoice("openai", "sonnet"), model.agents.single().desktopModel) + runCurrent() + + val patch = transport.patch() + assertEquals("mixed", patch.getValue("webSearchProvider").jsonPrimitive.content) + assertEquals("sonnet", patch.getValue("desktopModel").jsonObject.getValue("model").jsonPrimitive.content) + assertFalse(patch.containsKey("skills")) + assertFalse(patch.containsKey("sharedSkills")) + } + + @Test + fun clearingSendsNullSoTheServerDropsTheOldChoices() = runTest { + val transport = Replies { 200 to agentFixture("a1") } + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + model.agents = listOf(bot) + model.openEditor("a1") + model.agentDraft = model.agentDraft!!.copy(webSearchProvider = null, desktopProvider = "", desktopModel = "") + model.saveAgentEditor() + runCurrent() + + val patch = transport.patch() + assertEquals(JsonNull, patch["webSearchProvider"]) + assertEquals(JsonNull, patch["desktopModel"]) + } + + @Test + fun aProviderWithoutAModelDoesNotPickADesktopModel() { + val model = AppModel(client = null, scope = kotlinx.coroutines.test.TestScope()) + model.createAgent() + assertNull(model.agentDraft!!.copy(desktopProvider = "openai", desktopModel = " ").chosenDesktopModel) + } + + @Test + fun aFailedSaveRestoresTheOldChoicesAndKeepsTheDraft() = runTest { + val transport = Replies { 500 to """{"error":"no"}""" } + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + model.agents = listOf(bot) + model.openEditor("a1") + model.agentDraft = model.agentDraft!!.copy(webSearchProvider = "mixed") + model.saveAgentEditor() + assertNull(model.agentDraft) + assertEquals("mixed", model.agents.single().webSearchProvider) + runCurrent() + + assertEquals("exa", model.agents.single().webSearchProvider) + assertEquals(ModelChoice("openai", "gpt"), model.agents.single().desktopModel) + assertEquals("mixed", model.agentDraft!!.webSearchProvider) + } + + private fun levelTransport() = Replies { request -> + 200 to when { + "/models?provider=openai" in request.pathWithQuery -> + """[{"provider":"openai","id":"deep","name":"D","contextWindow":1,"reasoning":true,"thinkingLevels":["off","low","medium","high","max"]},""" + + """{"provider":"openai","id":"small","name":"S","contextWindow":1,"reasoning":true,"thinkingLevels":["off","low"]},""" + + """{"provider":"openai","id":"flat","name":"F","contextWindow":1,"reasoning":false,"thinkingLevels":["off"]}]""" + request.method == "POST" -> agentFixture("created") + else -> "[]" + } + } + + private fun Replies.savedLevel(): String? = + (CrumbleJson.parseToJsonElement(requests.last { it.method == "POST" }.body!!.toString(Charsets.UTF_8)) as JsonObject)["inference"] + ?.let { it as JsonObject }?.get("thinkingLevel")?.let { (it as JsonPrimitive).content } + + @Test + fun theEditorClampsReasoningToTheModelLikeTheWebsite() = runTest { + val transport = levelTransport() + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + model.createAgent() + model.agentDraft = model.agentDraft!!.copy(name = "Ada", provider = "openai", model = "deep") + model.changeEditorProvider("openai") + runCurrent() + model.agentDraft = model.agentDraft!!.copy(model = "deep", thinking = "max") + assertEquals(listOf("off", "low", "medium", "high", "max"), model.editorLevels) + assertEquals("max", model.editorLevel) + + model.agentDraft = model.agentDraft!!.copy(model = "small") + assertEquals("low", model.editorLevel) + + model.agentDraft = model.agentDraft!!.copy(model = "deep") + assertEquals("max", model.editorLevel) + + model.agentDraft = model.agentDraft!!.copy(model = "small") + model.saveAgentEditor() + runCurrent() + assertEquals("low", transport.savedLevel()) + } + + @Test + fun aModelOutsideTheCatalogKeepsAnyLevel() = runTest { + val model = AppModel(client = APIClient(SERVER, "session", levelTransport()), scope = this) + model.createAgent() + model.changeEditorProvider("openai") + runCurrent() + model.agentDraft = model.agentDraft!!.copy(model = "typed-by-hand", thinking = "high") + + assertEquals(THINKING_LEVELS.map { it.value }, model.editorLevels) + assertEquals("high", model.editorLevel) + } + + @Test + fun aProviderChangeClampsOnceItsModelsArrive() = runTest { + val transport = levelTransport() + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + val gate = CompletableDeferred() + model.createAgent() + runCurrent() + model.agentDraft = model.agentDraft!!.copy(thinking = "medium") + transport.held["/v1/models?provider=openai"] = gate + model.changeEditorProvider("openai") + runCurrent() + assertEquals("medium", model.editorLevel) + + gate.complete(Unit) + runCurrent() + model.agentDraft = model.agentDraft!!.copy(model = "flat") + + assertEquals(listOf("off"), model.editorLevels) + assertEquals("off", model.editorLevel) + } + + @Test + fun aLateModelListDoesNotReplaceTheNewerProviders() = runTest { + val transport = Replies { request -> + 200 to if ("/models?provider=google" in request.pathWithQuery) { + """[{"provider":"google","id":"g1","name":"G","contextWindow":1,"reasoning":false,"thinkingLevels":[]}]""" + } else { + "[]" + } + } + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + val gate = CompletableDeferred() + transport.held["/v1/models?provider=openai"] = gate + model.createAgent() + runCurrent() + model.changeEditorDesktopProvider("openai") + runCurrent() + model.changeEditorDesktopProvider("google") + runCurrent() + assertEquals(listOf("g1"), model.desktopModels.map { it.id }) + + gate.complete(Unit) + runCurrent() + assertEquals(listOf("g1"), model.desktopModels.map { it.id }) + } + + @Test + fun aProposalsChoicesCanBeChangedOrCleared() { + val proposal = CrumbleJson.decodeFromString(botRequestFixture()).proposal + + val changed = proposal.edited(Agent(name = "Scout", webSearchProvider = "mixed", desktopModel = ModelChoice("google", "g1"))) + assertEquals("mixed", changed.getValue("webSearchProvider").jsonPrimitive.content) + assertEquals("g1", changed.getValue("desktopModel").jsonObject.getValue("model").jsonPrimitive.content) + + val cleared = proposal.edited(Agent(name = "Scout")) + assertEquals(JsonNull, cleared["webSearchProvider"]) + assertEquals(JsonNull, cleared["desktopModel"]) + } + + @Test + fun aNewBotSendsItsChoicesAndLeavesOutUnsetOnes() = runTest { + val transport = Replies { 200 to agentFixture("created") } + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = backgroundScope) + model.createAgent() + model.agentDraft = model.agentDraft!!.copy(name = "New", provider = "openai", model = "gpt", webSearchProvider = "exa", desktopProvider = "openai", desktopModel = "gpt") + model.saveAgentEditor() + runCurrent() + + val body = transport.post() + assertEquals("exa", body.getValue("webSearchProvider").jsonPrimitive.content) + assertEquals("gpt", body.getValue("desktopModel").jsonObject.getValue("model").jsonPrimitive.content) + assertTrue(body.getValue("tools").toString().contains("web")) + + assertFalse(CrumbleJson.encodeToJsonElement(Agent(name = "New").wire()).jsonObject.containsKey("desktopModel")) + } + + // MARK: Display cards + + @Test + fun statsParseAndStayHiddenWhenTheyFailTheSchema() { + val card = displayOf(show("""{"kind":"stats","title":"Sales","items":[{"label":"Total","value":"12","change":"+3","trend":"up","caption":"week"}]}""")) + val stats = card as DisplayCard.Stats + assertEquals("Sales", stats.title) + assertEquals("up", stats.items.single().trend) + + assertNull(displayOf(show("""{"kind":"stats","items":[{"label":"Total"}]}"""))) + assertNull(displayOf(show("""{"kind":"stats","items":[{"label":"T","value":"1","trend":"sideways"}]}"""))) + assertNull(displayOf(show("""{"kind":"other"}"""))) + assertNull(displayOf(show("""{"kind":"stats","items":[]}""", isError = true))) + assertNull(displayOf(show("""{"kind":"stats","items":[]}""").copy(toolName = "other"))) + } + + @Test + fun tableColumnsAreNumericOnlyWhenEveryCellIs() { + val table = displayOf(show("""{"kind":"table","columns":["Name","Count","Mix"],"rows":[["a",1,"x"],["b",2.5,3]]}""")) as DisplayCard.Table + assertEquals(DisplayCell("a"), table.rows[0][0]) + assertEquals(2.5, table.rows[1][1].number!!, 0.0) + assertEquals(listOf(false, true, false), numericColumns(3, table.rows)) + assertNull(displayOf(show("""{"kind":"table","columns":["A"],"rows":[[true]]}"""))) + assertEquals(listOf(50f, 50f), fitColumns(listOf(40f, 40f), 100f)) + assertEquals(listOf(70f, 70f), fitColumns(listOf(70f, 70f), 100f)) + } + + private val chart = """{"kind":"chart","title":"Trend","layouts":[ + {"width":600,"height":300,"nodes":[],"points":[]}, + {"width":320,"height":200,"nodes":[ + {"kind":"line","x1":0,"y1":1,"x2":2,"y2":3,"stroke":"series-1","dash":[4,2]}, + {"kind":"path","commands":[["M",0,0],["L",1,1],["Q",1,2,3,4],["C",1,2,3,4,5,6],["Z"],["L",1]],"evenOdd":true}, + {"kind":"circle","x":5,"y":6,"radius":2,"fill":"#2a78d6"}, + {"kind":"rect","x":1,"y":2,"width":3,"height":4,"radius":1,"fill":"none","clip":[0,0,10,10]}, + {"kind":"text","x":1,"y":2,"text":"Jan","anchor":"middle","baseline":"hanging","rotate":0,"size":12,"weight":500}, + {"kind":"unknown"} + ],"points":[ + {"x":10,"y":10,"text":"Note","rows":[]}, + {"x":20,"y":10,"title":"Feb","rows":[{"label":"Sales","value":"12"}]} + ]} + ]}""" + + @Test + fun chartsParseEveryPrimitiveAndKeepTheChartWhenOneIsBad() { + val card = displayOf(show(chart)) as DisplayCard.Chart + val layouts = chartLayouts(card.layouts) + assertEquals(listOf(320f, 600f), layouts.map { it.width }) + + val nodes = layouts[0].nodes + assertEquals(5, nodes.size) + assertEquals(ChartInk.None, nodes[0].fill) + assertEquals(ChartInk.Foreground, nodes[1].fill) + assertEquals(5, (nodes[1].shape as ChartShape.Curve).commands.size) + assertTrue((nodes[1].shape as ChartShape.Curve).evenOdd) + assertEquals(ChartInk.Literal(0xFF2A78D6), nodes[2].fill) + assertEquals(ChartInk.None, nodes[3].fill) + assertEquals("Jan", (nodes[4].shape as ChartShape.Label).text) + assertEquals(10f, nodes[3].clip!!.width) + + assertEquals("Feb", layouts[0].points[1].title) + assertEquals("Note", layouts[0].points[0].text) + assertNull(displayOf(show("""{"kind":"chart","layouts":[{"nodes":[]}]}"""))) + } + + @Test + fun chartLayoutsMatchTheAvailableWidthAndColorsMatchTheWebsite() { + val layouts = chartLayouts((displayOf(show(chart)) as DisplayCard.Chart).layouts) + assertEquals(320f, chartLayoutFor(layouts, 100f)!!.width) + assertEquals(320f, chartLayoutFor(layouts, 599f)!!.width) + assertEquals(600f, chartLayoutFor(layouts, 600f)!!.width) + assertNull(chartLayoutFor(emptyList(), 600f)) + + assertEquals(ChartInk.Literal(0xFF737373), chartInk("series-1", ChartInk.None)) + assertEquals(ChartInk.Literal(0xFFD4D4D4), chartInk("series-5", ChartInk.None)) + assertEquals(ChartInk.Literal(0xFF737373), chartInk("series-6", ChartInk.None)) + assertEquals(ChartInk.Literal(0xFFFFAA00), chartInk("#fa0", ChartInk.None)) + assertEquals(ChartInk.Literal(0x80112233), chartInk("#11223380", ChartInk.None)) + assertEquals(ChartInk.Background, chartInk("background", ChartInk.None)) + assertEquals(ChartInk.Foreground, chartInk(null, ChartInk.Foreground)) + } + + @Test + fun aTouchFindsTheNearestPointWithinReach() { + val points = chartLayouts((displayOf(show(chart)) as DisplayCard.Chart).layouts)[0].points + assertEquals("Feb", nearestChartPoint(points, 18f, 10f, 32f)?.title) + assertEquals("Note", nearestChartPoint(points, 11f, 10f, 32f)?.text) + assertNull(nearestChartPoint(points, 100f, 100f, 32f)) + } + + @Test + fun cardsAndScreenshotsShowInTheChatButOtherToolsDoNot() { + val screenshot = Message(id = "s", entryId = "e1", role = "toolResult", toolName = "desktop_screenshot") + assertTrue(isDesktopScreenshot(screenshot)) + assertFalse(isDesktopScreenshot(screenshot.copy(isError = true))) + assertFalse(isDesktopScreenshot(screenshot.copy(entryId = null))) + + val messages = listOf( + show("""{"kind":"stats","items":[]}"""), + screenshot, + screenshot.copy(id = "failed", isError = true), + Message(id = "o", role = "toolResult", toolName = "web_search"), + ) + val rows = ChatRow.rows(messages, null, hasMore = false).filterIsInstance() + assertEquals(listOf("m", "s"), rows.map { it.message.id }) + } + + // MARK: Reactions + + private fun react(emoji: String, replyTo: String? = null, origin: String? = null) = Message( + id = "r$emoji", + role = "toolResult", + toolName = "react", + replyTo = replyTo, + origin = origin?.let { MessageOrigin(kind = "bot", name = it) }, + toolDetails = json("""{"emoji":"$emoji"}"""), + ) + + @Test + fun aBotsReactionLandsOnTheOwnersLastMessage() { + val messages = listOf( + Message(id = "1", entryId = "u1", role = "user"), + react("A"), + Message(id = "2", entryId = "a1", role = "assistant"), + Message(id = "3", entryId = "u2", role = "user"), + react("B"), + react("C", origin = "Kev"), + react("D").copy(isError = true), + ) + assertEquals(mapOf("u1" to listOf("A"), "u2" to listOf("B", "Kev C")), botReactions(messages)) + } + + @Test + fun aReactionBeforeAnyOwnerMessageIsDropped() { + assertTrue(botReactions(listOf(react("A"))).isEmpty()) + } + + @Test + fun groupReactionsStillUseTheRecordedTarget() { + val messages = listOf(Message(id = "1", entryId = "u1", role = "user"), react("A", replyTo = "other", origin = "Kev")) + assertEquals(mapOf("other" to listOf("Kev A")), groupReactions(messages)) + } + + // MARK: Live status + + private fun chats(vararg statuses: Pair): Replies { + val byBot = statuses.toMap().toMutableMap() + return Replies { request -> + val id = request.pathWithQuery.removePrefix("/v1/agents/").substringBefore('/') + when (val status = byBot[id]) { + null -> 404 to """{"error":"gone"}""" + else -> 200 to chatJson(status) + } + } + } + + private val a = Agent(id = "a", name = "A", enabled = true) + private val b = Agent(id = "b", name = "B", enabled = true) + private val off = Agent(id = "off", name = "Off", enabled = false) + + @Test + fun everyEnabledBotReportsWhetherItIsWorking() = runTest { + val transport = chats("a" to "idle", "b" to "running") + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + model.agents = listOf(a, b, off, Agent(id = "pending:1", name = "New", enabled = true)) + model.refreshBotStatuses() + + assertEquals(setOf("b"), model.workingBots) + assertEquals(BotState.working, model.botState(b)) + assertEquals(BotState.idle, model.botState(a)) + assertEquals(BotState.sleeping, model.botState(off)) + assertEquals(2, transport.requests.size) + assertTrue(transport.requests.all { it.pathWithQuery.endsWith("/chat?limit=1") }) + } + + @Test + fun aFailedReadKeepsTheLastKnownStatusAndAFinishedTurnClearsIt() = runTest { + var status = 500 + var body = """{"error":"down"}""" + val transport = Replies { status to body } + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + model.agents = listOf(a) + model.workingBots = setOf("a") + model.refreshBotStatuses() + assertEquals(setOf("a"), model.workingBots) + + status = 200 + body = chatJson("idle") + model.refreshBotStatuses() + assertTrue(model.workingBots.isEmpty()) + } + + @Test + fun aDeletedBotLeavesTheWorkingSet() = runTest { + val transport = chats("a" to "idle") + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + model.agents = listOf(a) + model.workingBots = setOf("gone") + model.refreshBotStatuses() + assertTrue(model.workingBots.isEmpty()) + } + + @Test + fun theOpenChatsStreamBeatsTheLastStatusCheck() = runTest { + val model = AppModel(client = APIClient(SERVER, "session", chats("a" to "idle", "b" to "idle")), scope = backgroundScope) + model.agents = listOf(a, b) + model.selectAgent("a") + model.workingBots = setOf("a") + model.snapshot = ChatSnapshot(status = "idle") + assertFalse(model.isWorking("a")) + model.snapshot = ChatSnapshot(status = "running") + model.workingBots = emptySet() + assertTrue(model.isWorking("a")) + } + + @Test + fun leavingARunningBotKeepsItWorkingInTheList() = runTest { + val transport = chats("a" to "running", "b" to "idle") + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = backgroundScope) + model.agents = listOf(a, b) + model.selectAgent("a") + model.snapshot = ChatSnapshot(status = "running") + model.selectAgent("b") + runCurrent() + + assertTrue(model.isWorking("a")) + + model.selectAgent("a") + model.snapshot = ChatSnapshot(status = "idle") + model.selectAgent("b") + runCurrent() + assertFalse(model.isWorking("a")) + } + + @Test + fun aLateStatusFromAnOldSessionIsDropped() = runTest { + val transport = chats("a" to "running") + val gate = CompletableDeferred() + transport.held["/v1/agents/a/chat"] = gate + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this, transport = transport) + model.agents = listOf(a) + val read = launch { model.refreshBotStatuses() } + runCurrent() + model.signOut() + runCurrent() + gate.complete(Unit) + read.join() + + assertTrue(model.workingBots.isEmpty()) + } + + @Test + fun followingPollsUntilTheListCloses() = runTest { + val transport = chats("a" to "idle") + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + model.agents = listOf(a) + val follow = launch { model.followBotStatuses() } + runCurrent() + assertEquals(1, transport.requests.size) + advanceTimeBy(5_001) + assertEquals(2, transport.requests.size) + + model.appActive = false + advanceTimeBy(5_001) + assertEquals(2, transport.requests.size) + + follow.cancel() + } + + @Test + fun theListLineSaysWhenABotIsWorking() { + assertEquals("Working…", botListLine(a.copy(lastMessage = "hi"), true)) + assertEquals("hi", botListLine(a.copy(lastMessage = "hi"), false)) + assertEquals("No messages yet", botListLine(a, false)) + } + + // MARK: Details + + private fun schedule(id: String, agentId: String = "a", enabled: Boolean = true, cron: String? = "0 9 * * *", nextRunAt: String? = null) = + Schedule(id = id, agentId = agentId, name = id, cron = cron, enabled = enabled, nextRunAt = nextRunAt, prompt = "p", timezone = "UTC") + + @Test + fun detailsListThisBotsTasksThatCanStillRun() { + val list = listOf(schedule("mine"), schedule("other", agentId = "b"), schedule("done", cron = null), schedule("next", cron = null, nextRunAt = "2030-01-01T00:00:00Z")) + assertEquals(listOf("mine", "next"), automationsOf("a", list).map { it.id }) + assertTrue(automationTiming(schedule("off", enabled = false), emptyList()).startsWith("Paused · ")) + } + + @Test + fun openingDetailsLoadsTasksAndReportsAFailure() = runTest { + var ok = false + val transport = Replies { request -> + if (request.pathWithQuery.startsWith("/v1/schedules") && !ok) 500 to """{"error":"Down"}""" else 200 to "[]" + } + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + model.openBotDetails() + assertTrue(model.showingBotDetails) + assertFalse(model.schedulesLoaded) + runCurrent() + assertFalse(model.schedulesLoaded) + assertTrue(model.schedulesError.isNotEmpty()) + + ok = true + model.openBotDetails() + assertEquals("", model.schedulesError) + runCurrent() + assertTrue(model.schedulesLoaded) + } + + @Test + fun aFailedToggleInDetailsRollsBackAndADelayedOneWaits() = runTest { + val gate = CompletableDeferred() + val transport = Replies { 500 to """{"error":"no"}""" } + transport.held["/v1/schedules/mine"] = gate + val model = AppModel(client = APIClient(SERVER, "session", transport), scope = this) + model.schedules = listOf(schedule("mine")) + model.toggleSchedule("mine") + assertFalse(model.schedules.single().enabled) + assertTrue(model.schedulePending("mine")) + runCurrent() + assertFalse(model.schedules.single().enabled) + + gate.complete(Unit) + runCurrent() + assertTrue(model.schedules.single().enabled) + assertFalse(model.schedulePending("mine")) + } + + @Test + fun choosingAnotherBotClosesDetails() = runTest { + val model = AppModel(client = APIClient(SERVER, "session", chats("a" to "idle", "b" to "idle")), scope = backgroundScope) + model.agents = listOf(a, b) + model.selectAgent("a") + model.showingBotDetails = true + model.selectAgent("a") + assertTrue(model.showingBotDetails) + model.selectAgent("b") + assertFalse(model.showingBotDetails) + } +} diff --git a/app/src/test/java/dev/crumble/android/ChatParityTests.kt b/app/src/test/java/dev/crumble/android/ChatParityTests.kt new file mode 100644 index 0000000..c7478fb --- /dev/null +++ b/app/src/test/java/dev/crumble/android/ChatParityTests.kt @@ -0,0 +1,533 @@ +package dev.crumble.android + +import dev.crumble.android.model.ActivityRecord +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.BotRequestRef +import dev.crumble.android.model.ChatRow +import dev.crumble.android.model.ChatSnapshot +import dev.crumble.android.model.CrumbleJson +import dev.crumble.android.model.Inference +import dev.crumble.android.model.JobItem +import dev.crumble.android.model.JobKind +import dev.crumble.android.model.JobRef +import dev.crumble.android.model.Message +import dev.crumble.android.model.ModelSummary +import dev.crumble.android.model.SourceChip +import dev.crumble.android.model.clampLevel +import dev.crumble.android.model.costLine +import dev.crumble.android.model.headline +import dev.crumble.android.model.jobItems +import dev.crumble.android.model.jobMarkdown +import dev.crumble.android.model.jobOf +import dev.crumble.android.model.levelsOf +import dev.crumble.android.model.mergeJobPages +import dev.crumble.android.model.siteOf +import dev.crumble.android.model.sourceKey +import dev.crumble.android.model.sourcesOf +import dev.crumble.android.model.splitSources +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import java.nio.charset.StandardCharsets +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +private fun json(text: String) = CrumbleJson.parseToJsonElement(text) + +private fun bodyOf(request: HttpRequestData) = json(request.body!!.toString(StandardCharsets.UTF_8)).jsonObject + +/** Answers from `handler`, holding back any path listed in `held` until its gate opens. */ +private class ScriptedTransport( + private val handler: (HttpRequestData) -> Pair, +) : HttpTransport { + val requests = mutableListOf() + val held = mutableMapOf>() + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + requests.add(request) + held[request.pathWithQuery]?.await() + val (status, body) = handler(request) + return HttpResponseData(status, body.toByteArray(StandardCharsets.UTF_8)) + } + + override suspend fun openStream(request: HttpRequestData): HttpStreamResponse = + throw UnsupportedOperationException("streams are not used here") +} + +private const val AVATAR = """{"definition":{"version":1,"id":"box","name":"Box","body":{"path":"M20 20H80V80H20Z"},"eyes":{"x":50,"y":46,"spacing":15,"scale":1}},"color":"#38bdf8","eyeColor":"#151515"}""" + +internal fun botRequestFixture(status: String = "pending") = """{"id":"r1","agentId":"a1","reason":"Needs a scout","status":"$status","createdAgentId":null,"requestedAt":"2026-11-05T10:00:00Z","decidedAt":null,"proposal":{"name":"Scout","avatar":$AVATAR,"description":"Finds things","instructions":"Look around","provider":"openai","model":"gpt","webSearchProvider":"exa","enabled":true,"tools":["memory","web","coding"],"skills":[{"name":"Map","instructions":"Draw"}],"sharedSkills":["s1"],"sharedMemory":true,"mcpServers":["m1"],"delegates":["a2"],"inference":{"thinkingLevel":"high","temperature":0.5},"review":{"enabled":true},"reviewModel":{"provider":"openai","model":"mini"},"desktopModel":{"provider":"openai","model":"desk"}}}""" + +private fun approvedFixture() = """{"request":${botRequestFixture("approved")},"agent":${agentFixture("a9", name = "Scout Prime")}}""" + +private val botRequestMessage = Message(id = "t1", entryId = "t", role = "toolResult", botRequest = BotRequestRef("r1", "Scout")) + +private fun jobResult(tool: String = "coding", name: String = "fix-login", status: String = "working") = Message( + id = "t1", entryId = "t", role = "toolResult", toolName = tool, + toolDetails = buildJsonObject { put("name", name); put("status", status) }, +) + +private fun jobFixture(name: String, status: String, usage: String = """{"models":{"a/one":{"cost":{"total":1.5}}}}""") = + """{"name":"$name","conversationId":"c","status":"$status","model":{"provider":"openai","model":"gpt"},"usage":$usage}""" + +private fun history(ids: List, hasMore: Boolean = false, oldest: String? = null) = buildString { + append("""{"messages":[""") + append(ids.joinToString(",") { """{"id":"$it","entryId":"$it","role":"user","content":"task $it"}""" }) + append("""],"hasMore":$hasMore,"oldestEntryId":${oldest?.let { "\"$it\"" } ?: "null"}}""") +} + +@OptIn(ExperimentalCoroutinesApi::class) +class ChatParityTests { + private fun web(tool: String, vararg pages: String) = Message( + id = "tool", role = "toolResult", toolName = tool, + toolDetails = JsonArray(pages.map { json(it) }), + ) + + @Test + fun sourceKeyIgnoresFragmentTrailingSlashAndHostCase() { + assertEquals("example.com/a?b=1", sourceKey("https://EXAMPLE.com/a/?b=1#top")) + assertEquals("example.com", sourceKey("http://example.com/")) + assertEquals("example.com", sourceKey("https://example.com:443")) + assertEquals("example.com:8443/a", sourceKey("https://example.com:8443/a")) + assertEquals("example.com/a?q=x|y", sourceKey("https://example.com/a?q=x|y")) + assertNull(sourceKey("ftp://example.com/a")) + assertNull(sourceKey("not a url")) + } + + @Test + fun sourcesBelongToTheTurnThatReadThem() { + val first = Message(id = "r1", role = "assistant") + val second = Message(id = "r2", role = "assistant") + val page = """{"url":"https://a.com/x","title":"A"}""" + val failed = web("web_extract", """{"url":"https://c.com","title":"C"}""").copy(isError = true) + val messages = listOf( + web("web_search", page, """{"url":"https://b.com","title":"B","error":"blocked"}"""), + failed, + first, + Message(id = "u", role = "user"), + second, + ) + val sources = sourcesOf(messages) + assertEquals(mapOf("r1" to mapOf("a.com/x" to "A")), sources) + } + + @Test + fun splitSourcesMovesCitationsToChipsAndLeavesCodeAlone() { + val sources = mapOf("a.com/x" to "A", "b.com" to "B") + val reply = splitSources( + """ + Fact one ([source](https://a.com/x/), [source](https://b.com)). Again [source](https://a.com/x). + Unread [source](https://z.com) stays, `[source](https://a.com/x)` too. + ``` + [source](https://a.com/x) + ``` + """.trimIndent(), + sources, + ) + assertEquals(listOf(SourceChip("https://a.com/x/", "A"), SourceChip("https://b.com", "B")), reply.chips) + assertEquals( + """ + Fact one. Again. + Unread [source](https://z.com) stays, `[source](https://a.com/x)` too. + ``` + [source](https://a.com/x) + ``` + """.trimIndent(), + reply.text, + ) + } + + @Test + fun siteOfDropsWwwAndPort() { + assertEquals("example.com", siteOf("https://www.Example.com:8443/a")) + } + + @Test + fun costLineSumsModelsAndHidesZero() { + assertEquals("$3.0000", costLine(json("""{"models":{"a/one":{"cost":{"total":1.5}},"b/two":{"cost":{"total":1.5}}}}"""))) + assertNull(costLine(json("""{"models":{"claude-code/one":{"cost":{"total":0}}}}"""))) + assertNull(costLine(json("""{"models":{}}"""))) + assertNull(costLine(null)) + } + + @Test + fun jobResultsAreChatRows() { + assertEquals(JobRef(JobKind.desktop, "browse", "idle"), jobOf(jobResult("desktop", "browse", "idle"))) + assertNull(jobOf(jobResult().copy(isError = true))) + assertNull(jobOf(jobResult("web_search"))) + assertTrue(ChatRow.shownInChat(jobResult())) + } + + @Test + fun jobItemsAttachResultsToSteps() { + val assistant = Message( + id = "m2", role = "assistant", + blocks = json("""[{"type":"text","text":"On it"},{"type":"toolCall","id":"c1","name":"bash","arguments":{"command":"ls"}},{"type":"toolCall","id":"c2","name":"read","arguments":{"path":"a.kt"}}]"""), + ) + val result = Message(id = "m3", role = "toolResult", toolCallId = "c1", isError = true, content = JsonPrimitive("nope")) + val items = jobItems(listOf(Message(id = "m1", role = "user", content = JsonPrimitive("Fix it")), assistant, result)) + assertEquals(JobItem.Task("m1", "Fix it"), items[0]) + assertEquals(JobItem.Reply("m2:0", "On it"), items[1]) + assertEquals(JobItem.Step("c1", "bash", "ls", result), items[2]) + assertEquals(JobItem.Step("c2", "read", "a.kt", null), items[3]) + } + + @Test + fun jobMarkdownFencesToolOutputAgainstBackticks() { + val messages = listOf( + Message(id = "m1", role = "user", content = JsonPrimitive("Fix it")), + Message(id = "m2", role = "toolResult", isError = true, content = JsonPrimitive("a ```` b")), + ) + assertEquals( + "# fix\n\nCoding job\n\n## Task\n\nFix it\n\nFailed:\n\n`````\na ```` b\n`````\n", + jobMarkdown(JobRef(JobKind.coding, "fix"), messages), + ) + } + + @Test + fun mergeJobPagesKeepsRowsThePageMovedPast() { + fun rows(vararg ids: String) = ids.map { Message(id = it) } + assertEquals(rows("1", "2", "3", "4"), mergeJobPages(rows("1", "2", "3"), rows("2", "3", "4"))) + assertEquals(rows("1"), mergeJobPages(rows("1"), emptyList())) + } + + @Test + fun clampLevelPrefersTheNearestHigherLevel() { + assertEquals("high", clampLevel("medium", listOf("off", "high"))) + assertEquals("low", clampLevel("max", listOf("off", "low"))) + assertEquals("off", clampLevel("high", emptyList())) + assertEquals(7, levelsOf(null).size) + assertEquals(listOf("off"), levelsOf(ModelSummary(thinkingLevels = listOf("off")))) + } + + @Test + fun changeRowsReadLikeTheWebHeadline() { + val skill = ActivityRecord( + kind = "change", agentName = "Kev", + details = json("""{"actor":"review","target":"skill","targetId":"s1","action":"update","agentId":"a1","after":{"name":"Triage"},"before":null}"""), + ) + assertEquals("Kev's review changed a skill · Triage", skill.headline().run { "$lead $verb $target" }) + val memory = ActivityRecord( + kind = "change", + details = json("""{"actor":"owner","target":"memory","targetId":"m1","action":"delete","before":{"content":"First\nSecond"}}"""), + ) + assertEquals("You deleted a shared memory · First", memory.headline().run { "$lead $verb $target" }) + } + + private fun modelWith(transport: ScriptedTransport, scope: TestScope, agents: List = emptyList()): AppModel { + val client = APIClient(baseURL = "http://crumble.test/", token = "", transport = transport) + return AppModel(client = client, scope = scope).also { it.agents = agents } + } + + @Test + fun plainApprovalSendsNoProposal() = runTest { + val transport = ScriptedTransport { 200 to approvedFixture() } + val client = APIClient(baseURL = "http://crumble.test/", token = "", transport = transport) + client.approveBotRequest("a1", "r1") + assertEquals(JsonObject(emptyMap()), bodyOf(transport.requests.single())) + } + + @Test + fun editedApprovalKeepsFieldsTheEditorHidesAndWaitsForTheServer() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val approve = "/v1/agents/a1/bot-requests/r1/approve" + var refuse = true + val transport = ScriptedTransport { req -> + when (req.pathWithQuery) { + "/v1/agents/a1/bot-requests" -> 200 to "[${botRequestFixture(if (refuse) "pending" else "approved")}]" + approve -> if (refuse) 503 to """{"error":"busy"}""" else 200 to approvedFixture() + else -> 503 to "" + } + } + val gate = CompletableDeferred().also { transport.held[approve] = it } + val model = modelWith(transport, scope) + model.selectAgent("a1") + model.applySnapshot(ChatSnapshot(agentId = "a1", messages = listOf(botRequestMessage))) + testScheduler.runCurrent() + + model.openBotRequestEditor("r1") + val draft = model.agentDraft!! + assertEquals(setOf("web", "coding"), draft.otherTools) + assertEquals("Look around", draft.instructions) + model.agentDraft = draft.copy(name = "Scout Prime", description = "", otherTools = setOf("web")) + model.saveAgentEditor() + testScheduler.runCurrent() + + assertTrue("r1" in model.decidingIDs) + assertEquals("Scout Prime", model.agentDraft?.name) + assertTrue(model.agents.isEmpty()) + + gate.complete(Unit) + testScheduler.runCurrent() + assertTrue(model.decisionErrors["r1"].orEmpty().contains("busy")) + assertEquals("Scout Prime", model.agentDraft?.name) + assertTrue(model.agents.isEmpty()) + + refuse = false + model.saveAgentEditor() + testScheduler.runCurrent() + assertNull(model.agentDraft) + assertEquals(listOf("a9"), model.agents.map { it.id }) + assertEquals("approved", model.botRequests.single().status) + + val sent = bodyOf(transport.requests.last { it.pathWithQuery == approve })["proposal"]!!.jsonObject + assertEquals("Scout Prime", sent["name"]!!.jsonPrimitive.content) + assertEquals("", sent["description"]!!.jsonPrimitive.content) + assertEquals("exa", sent["webSearchProvider"]!!.jsonPrimitive.content) + assertEquals(json("""{"provider":"openai","model":"desk"}"""), sent["desktopModel"]) + assertEquals(json("""{"provider":"openai","model":"mini"}"""), sent["reviewModel"]) + assertEquals(json("""{"enabled":true}"""), sent["review"]) + assertEquals(json("""["memory","web"]"""), sent["tools"]) + assertEquals(json("""["s1"]"""), sent["sharedSkills"]) + assertEquals(json("""["m1"]"""), sent["mcpServers"]) + assertEquals(json("""{"thinkingLevel":"high","temperature":0.5}"""), sent["inference"]) + model.cancelStream() + } + + @Test + fun editorClosesWhenTheRequestSettlesElsewhere() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + var status = "pending" + val transport = ScriptedTransport { req -> + if (req.pathWithQuery == "/v1/agents/a1/bot-requests") 200 to "[${botRequestFixture(status)}]" else 503 to "" + } + val model = modelWith(transport, scope) + model.selectAgent("a1") + model.applySnapshot(ChatSnapshot(agentId = "a1", messages = listOf(botRequestMessage))) + testScheduler.runCurrent() + model.openBotRequestEditor("r1") + status = "declined" + testScheduler.advanceTimeBy(5_100) + testScheduler.runCurrent() + assertNull(model.agentDraft) + model.cancelStream() + } + + @Test + fun chatJobsReloadWhenAJobMessageArrives() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = ScriptedTransport { req -> + when (req.pathWithQuery) { + "/v1/agents/a1/coding-jobs" -> 200 to """{"jobs":[${jobFixture("fix-login", "idle")}]}""" + "/v1/agents/a1/desktop-jobs" -> 200 to """{"jobs":[{"name":"browse","conversationId":"c","status":"working","question":{"id":"q1","text":"Which?","askedAt":1}}]}""" + else -> 503 to "" + } + } + val model = modelWith(transport, scope) + model.selectAgent("a1") + model.applySnapshot(ChatSnapshot(agentId = "a1", messages = listOf(jobResult()))) + testScheduler.runCurrent() + assertEquals("gpt · $1.5000", model.jobs.first().subtitle) + assertEquals("q1", model.jobs.last().question?.id) + + val reads = transport.requests.size + model.applySnapshot(ChatSnapshot(agentId = "a1", messages = listOf(jobResult()))) + testScheduler.runCurrent() + assertEquals(reads, transport.requests.size) + + val reply = Message(id = "x:9:0", role = "user", origin = dev.crumble.android.model.MessageOrigin(kind = "coding")) + model.applySnapshot(ChatSnapshot(agentId = "a1", messages = listOf(jobResult(), reply))) + testScheduler.runCurrent() + assertEquals(reads + 2, transport.requests.size) + model.cancelStream() + } + + @Test + fun jobPanelFollowsAWorkingJobThenStopsPollingWhenIdle() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + var status = "working" + var page = history(listOf("1", "2"), hasMore = true, oldest = "1") + val transport = ScriptedTransport { req -> + val path = req.pathWithQuery + when { + path == "/v1/agents/a1/coding-jobs" -> 200 to """{"jobs":[${jobFixture("fix login", status)}]}""" + path == "/v1/agents/a1/desktop-jobs" -> 200 to """{"jobs":[]}""" + path == "/v1/agents/a1/coding-jobs/fix%20login/history?limit=100" -> 200 to page + path == "/v1/agents/a1/coding-jobs/fix%20login/history?limit=100&before=1" -> 200 to history(listOf("0")) + else -> 503 to "" + } + } + val model = modelWith(transport, scope) + model.selectAgent("a1") + model.openJob(JobRef(JobKind.coding, "fix login", "working")) + testScheduler.runCurrent() + assertEquals(JobRef(JobKind.coding, "fix login"), model.jobPanel?.job) + assertEquals(listOf("1", "2"), model.jobPanel?.messages?.map { it.id }) + assertEquals(true, model.jobPanel?.hasMore) + + page = history(listOf("2", "3"), hasMore = true, oldest = "2") + testScheduler.advanceTimeBy(3_100) + testScheduler.runCurrent() + assertEquals(listOf("1", "2", "3"), model.jobPanel?.messages?.map { it.id }) + assertEquals("1", model.jobPanel?.oldestEntryID) + + model.loadEarlierJobActivity() + testScheduler.runCurrent() + assertEquals(listOf("0", "1", "2", "3"), model.jobPanel?.messages?.map { it.id }) + assertEquals(false, model.jobPanel?.hasMore) + + status = "idle" + page = history(listOf("3", "4")) + testScheduler.advanceTimeBy(3_100) + testScheduler.runCurrent() + assertEquals("4", model.jobPanel?.messages?.last()?.id) + + val reads = transport.requests.count { it.pathWithQuery.contains("/history") } + testScheduler.advanceTimeBy(14_000) + testScheduler.runCurrent() + assertEquals(reads, transport.requests.count { it.pathWithQuery.contains("/history") }) + model.closeJob() + assertNull(model.jobPanel) + } + + @Test + fun aLateHistoryPageIsDroppedAfterTheBotChanges() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val path = "/v1/agents/a1/desktop-jobs/browse/history?limit=100" + val transport = ScriptedTransport { req -> + when (req.pathWithQuery) { + "/v1/agents/a1/coding-jobs", "/v1/agents/a1/desktop-jobs" -> 200 to """{"jobs":[]}""" + path -> 200 to history(listOf("1")) + else -> 503 to "" + } + } + val gate = CompletableDeferred().also { transport.held[path] = it } + val model = modelWith(transport, scope) + model.selectAgent("a1") + model.openJob(JobRef(JobKind.desktop, "browse")) + testScheduler.runCurrent() + assertTrue(transport.requests.any { it.pathWithQuery == path }) + + model.selectAgent("a2") + model.openJob(JobRef(JobKind.desktop, "browse")) + gate.complete(Unit) + testScheduler.runCurrent() + assertEquals(emptyList(), model.jobPanel?.messages) + model.cancelStream() + } + + @Test + fun jobHistoryFailureOffersRetryAndKeepsThePanelOpen() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + var fail = true + val transport = ScriptedTransport { req -> + when { + req.pathWithQuery.endsWith("-jobs") -> 200 to """{"jobs":[${jobFixture("fix", "idle")}]}""".takeIf { "coding" in req.pathWithQuery }.orEmpty().ifEmpty { """{"jobs":[]}""" } + fail -> 503 to "" + else -> 200 to history(listOf("1")) + } + } + val model = modelWith(transport, scope) + model.selectAgent("a1") + model.openJob(JobRef(JobKind.coding, "fix")) + testScheduler.runCurrent() + assertEquals(true, model.jobPanel?.failed) + assertEquals(false, model.jobPanel?.loaded) + + fail = false + model.retryJobHistory() + testScheduler.runCurrent() + assertEquals(false, model.jobPanel?.failed) + assertEquals(listOf("1"), model.jobPanel?.messages?.map { it.id }) + model.cancelStream() + } + + @Test + fun answeringFromThePanelRefreshesItsQuestion() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + var waiting = true + val transport = ScriptedTransport { req -> + val question = if (waiting) ""","question":{"id":"q1","text":"Which?","askedAt":1}""" else "" + when (req.pathWithQuery) { + "/v1/agents/a1/coding-jobs" -> 200 to """{"jobs":[{"name":"fix","conversationId":"c","status":"idle"$question}]}""" + "/v1/agents/a1/desktop-jobs" -> 200 to """{"jobs":[]}""" + "/v1/agents/a1/coding-jobs/fix/answer" -> { waiting = false; 200 to """{"answered":true}""" } + else -> 200 to history(emptyList()) + } + } + val model = modelWith(transport, scope) + model.selectAgent("a1") + model.openJob(JobRef(JobKind.coding, "fix")) + testScheduler.runCurrent() + assertEquals("q1", model.jobs.single().question?.id) + model.answerJobQuestion("fix", "q1", "That one") + testScheduler.runCurrent() + assertNull(model.jobs.single().question) + model.cancelStream() + } + + @Test + fun jobListLoadsBothKindsAndRecoversFromFailure() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + var fail = true + val transport = ScriptedTransport { req -> + when { + fail -> 503 to "" + "coding" in req.pathWithQuery -> 200 to """{"jobs":[${jobFixture("fix", "idle")}]}""" + else -> 200 to """{"jobs":[${jobFixture("browse", "idle")}]}""" + } + } + val model = modelWith(transport, scope) + model.selectAgent("a1") + model.openJobList() + testScheduler.runCurrent() + assertTrue(model.jobsFailed) + + fail = false + model.openJobList() + testScheduler.runCurrent() + assertFalse(model.jobsFailed) + assertEquals(listOf(JobKind.coding, JobKind.desktop), model.jobs.map { it.kind }) + model.closeJobList() + val reads = transport.requests.size + testScheduler.advanceTimeBy(30_000) + testScheduler.runCurrent() + assertEquals(reads, transport.requests.size) + } + + @Test + fun transcriptDownloadReadsEveryPageOldestFirst() = runTest { + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val transport = ScriptedTransport { req -> + when (req.pathWithQuery) { + "/v1/agents/a1/coding-jobs/fix/history?limit=200" -> 200 to history(listOf("2"), hasMore = true, oldest = "2") + "/v1/agents/a1/coding-jobs/fix/history?limit=200&before=2" -> 200 to history(listOf("1")) + "/v1/agents/a1/coding-jobs/fix/history?limit=100" -> 200 to history(listOf("2")) + else -> 200 to """{"jobs":[]}""" + } + } + val model = modelWith(transport, scope) + model.selectAgent("a1") + model.openJob(JobRef(JobKind.coding, "fix")) + testScheduler.runCurrent() + var written = "" + model.downloadJobTranscript { written = it } + assertEquals(true, model.jobPanel?.downloading) + testScheduler.runCurrent() + assertEquals("# fix\n\nCoding job\n\n## Task\n\ntask 1\n\n## Task\n\ntask 2\n", written) + assertEquals(false, model.jobPanel?.downloading) + + model.downloadJobTranscript { error("disk full") } + testScheduler.runCurrent() + assertEquals(true, model.jobPanel?.downloadFailed) + model.cancelStream() + } +} diff --git a/app/src/test/java/dev/crumble/android/ComposerDraftTests.kt b/app/src/test/java/dev/crumble/android/ComposerDraftTests.kt new file mode 100644 index 0000000..ed3d0f7 --- /dev/null +++ b/app/src/test/java/dev/crumble/android/ComposerDraftTests.kt @@ -0,0 +1,389 @@ +package dev.crumble.android + +import dev.crumble.android.generated.GroupChat +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.ChatSnapshot +import dev.crumble.android.model.PendingAttachment +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import dev.crumble.android.storage.CredentialStore +import dev.crumble.android.storage.InMemoryCredentialStore +import java.io.ByteArrayInputStream +import java.nio.charset.StandardCharsets +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +private const val SERVER = "https://crumble.example" +private const val GROUP = "11111111-1111-4111-8111-111111111111" +private const val GROUP_PATH = "/v1/group-chats/$GROUP" +private const val SEND = "POST /v1/agents/a1/messages" +private const val SAVE_DELAY = 1_000L + +private val GROUP_JSON = """{"id":"$GROUP","name":"Team","memberIds":["a1","a2"],"createdAt":"t","updatedAt":"t"}""" +private val GROUP_SNAPSHOT = """{"messages":[],"hasMore":false,"oldestEntryId":null,"groupChat":$GROUP_JSON,"activity":{"paused":false,"botTurns":0,"members":[]},"updatedAt":1}""" + +private class DraftTransport : HttpTransport { + val responses = mutableMapOf( + "GET /v1/agents" to (200 to "[${agentFixture("a1", "Ada")},${agentFixture("a2", "Kev")}]"), + "GET /v1/agents/a1/chat?limit=5" to (200 to snapshotFixture(ChatSnapshot(agentId = "a1", status = "idle"))), + "GET /v1/agents/a2/chat?limit=5" to (200 to snapshotFixture(ChatSnapshot(agentId = "a2", status = "idle"))), + "GET $GROUP_PATH/chat" to (200 to GROUP_SNAPSHOT), + "POST $GROUP_PATH/messages" to (201 to """{"requestId":"r","entryId":"e"}"""), + "DELETE $GROUP_PATH" to (204 to ""), + "POST /api/auth/sign-out" to (200 to "{}"), + SEND to (202 to executionFixture), + ) + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + val (status, body) = responses["${request.method} ${request.pathWithQuery}"] ?: (404 to "") + return HttpResponseData(status, body.toByteArray(StandardCharsets.UTF_8)) + } + + // A 404 would read as the group having been deleted, which deletes its draft. + override suspend fun openStream(request: HttpRequestData) = + HttpStreamResponse(200, ByteArrayInputStream(ByteArray(0))) +} + +@OptIn(ExperimentalCoroutinesApi::class) +class ComposerDraftTests { + private val scopes = mutableListOf() + private val transport = DraftTransport() + private val store = InMemoryCredentialStore() + + private fun scenario(body: suspend TestScope.() -> Unit) = runTest { + try { + body() + } finally { + scopes.forEach { it.cancel() } + } + } + + /** Each call is a fresh process: nothing carries over but the store. */ + private fun TestScope.launchApp(token: String = "session", server: String = SERVER) = AppModel( + client = APIClient(server, token, transport), + credentials = store, + scope = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler)).also { scopes.add(it) }, + transport = transport, + ).also { + it.agents = listOf(Agent(id = "a1", name = "Ada"), Agent(id = "a2", name = "Kev")) + it.groupChats = listOf(GroupChat(GROUP, "Team", listOf("a1", "a2"), "t", "t")) + } + + private fun TestScope.settle() { + advanceTimeBy(SAVE_DELAY) + runCurrent() + } + + private fun TestScope.open(model: AppModel, id: String = "a1") { + model.selectAgent(id) + runCurrent() + } + + private fun TestScope.openGroup(model: AppModel) { + model.openGroupChat(GROUP) + runCurrent() + } + + private fun TestScope.assertNoDrafts() { + val app = launchApp() + open(app) + assertEquals("", app.draft) + open(app, "a2") + assertEquals("", app.draft) + openGroup(app) + assertEquals("", app.groupText()) + } + + private fun AppModel.groupText() = groupComposer(GROUP).draft + + private fun AppModel.typeInGroup(text: String) = updateGroupComposer(GROUP) { it.copy(draft = text) } + + @Test + fun aBotDraftSurvivesARestart() = scenario { + val first = launchApp() + open(first) + first.draft = "half written" + settle() + + val second = launchApp() + open(second) + + assertEquals("half written", second.draft) + } + + @Test + fun aDraftStaysWithItsBot() = scenario { + val first = launchApp() + open(first) + first.draft = "for Ada" + open(first, "a2") + first.draft = "for Kev" + settle() + + val second = launchApp() + open(second, "a2") + assertEquals("for Kev", second.draft) + open(second, "a1") + assertEquals("for Ada", second.draft) + } + + @Test + fun anotherAccountOrServerSeesNoDraft() = scenario { + val first = launchApp() + open(first) + first.draft = "private" + settle() + + val otherAccount = launchApp(token = "other") + open(otherAccount) + assertEquals("", otherAccount.draft) + + val otherServer = launchApp(server = "https://other.example") + open(otherServer) + assertEquals("", otherServer.draft) + } + + @Test + fun attachmentsAndReplyTargetsAreNeverSaved() = scenario { + val first = launchApp() + open(first) + first.draft = "with a file" + first.attachments = listOf(PendingAttachment(name = "note.txt", mimeType = "text/plain", data = "hi".toByteArray())) + settle() + + val second = launchApp() + open(second) + + assertEquals("with a file", second.draft) + assertTrue(second.attachments.isEmpty()) + } + + @Test + fun aSentDraftDoesNotComeBack() = scenario { + val first = launchApp() + open(first) + first.draft = "sent" + settle() + first.applySnapshot(ChatSnapshot(agentId = "a1", status = "idle")) + first.sendMessage() + runCurrent() + settle() + + val second = launchApp() + open(second) + + assertEquals("", second.draft) + } + + @Test + fun aFailedSendIsStillADraftAfterARestart() = scenario { + transport.responses[SEND] = 503 to """{"error":"busy"}""" + val first = launchApp() + open(first) + first.applySnapshot(ChatSnapshot(agentId = "a1", status = "idle")) + first.draft = "keep me" + first.sendMessage() + runCurrent() + assertEquals("keep me", first.draft) + settle() + + val second = launchApp() + open(second) + + assertEquals("keep me", second.draft) + } + + @Test + fun aFailedSendForAnotherBotIsSavedToo() = scenario { + transport.responses[SEND] = 503 to """{"error":"busy"}""" + val first = launchApp() + open(first) + first.applySnapshot(ChatSnapshot(agentId = "a1", status = "idle")) + first.draft = "keep me" + first.sendMessage() + open(first, "a2") + runCurrent() + settle() + + val second = launchApp() + open(second) + + assertEquals("keep me", second.draft) + } + + @Test + fun aGroupDraftSurvivesARestart() = scenario { + val first = launchApp() + openGroup(first) + first.typeInGroup("to the team") + settle() + + val second = launchApp() + openGroup(second) + + assertEquals("to the team", second.groupText()) + } + + @Test + fun aSentGroupDraftDoesNotComeBack() = scenario { + val first = launchApp() + openGroup(first) + first.typeInGroup("to the team") + settle() + first.sendGroupMessage() + runCurrent() + settle() + + val second = launchApp() + openGroup(second) + + assertEquals("", second.groupText()) + } + + @Test + fun deletingAGroupDeletesItsDraft() = scenario { + val first = launchApp() + openGroup(first) + first.typeInGroup("to the team") + settle() + first.deleteGroup(GROUP) + runCurrent() + settle() + + val second = launchApp() + openGroup(second) + + assertEquals("", second.groupText()) + } + + @Test + fun signingOutDeletesDraftsEvenOnesNotYetSaved() = scenario { + val first = launchApp() + openGroup(first) + first.typeInGroup("to the team") + open(first) + first.draft = "saved" + settle() + open(first, "a2") + first.draft = "still in memory" + first.signOut() + runCurrent() + settle() + + assertNoDrafts() + } + + @Test + fun changingServerDeletesDrafts() = scenario { + val first = launchApp() + openGroup(first) + first.typeInGroup("to the team") + open(first, "a2") + first.draft = "not yet stored" + settle() + open(first) + first.draft = "for the old server" + first.serverURL = "https://other.example" + first.password = "secret" + first.email = "a@b.dev" + transport.responses["POST /api/auth/sign-in/email"] = 200 to """{"token":"new"}""" + first.saveSettings() + runCurrent() + settle() + assertEquals("https://other.example", first.client?.baseURL) + + assertNoDrafts() + } + + @Test + fun leavingTheScreenSavesAtOnce() = scenario { + val first = launchApp() + open(first) + first.draft = "typed just before leaving" + first.saveDrafts() + + val second = launchApp() + open(second) + + assertEquals("typed just before leaving", second.draft) + } + + @Test + fun aDraftNotYetStoredIsStillThereWhenTheBotReopens() = scenario { + val model = launchApp() + open(model) + model.draft = "typed" + model.draft = "" + open(model, "a2") + model.draft = "typed for Kev" + open(model, "a1") + + assertEquals("", model.draft) + open(model, "a2") + assertEquals("typed for Kev", model.draft) + } + + @Test + fun anAttachmentParkedWithADraftComesBackWithIt() = scenario { + val model = launchApp() + open(model) + model.draft = "with a file" + model.attachments = listOf(PendingAttachment(name = "note.txt", mimeType = "text/plain", data = "hi".toByteArray())) + settle() + open(model, "a2") + open(model, "a1") + + assertEquals("with a file", model.draft) + assertEquals(1, model.attachments.size) + } + + @Test + fun deletingABotDeletesItsDraft() = scenario { + transport.responses["DELETE /v1/agents/a1"] = 204 to "" + val first = launchApp() + open(first) + first.draft = "for a gone bot" + settle() + first.deleteSelected() + runCurrent() + settle() + + val second = launchApp() + open(second) + + assertEquals("", second.draft) + } + + @Test + fun theStoreNeverHoldsAFailedWrite() = scenario { + val failing = object : CredentialStore by store { + override fun write(account: String, value: String) = throw IllegalStateException("full") + } + val model = AppModel( + client = APIClient(SERVER, "session", transport), + credentials = failing, + scope = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler)).also { scopes.add(it) }, + transport = transport, + ) + model.selectAgent("a1") + runCurrent() + model.draft = "still typed" + settle() + + assertEquals("still typed", model.draft) + } +} diff --git a/app/src/test/java/dev/crumble/android/ConnectionSafetyTests.kt b/app/src/test/java/dev/crumble/android/ConnectionSafetyTests.kt new file mode 100644 index 0000000..90b9a19 --- /dev/null +++ b/app/src/test/java/dev/crumble/android/ConnectionSafetyTests.kt @@ -0,0 +1,403 @@ +package dev.crumble.android + +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.MCPServer +import dev.crumble.android.model.Route +import dev.crumble.android.model.isExposedHttp +import dev.crumble.android.model.splitSources +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import dev.crumble.android.storage.AndroidKeyStoreCredentials +import dev.crumble.android.storage.InMemoryCredentialStore +import java.io.File +import java.nio.charset.StandardCharsets +import java.security.MessageDigest +import javax.xml.parsers.DocumentBuilderFactory +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.w3c.dom.Document +import org.w3c.dom.Element + +private const val BASE = "https://example.test" +private const val CALLBACK = "dev.crumble.android:/oauth/callback?code=c&state=x" +private const val START = "POST /v1/mcp-servers/s1/oauth" +private const val FINISH = "POST /v1/mcp-servers/s1/oauth/callback" + +private val SIGNED_IN = + """{"id":"s1","name":"Linear","url":"https://mcp.linear.app/mcp","enabled":true,"agentId":null,"oauthClientId":null,"oauthClientSecret":{"configured":false,"passwordManager":null,"reference":null},"token":{"configured":false,"passwordManager":null,"reference":null},"error":null,"auth":"oauth","authenticated":true}""" + +private class SafetyTransport : HttpTransport { + val requests = mutableListOf() + val held = mutableMapOf>() + val responses = mutableMapOf>() + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + val key = "${request.method} ${request.pathWithQuery}" + requests.add(request) + held[key]?.await() + val (status, body) = responses[key] ?: (503 to """{"error":"unscripted"}""") + return HttpResponseData(status, body.toByteArray(StandardCharsets.UTF_8)) + } + + override suspend fun openStream(request: HttpRequestData): HttpStreamResponse = + throw UnsupportedOperationException("streams are not used here") + + fun sent(key: String) = requests.count { "${it.method} ${it.pathWithQuery}" == key } + + fun hold(key: String) = CompletableDeferred().also { held[key] = it } +} + +private fun cachedChatKey(id: String): String { + val digest = MessageDigest.getInstance("SHA-256").digest("$BASE\nsession".toByteArray()) + return "recent-chat:${digest.joinToString("") { "%02x".format(it) }}:$id" +} + +private fun xml(path: String): Document = + DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(File(path)) + +private fun Element.excludes(domain: String, path: String): Boolean { + val rules = getElementsByTagName("exclude") + return (0 until rules.length).map { rules.item(it) as Element } + .any { it.getAttribute("domain") == domain && it.getAttribute("path") == path } +} + +@OptIn(ExperimentalCoroutinesApi::class) +class ConnectionSafetyTests { + private fun modelWith(transport: SafetyTransport, scope: CoroutineScope, credentials: InMemoryCredentialStore = InMemoryCredentialStore()) = + AppModel( + client = APIClient(BASE, "session", transport), + credentials = credentials, + scope = scope, + transport = transport, + ).also { + it.agents = listOf(Agent(id = "a1", name = "Atlas"), Agent(id = "a2", name = "Scout")) + it.mcpServers = listOf(MCPServer(id = "s1", name = "Linear"), MCPServer(id = "s2", name = "Notion")) + } + + private fun signInTransport() = SafetyTransport().apply { + responses[START] = 200 to """{"authorizationUrl":"https://auth.example.com/authorize?state=x"}""" + responses["POST /v1/mcp-servers/s2/oauth"] = 200 to """{"authorizationUrl":"https://auth.example.com/authorize?state=y"}""" + responses[FINISH] = 200 to SIGNED_IN + } + + @Test + fun dismissingSettingsDropsTypedSecrets() = runTest { + val model = modelWith(SafetyTransport(), backgroundScope) + model.navigate(Route.General) + model.password = "typed" + model.inviteCode = "invite" + + model.navigate(Route.General.parent) + + assertEquals("", model.password) + assertEquals("", model.inviteCode) + } + + @Test + fun aConnectionThatFailsAfterDismissalLeavesNoSecretBehind() = runTest { + val transport = SafetyTransport() + val gate = transport.hold("POST /api/auth/sign-in/email") + val model = modelWith(transport, backgroundScope) + model.serverURL = BASE + model.email = "me@example.com" + model.password = "typed" + model.saveSettings() + runCurrent() + + model.navigate(Route.General) + model.navigate(Route.General.parent) + gate.complete(Unit) + runCurrent() + + assertEquals("", model.password) + assertFalse(model.savingConnection) + assertTrue(model.errorText.isNotEmpty()) + } + + @Test + fun leavingAPanelForTheSelectedBotDropsItsCredentialForm() = runTest { + val model = modelWith(SafetyTransport(), backgroundScope) + model.selectAgent("a1") + runCurrent() + model.openPanel(Route.Credentials) + model.openCredentialForm("a1") + assertNotNull(model.credentialForm) + + model.selectAgent("a1") + + assertEquals(Route.AgentChat("a1"), model.route) + assertNull(model.credentialForm) + } + + @Test + fun reselectingTheOpenChatKeepsAnOpenCredentialForm() = runTest { + val model = modelWith(SafetyTransport(), backgroundScope) + model.selectAgent("a1") + runCurrent() + model.openCredentialForm("a1") + + model.selectAgent("a1") + + assertNotNull(model.credentialForm) + } + + @Test + fun deletingABotRemovesItsCachedChatOnceConfirmed() = runTest { + val transport = SafetyTransport() + val gate = transport.hold("DELETE /v1/agents/a1") + transport.responses["DELETE /v1/agents/a1"] = 200 to "" + val store = InMemoryCredentialStore(mapOf(cachedChatKey("a1") to "{}", cachedChatKey("a2") to "{}")) + val model = modelWith(transport, backgroundScope, store) + model.selectAgent("a1") + runCurrent() + + model.deleteSelected() + runCurrent() + assertEquals("{}", store.read(cachedChatKey("a1"))) + + gate.complete(Unit) + runCurrent() + assertNull(store.read(cachedChatKey("a1"))) + assertEquals("{}", store.read(cachedChatKey("a2"))) + } + + @Test + fun aFailedBotDeleteKeepsItsCachedChat() = runTest { + val transport = SafetyTransport() + val store = InMemoryCredentialStore(mapOf(cachedChatKey("a1") to "{}")) + val model = modelWith(transport, backgroundScope, store) + model.selectAgent("a1") + runCurrent() + + model.deleteSelected() + runCurrent() + + assertEquals("{}", store.read(cachedChatKey("a1"))) + assertTrue(model.agents.any { it.id == "a1" }) + } + + @Test + fun backingOutOfTheBrowserEndsTheWait() = runTest { + val transport = signInTransport() + val model = modelWith(transport, backgroundScope) + val opened = mutableListOf() + model.beginMCPSignIn("s1") { opened.add(it) } + runCurrent() + assertEquals("s1", model.signingIn) + assertEquals(1, opened.size) + + model.browserReturned() + + assertNull(model.signingIn) + model.beginMCPSignIn("s2") { opened.add(it) } + runCurrent() + assertEquals("s2", model.signingIn) + assertEquals(2, opened.size) + } + + @Test + fun resumingBeforeTheBrowserOpensKeepsThePendingState() = runTest { + val transport = signInTransport() + val gate = transport.hold(START) + val model = modelWith(transport, backgroundScope) + val opened = mutableListOf() + model.beginMCPSignIn("s1") { opened.add(it) } + runCurrent() + + model.browserReturned() + assertEquals("s1", model.signingIn) + + gate.complete(Unit) + runCurrent() + assertEquals(1, opened.size) + assertEquals("s1", model.signingIn) + } + + @Test + fun theResumeAfterACallbackWaitsForTheServer() = runTest { + val transport = signInTransport() + val gate = transport.hold(FINISH) + val model = modelWith(transport, backgroundScope) + model.beginMCPSignIn("s1") {} + runCurrent() + + model.handleOAuthCallback(CALLBACK) + model.browserReturned() + runCurrent() + assertEquals("s1", model.signingIn) + assertEquals("", model.notice) + + gate.complete(Unit) + runCurrent() + assertNull(model.signingIn) + assertEquals("Signed in", model.notice) + assertEquals(true, model.mcpServers.first { it.id == "s1" }.authenticated) + } + + @Test + fun aCallbackAfterLookingAwayStillFinishes() = runTest { + val transport = signInTransport() + val gate = transport.hold(FINISH) + val model = modelWith(transport, backgroundScope) + model.beginMCPSignIn("s1") {} + runCurrent() + model.browserReturned() + + model.handleOAuthCallback(CALLBACK) + runCurrent() + assertEquals("s1", model.signingIn) + + gate.complete(Unit) + runCurrent() + assertNull(model.signingIn) + assertEquals("Signed in", model.notice) + } + + @Test + fun aRefusedCallbackAllowsARetry() = runTest { + val transport = signInTransport() + transport.responses[FINISH] = 400 to """{"error":"Sign-in expired"}""" + val model = modelWith(transport, backgroundScope) + model.beginMCPSignIn("s1") {} + runCurrent() + + model.handleOAuthCallback(CALLBACK) + runCurrent() + + assertNull(model.signingIn) + assertTrue(model.errorText.contains("Sign-in expired")) + assertEquals("", model.notice) + } + + @Test + fun aNewSignInReplacesAnAbandonedOne() = runTest { + val transport = signInTransport() + val gate = transport.hold("POST /v1/mcp-servers/s2/oauth") + val model = modelWith(transport, backgroundScope) + model.beginMCPSignIn("s1") {} + runCurrent() + model.browserReturned() + model.beginMCPSignIn("s2") {} + runCurrent() + + model.handleOAuthCallback(CALLBACK) + runCurrent() + + assertEquals("s2", model.signingIn) + assertEquals(0, transport.sent(FINISH)) + gate.complete(Unit) + runCurrent() + } + + @Test + fun aBrowserThatWontOpenReportsTheFailure() = runTest { + val model = modelWith(signInTransport(), backgroundScope) + + model.beginMCPSignIn("s1") { throw IllegalStateException("No browser") } + runCurrent() + model.handleOAuthCallback(CALLBACK) + runCurrent() + + assertNull(model.signingIn) + assertEquals("", model.notice) + } + + @Test + fun onlyPublicHttpAddressesAreExposed() { + for (url in listOf( + "http://crumble.example", + "HTTP://crumble.example:7337/", + " http://crumble.example ", + "http://8.8.8.8:7337", + "http://172.32.0.1", + "http://192.169.0.1", + "http://11.0.0.1", + "http://[2001:4860:4860::8888]", + "http://localhost.evil.example", + "http://2130706433", + )) assertTrue(url, isExposedHttp(url)) + + for (url in listOf( + "https://crumble.example", + "http://localhost:7337", + "http://LOCALHOST.", + "http://app.localhost", + "http://127.0.0.1:7337", + "http://127.8.8.8", + "http://10.0.2.2:7337", + "http://172.16.0.1", + "http://172.31.255.1", + "http://192.168.1.20", + "http://169.254.1.1", + "http://[::1]:7337", + "http://[fd00::1]", + "http://[fe80::1]", + "http://[::ffff:192.168.1.20]", + "", + "not a url", + "http://999.1.1.1", + )) assertFalse(url, isExposedHttp(url)) + } + + @Test + fun sessionResetRunsOnSignOutAndReconnect() = runTest { + val transport = SafetyTransport() + transport.responses["POST /api/auth/sign-out"] = 200 to "{}" + transport.responses["POST /api/auth/sign-in/email"] = 200 to """{"token":"next"}""" + transport.responses["GET /v1/agents"] = 200 to "[]" + var resets = 0 + val model = AppModel( + client = APIClient(BASE, "session", transport), + scope = backgroundScope, + transport = transport, + onSessionReset = { resets += 1 }, + ) + model.serverURL = BASE + model.email = "me@example.com" + model.password = "typed" + model.saveSettings() + runCurrent() + assertEquals(1, resets) + + model.signOut() + runCurrent() + assertEquals(2, resets) + } + + @Test + fun citationsOfOtherSchemesNeverBecomeChips() { + val reply = splitSources("See [source](javascript:alert(1)) and [source](intent://x).", mapOf("x" to "Title")) + assertTrue(reply.chips.isEmpty()) + } + + @Test + fun backupsLeaveOutTheCredentialPreferences() { + val prefs = "${AndroidKeyStoreCredentials.SERVICE}.xml" + val full = xml("src/main/res/xml/backup_rules.xml").documentElement + assertTrue(full.excludes("sharedpref", prefs)) + + val extraction = xml("src/main/res/xml/data_extraction_rules.xml").documentElement + for (scope in listOf("cloud-backup", "device-transfer")) { + val rules = extraction.getElementsByTagName(scope).item(0) as Element + assertTrue(scope, rules.excludes("sharedpref", prefs)) + } + + val application = xml("src/main/AndroidManifest.xml").documentElement + .getElementsByTagName("application").item(0) as Element + assertEquals("@xml/backup_rules", application.getAttribute("android:fullBackupContent")) + assertEquals("@xml/data_extraction_rules", application.getAttribute("android:dataExtractionRules")) + } +} diff --git a/app/src/test/java/dev/crumble/android/ConnectionsTests.kt b/app/src/test/java/dev/crumble/android/ConnectionsTests.kt new file mode 100644 index 0000000..d7702ec --- /dev/null +++ b/app/src/test/java/dev/crumble/android/ConnectionsTests.kt @@ -0,0 +1,865 @@ +package dev.crumble.android + +import dev.crumble.android.generated.PluginSetting +import dev.crumble.android.generated.PluginSettings +import dev.crumble.android.generated.PluginSettingsPluginsItem +import dev.crumble.android.generated.SecretStatus +import dev.crumble.android.generated.ServerSettings +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.CreateGitHubAppForm +import dev.crumble.android.model.CrumbleJson +import dev.crumble.android.model.GatewayAlias +import dev.crumble.android.model.GatewayAliasRow +import dev.crumble.android.model.GatewayChannelRow +import dev.crumble.android.model.GatewayConfig +import dev.crumble.android.model.GitHubStep +import dev.crumble.android.model.MCPDraft +import dev.crumble.android.model.MCPServer +import dev.crumble.android.model.PluginRow +import dev.crumble.android.model.Route +import dev.crumble.android.model.SecretDraft +import dev.crumble.android.model.SecretInput +import dev.crumble.android.model.ServerSettingsForm +import dev.crumble.android.model.WorkspaceField +import dev.crumble.android.model.gatewayBotOptions +import dev.crumble.android.model.gatewayErrors +import dev.crumble.android.model.gatewayForm +import dev.crumble.android.model.isGitHubReturn +import dev.crumble.android.model.judgeOptions +import dev.crumble.android.model.judgeValue +import dev.crumble.android.model.matchesMCP +import dev.crumble.android.model.pluginRows +import dev.crumble.android.model.relayStatusLabel +import dev.crumble.android.model.serverSettingsForm +import dev.crumble.android.model.toggled +import dev.crumble.android.model.visionOptions +import dev.crumble.android.model.visionStatus +import dev.crumble.android.model.webOrigin +import dev.crumble.android.model.workspaceHelp +import dev.crumble.android.model.workspaceRowTitle +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import java.nio.charset.StandardCharsets +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.jsonObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +private const val SECRET = "s3cret-value" +private const val BOT_A = "00000000-0000-4000-8000-000000000001" +private const val BOT_B = "00000000-0000-4000-8000-000000000002" + +private class ConnectionTransport : HttpTransport { + val requests = mutableListOf() + val held = mutableMapOf>() + val responses = mutableMapOf>() + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + requests.add(request) + val key = "${request.method} ${request.pathWithQuery}" + held[key]?.await() + val (status, body) = responses[key] ?: (503 to """{"error":"unscripted $key"}""") + return HttpResponseData(status, body.toByteArray(StandardCharsets.UTF_8)) + } + + override suspend fun openStream(request: HttpRequestData): HttpStreamResponse = + throw UnsupportedOperationException("streams are not used here") + + fun sent(key: String) = requests.filter { "${it.method} ${it.pathWithQuery}" == key } + fun hold(key: String) = CompletableDeferred().also { held[key] = it } + fun answer(key: String, status: Int = 200, body: String) { + responses[key] = status to body + } +} + +private fun bodyText(request: HttpRequestData) = request.body?.toString(StandardCharsets.UTF_8).orEmpty() +private fun bodyOf(request: HttpRequestData) = CrumbleJson.parseToJsonElement(bodyText(request)).jsonObject + +private const val NONE = """{"configured":false,"passwordManager":null,"reference":null}""" +private const val SAVED = """{"configured":true,"passwordManager":null,"reference":null}""" + +private fun appJson(id: String = "app1", bots: String = "", installed: Boolean = true, user: String? = null, secret: String = NONE) = + """{"id":"$id","slug":"$id","name":"$id","login":"$id[bot]","htmlUrl":"https://github.com/apps/$id","installUrl":"https://github.com/apps/$id/installations/new","account":"leo","installed":$installed,"clientSecret":$secret,"user":${user?.let { "\"$it\"" }},"botIds":[$bots],"createdAt":"t"}""" + +private fun accountJson(id: String = "acc1", bots: String = "") = + """{"id":"$id","login":"$id","htmlUrl":"https://github.com/$id","botIds":[$bots],"token":$SAVED,"signingKey":"ssh-ed25519 AAA","createdAt":"t"}""" + +private fun gatewayJson(enabled: Boolean = true, owner: String? = null, status: String = "connected") = + """{"id":"discord","label":"Discord","secretKey":"discord:token","tokenConfigured":true,"config":{"enabled":$enabled,"defaultBotId":null,"ownerId":${owner?.let { "\"$it\"" }},"allowedChannelIds":[],"allowDirectMessages":false,"aliases":[]},"status":"$status","error":null,"pendingCount":0,"failedCount":0}""" + +private fun relayJson(url: String? = null, status: String = "disconnected", error: String? = null) = + """{"url":${url?.let { "\"$it\"" }},"tokenConfigured":false,"status":"$status","error":${error?.let { "\"$it\"" }}}""" + +private fun judgeJson(chosen: String? = null) = + """{"judgeModel":${chosen?.let { """{"provider":"openai","model":"$it"}""" }},"effective":{"provider":"openai","model":"luna","name":"Luna","kind":"classifier"},"choices":[{"provider":"openai","model":"luna","name":"Luna","kind":"classifier"},{"provider":"openai","model":"sol","name":"Sol","kind":"classifier"}]}""" + +private fun settingsJson(cpus: Int = 2, memory: Int = 4096, image: String? = "img", grace: Int = 30) = + """{"signUpOpen":false,"workspaceCpus":$cpus,"workspaceMemoryMib":$memory,"codingImage":${image?.let { "\"$it\"" }},"questionGraceMinutes":$grace}""" + +private fun pluginJson(configured: Boolean = false) = + """{"key":"token","kind":"secret","label":"Bot token","whenMissing":"x","secret":${if (configured) SAVED else NONE}}""" + +private fun pluginsJson(configured: Boolean = false) = + """{"plugins":[{"id":"discord","contributes":["chatAdapters"],"settings":[${pluginJson(configured)}]}]}""" + +private val PLUGIN_PATH = "/v1/plugin-settings/discord/token" + +@OptIn(ExperimentalCoroutinesApi::class) +class ConnectionsTests { + private fun modelWith(transport: ConnectionTransport, scope: TestScope): AppModel { + val client = APIClient(baseURL = "https://crumble.example:8443/", token = "session", transport = transport) + return AppModel(client = client, scope = scope).also { + it.agents = listOf(Agent(id = BOT_A, name = "Atlas"), Agent(id = BOT_B, name = "Scout")) + } + } + + private fun scripted() = ConnectionTransport().apply { + answer("GET /v1/agents", body = "[${agentFixture(BOT_A)},${agentFixture(BOT_B, "Scout")}]") + answer("GET /v1/password-managers", body = """{"passwordManagers":[]}""") + answer("GET /v1/plugin-settings", body = pluginsJson()) + answer("GET /v1/message-gateways", body = """{"gateways":[${gatewayJson()}]}""") + answer("GET /v1/github-apps", body = """{"apps":[${appJson()}]}""") + answer("GET /v1/github-accounts", body = """{"accounts":[${accountJson()}]}""") + answer("GET /v1/admin/settings", body = settingsJson()) + answer("GET /v1/capabilities", body = """{"coding":true,"desktop":false,"jobKinds":["coding"]}""") + answer("GET /v1/event-relay", body = relayJson()) + answer("GET /v1/event-sources", body = """{"sources":[]}""") + answer("GET /v1/judge-model", body = judgeJson()) + answer("GET /v1/vision-model", body = """{"visionModel":null,"choices":[{"provider":"openai","model":"eye","name":"Eye"}]}""") + answer("GET /v1/web-search", body = """{"defaultProvider":"mixed","exaKeyConfigured":false}""") + } + + // MARK: Pure rules + + @Test + fun gatewayConfigMatchesTheServerRules() { + val bots = setOf(BOT_A) + assertEquals(emptyMap(), gatewayErrors(GatewayConfig(ownerId = "12345"), bots)) + assertEquals("Enter one user ID, without spaces or commas.", gatewayErrors(GatewayConfig(ownerId = "1 2"), bots)["ownerId"]) + assertEquals("Enter one user ID, without spaces or commas.", gatewayErrors(GatewayConfig(ownerId = "1,2"), bots)["ownerId"]) + assertEquals( + "Use letters, numbers, underscores or hyphens, without @.", + gatewayErrors(GatewayConfig(aliases = listOf(GatewayAlias("@me", BOT_A))), bots)["aliases"], + ) + assertEquals( + "Choose a bot for every alias.", + gatewayErrors(GatewayConfig(aliases = listOf(GatewayAlias("me", ""))), bots)["aliases"], + ) + assertEquals( + "Alias handles must be unique (ignoring case)", + gatewayErrors(GatewayConfig(aliases = listOf(GatewayAlias("Me", BOT_A), GatewayAlias("mE", BOT_A))), bots)["aliases"], + ) + assertEquals( + emptyMap(), + gatewayErrors(GatewayConfig(aliases = listOf(GatewayAlias("résumé_1", BOT_A))), bots), + ) + } + + @Test + fun deletedBotsBlockOnlyAnEnabledGateway() { + val gone = GatewayConfig(enabled = true, defaultBotId = BOT_B, aliases = listOf(GatewayAlias("a", BOT_B))) + val errors = gatewayErrors(gone, setOf(BOT_A)) + assertEquals("The saved bot was deleted. Choose another.", errors["defaultBotId"]) + assertEquals("Choose an existing bot for every alias.", errors["aliases"]) + assertTrue(gatewayErrors(gone.copy(enabled = false), setOf(BOT_A)).isEmpty()) + assertEquals("Deleted bot", gatewayBotOptions(emptyList(), BOT_B, optional = true).last().label) + } + + @Test + fun gatewayFormTrimsAndDedupesLikeTheWeb() { + val form = gatewayForm("discord", GatewayConfig()).copy( + owner = " ", + channels = listOf(GatewayChannelRow(" 1 "), GatewayChannelRow("1"), GatewayChannelRow(" ")), + aliases = listOf(GatewayAliasRow(" me ", BOT_A)), + ) + val config = form.config() + assertNull(config.ownerId) + assertEquals(listOf("1"), config.allowedChannelIds) + assertEquals(listOf(GatewayAlias("me", BOT_A)), config.aliases) + } + + @Test + fun pluginRowsFilterByContributionPluginAndKey() { + val status = SecretStatus(false, null, null) + val settings = PluginSettings( + listOf( + PluginSettingsPluginsItem("exa", listOf("webSearchProviders"), listOf(PluginSetting("key", "secret", "Exa key", "x", status))), + PluginSettingsPluginsItem("doorstep", emptyList(), listOf(PluginSetting("token", "secret", "Token", "x", status))), + PluginSettingsPluginsItem( + "discord", listOf("chatAdapters"), + listOf(PluginSetting("token", "secret", "Discord", "x", status), PluginSetting("other", "secret", "Other", "x", status)), + ), + ), + ) + assertEquals(listOf("exa"), pluginRows(settings, contributes = "webSearchProviders").map { it.pluginID }) + assertEquals(listOf("doorstep"), pluginRows(settings, pluginID = "doorstep").map { it.pluginID }) + assertEquals(listOf("Discord"), pluginRows(settings, contributes = "chatAdapters", secretKey = "discord:token").map { it.setting.label }) + assertTrue(pluginRows(null).isEmpty()) + } + + @Test + fun returnPagesMatchOnlyTheirStepAndOlderPrefixes() { + assertTrue(isGitHubReturn("https://c.example/github-app/callback?code=1&state=2", GitHubStep.created)) + assertTrue(isGitHubReturn("https://c.example/ui/github-app/authorized?code=1", GitHubStep.authorized)) + assertFalse(isGitHubReturn("https://c.example/github-app/installed", GitHubStep.created)) + assertFalse(isGitHubReturn("https://github.com/settings/apps/new", GitHubStep.created)) + assertFalse(isGitHubReturn("not a url", GitHubStep.installed)) + assertEquals("https://crumble.example:8443", webOrigin("https://crumble.example:8443/")) + assertEquals("https://crumble.example", webOrigin("https://crumble.example/app")) + } + + @Test + fun workspaceRowsAndNumbersReadLikeTheWeb() { + val settings = ServerSettings(false, 4, 2048, null, 30) + assertEquals("Workspace size (4 CPUs, 2 GB)", workspaceRowTitle(WorkspaceField.size, settings)) + assertEquals("Coding image (server default)", workspaceRowTitle(WorkspaceField.image, settings)) + assertEquals("Question grace period (30 min)", workspaceRowTitle(WorkspaceField.grace, settings)) + assertEquals(listOf("Desktop jobs need CRUMBLE_WORKSPACE_DESKTOP_IMAGE on the server."), workspaceHelp(coding = true, desktop = false)) + val size = serverSettingsForm(WorkspaceField.size, settings) + assertEquals("2", size.memory) + assertNull(size.copy(cpus = "many").patch()) + assertNull(ServerSettingsForm(WorkspaceField.grace, "1", "1", "", "soon").patch()) + } + + @Test + fun aGoneModelStaysListedWithItsReason() { + val judge = CrumbleJson.decodeFromString(judgeJson("gone")) + assertEquals("openai/gone", judgeValue(judge)) + assertEquals("gone (no key)", judgeOptions(judge).last().label) + val vision = CrumbleJson.decodeFromString( + """{"visionModel":{"provider":"openai","model":"gone"},"choices":[]}""", + ) + assertEquals("gone (no key)", visionOptions(vision).last().label) + assertTrue(visionStatus(vision).startsWith("No provider key reaches gone")) + } + + @Test + fun relayLabelsAndBotToggles() { + assertEquals("Not set up", relayStatusLabel("disconnected")) + assertEquals(listOf("a", "b"), toggled(listOf("a"), "b", true)) + assertEquals(emptyList(), toggled(listOf("a"), "a", false)) + assertTrue(matchesMCP(MCPServer(name = "Linear", url = "https://mcp.linear.app"), "linear")) + assertFalse(matchesMCP(MCPServer(name = "Linear", url = "https://mcp.linear.app"), "notion")) + } + + // MARK: Choices + + @Test + fun judgeChoiceAppliesAtOnceAndAReadCannotReplaceIt() = runTest { + val transport = scripted() + val model = modelWith(transport, this) + model.navigate(Route.JudgeModel) + runCurrent() + transport.answer("PUT /v1/judge-model", body = judgeJson("sol")) + val gate = transport.hold("PUT /v1/judge-model") + + model.chooseJudgeModel("openai/sol") + runCurrent() + assertEquals("openai/sol", judgeValue(model.judgeModel.value!!)) + assertEquals("""{"judgeModel":{"provider":"openai","model":"sol"}}""", bodyText(transport.sent("PUT /v1/judge-model").single())) + + model.loadJudgeModel() + runCurrent() + assertEquals("openai/sol", judgeValue(model.judgeModel.value!!)) + + gate.complete(Unit) + runCurrent() + assertEquals("openai/sol", judgeValue(model.judgeModel.value!!)) + assertTrue(model.pendingMutations.isEmpty()) + } + + @Test + fun judgeChoiceRollsBackAndSaysWhy() = runTest { + val transport = scripted() + val model = modelWith(transport, this) + model.navigate(Route.JudgeModel) + runCurrent() + transport.answer("PUT /v1/judge-model", 500, """{"error":"Could not save"}""") + + model.chooseJudgeModel("openai/sol") + runCurrent() + assertEquals("default", judgeValue(model.judgeModel.value!!)) + assertEquals("Could not save", model.judgeModel.failure) + } + + @Test + fun choosingTheDefaultSendsNull() = runTest { + val transport = scripted() + transport.answer("GET /v1/judge-model", body = judgeJson("sol")) + transport.answer("PUT /v1/judge-model", body = judgeJson()) + val model = modelWith(transport, this) + model.navigate(Route.JudgeModel) + runCurrent() + model.chooseJudgeModel("default") + runCurrent() + assertEquals("""{"judgeModel":null}""", bodyText(transport.sent("PUT /v1/judge-model").single())) + } + + @Test + fun visionAndWebSearchRollBackOnFailure() = runTest { + val transport = scripted() + val model = modelWith(transport, this) + model.navigate(Route.VisionModel) + model.navigate(Route.WebSearch) + runCurrent() + transport.answer("PUT /v1/vision-model", 500, """{"error":"no"}""") + transport.answer("PUT /v1/web-search", 500, """{"error":"nope"}""") + + model.chooseVisionModel("openai/eye") + model.chooseWebSearchProvider("exa") + assertEquals("exa", model.webSearch.value?.defaultProvider) + assertNotNull(model.visionModel.value?.visionModel) + runCurrent() + assertNull(model.visionModel.value?.visionModel) + assertEquals("mixed", model.webSearch.value?.defaultProvider) + assertEquals("nope", model.webSearch.failure) + } + + // MARK: Plugin settings + + private fun pluginRow(model: AppModel) = pluginRows(model.pluginSettings.value).single() + + @Test + fun pluginValueAppliesAtOnceAndReopensOnFailure() = runTest { + val transport = scripted() + val model = modelWith(transport, this) + model.navigate(Route.MessageGateway("discord")) + runCurrent() + val row = pluginRow(model) + val gate = transport.hold("PUT $PLUGIN_PATH") + transport.answer("PUT $PLUGIN_PATH", 500, """{"error":"Bad token"}""") + + model.openPluginSetting(row) + model.pluginForm = model.pluginForm?.copy(secret = SecretDraft(text = SECRET)) + model.savePluginSetting() + runCurrent() + assertNull(model.pluginForm) + assertTrue(pluginRow(model).setting.secret.configured) + assertEquals("""{"value":"$SECRET"}""", bodyText(transport.sent("PUT $PLUGIN_PATH").single())) + + gate.complete(Unit) + runCurrent() + assertFalse(pluginRow(model).setting.secret.configured) + assertEquals("Bad token", model.pluginForm?.error) + assertEquals(SECRET, model.pluginForm?.secret?.text) + } + + @Test + fun pluginReferenceStaysPendingUntilThePasswordManagerAnswers() = runTest { + val transport = scripted() + val model = modelWith(transport, this) + model.navigate(Route.MessageGateway("discord")) + runCurrent() + val gate = transport.hold("PUT $PLUGIN_PATH") + transport.answer("PUT $PLUGIN_PATH", body = pluginJson(configured = true)) + transport.answer("GET /v1/plugin-settings", body = pluginsJson(configured = true)) + val refreshes = transport.sent("GET /v1/message-gateways").size + + model.openPluginSetting(pluginRow(model)) + model.pluginForm = model.pluginForm?.copy(secret = SecretDraft(manager = "1password", text = "op://v/i/f")) + model.savePluginSetting() + runCurrent() + assertTrue(model.pluginForm?.saving == true) + assertFalse(pluginRow(model).setting.secret.configured) + assertEquals( + """{"reference":{"passwordManager":"1password","reference":"op://v/i/f"}}""", + bodyText(transport.sent("PUT $PLUGIN_PATH").single()), + ) + + gate.complete(Unit) + runCurrent() + assertNull(model.pluginForm) + assertTrue(pluginRow(model).setting.secret.configured) + assertTrue(transport.sent("GET /v1/message-gateways").size > refreshes) + } + + @Test + fun pluginRemovalRollsBack() = runTest { + val transport = scripted() + transport.answer("GET /v1/plugin-settings", body = pluginsJson(configured = true)) + val model = modelWith(transport, this) + model.navigate(Route.EventRelay) + runCurrent() + val row: PluginRow = pluginRow(model) + val gate = transport.hold("DELETE $PLUGIN_PATH") + transport.answer("DELETE $PLUGIN_PATH", 500, """{"error":"nope"}""") + + model.removePluginSetting(row) + runCurrent() + assertFalse(pluginRow(model).setting.secret.configured) + gate.complete(Unit) + runCurrent() + assertTrue(pluginRow(model).setting.secret.configured) + assertEquals("nope", model.errorText) + } + + // MARK: Event relay + + @Test + fun relayStatusComesOnlyFromTheServerAndAFailureKeepsTheAddress() = runTest { + val transport = scripted() + val model = modelWith(transport, this) + model.navigate(Route.EventRelay) + runCurrent() + val gate = transport.hold("PUT /v1/event-relay") + transport.answer("PUT /v1/event-relay", 502, """{"error":"Relay unreachable"}""") + + model.relayDraft = " https://relay.example " + model.saveRelay() + runCurrent() + assertTrue(model.relaySaving) + assertEquals("disconnected", model.eventRelay.value?.status) + assertEquals("""{"url":"https://relay.example"}""", bodyText(transport.sent("PUT /v1/event-relay").single())) + + gate.complete(Unit) + runCurrent() + assertFalse(model.relaySaving) + assertEquals("Relay unreachable", model.eventRelay.failure) + assertEquals(" https://relay.example ", model.relayDraft) + + transport.held.clear() + transport.answer("PUT /v1/event-relay", body = relayJson("https://relay.example", "connecting")) + model.saveRelay() + runCurrent() + assertEquals("connecting", model.eventRelay.value?.status) + assertEquals("https://relay.example", model.relayDraft) + assertEquals("", model.eventRelay.failure) + } + + @Test + fun aRefreshKeepsATypedRelayAddress() = runTest { + val transport = scripted() + val model = modelWith(transport, this) + model.navigate(Route.EventRelay) + runCurrent() + model.relayDraft = "https://typed.example" + transport.answer("GET /v1/event-relay", body = relayJson("https://other.example", "connected")) + model.loadRelay() + runCurrent() + assertEquals("connected", model.eventRelay.value?.status) + assertEquals("https://typed.example", model.relayDraft) + } + + // MARK: Gateways + + private fun TestScope.gatewayModel(transport: ConnectionTransport): AppModel { + val model = modelWith(transport, this) + model.navigate(Route.MessageGateway("discord")) + runCurrent() + return model + } + + @Test + fun invalidGatewayEditsSendNothing() = runTest { + val transport = scripted() + val model = gatewayModel(transport) + model.gatewayForm = model.gatewayForm?.copy(owner = "two words") + model.saveGateway() + runCurrent() + assertTrue(model.gatewayForm?.attempted == true) + assertTrue(transport.sent("PUT /v1/message-gateways/discord").isEmpty()) + } + + @Test + fun failedGatewaySaveKeepsEditsAndRestoresTheRecord() = runTest { + val transport = scripted() + val model = gatewayModel(transport) + val gate = transport.hold("PUT /v1/message-gateways/discord") + transport.answer("PUT /v1/message-gateways/discord", 500, """{"error":"Could not save gateway"}""") + + model.gatewayForm = model.gatewayForm?.copy(enabled = false, owner = "123") + model.saveGateway() + runCurrent() + assertFalse(model.gateways.value!!.single().config.enabled) + assertTrue(model.gatewayForm?.saving == true) + + gate.complete(Unit) + runCurrent() + assertTrue(model.gateways.value!!.single().config.enabled) + assertEquals("123", model.gatewayForm?.owner) + assertFalse(model.gatewayForm?.enabled == true) + assertEquals("Could not save gateway", model.gatewayForm?.error) + assertFalse(model.gatewayForm?.saving == true) + } + + @Test + fun aLateGatewayResponseKeepsNewerEdits() = runTest { + val transport = scripted() + val model = gatewayModel(transport) + val gate = transport.hold("PUT /v1/message-gateways/discord") + transport.answer("PUT /v1/message-gateways/discord", body = gatewayJson(owner = "123", status = "connecting")) + + model.gatewayForm = model.gatewayForm?.copy(owner = "123") + model.saveGateway() + runCurrent() + model.gatewayForm = model.gatewayForm?.copy(owner = "456") + transport.answer("GET /v1/message-gateways", body = """{"gateways":[${gatewayJson(owner = "123", status = "connecting")}]}""") + + gate.complete(Unit) + runCurrent() + assertEquals("456", model.gatewayForm?.owner) + assertFalse(model.gatewayForm?.saving == true) + assertFalse(model.gatewayForm?.saved == true) + assertEquals("123", model.gateways.value!!.single().config.ownerId) + } + + @Test + fun aConfirmedGatewaySaveReportsSavedAndTheServerStatus() = runTest { + val transport = scripted() + val model = gatewayModel(transport) + transport.answer("PUT /v1/message-gateways/discord", body = gatewayJson(owner = "123", status = "connecting")) + transport.answer("GET /v1/message-gateways", body = """{"gateways":[${gatewayJson(owner = "123", status = "connecting")}]}""") + + model.gatewayForm = model.gatewayForm?.copy(owner = "123", channels = listOf(GatewayChannelRow("c1"))) + model.saveGateway() + runCurrent() + val body = bodyOf(transport.sent("PUT /v1/message-gateways/discord").single()) + assertEquals("""["c1"]""", body["allowedChannelIds"].toString()) + assertEquals("connecting", model.gateways.value!!.single().status) + assertTrue(model.gatewayForm?.saved == true) + } + + @Test + fun aRefreshDoesNotReplaceAGatewayDraft() = runTest { + val transport = scripted() + val model = gatewayModel(transport) + model.gatewayForm = model.gatewayForm?.copy(owner = "typed") + transport.answer("GET /v1/message-gateways", body = """{"gateways":[${gatewayJson(status = "error")}]}""") + model.loadGateways() + runCurrent() + assertEquals("typed", model.gatewayForm?.owner) + assertEquals("error", model.gateways.value!!.single().status) + } + + // MARK: GitHub + + @Test + fun creatingAnAppPostsTheManifestAndCountsOnlyOnceConfirmed() = runTest { + val transport = scripted() + val model = modelWith(transport, this) + model.navigate(Route.Coding) + runCurrent() + transport.answer("POST /v1/github-apps/manifest", body = """{"url":"https://github.com/settings/apps/new?state=s","manifest":"{}"}""") + val gate = transport.hold("POST /v1/github-apps/complete") + transport.answer("POST /v1/github-apps/complete", body = appJson("app2")) + + model.openCreateApp() + model.createAppForm = CreateGitHubAppForm(name = " frien-bot ", organization = " ") + model.createGitHubApp() + runCurrent() + val body = bodyText(transport.sent("POST /v1/github-apps/manifest").single()) + assertEquals("""{"name":"frien-bot","origin":"https://crumble.example:8443"}""", body) + assertNull(model.createAppForm) + assertEquals("{}", model.githubFlow?.manifest) + + model.finishGitHubFlow("https://crumble.example:8443/github-app/callback?code=c&state=s") + runCurrent() + assertTrue(model.githubFlow?.finishing == true) + assertEquals(listOf("app1"), model.githubApps.value?.map { it.id }) + model.finishGitHubFlow("https://crumble.example:8443/github-app/callback?code=c&state=s") + + gate.complete(Unit) + runCurrent() + assertNull(model.githubFlow) + assertEquals(1, transport.sent("POST /v1/github-apps/complete").size) + assertEquals("""{"code":"c","state":"s"}""", bodyText(transport.sent("POST /v1/github-apps/complete").single())) + } + + @Test + fun aRefusedSignInSaysSoAndSendsNothing() = runTest { + val transport = scripted() + val model = modelWith(transport, this) + model.navigate(Route.Coding) + runCurrent() + transport.answer("POST /v1/github-apps/app1/sign-in", body = """{"url":"https://github.com/login/oauth/authorize?x=1"}""") + val app = model.githubApps.value!!.single() + model.openGitHubApp(app) + model.signInToGitHubApp(app) + runCurrent() + assertEquals("""{"origin":"https://crumble.example:8443"}""", bodyText(transport.sent("POST /v1/github-apps/app1/sign-in").single())) + assertEquals(GitHubStep.authorized, model.githubFlow?.step) + + model.finishGitHubFlow("https://crumble.example:8443/github-app/authorized?error=access_denied") + runCurrent() + assertEquals("Sign-in was refused: access_denied", model.githubFlow?.error) + assertTrue(transport.sent("POST /v1/github-apps/sign-in/complete").isEmpty()) + } + + @Test + fun aFinishedInstallConnectsTheApp() = runTest { + val transport = scripted() + transport.answer("GET /v1/github-apps", body = """{"apps":[${appJson(installed = false)}]}""") + val model = modelWith(transport, this) + model.navigate(Route.Coding) + runCurrent() + transport.answer("POST /v1/github-apps/app1/connect", body = appJson()) + transport.answer("GET /v1/github-apps", body = """{"apps":[${appJson()}]}""") + + model.installGitHubApp(model.githubApps.value!!.single()) + assertEquals(GitHubStep.installed, model.githubFlow?.step) + model.finishGitHubFlow("https://crumble.example:8443/github-app/installed?installation_id=1") + runCurrent() + assertNull(model.githubFlow) + assertTrue(model.githubApps.value!!.single().installed) + } + + @Test + fun appBotsApplyAtOnceAndReopenOnFailure() = runTest { + val transport = scripted() + val model = modelWith(transport, this) + model.navigate(Route.Coding) + runCurrent() + val gate = transport.hold("PUT /v1/github-apps/app1/bots") + transport.answer("PUT /v1/github-apps/app1/bots", 500, """{"error":"nope"}""") + + model.openGitHubApp(model.githubApps.value!!.single()) + model.githubAppForm = model.githubAppForm?.copy(botIDs = listOf(BOT_A)) + model.saveGitHubAppBots() + runCurrent() + assertNull(model.githubAppForm) + assertEquals(listOf(BOT_A), model.githubApps.value!!.single().botIds) + + gate.complete(Unit) + runCurrent() + assertEquals(emptyList(), model.githubApps.value!!.single().botIds) + assertEquals(listOf(BOT_A), model.githubAppForm?.botIDs) + assertEquals("nope", model.githubAppForm?.error) + } + + @Test + fun removedAppsReturnToTheirPlaceOnFailure() = runTest { + val transport = scripted() + transport.answer("GET /v1/github-apps", body = """{"apps":[${appJson("a")},${appJson("b")},${appJson("c")}]}""") + val model = modelWith(transport, this) + model.navigate(Route.Coding) + runCurrent() + val gate = transport.hold("DELETE /v1/github-apps/b") + transport.answer("DELETE /v1/github-apps/b", 500, """{"error":"nope"}""") + + model.deleteGitHubApp(model.githubApps.value!![1]) + runCurrent() + assertEquals(listOf("a", "c"), model.githubApps.value?.map { it.id }) + gate.complete(Unit) + runCurrent() + assertEquals(listOf("a", "b", "c"), model.githubApps.value?.map { it.id }) + } + + @Test + fun aMachineAccountAppearsOnlyWhenGitHubAcceptsItsToken() = runTest { + val transport = scripted() + val model = modelWith(transport, this) + model.navigate(Route.Coding) + runCurrent() + val gate = transport.hold("POST /v1/github-accounts") + transport.answer("POST /v1/github-accounts", 400, """{"error":"Bad credentials"}""") + + model.openAddAccount() + model.addAccountForm = model.addAccountForm?.copy(token = SecretDraft(text = SECRET)) + model.addGitHubAccount() + runCurrent() + assertTrue(model.addAccountForm?.saving == true) + assertEquals(1, model.githubAccounts.value?.size) + + gate.complete(Unit) + runCurrent() + assertEquals("Bad credentials", model.addAccountForm?.error) + assertEquals(SECRET, model.addAccountForm?.token?.text) + assertEquals(1, model.githubAccounts.value?.size) + } + + @Test + fun aSavedTokenIsNotSentAgainWhenTheBotsFailed() = runTest { + val transport = scripted() + val model = modelWith(transport, this) + model.navigate(Route.Coding) + runCurrent() + transport.answer("PUT /v1/github-accounts/acc1/token", body = accountJson()) + transport.answer("PUT /v1/github-accounts/acc1/bots", 500, """{"error":"nope"}""") + + model.openGitHubAccount(model.githubAccounts.value!!.single()) + model.githubAccountForm = model.githubAccountForm?.copy(botIDs = listOf(BOT_A), token = SecretDraft(text = SECRET)) + model.saveGitHubAccount() + runCurrent() + assertEquals("nope", model.githubAccountForm?.error) + assertFalse(model.githubAccountForm?.token?.changed == true) + assertEquals(listOf(BOT_A), model.githubAccountForm?.botIDs) + + transport.answer("PUT /v1/github-accounts/acc1/bots", body = accountJson(bots = "\"$BOT_A\"")) + transport.answer("GET /v1/github-accounts", body = """{"accounts":[${accountJson(bots = "\"$BOT_A\"")}]}""") + model.saveGitHubAccount() + runCurrent() + assertNull(model.githubAccountForm) + assertEquals(1, transport.sent("PUT /v1/github-accounts/acc1/token").size) + assertEquals(listOf(BOT_A), model.githubAccounts.value!!.single().botIds) + } + + // MARK: Workspaces + + @Test + fun nonAdminsSeeNoServerSettings() = runTest { + val transport = scripted() + transport.answer("GET /v1/admin/settings", 403, """{"error":"Only admins can do this"}""") + val model = modelWith(transport, this) + model.navigate(Route.Coding) + runCurrent() + assertEquals(false, model.isAdmin) + assertEquals("", model.serverSettings.error) + assertEquals("", model.errorText) + } + + @Test + fun serverSettingsApplyAtOnceAndReopenOnFailure() = runTest { + val transport = scripted() + val model = modelWith(transport, this) + model.navigate(Route.Coding) + runCurrent() + assertEquals(true, model.isAdmin) + val gate = transport.hold("PATCH /v1/admin/settings") + transport.answer("PATCH /v1/admin/settings", 400, """{"error":"Too small"}""") + + model.openServerSettings(WorkspaceField.size) + model.serverSettingsForm = model.serverSettingsForm?.copy(cpus = "8", memory = "1.5") + model.saveServerSettings() + runCurrent() + assertEquals("""{"workspaceCpus":8,"workspaceMemoryMib":1536}""", bodyText(transport.sent("PATCH /v1/admin/settings").single())) + assertEquals(8L, model.serverSettings.value?.workspaceCpus) + assertEquals("img", model.serverSettings.value?.codingImage) + + gate.complete(Unit) + runCurrent() + assertEquals(2L, model.serverSettings.value?.workspaceCpus) + assertEquals("Too small", model.serverSettingsForm?.error) + assertEquals("8", model.serverSettingsForm?.cpus) + } + + @Test + fun clearingTheImageSendsNull() = runTest { + val transport = scripted() + val model = modelWith(transport, this) + model.navigate(Route.Coding) + runCurrent() + transport.answer("PATCH /v1/admin/settings", body = settingsJson(image = null)) + model.openServerSettings(WorkspaceField.image) + model.serverSettingsForm = model.serverSettingsForm?.copy(image = " ") + model.saveServerSettings() + assertNull(model.serverSettings.value?.codingImage) + runCurrent() + assertEquals("""{"codingImage":null}""", bodyText(transport.sent("PATCH /v1/admin/settings").single())) + } + + // MARK: MCP servers + + private fun mcpJson(id: String = "m1", client: String? = null) = + """{"id":"$id","name":"Linear","url":"https://mcp.linear.app","enabled":true,"agentId":null,"oauthClientId":${client?.let { "\"$it\"" }},"token":$NONE,"oauthClientSecret":${if (client != null) SAVED else NONE},"auth":"none","error":null,"authenticated":false}""" + + private fun plainMcpJson(id: String = "m1") = + """{"id":"$id","name":"Linear","url":"https://mcp.linear.app","enabled":true,"agentId":null,"oauthClientId":null,"token":$NONE,"oauthClientSecret":$NONE}""" + + private fun TestScope.mcpModel(transport: ConnectionTransport, client: String? = null): AppModel { + transport.answer("GET /v1/mcp-servers", body = "[${mcpJson(client = client)}]") + val model = modelWith(transport, this) + model.navigate(Route.Integrations) + runCurrent() + return model + } + + @Test + fun aMcpReferenceWaitsForThePasswordManager() = runTest { + val transport = scripted() + val model = mcpModel(transport) + val gate = transport.hold("POST /v1/mcp-servers") + transport.answer("POST /v1/mcp-servers", body = plainMcpJson("m2")) + + model.mcpDraft = MCPDraft( + serverID = "", name = "Notion", url = "https://mcp.notion.com", + token = SecretDraft(manager = "1password", text = "op://v/i/f"), + ) + model.saveMCP() + runCurrent() + assertTrue(model.mcpDraft?.saving == true) + assertEquals("none", model.mcpServers.last().auth) + assertEquals( + """{"passwordManager":"1password","reference":"op://v/i/f"}""", + bodyOf(transport.sent("POST /v1/mcp-servers").single())["token"]!!.jsonObject["reference"].toString(), + ) + + gate.complete(Unit) + runCurrent() + assertNull(model.mcpDraft) + assertEquals("m2", model.mcpServers.last().id) + } + + @Test + fun aFailedMcpReferenceKeepsTheSheet() = runTest { + val transport = scripted() + val model = mcpModel(transport) + transport.answer("POST /v1/mcp-servers", 400, """{"error":"Can't read it"}""") + + model.mcpDraft = MCPDraft(serverID = "", name = "Notion", url = "https://mcp.notion.com", token = SecretDraft(manager = "1password", text = "op://x")) + model.saveMCP() + runCurrent() + assertEquals("Notion", model.mcpDraft?.name) + assertFalse(model.mcpDraft?.saving == true) + assertEquals("Can't read it", model.errorText) + assertEquals(listOf("m1"), model.mcpServers.map { it.id }) + } + + @Test + fun clearingTheClientIdRemovesItsSecret() = runTest { + val transport = scripted() + val model = mcpModel(transport, client = "client-1") + transport.answer("PATCH /v1/mcp-servers/m1", body = plainMcpJson()) + + model.openMCPForm("m1") + assertEquals("client-1", model.mcpDraft?.clientID) + model.mcpDraft = model.mcpDraft?.copy(clientID = " ") + model.saveMCP() + runCurrent() + val body = bodyOf(transport.sent("PATCH /v1/mcp-servers/m1").single()) + assertEquals("null", body["oauthClientId"].toString()) + assertEquals("null", body["oauthClientSecret"].toString()) + } + + @Test + fun aNewClientSecretGoesWithItsClientId() = runTest { + val transport = scripted() + val model = mcpModel(transport) + transport.answer("PATCH /v1/mcp-servers/m1", body = plainMcpJson()) + + model.openMCPForm("m1") + model.mcpDraft = model.mcpDraft?.copy(clientID = "client-1", clientSecret = SecretDraft(text = SECRET)) + model.saveMCP() + assertNull(model.mcpDraft) + runCurrent() + val body = bodyOf(transport.sent("PATCH /v1/mcp-servers/m1").single()) + assertEquals("\"client-1\"", body["oauthClientId"].toString()) + assertEquals("""{"value":"$SECRET"}""", body["oauthClientSecret"].toString()) + } + + @Test + fun typedConnectionSecretsAreRedactedAndLeaveWithTheScreen() = runTest { + val transport = scripted() + val model = modelWith(transport, this) + model.navigate(Route.Coding) + runCurrent() + model.openAddAccount() + model.addAccountForm = model.addAccountForm?.copy(token = SecretDraft(text = SECRET)) + assertFalse(model.addAccountForm.toString().contains(SECRET)) + assertFalse(MCPDraft(serverID = "", token = SecretDraft(text = SECRET)).toString().contains(SECRET)) + assertFalse(SecretInput.Value(SECRET).toString().contains(SECRET)) + model.navigate(Route.Memory) + assertNull(model.addAccountForm) + } +} diff --git a/app/src/test/java/dev/crumble/android/ContractFixtures.kt b/app/src/test/java/dev/crumble/android/ContractFixtures.kt index e4810fc..15cb4ae 100644 --- a/app/src/test/java/dev/crumble/android/ContractFixtures.kt +++ b/app/src/test/java/dev/crumble/android/ContractFixtures.kt @@ -4,10 +4,19 @@ import dev.crumble.android.model.ChatSnapshot import dev.crumble.android.model.CrumbleJson import kotlinx.serialization.json.* +private val avatarFixture = buildJsonObject { + put("definition", buildJsonObject { + put("version", 1); put("id", "box"); put("name", "Box") + put("body", buildJsonObject { put("path", "M20 20H80V80H20Z") }) + put("eyes", buildJsonObject { put("x", 50); put("y", 46); put("spacing", 15); put("scale", 1) }) + }) + put("color", "#38bdf8"); put("eyeColor", "#151515") +} + internal fun agentFixture(id: String, name: String = "Atlas", enabled: Boolean = true, lastMessage: String? = null): String = buildJsonObject { put("id", id); put("name", name); put("enabled", enabled) - put("avatar", "bot"); put("description", ""); put("instructions", "") + put("avatar", avatarFixture); put("description", ""); put("instructions", "") put("provider", "openai"); put("model", "model") for (key in listOf("tools", "skills", "mcpServers", "delegates")) put(key, JsonArray(emptyList())) put("createdAt", "2026-10-18T10:00:00Z"); put("updatedAt", "2026-10-18T10:00:00Z") @@ -16,7 +25,7 @@ internal fun agentFixture(id: String, name: String = "Atlas", enabled: Boolean = internal fun memoryFixture(id: String, content: String): String = buildJsonObject { - put("id", id); put("agentId", JsonNull); put("content", content) + put("id", id); put("agentId", JsonNull); put("content", content); put("source", JsonNull) put("createdAt", "2026-10-18T10:00:00Z"); put("updatedAt", "2026-10-18T10:00:00Z") }.toString() diff --git a/app/src/test/java/dev/crumble/android/CronTests.kt b/app/src/test/java/dev/crumble/android/CronTests.kt new file mode 100644 index 0000000..c33133f --- /dev/null +++ b/app/src/test/java/dev/crumble/android/CronTests.kt @@ -0,0 +1,72 @@ +package dev.crumble.android + +import dev.crumble.android.model.describeCron +import dev.crumble.android.model.hasHashedField +import dev.crumble.android.model.nextOccurrence +import dev.crumble.android.model.wordedCron +import java.time.Instant +import java.time.ZoneId +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** cron-reference.json holds what cronstrue 3.38.0 and cron-parser 5.10.2 answer for these expressions. */ +class CronTests { + private val reference: JsonObject = Json.parseToJsonElement( + checkNotNull(javaClass.classLoader?.getResource("cron-reference.json")).readText(), + ).jsonObject + private val starts = reference.getValue("from").jsonArray.map { (it as JsonArray)[0].jsonPrimitive.content to it[1].jsonPrimitive.content } + private val cases = reference.getValue("out").jsonArray.map { it.jsonObject } + private fun JsonObject.cron() = getValue("c").jsonPrimitive.content + + @Test + fun wordingMatchesCronstrue() { + val differing = cases.mapNotNull { case -> + val cron = case.cron() + val expected = case.getValue("word").jsonPrimitive.contentOrNull + // The app keeps the raw text for L, #, and seconds; cronstrue gives up on name lists it can word. + val raw = cron.any { it in "L#" } || cron == "15 30 9 * * *" + val wanted = if (raw) null else expected + (cron to "$wanted != ${wordedCron(cron)}").takeIf { wanted != wordedCron(cron) && cron != "0 12 * JAN,JUL *" } + } + assertEquals(emptyList>(), differing) + } + + @Test + fun nextRunsMatchCronParser() { + val differing = cases.filterNot { hasHashedField(it.cron()) }.flatMap { case -> + val cron = case.cron() + case.getValue("next").jsonArray.mapIndexedNotNull { index, value -> + val (from, zone) = starts[index] + val expected = value.jsonPrimitive.contentOrNull?.let(Instant::parse) + val actual = nextOccurrence(cron, ZoneId.of(zone), Instant.parse(from)) + "$cron from $from $zone: $expected != $actual".takeIf { expected != actual } + } + } + assertEquals(emptyList(), differing) + } + + @Test + fun describingMatchesTheWebFallbacks() { + assertEquals("At 09:00", describeCron("0 9 * * *", "UTC", "UTC")) + assertEquals("At 09:00 (Asia/Tokyo)", describeCron("0 9 * * *", "Asia/Tokyo", "UTC")) + assertEquals("0 0 15 * 1", describeCron("0 0 15 * 1", "UTC", "UTC")) + assertEquals("0 9 * * 1/2", describeCron("0 9 * * 1/2", "UTC", "UTC")) + assertEquals("not a cron (Asia/Tokyo)", describeCron("not a cron", "Asia/Tokyo", "UTC")) + } + + @Test + fun onlyAWholeHTokenCountsAsHashed() { + assertTrue(hasHashedField("H * * * *")) + assertTrue(hasHashedField("0 H/2 * * *")) + assertFalse(hasHashedField("0 9 * MAR THU")) + } +} diff --git a/app/src/test/java/dev/crumble/android/CrumbleTests.kt b/app/src/test/java/dev/crumble/android/CrumbleTests.kt index f6b4183..a616628 100644 --- a/app/src/test/java/dev/crumble/android/CrumbleTests.kt +++ b/app/src/test/java/dev/crumble/android/CrumbleTests.kt @@ -4,11 +4,20 @@ import dev.crumble.android.model.ActivityEvent import dev.crumble.android.model.Agent import dev.crumble.android.model.AgentDraft import dev.crumble.android.model.AppModel +import dev.crumble.android.network.wire +import dev.crumble.android.ui.avatarColor +import dev.crumble.android.ui.geometry +import dev.crumble.android.ui.importAvatar +import dev.crumble.android.ui.isAvatarColor +import dev.crumble.android.ui.placeholderAvatar +import dev.crumble.android.ui.withColors +import dev.crumble.android.model.BotRequestRef +import dev.crumble.android.model.HeldActionRef import dev.crumble.android.model.AttachmentError import dev.crumble.android.model.ChatRow import dev.crumble.android.model.ChatSnapshot import dev.crumble.android.model.CrumbleJson -import dev.crumble.android.model.displayLabel +import dev.crumble.android.model.headline import dev.crumble.android.model.Memory import dev.crumble.android.model.MentionCompletion import dev.crumble.android.model.Message @@ -38,9 +47,7 @@ import dev.crumble.android.network.SSEParser import dev.crumble.android.network.SignInError import dev.crumble.android.network.friendlyError import dev.crumble.android.network.oauthResult -import dev.crumble.android.ui.BotLook import dev.crumble.android.ui.MarkdownBlock -import dev.crumble.android.ui.agentAvatarSeed import java.io.ByteArrayInputStream import java.nio.charset.StandardCharsets import java.time.ZoneId @@ -121,12 +128,11 @@ class CrumbleTests { @Test fun personalSkillFailureRestoresDraftAndSkillsWithoutClobberingNewerAgentFields() = runTest { - val oldSkill = Skill(id = "old", name = "Old", instructions = "Keep this") val transport = GatedTransport(500, "{\"error\":\"busy\"}") val client = APIClient(baseURL = "http://crumble.test/", token = "token", transport = transport) val model = AppModel(client = client, scope = TestScope(StandardTestDispatcher(testScheduler))) model.route = Route.Skills - model.agents = listOf(Agent(id = "a1", name = "Before", skills = listOf(oldSkill))) + model.agents = listOf(Agent(id = "a1", name = "Before")) model.skillDraft = dev.crumble.android.model.SkillDraft( skillID = "", agentID = "a1", @@ -136,13 +142,14 @@ class CrumbleTests { model.saveSkill() testScheduler.runCurrent() + assertEquals("New skill", model.agentSkills["a1"]?.last()?.name) assertEquals("New skill", model.agents.single().skills?.last()?.name) model.agents = model.agents.map { it.copy(name = "Newer name") } transport.gate.complete(Unit) advanceUntilIdle() assertEquals("Newer name", model.agents.single().name) - assertEquals(listOf(oldSkill), model.agents.single().skills) + assertEquals(emptyList(), model.agents.single().skills) assertEquals("New skill", model.skillDraft?.name) assertTrue(model.errorText.contains("busy")) } @@ -183,13 +190,13 @@ class CrumbleTests { fun activityFeedDecodesOperationalRecordsAndDetails() = runTest { val (client, stub) = StubTransport.client { req -> assertEquals("/v1/activity/feed", req.pathWithQuery) - 200 to """{"activities":[{"id":"evt-1","agentId":"a1","agentName":"Atlas","entryId":"run-1","timestamp":1720000000000,"kind":"tool-call","details":{"toolName":"search","query":"calendar"}}],"hasMore":true}""" + 200 to """{"activities":[{"id":"evt-1","agentId":"a1","agentName":"Atlas","entryId":"run-1","timestamp":1720000000000,"kind":"tool-call","details":{"toolName":"search","query":"calendar"}}],"nextCursor":null,"hasMore":true}""" } val feed = client.activityFeed() assertTrue(feed.hasMore) assertEquals("evt-1", feed.activities.single().id) assertEquals("tool-call", feed.activities.single().kind) - assertEquals("search", feed.activities.single().displayLabel()) + assertEquals("search", feed.activities.single().headline().target) assertEquals("/v1/activity/feed", stub.requests.single().pathWithQuery) } @@ -345,7 +352,7 @@ class CrumbleTests { val (client, stub) = StubTransport.client { req -> when (req.pathWithQuery) { "/v1/mcp-servers/s1/oauth" -> 200 to """{"authorizationUrl":"https://auth.example.com/authorize?state=x"}""" - "/v1/mcp-servers/s1/oauth/callback" -> 200 to """{"id":"s1","name":"Linear","url":"https://mcp.linear.app/mcp","enabled":true,"agentId":null,"auth":"oauth","authenticated":true}""" + "/v1/mcp-servers/s1/oauth/callback" -> 200 to """{"id":"s1","name":"Linear","url":"https://mcp.linear.app/mcp","enabled":true,"agentId":null,"oauthClientId":null,"oauthClientSecret":{"configured":false,"passwordManager":null,"reference":null},"token":{"configured":false,"passwordManager":null,"reference":null},"error":null,"auth":"oauth","authenticated":true}""" else -> 404 to "" } } @@ -368,7 +375,7 @@ class CrumbleTests { } catch (e: APIError) { assertEquals(401, e.statusCode) assertEquals("bad token", e.body) - assertEquals("Authentication failed. Check the server token in Settings.", friendlyError(e)) + assertEquals("Authentication failed. Sign in again in Settings.", friendlyError(e)) } } @@ -381,7 +388,7 @@ class CrumbleTests { @Test fun taskPickersPreserveTheInstantAndSubmitOnlyTheSelectedMode() = runTest { val testScope = TestScope(StandardTestDispatcher(testScheduler)) - val response = """{"id":"s1","agentId":"a1","name":"Greeting","prompt":"Say hi","enabled":true,"timezone":"Europe/Berlin","runAt":"2026-10-18T10:10:00Z","cron":null,"nextRunAt":null,"createdAt":"2026-10-18T10:00:00Z","createdByAgentId":null}""" + val response = """{"id":"s1","agentId":"a1","name":"Greeting","kind":"prompt","prompt":"Say hi","command":null,"timeoutSeconds":600,"notify":true,"eventSourceId":null,"enabled":true,"timezone":"Europe/Berlin","runAt":"2026-10-18T10:10:00Z","cron":null,"nextRunAt":null,"createdAt":"2026-10-18T10:00:00Z","createdByAgentId":null}""" val (client, stub) = StubTransport.client { req -> 200 to if (req.method == "PATCH") response else "[]" } @@ -474,6 +481,88 @@ class CrumbleTests { model.cancelStream() } + @Test + fun heldActionKeepsItsCardWhenADecisionFailsThenSettles() = runTest { + val testScope = TestScope(StandardTestDispatcher(testScheduler)) + var status = "pending" + var refuse = true + fun held() = """{"id":"h1","job":"browse","action":"Pay the invoice","page":null,"ownerMessages":[],"reason":"Not asked for","status":"$status","declineReason":null,"heldAt":"2026-11-05T10:00:00Z","decidedAt":null}""" + val (client, _) = StubTransport.client { req -> + when (req.pathWithQuery) { + "/v1/agents/a1/held-actions" -> 200 to "[${held()}]" + "/v1/agents/a1/held-actions/h1/approve" -> + if (refuse) 503 to """{"error":"busy"}""" else { status = "approved"; 200 to held() } + else -> 503 to "" + } + } + val model = AppModel(client = client, credentials = dev.crumble.android.storage.InMemoryCredentialStore(), scope = testScope) + model.selectAgent("a1") + val event = Message(id = "e1", entryId = "e1", role = "event", content = JsonPrimitive("Pay the invoice"), heldAction = HeldActionRef("h1", "browse")) + model.applySnapshot(ChatSnapshot(agentId = "a1", messages = listOf(event), hasMore = false, oldestEntryId = null)) + testScheduler.runCurrent() + assertEquals("pending", model.heldActions.single().status) + + model.decideHeldAction("h1", approve = true) + assertTrue("h1" in model.decidingIDs) + testScheduler.runCurrent() + assertTrue(model.decisionErrors["h1"].orEmpty().contains("busy")) + assertEquals("pending", model.heldActions.single().status) + assertTrue(model.decidingIDs.isEmpty()) + + refuse = false + model.decideHeldAction("h1", approve = true) + testScheduler.runCurrent() + assertTrue(model.decisionErrors.isEmpty()) + assertEquals("approved", model.heldActions.single().status) + model.cancelStream() + } + + @Test + fun requestBotResultBecomesAChatRow() = runTest { + val (client, _) = StubTransport.client { + 200 to """{"messages":[{"id":"t1","entryId":"t","role":"toolResult","content":"","toolName":"request_bot","toolDetails":{"id":"r1","proposal":{"name":"Scout"}}},{"id":"t2","entryId":"t","role":"toolResult","content":"","toolName":"request_bot","isError":true}],"hasMore":false,"oldestEntryId":null}""" + } + val messages = client.chatHistory("a1", before = "t", limit = 10).messages.orEmpty() + assertEquals(BotRequestRef("r1", "Scout"), messages[0].botRequest) + assertEquals(listOf(true, false), messages.map { ChatRow.shownInChat(it) }) + } + + @Test + fun avatarColorsExpandShortHex() { + assertEquals(avatarColor("#aabbcc"), avatarColor("#abc")) + assertTrue(isAvatarColor("#ABC") && isAvatarColor("#38bdf8")) + assertFalse(isAvatarColor("38bdf8") || isAvatarColor("#38bd")) + } + + @Test + fun avatarImportKeepsColorsAndRejectsInvalidGeometry() { + val current = placeholderAvatar("a1").copy(color = "#123456", eyeColor = "#654321") + val json = """{"version":1,"id":"box","name":"Box","body":{"path":"M20 20H80V80H20Z"},"eyes":{"x":50,"y":46,"spacing":15,"scale":1}}""" + val imported = importAvatar(json, current).getOrThrow() + assertEquals("box", imported.definition.id) + assertEquals("#123456", imported.color) + assertTrue(importAvatar("""{"version":1}""", current).isFailure) + } + + @Test + fun avatarRoundTripsThroughTheCreateRequest() { + val avatar = placeholderAvatar("a1") + assertEquals(avatar.definition.body.path, avatar.wire()?.definition?.body?.path) + assertEquals(avatar, avatar.geometry().withColors(avatar.color, avatar.eyeColor)) + } + + @Test + fun emptyChatSnapshotAppliesWithoutMessages() = runTest { + val credentials = dev.crumble.android.storage.InMemoryCredentialStore() + val testScope = TestScope(StandardTestDispatcher(testScheduler)) + val (client, _) = StubTransport.client(token = "owner-one") { 503 to "" } + val model = AppModel(client = client, credentials = credentials, scope = testScope) + model.selectAgent("a1") + model.applySnapshot(ChatSnapshot(agentId = "a1", messages = emptyList(), status = "idle", hasMore = false, oldestEntryId = null)) + assertTrue(model.messages.isEmpty()) + model.cancelStream() + } + @Test fun recentChatIsVisibleBeforeNetworkAndScopedToConnectionAndBot() = runTest { val credentials = dev.crumble.android.storage.InMemoryCredentialStore() @@ -708,7 +797,7 @@ class CrumbleTests { val model = AppModel(client = client, scope = testScope) model.agents = listOf(Agent(id = "a1", name = "Before", lastMessage = "Latest reply")) model.route = Route.Memory - model.agentDraft = AgentDraft(isNew = false, agentID = "a1", name = "After") + model.agentDraft = AgentDraft(isNew = false, agentID = "a1", name = "After", provider = "openai", model = "gpt") model.saveAgentEditor() assertEquals("After", model.agents.first().name) assertEquals("Latest reply", model.agents.first().lastMessage) @@ -728,7 +817,7 @@ class CrumbleTests { } val model = AppModel(client = client, scope = testScope) model.route = Route.Memory - model.agentDraft = AgentDraft(isNew = true, agentID = "", name = "New bot") + model.agentDraft = AgentDraft(isNew = true, agentID = "", name = "New bot", provider = "openai", model = "gpt") model.saveAgentEditor() assertTrue(model.agents.first().id.startsWith("pending:")) assertNull(model.agentDraft) @@ -825,21 +914,6 @@ class CrumbleTests { assertTrue(regex.matches(newRequestID())) } - @Test - fun avatarSeedsAcceptLegacyValues() { - val cases = mapOf( - "bot:violet" to "violet", - "critters:violet" to "violet", - "sparkles" to "a1", - "😀" to "a1", - "" to "a1", - ) - for ((avatar, seed) in cases) { - assertEquals(seed, agentAvatarSeed(Agent(id = "a1", avatar = avatar))) - } - assertEquals(BotLook("agent-seed"), BotLook("agent-seed")) - } - @Test fun chatHidesToolActivity() { val tool = Message( diff --git a/app/src/test/java/dev/crumble/android/DefectRegressionTests.kt b/app/src/test/java/dev/crumble/android/DefectRegressionTests.kt new file mode 100644 index 0000000..a60ab13 --- /dev/null +++ b/app/src/test/java/dev/crumble/android/DefectRegressionTests.kt @@ -0,0 +1,503 @@ +package dev.crumble.android + +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.ViewModelStore +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.AttachmentError +import dev.crumble.android.generated.Credential +import dev.crumble.android.generated.Credentials +import dev.crumble.android.model.AttachmentLimits +import dev.crumble.android.model.ChatRow +import dev.crumble.android.model.CrumbleJson +import dev.crumble.android.model.JobKind +import dev.crumble.android.model.JobRef +import dev.crumble.android.model.MCPServer +import dev.crumble.android.model.Message +import dev.crumble.android.model.MessageOrigin +import dev.crumble.android.model.ProviderStatus +import dev.crumble.android.model.Route +import dev.crumble.android.model.botProviderOptions +import dev.crumble.android.model.messageLabel +import dev.crumble.android.model.readAttachment +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import dev.crumble.android.storage.InMemoryCredentialStore +import java.io.InputStream +import java.nio.charset.StandardCharsets +import java.time.ZoneId +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.jsonObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +private const val BASE = "https://crumble.example" + +private fun providerList(vararg providers: Pair) = providers.joinToString(",", "[", "]") { (id, configured) -> + """{"provider":"$id","name":"${id.uppercase()}","configured":$configured,"authMethods":[{"type":"api_key","label":"Key","subscription":false}],"credentialType":null,"apiKey":{"configured":false,"passwordManager":null,"reference":null},"activeLoginId":null,"externalAuth":null}""" +} + +private class RegressionTransport : HttpTransport { + val requests = mutableListOf() + val held = mutableMapOf>() + val responses = mutableMapOf>() + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + val key = "${request.method} ${request.pathWithQuery}" + requests.add(request) + val (status, body) = responses[key] ?: (503 to """{"error":"unscripted"}""") + held[key]?.await() + return HttpResponseData(status, body.toByteArray(StandardCharsets.UTF_8)) + } + + override suspend fun openStream(request: HttpRequestData): HttpStreamResponse = + throw UnsupportedOperationException("streams are not used here") + + fun hold(key: String) = CompletableDeferred().also { held[key] = it } + + fun sent(key: String) = requests.filter { "${it.method} ${it.pathWithQuery}" == key } + + fun json(key: String): JsonObject = + CrumbleJson.parseToJsonElement(String(sent(key).single().body!!, StandardCharsets.UTF_8)).jsonObject +} + +private class CountingStream(private val size: Int) : InputStream() { + var served = 0 + + override fun read(): Int = if (served < size) { served += 1; 'a'.code } else -1 + + override fun read(b: ByteArray, off: Int, len: Int): Int { + if (served >= size) return -1 + val count = minOf(len, size - served) + b.fill('a'.code.toByte(), off, off + count) + served += count + return count + } +} + +private val RUNNABLE_BOT = Agent(id = "a1", name = "Atlas", provider = "openai", model = "gpt", tools = listOf("memory", "delegate")) + +@OptIn(ExperimentalCoroutinesApi::class) +class DefectRegressionTests { + private fun model(transport: RegressionTransport, scope: CoroutineScope, credentials: InMemoryCredentialStore = InMemoryCredentialStore(), onSignOut: suspend (APIClient) -> Unit = {}) = + AppModel(client = APIClient(BASE, "session", transport), credentials = credentials, scope = scope, transport = transport, onSignOut = onSignOut) + .also { it.agents = listOf(RUNNABLE_BOT) } + + // Activity recreation + + private fun appViewModel(store: ViewModelStore, transport: RegressionTransport) = ViewModelProvider.create( + store, + viewModelFactory { + initializer { + AppViewModel { scope, changed -> + AppModel(client = APIClient(BASE, "session", transport), scope = scope, transport = transport, onNotificationsChanged = changed) + } + } + }, + )[AppViewModel::class] + + @Test + fun aSaveStartedBeforeRecreationStillRollsBackInTheNewActivity() = runTest { + Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler)) + try { + val store = ViewModelStore() + val transport = RegressionTransport() + val patch = transport.hold("PATCH /v1/agents/a1") + val first = appViewModel(store, transport) + val model = first.model + model.agents = listOf(RUNNABLE_BOT) + model.draft = "half a sentence" + model.openEditor("a1") + model.agentDraft = model.agentDraft!!.copy(name = "Renamed") + model.saveAgentEditor() + assertNull(model.agentDraft) + + // The old activity's lifecycle ends here; the store outlives it. + val second = appViewModel(store, transport) + assertSame(model, second.model) + assertEquals("half a sentence", second.model.draft) + + patch.complete(Unit) + runCurrent() + assertEquals("Atlas", second.model.agents.single().name) + assertEquals("Renamed", second.model.agentDraft?.name) + store.clear() + } finally { + Dispatchers.resetMain() + } + } + + @Test + fun launchWorkAndItsIntentRunOncePerModel() = runTest { + Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler)) + try { + val store = ViewModelStore() + val owner = appViewModel(store, RegressionTransport()) + assertTrue(owner.start()) + assertFalse(appViewModel(store, RegressionTransport()).start()) + store.clear() + } finally { + Dispatchers.resetMain() + } + } + + @Test + fun notificationChangesReachTheCurrentActivityOnly() = runTest { + Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler)) + try { + val calls = mutableListOf() + var fired: () -> Unit = {} + val store = ViewModelStore() + val owner = ViewModelProvider.create( + store, + viewModelFactory { initializer { AppViewModel { scope, changed -> fired = changed; AppModel(client = null, scope = scope) } } }, + )[AppViewModel::class] + owner.model + owner.onNotificationsChanged = { calls.add("old") } + owner.onNotificationsChanged = { calls.add("new") } + fired() + assertEquals(listOf("new"), calls) + store.clear() + } finally { + Dispatchers.resetMain() + } + } + + // Bot editor + + @Test + fun aNewBotStartsOnTheFirstConfiguredProvider() = runTest { + val model = model(RegressionTransport(), backgroundScope) + model.providers = listOf(ProviderStatus("melious", "Melious", false), ProviderStatus("openai", "OpenAI", true)) + model.createAgent() + assertEquals("openai", model.agentDraft!!.provider) + assertEquals(listOf("openai"), botProviderOptions(model.providers, "openai").map { it.value }) + } + + @Test + fun aProviderListThatArrivesLateFillsTheDefaultWithoutTouchingATypedModel() = runTest { + val transport = RegressionTransport() + transport.responses["GET /v1/providers"] = 200 to providerList("melious" to false, "openai" to true) + val gate = transport.hold("GET /v1/providers") + val model = model(transport, backgroundScope) + model.createAgent() + runCurrent() + assertEquals("", model.agentDraft!!.provider) + model.agentDraft = model.agentDraft!!.copy(model = "typed") + + gate.complete(Unit) + runCurrent() + assertEquals("openai", model.agentDraft!!.provider) + assertEquals("typed", model.agentDraft!!.model) + } + + @Test + fun aMissingProviderOrModelStopsTheSave() = runTest { + val transport = RegressionTransport() + val model = model(transport, backgroundScope) + model.createAgent() + model.agentDraft = model.agentDraft!!.copy(name = "New") + model.saveAgentEditor() + runCurrent() + assertTrue(transport.sent("POST /v1/agents").isEmpty()) + assertNotNull(model.agentDraft) + assertTrue(model.errorText.isNotEmpty()) + + model.agentDraft = model.agentDraft!!.copy(provider = "openai", model = " ") + model.saveAgentEditor() + runCurrent() + assertTrue(transport.sent("POST /v1/agents").isEmpty()) + } + + @Test + fun theCurrentProviderStaysListedWhenItsKeyIsGone() { + val providers = listOf(ProviderStatus("melious", "Melious", false), ProviderStatus("openai", "OpenAI", true)) + assertEquals(listOf("Melious (not set up)", "OpenAI"), botProviderOptions(providers, "melious").map { it.label }) + assertEquals(listOf("Choose a provider", "OpenAI"), botProviderOptions(providers, "").map { it.label }) + } + + @Test + fun savingABotSendsNeitherDelegatesNorSharedMemory() = runTest { + val transport = RegressionTransport() + transport.responses["PATCH /v1/agents/a1"] = 200 to agentFixture("a1") + transport.responses["POST /v1/agents"] = 201 to agentFixture("created", "New") + val model = model(transport, backgroundScope) + model.openEditor("a1") + model.saveAgentEditor() + runCurrent() + val patch = transport.json("PATCH /v1/agents/a1") + assertFalse(patch.containsKey("delegates")) + assertFalse(patch.containsKey("sharedMemory")) + + model.createAgent() + model.agentDraft = model.agentDraft!!.copy(name = "New", provider = "openai", model = "gpt") + model.saveAgentEditor() + runCurrent() + val post = transport.json("POST /v1/agents") + assertFalse(post.containsKey("delegates")) + assertFalse(post.containsKey("sharedMemory")) + } + + // Message origins + + private fun user(kind: String?, name: String? = null, source: String? = null) = Message( + id = "m", + role = "user", + content = JsonPrimitive("hello"), + origin = kind?.let { MessageOrigin(kind = it, name = name, source = source) }, + ) + + @Test + fun onlyTheOwnersMessagesAreLabelledYou() { + assertEquals("You", messageLabel(user(null))) + assertEquals("You", messageLabel(user("owner"))) + assertEquals("Automation · Deploy, event from GitHub", messageLabel(user("event", "Deploy", "GitHub"))) + assertEquals("Automation · Deploy, event from a deleted source", messageLabel(user("event", "Deploy"))) + assertEquals("Script automation · Nightly", messageLabel(user("script", "Nightly"))) + assertEquals("Credential · ACME_TOKEN", messageLabel(user("credential", "ACME_TOKEN"))) + assertEquals("Bot request", messageLabel(user("bot_request"))) + } + + @Test + fun jobMessagesStayOutOfTheChat() { + assertFalse(ChatRow.shownInChat(user("coding", "fix"))) + assertFalse(ChatRow.shownInChat(user("desktop", "browse"))) + assertTrue(ChatRow.shownInChat(user("event", "Deploy", "GitHub"))) + assertTrue(ChatRow.shownInChat(user(null))) + } + + // MCP sign-in + + @Test + fun aSignInAddressThatIsNotAWebPageNeverLeavesTheApp() = runTest { + val transport = RegressionTransport() + transport.responses["POST /v1/mcp-servers/s1/oauth"] = 200 to """{"authorizationUrl":"intent://evil#Intent;scheme=other;end"}""" + val model = model(transport, backgroundScope) + model.mcpServers = listOf(MCPServer(id = "s1", name = "Linear")) + val opened = mutableListOf() + model.beginMCPSignIn("s1") { opened.add(it) } + runCurrent() + + assertTrue(opened.isEmpty()) + assertNull(model.signingIn) + assertTrue(model.errorText.isNotEmpty()) + } + + // Attachments + + @Test + fun aHugeTextFileIsRefusedWithoutReadingItAll() { + val stream = CountingStream(2 * AttachmentLimits.TEXT_BYTES) + val error = assertThrows(AttachmentError::class.java) { + readAttachment("big.txt", "text/plain", declaredSize = null) { stream } + } + assertEquals("big.txt is larger than 512 KB.", error.message) + assertTrue("read ${stream.served}", stream.served <= AttachmentLimits.TEXT_BYTES + 8192) + } + + @Test + fun aDeclaredSizeOverTheLimitNeverOpensTheFile() { + var opened = false + assertThrows(AttachmentError::class.java) { + readAttachment("big.txt", "text/plain", declaredSize = 10L * 1024 * 1024 * 1024) { opened = true; null } + } + assertFalse(opened) + } + + @Test + fun aBinaryFileIsRefusedWithoutReadingIt() { + var opened = false + val error = assertThrows(AttachmentError::class.java) { + readAttachment("disk.img", "application/octet-stream", declaredSize = null) { opened = true; null } + } + assertEquals("disk.img can't be attached. Attach images or text files.", error.message) + assertFalse(opened) + } + + @Test + fun anOversizedPhotoStillReachesTheReencoderButAHugeOneDoesNot() { + val photo = readAttachment( + "photo.jpg", + "image/jpeg", + declaredSize = null, + jpegReencoder = { byteArrayOf(1, 2, 3) }, + ) { CountingStream(AttachmentLimits.IMAGE_BYTES + 1) } + assertEquals("photo.jpg", photo.name) + assertEquals(3, photo.data.size) + + val stream = CountingStream(AttachmentLimits.IMAGE_SOURCE_BYTES + 1024 * 1024) + assertThrows(AttachmentError::class.java) { + readAttachment("huge.jpg", "image/jpeg", declaredSize = null, jpegReencoder = { byteArrayOf(1) }) { stream } + } + assertTrue("read ${stream.served}", stream.served <= AttachmentLimits.IMAGE_SOURCE_BYTES + 8192) + } + + // GitHub-managed credentials + + private fun credential(name: String, github: Boolean) = Credential(name, listOf("github.com"), null, "t", "t", null, null, github) + + @Test + fun aGithubCredentialCanBeNeitherEditedNorDeleted() = runTest { + val transport = RegressionTransport() + val model = model(transport, backgroundScope) + val github = credential("GITHUB_TOKEN", true) + model.botCredentials = mapOf("a1" to Credentials(listOf(github, credential("ACME", false)), emptyList())) + + model.openCredentialForm("a1", existing = github) + assertNull(model.credentialForm) + + model.deleteCredential("a1", "GITHUB_TOKEN") + runCurrent() + assertTrue(transport.sent("DELETE /v1/agents/a1/credentials/GITHUB_TOKEN").isEmpty()) + assertEquals(2, model.botCredentials.getValue("a1").credentials.size) + } + + // Timezone + + @Test + fun aBotChatMessageCarriesTheDeviceTimezone() = runTest { + val transport = RegressionTransport() + transport.responses["POST /v1/agents/a1/messages"] = 200 to executionFixture + val client = APIClient(BASE, "session", transport) + client.sendChatMessage("a1", "hello", "request", "") + val body = CrumbleJson.parseToJsonElement(String(transport.requests.single().body!!, StandardCharsets.UTF_8)).jsonObject + assertEquals(JsonPrimitive(ZoneId.systemDefault().id), body["timezone"]) + } + + // Reconnecting + + private fun connecting(transport: RegressionTransport) = transport.apply { + responses["POST /api/auth/sign-in/email"] = 200 to """{"token":"next"}""" + responses["GET /v1/agents"] = 200 to "[${agentFixture("a1")}]" + responses["POST /api/auth/sign-out"] = 200 to "{}" + } + + @Test + fun connectingWithANewSessionEndsTheOldOne() = runTest { + val transport = connecting(RegressionTransport()) + val unregistered = mutableListOf>() + lateinit var model: AppModel + model = model(transport, backgroundScope, onSignOut = { unregistered.add(it.token to model.client?.token) }) + model.token = "session" + model.serverURL = BASE + model.email = "me@example.com" + model.password = "secret" + model.saveSettings() + runCurrent() + + assertEquals("next", model.client?.token) + assertEquals("the old session unregisters before the new one takes over", listOf("session" to "session"), unregistered) + assertEquals("Bearer session", transport.sent("POST /api/auth/sign-out").single().headers["Authorization"]) + } + + @Test + fun keepingTheSameSessionRevokesNothing() = runTest { + val transport = connecting(RegressionTransport()) + val model = model(transport, backgroundScope) + model.token = "session" + model.serverURL = BASE + model.saveSettings() + runCurrent() + + assertTrue(transport.sent("POST /api/auth/sign-out").isEmpty()) + } + + @Test + fun aFailedRevokeDoesNotUndoTheNewConnection() = runTest { + val transport = connecting(RegressionTransport()) + transport.responses["POST /api/auth/sign-out"] = 503 to """{"error":"down"}""" + val model = model(transport, backgroundScope) + model.token = "session" + model.serverURL = BASE + model.email = "me@example.com" + model.password = "secret" + model.saveSettings() + runCurrent() + + assertEquals("next", model.client?.token) + assertEquals("", model.errorText) + } + + // OAuth return + + @Test + fun aCallbackWithNoSignInWaitingSaysSo() = runTest { + val transport = RegressionTransport() + val model = model(transport, backgroundScope) + model.handleOAuthCallback("dev.crumble.android:/oauth/callback?code=c&state=x") + runCurrent() + assertTrue(transport.requests.isEmpty()) + assertTrue(model.errorText.isNotEmpty()) + } + + // Panels and the bot list + + @Test + fun reconnectingFromAPanelStaysOnThePanel() = runTest { + val transport = connecting(RegressionTransport()) + val model = model(transport, backgroundScope) + model.token = "session" + model.serverURL = BASE + model.navigate(Route.Memory) + runCurrent() + val reads = transport.sent("GET /v1/memories").size + model.saveSettings() + runCurrent() + + assertEquals(Route.Memory, model.route) + assertEquals("a1", model.selectedAgentID) + assertTrue(transport.sent("GET /v1/memories").size > reads) + } + + // Job questions + + @Test + fun aJobListThatLandsAfterASessionChangeIsDropped() = runTest { + val transport = connecting(RegressionTransport()) + transport.responses["GET /v1/agents/a1/coding-jobs"] = 200 to """{"jobs":[{"name":"old","conversationId":"c","status":"idle"}]}""" + transport.responses["GET /v1/agents/a1/desktop-jobs"] = 200 to """{"jobs":[]}""" + transport.responses["POST /v1/agents/a1/coding-jobs/fix/answer"] = 200 to """{"answered":true}""" + val model = model(transport, backgroundScope) + model.token = "session" + model.serverURL = BASE + model.selectAgent("a1") + model.openJob(JobRef(JobKind.coding, "fix")) + runCurrent() + val late = transport.hold("GET /v1/agents/a1/coding-jobs") + model.answerJobQuestion("fix", "q1", "That one") + runCurrent() + + transport.held.clear() + transport.responses["GET /v1/agents/a1/coding-jobs"] = 200 to """{"jobs":[]}""" + model.email = "me@example.com" + model.password = "secret" + model.saveSettings() + runCurrent() + model.selectAgent("a1") + runCurrent() + late.complete(Unit) + runCurrent() + assertTrue(model.jobs.none { it.name == "old" }) + } +} diff --git a/app/src/test/java/dev/crumble/android/DraftsAndReadsTests.kt b/app/src/test/java/dev/crumble/android/DraftsAndReadsTests.kt new file mode 100644 index 0000000..fdf715a --- /dev/null +++ b/app/src/test/java/dev/crumble/android/DraftsAndReadsTests.kt @@ -0,0 +1,632 @@ +package dev.crumble.android + +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.ChatSnapshot +import dev.crumble.android.model.CrumbleJson +import dev.crumble.android.model.MCPDraft +import dev.crumble.android.model.MCPServer +import dev.crumble.android.model.Memory +import dev.crumble.android.model.MemoryDraft +import dev.crumble.android.model.Message +import dev.crumble.android.model.MessageDeliveryState +import dev.crumble.android.model.PendingAttachment +import dev.crumble.android.model.Route +import dev.crumble.android.model.Schedule +import dev.crumble.android.model.mentionableBots +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import dev.crumble.android.storage.InMemoryCredentialStore +import java.io.ByteArrayInputStream +import java.nio.charset.StandardCharsets +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +private const val SERVER = "https://crumble.example" +private const val SEND = "POST /v1/agents/a1/messages" +private const val BUSY = """{"error":"busy"}""" + +/** Answers from `responses`; a held request waits until the test releases it. */ +private class Scripted : HttpTransport { + val requests = mutableListOf() + val responses = mutableMapOf>() + val held = mutableMapOf>() + + init { + responses["GET /v1/agents/a1/chat?limit=5"] = 200 to snapshotFixture(ChatSnapshot(agentId = "a1", status = "idle")) + responses["GET /v1/agents/a2/chat?limit=5"] = 200 to snapshotFixture(ChatSnapshot(agentId = "a2", status = "idle")) + responses["GET /v1/agents"] = 200 to "[${agentFixture("a1", "Ada")},${agentFixture("a2", "Kev")}]" + responses["GET /v1/memories"] = 200 to "[]" + responses["GET /v1/agents/a1/memories"] = 200 to "[]" + responses["GET /v1/agents/a2/memories"] = 200 to "[]" + responses[SEND] = 202 to executionFixture + } + + fun hold(key: String) = CompletableDeferred().also { held[key] = it } + fun sent(key: String) = requests.filter { "${it.method} ${it.pathWithQuery}" == key } + + fun requestIDs() = sent(SEND).map { request -> + val body = CrumbleJson.parseToJsonElement(String(request.body!!, StandardCharsets.UTF_8)) as JsonObject + (body["requestId"] as JsonPrimitive).content + } + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + val key = "${request.method} ${request.pathWithQuery}" + requests.add(request) + held[key]?.await() + val (status, body) = responses[key] ?: (404 to "") + return HttpResponseData(status, body.toByteArray(StandardCharsets.UTF_8)) + } + + override suspend fun openStream(request: HttpRequestData) = + HttpStreamResponse(404, ByteArrayInputStream(ByteArray(0))) +} + +private fun scheduleJson(id: String, name: String) = + """{"id":"$id","agentId":"a1","name":"$name","kind":"prompt","prompt":"Hi","command":null,"timeoutSeconds":600,"notify":false,"eventSourceId":null,"enabled":true,"timezone":"UTC","runAt":null,"cron":"0 9 * * *","nextRunAt":null,"createdAt":"2026-11-05T10:00:00Z","createdByAgentId":null}""" + +private fun scheduleOf(id: String, name: String = "Task") = CrumbleJson.decodeFromString(Schedule.serializer(), scheduleJson(id, name)) + +private val ATTACHMENT = PendingAttachment( + name = "note.txt", + mimeType = "text/plain", + data = "hi".toByteArray(), +) + +@OptIn(ExperimentalCoroutinesApi::class) +class DraftsAndReadsTests { + private val scopes = mutableListOf() + + /** Chat streams retry forever, so a failed assertion must still stop them or the test never ends. */ + private fun scenario(body: suspend TestScope.() -> Unit) = runTest { + try { + body() + } finally { + scopes.forEach { it.cancel() } + } + } + + private fun TestScope.model(transport: Scripted) = AppModel( + client = APIClient(SERVER, "session", transport), + credentials = InMemoryCredentialStore(), + scope = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler)).also { scopes.add(it) }, + transport = transport, + ) + + private fun TestScope.openChat(model: AppModel, id: String = "a1") { + model.selectAgent(id) + runCurrent() + } + + // Drafts + + @Test + fun returningFromAPanelKeepsTheComposer() = scenario { + val model = model(Scripted()) + openChat(model) + val reply = Message(id = "r", entryId = "a1:1", role = "assistant", content = JsonPrimitive("Hi")) + model.draft = "half written" + model.attachments = listOf(ATTACHMENT) + model.replyTo = reply + + model.navigate(Route.Memory) + runCurrent() + model.navigate(Route.AgentChat("a1")) + runCurrent() + + assertEquals("half written", model.draft) + assertEquals(listOf(ATTACHMENT), model.attachments) + assertEquals(reply, model.replyTo) + } + + @Test + fun eachBotKeepsItsOwnDraft() = scenario { + val model = model(Scripted()) + openChat(model) + model.draft = "for Ada" + model.attachments = listOf(ATTACHMENT) + + openChat(model, "a2") + assertEquals("", model.draft) + assertTrue(model.attachments.isEmpty()) + model.draft = "for Kev" + + openChat(model, "a1") + assertEquals("for Ada", model.draft) + assertEquals(listOf(ATTACHMENT), model.attachments) + + openChat(model, "a2") + assertEquals("for Kev", model.draft) + assertTrue(model.attachments.isEmpty()) + } + + @Test + fun anotherAccountStartsWithEmptyDrafts() = scenario { + val model = model(Scripted()) + openChat(model) + model.draft = "for Ada" + openChat(model, "a2") + model.draft = "for Kev" + model.token = "session" + + model.signOut() + runCurrent() + assertEquals("", model.draft) + + openChat(model) + assertEquals("", model.draft) + } + + @Test + fun aBotDeletedForGoodLeavesNoDraft() = scenario { + val transport = Scripted().apply { responses["DELETE /v1/agents/a1"] = 204 to "" } + val model = model(transport) + model.agents = listOf(Agent(id = "a1", name = "Ada"), Agent(id = "a2", name = "Kev")) + openChat(model) + model.draft = "for Ada" + + model.deleteSelected() + runCurrent() + assertEquals("", model.draft) + + openChat(model, "a1") + assertEquals("", model.draft) + } + + // Retrying a failed send + + @Test + fun sendingARestoredDraftRetriesWithTheSameRequestID() = scenario { + val transport = Scripted().apply { responses[SEND] = 500 to BUSY } + val model = model(transport) + openChat(model) + model.draft = "only once" + model.attachments = listOf(ATTACHMENT) + model.sendMessage() + runCurrent() + + assertEquals("only once", model.draft) + assertEquals(listOf(ATTACHMENT), model.attachments) + transport.responses[SEND] = 202 to executionFixture + model.sendMessage() + runCurrent() + + assertEquals(1, transport.requestIDs().toSet().size) + assertEquals(2, transport.requestIDs().size) + assertEquals(1, model.messages.count { it.text == "only once" }) + assertEquals(MessageDeliveryState.sending, model.messages.single().deliveryState) + assertEquals("", model.draft) + assertTrue(model.attachments.isEmpty()) + } + + @Test + fun anEditedDraftIsANewMessage() = scenario { + val transport = Scripted().apply { responses[SEND] = 500 to BUSY } + val model = model(transport) + openChat(model) + model.draft = "first try" + model.sendMessage() + runCurrent() + + transport.responses[SEND] = 202 to executionFixture + model.draft = "second thoughts" + model.sendMessage() + runCurrent() + + assertEquals(2, transport.requestIDs().toSet().size) + assertEquals(MessageDeliveryState.failed, model.messages.first { it.text == "first try" }.deliveryState) + } + + @Test + fun aSnapshotConfirmingAFailedSendClearsTheRestoredDraft() = scenario { + val transport = Scripted().apply { responses[SEND] = 500 to BUSY } + val model = model(transport) + openChat(model) + model.draft = "arrived anyway" + model.sendMessage() + runCurrent() + val requestID = transport.requestIDs().single() + + model.applySnapshot( + ChatSnapshot( + agentId = "a1", + status = "idle", + messages = listOf(Message(id = "a1:1:0", entryId = "a1:1", role = "user", content = JsonPrimitive("arrived anyway"), requestId = requestID)), + ), + ) + + assertEquals("", model.draft) + model.sendMessage() + runCurrent() + assertEquals(1, transport.sent(SEND).size) + } + + @Test + fun aSendFailingAfterReturningToTheBotStillFailsItsRow() = scenario { + val transport = Scripted() + val gate = transport.hold(SEND) + val model = model(transport) + openChat(model) + model.draft = "slow" + model.sendMessage() + runCurrent() + + model.navigate(Route.Memory) + runCurrent() + model.navigate(Route.AgentChat("a1")) + runCurrent() + transport.responses[SEND] = 500 to BUSY + gate.complete(Unit) + runCurrent() + + assertEquals(MessageDeliveryState.failed, model.messages.single { it.text == "slow" }.deliveryState) + assertEquals("slow", model.draft) + } + + @Test + fun aSendFailingWhileOnAnotherBotRestoresItsDraftThere() = scenario { + val transport = Scripted() + val gate = transport.hold(SEND) + val model = model(transport) + openChat(model) + model.draft = "slow" + model.sendMessage() + runCurrent() + + openChat(model, "a2") + model.draft = "for Kev" + transport.responses[SEND] = 500 to BUSY + gate.complete(Unit) + runCurrent() + assertEquals("for Kev", model.draft) + + openChat(model, "a1") + assertEquals("slow", model.draft) + assertEquals(MessageDeliveryState.failed, model.messages.single { it.text == "slow" }.deliveryState) + } + + // Panel reads + + @Test + fun aPageLoadsDuringAnUnrelatedSlowSave() = scenario { + val transport = Scripted().apply { + responses["GET /v1/memories"] = 200 to "[${memoryFixture("m1", "Fresh")}]" + responses["PATCH /v1/agents/a1"] = 200 to agentFixture("a1", "Ada") + hold("PATCH /v1/agents/a1") + } + val model = model(transport) + model.agents = listOf(Agent(id = "a1", name = "Ada", provider = "openai", model = "gpt", tools = listOf("memory"))) + model.openEditor("a1") + model.saveAgentEditor() + runCurrent() + assertTrue(model.pendingMutations.isNotEmpty()) + + model.openPanel(Route.Memory) + runCurrent() + + assertEquals(listOf("Fresh"), model.sharedMemories.map { it.content }) + } + + @Test + fun aReadKeepsOnlyTheRecordsBeingChanged() = scenario { + val transport = Scripted().apply { + responses["GET /v1/memories"] = 200 to "[${memoryFixture("edited", "Server")},${memoryFixture("deleted", "Server")},${memoryFixture("other", "Fresh")}]" + responses["PATCH /v1/memories/edited"] = 200 to memoryFixture("edited", "Mine") + hold("PATCH /v1/memories/edited") + hold("DELETE /v1/memories/deleted") + } + val model = model(transport) + model.route = Route.Memory + model.sharedMemories = listOf( + Memory(id = "edited", content = "Before"), + Memory(id = "deleted", content = "Before"), + Memory(id = "other", content = "Stale"), + ) + model.memoryDraft = MemoryDraft(memoryID = "edited", content = "Mine") + model.saveMemory() + model.deleteMemory("deleted") + runCurrent() + + model.openPanel(Route.Memory) + runCurrent() + + assertEquals(listOf("edited" to "Mine", "other" to "Fresh"), model.sharedMemories.map { it.id to it.content }) + } + + @Test + fun aReadOverlappingAConfirmedChangeFetchesAgain() = scenario { + val transport = Scripted().apply { + responses["POST /v1/memories"] = 200 to memoryFixture("m1", "Saved") + } + val model = model(transport) + model.route = Route.Memory + val read = transport.hold("GET /v1/memories") + model.openPanel(Route.Memory) + runCurrent() + + model.memoryDraft = MemoryDraft(memoryID = "", content = "Saved") + model.saveMemory() + runCurrent() + assertEquals(listOf("m1"), model.sharedMemories.map { it.id }) + + val second = transport.hold("GET /v1/memories") + read.complete(Unit) + runCurrent() + assertEquals(2, transport.sent("GET /v1/memories").size) + assertEquals(listOf("m1"), model.sharedMemories.map { it.id }) + + transport.responses["GET /v1/memories"] = 200 to "[${memoryFixture("m1", "Saved")},${memoryFixture("m2", "Another client")}]" + second.complete(Unit) + runCurrent() + assertEquals(listOf("m1", "m2"), model.sharedMemories.map { it.id }) + } + + @Test + fun aCreateSeenByAReadBeforeItsSaveAnswersShowsOnce() = scenario { + val transport = Scripted().apply { + responses["POST /v1/memories"] = 200 to memoryFixture("m1", "Saved") + responses["GET /v1/memories"] = 200 to "[${memoryFixture("m1", "Saved")}]" + } + val save = transport.hold("POST /v1/memories") + val model = model(transport) + model.route = Route.Memory + model.memoryDraft = MemoryDraft(memoryID = "", content = "Saved") + model.saveMemory() + runCurrent() + + model.openPanel(Route.Memory) + runCurrent() + save.complete(Unit) + runCurrent() + + assertEquals(listOf("m1"), model.sharedMemories.map { it.id }) + } + + @Test + fun tasksLoadDuringAnUnrelatedSaveAndKeepTheOneBeingEdited() = scenario { + val transport = Scripted().apply { + responses["GET /v1/schedules"] = 200 to "[${scheduleJson("s1", "Server")},${scheduleJson("s2", "Fresh")}]" + responses["PATCH /v1/schedules/s1"] = 200 to scheduleJson("s1", "Mine") + hold("PATCH /v1/schedules/s1") + } + val model = model(transport) + model.route = Route.Tasks + model.agents = listOf(Agent(id = "a1", name = "Ada")) + model.schedules = listOf(scheduleOf("s1", "Before")) + model.openTaskForm("s1") + model.taskDraft = model.taskDraft!!.copy(name = "Mine") + model.saveTask() + runCurrent() + + model.openPanel(Route.Tasks) + runCurrent() + + assertEquals(listOf("Mine", "Fresh"), model.schedules.map { it.name }) + } + + @Test + fun refreshingDuringAnUnrelatedSaveStillLoadsBots() = scenario { + val transport = Scripted().apply { + responses["PATCH /v1/memories/m1"] = 200 to memoryFixture("m1", "Mine") + hold("PATCH /v1/memories/m1") + } + val model = model(transport) + model.sharedMemories = listOf(Memory(id = "m1", content = "Before")) + model.memoryDraft = MemoryDraft(memoryID = "m1", content = "Mine") + model.saveMemory() + runCurrent() + + model.refresh() + runCurrent() + + assertEquals(listOf("a1", "a2"), model.agents.map { it.id }) + assertEquals("a1", model.selectedAgentID) + } + + // Server scope + + @Test + fun aLateBotApprovalStaysOnItsServer() = scenario { + val transport = Scripted().apply { + responses["POST /v1/agents/a1/bot-requests/b1/approve"] = 200 to """{"request":${botRequestFixture("approved")},"agent":${agentFixture("created", "Old server")}}""" + } + val gate = transport.hold("POST /v1/agents/a1/bot-requests/b1/approve") + val model = model(transport) + openChat(model) + model.token = "session" + model.decideBotRequest("b1", approve = true) + runCurrent() + assertEquals(1, transport.sent("POST /v1/agents/a1/bot-requests/b1/approve").size) + + model.signOut() + runCurrent() + gate.complete(Unit) + runCurrent() + + assertTrue(model.agents.none { it.id == "created" }) + } + + @Test + fun attachmentImagesDoNotOutliveTheSession() = scenario { + val transport = Scripted().apply { + responses["GET /v1/agents/a1/attachments/a1%3A1/0"] = 200 to "image" + } + val model = model(transport) + openChat(model) + model.loadAttachmentImage("a1:1", 0) + assertEquals(1, model.attachmentBytes.size) + model.token = "session" + + model.signOut() + runCurrent() + + assertTrue(model.attachmentBytes.isEmpty()) + } + + // Rollback + + @Test + fun aFailedBotDeleteRestoresUnsavedProfileEdits() = scenario { + val transport = Scripted().apply { responses["DELETE /v1/agents/a1"] = 500 to BUSY } + val model = model(transport) + model.agents = listOf(Agent(id = "a1", name = "Ada"), Agent(id = "a2", name = "Kev")) + openChat(model) + model.openEditor("a1") + val edits = model.agentDraft!!.copy(name = "Unsaved") + model.agentDraft = edits + + model.deleteSelected() + assertNull(model.agentDraft) + runCurrent() + + assertEquals(edits, model.agentDraft) + assertEquals("a1", model.selectedAgentID) + } + + @Test + fun aFailedTaskSaveKeepsTheTaskInPlace() = scenario { + val transport = Scripted().apply { responses["PATCH /v1/schedules/s1"] = 500 to BUSY } + val model = model(transport) + model.route = Route.Tasks + model.agents = listOf(Agent(id = "a1", name = "Ada")) + model.schedules = listOf(scheduleOf("s1"), scheduleOf("s2")) + model.openTaskForm("s1") + model.taskDraft = model.taskDraft!!.copy(name = "Renamed") + model.saveTask() + runCurrent() + + assertEquals(listOf("s1", "s2"), model.schedules.map { it.id }) + assertEquals("Task", model.schedules.first().name) + } + + @Test + fun aFailedServerSaveKeepsTheServerInPlace() = scenario { + val transport = Scripted().apply { responses["PATCH /v1/mcp-servers/m1"] = 500 to BUSY } + val model = model(transport) + model.route = Route.Integrations + model.mcpServers = listOf( + MCPServer(id = "m1", name = "One", url = "https://one.example"), + MCPServer(id = "m2", name = "Two", url = "https://two.example"), + ) + model.openMCPForm("m1") + model.mcpDraft = model.mcpDraft!!.copy(name = "Renamed") + model.saveMCP() + runCurrent() + + assertEquals(listOf("m1", "m2"), model.mcpServers.map { it.id }) + assertEquals("One", model.mcpServers.first().name) + } + + @Test + fun aFailedBotSaveKeepsChangesConfirmedMeanwhile() = scenario { + val transport = Scripted().apply { + responses["PATCH /v1/agents/a1"] = 500 to BUSY + hold("PATCH /v1/agents/a1") + } + val gate = transport.held.getValue("PATCH /v1/agents/a1") + val model = model(transport) + model.agents = listOf(Agent(id = "a1", name = "Ada", provider = "openai", model = "gpt", description = "Before", sharedSkills = listOf("s1"), lastMessage = "Old")) + model.openEditor("a1") + model.agentDraft = model.agentDraft!!.copy(name = "Renamed") + model.saveAgentEditor() + runCurrent() + assertEquals("Renamed", model.agents.single().name) + + model.agents = model.agents.map { it.copy(sharedSkills = listOf("s1", "s2"), lastMessage = "New", description = "Other client") } + gate.complete(Unit) + runCurrent() + + val bot = model.agents.single() + assertEquals("Ada", bot.name) + assertEquals(listOf("s1", "s2"), bot.sharedSkills) + assertEquals("New", bot.lastMessage) + assertEquals("Other client", bot.description) + } + + // Saves that cannot start + + @Test + fun aSaveThatCannotStartKeepsItsForm() = scenario { + val transport = Scripted().apply { + responses["PATCH /v1/memories/m1"] = 200 to memoryFixture("m1", "First") + hold("PATCH /v1/memories/m1") + } + val model = model(transport) + model.route = Route.Memory + model.sharedMemories = listOf(Memory(id = "m1", content = "Before")) + model.memoryDraft = MemoryDraft(memoryID = "m1", content = "First") + model.saveMemory() + runCurrent() + + val second = MemoryDraft(memoryID = "m1", content = "Second") + model.memoryDraft = second + model.saveMemory() + + assertEquals(second, model.memoryDraft) + assertTrue(model.errorText.isNotEmpty()) + } + + @Test + fun aBusyServerFormDoesNotStayWaiting() = scenario { + val transport = Scripted().apply { hold("PATCH /v1/mcp-servers/m1") } + val model = model(transport) + model.route = Route.Integrations + val server = MCPServer(id = "m1", name = "One", url = "https://one.example") + model.mcpServers = listOf(server) + model.openMCPForm("m1") + model.saveMCP() + runCurrent() + + val form = MCPDraft(serverID = "m1", name = "Again", url = "https://one.example") + model.mcpDraft = form + model.saveMCP() + + assertEquals(form, model.mcpDraft) + assertFalse(model.mcpDraft!!.saving) + } + + // Bot defaults and mentions + + @Test + fun aNewBotStartsWithTheWebsitesTools() = scenario { + val transport = Scripted().apply { responses["POST /v1/agents"] = 201 to agentFixture("created", "New") } + val model = model(transport) + model.createAgent() + model.agentDraft = model.agentDraft!!.copy(name = "New", provider = "openai", model = "gpt") + model.saveAgentEditor() + runCurrent() + + val body = CrumbleJson.parseToJsonElement(String(transport.sent("POST /v1/agents").single().body!!, StandardCharsets.UTF_8)).jsonObject + assertEquals(setOf("memory", "web", "delegate"), body.getValue("tools").jsonArray.map { it.jsonPrimitive.content }.toSet()) + } + + @Test + fun mentionsNeedOnlyTheDelegateTool() { + val ada = Agent(id = "a1", name = "Ada", tools = listOf("delegate"), delegates = emptyList()) + val kev = Agent(id = "a2", name = "Kev", enabled = true) + val asleep = Agent(id = "a3", name = "Zed", enabled = false) + + assertEquals(listOf(kev), mentionableBots(ada, listOf(ada, kev, asleep))) + assertTrue(mentionableBots(ada.copy(tools = listOf("web")), listOf(ada, kev)).isEmpty()) + } +} diff --git a/app/src/test/java/dev/crumble/android/GeneralSettingsTests.kt b/app/src/test/java/dev/crumble/android/GeneralSettingsTests.kt new file mode 100644 index 0000000..1997926 --- /dev/null +++ b/app/src/test/java/dev/crumble/android/GeneralSettingsTests.kt @@ -0,0 +1,455 @@ +package dev.crumble.android + +import dev.crumble.android.generated.GroupChat +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.ChatSnapshot +import dev.crumble.android.model.NotificationSettings +import dev.crumble.android.model.PaletteAction +import dev.crumble.android.model.PaletteSection +import dev.crumble.android.model.Route +import dev.crumble.android.model.ThemeChoice +import dev.crumble.android.model.botStatusLine +import dev.crumble.android.model.paletteSections +import dev.crumble.android.model.replyNotificationsDescription +import dev.crumble.android.model.searchPalette +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import dev.crumble.android.storage.InMemoryCredentialStore +import java.nio.charset.StandardCharsets +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +private const val SERVER = "https://crumble.example" +private const val SAVE_THEME = "POST /api/auth/update-user" +private const val SESSION = "GET /api/auth/get-session" +private const val BOTS = "GET /v1/agents" + +private fun session(theme: String) = """{"user":{"id":"me","role":"user","theme":"$theme"}}""" + +private class SettingsTransport : HttpTransport { + val requests = mutableListOf() + val responses = mutableMapOf( + SESSION to (200 to """{"user":{"id":"me","role":"user"}}"""), + BOTS to (200 to "[]"), + SAVE_THEME to (200 to """{"status":true}"""), + "GET /v1/group-chats" to (200 to """{"groups":[]}"""), + ) + val held = mutableListOf>>>() + + fun hold(key: String) = CompletableDeferred>().also { held.add(key to it) } + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + requests.add(request) + val key = "${request.method} ${request.pathWithQuery}" + val hold = held.firstOrNull { it.first == key } + hold?.let { held.remove(it) } + val (status, body) = hold?.second?.await() ?: responses[key] ?: (503 to """{"error":"unscripted $key"}""") + return HttpResponseData(status, body.toByteArray(StandardCharsets.UTF_8)) + } + + override suspend fun openStream(request: HttpRequestData): HttpStreamResponse = + throw UnsupportedOperationException("streams are not used here") + + fun themesSent() = requests.filter { "${it.method} ${it.pathWithQuery}" == SAVE_THEME }.map { String(it.body!!, StandardCharsets.UTF_8) } +} + +@OptIn(ExperimentalCoroutinesApi::class) +class GeneralSettingsTests { + private fun TestScope.model( + transport: SettingsTransport = SettingsTransport(), + store: InMemoryCredentialStore = InMemoryCredentialStore(), + onChanged: () -> Unit = {}, + ) = AppModel( + client = APIClient(SERVER, "session", transport), + credentials = store, + scope = this, + onNotificationsChanged = onChanged, + ) + + @Test + fun aThemeAppliesBeforeTheServerAnswers() = runTest { + val transport = SettingsTransport() + val store = InMemoryCredentialStore() + val answer = transport.hold(SAVE_THEME) + val model = model(transport, store) + + model.chooseTheme(ThemeChoice.Dark) + runCurrent() + + assertEquals(ThemeChoice.Dark, model.theme) + assertEquals("dark", store.read("theme")) + assertEquals(listOf("""{"theme":"dark"}"""), transport.themesSent()) + + answer.complete(200 to "{}") + runCurrent() + assertEquals(ThemeChoice.Dark, model.theme) + assertEquals("", model.errorText) + } + + @Test + fun aFailedThemeSaveGoesBackAndSaysSo() = runTest { + val transport = SettingsTransport() + val store = InMemoryCredentialStore(mapOf("theme" to "light")) + transport.responses[SAVE_THEME] = 500 to """{"message":"nope"}""" + val model = model(transport, store) + + model.chooseTheme(ThemeChoice.Dark) + runCurrent() + + assertEquals(ThemeChoice.Light, model.theme) + assertEquals("light", store.read("theme")) + assertTrue(model.errorText.isNotEmpty()) + } + + @Test + fun aLateFailureKeepsTheNewerChoiceAndSavesIt() = runTest { + val transport = SettingsTransport() + val first = transport.hold(SAVE_THEME) + val model = model(transport) + + model.chooseTheme(ThemeChoice.Dark) + runCurrent() + model.chooseTheme(ThemeChoice.Light) + runCurrent() + assertEquals(1, transport.themesSent().size) + + first.complete(500 to "{}") + runCurrent() + + assertEquals(ThemeChoice.Light, model.theme) + assertEquals("", model.errorText) + assertEquals("""{"theme":"light"}""", transport.themesSent().last()) + } + + @Test + fun theAccountsThemeArrivesWithTheSession() = runTest { + val transport = SettingsTransport() + val store = InMemoryCredentialStore() + transport.responses[SESSION] = 200 to session("dark") + val model = model(transport, store) + + model.refresh() + runCurrent() + + assertEquals(ThemeChoice.Dark, model.theme) + assertEquals("dark", store.read("theme")) + } + + @Test + fun aSessionReadStartedBeforeAChoiceCannotUndoIt() = runTest { + val transport = SettingsTransport() + val read = transport.hold(SESSION) + val model = model(transport) + + model.refresh() + runCurrent() + model.chooseTheme(ThemeChoice.Dark) + runCurrent() + read.complete(200 to session("light")) + runCurrent() + + assertEquals(ThemeChoice.Dark, model.theme) + } + + @Test + fun anUnknownAccountThemeIsIgnored() = runTest { + val transport = SettingsTransport() + transport.responses[SESSION] = 200 to session("sepia") + val model = model(transport, InMemoryCredentialStore(mapOf("theme" to "dark"))) + + model.refresh() + runCurrent() + + assertEquals(ThemeChoice.Dark, model.theme) + } + + @Test + fun signedOutThemesStayOnTheDevice() = runTest { + val transport = SettingsTransport() + val store = InMemoryCredentialStore() + val model = AppModel(client = APIClient(SERVER, "", transport), credentials = store, scope = this) + + model.chooseTheme(ThemeChoice.Light) + runCurrent() + + assertEquals(ThemeChoice.Light, model.theme) + assertEquals("light", store.read("theme")) + assertTrue(transport.themesSent().isEmpty()) + } + + @Test + fun aSaveInterruptedBySignOutDoesNotBlockTheNextOne() = runTest { + val transport = SettingsTransport() + transport.responses["POST /api/auth/sign-in/email"] = 200 to """{"token":"next"}""" + transport.hold(SAVE_THEME) + val model = AppModel( + client = APIClient(SERVER, "session", transport), + scope = backgroundScope, + transport = transport, + ) + model.serverURL = SERVER + + model.chooseTheme(ThemeChoice.Dark) + runCurrent() + model.signOut() + runCurrent() + model.email = "me@example.com" + model.password = "secret" + model.saveSettings() + runCurrent() + model.chooseTheme(ThemeChoice.Light) + runCurrent() + + assertEquals("""{"theme":"light"}""", transport.themesSent().last()) + } + + @Test + fun notificationChoicesDefaultOnPersistAndReachTheActivity() = runTest { + val store = InMemoryCredentialStore() + var changes = 0 + val model = model(store = store, onChanged = { changes += 1 }) + + assertTrue(model.replyNotifications) + assertTrue(model.notificationSound) + + model.changeReplyNotifications(false) + model.changeNotificationSound(false) + + assertEquals(1, changes) + assertFalse(NotificationSettings(store).replies) + assertFalse(NotificationSettings(store).sound) + assertFalse(model(store = store).replyNotifications) + assertFalse(model(store = store).notificationSound) + } + + @Test + fun theReplyRowExplainsWhyNothingShows() { + assertEquals("Replies from chats you don't have open show as notifications.", replyNotificationsDescription(true, true)) + assertEquals("Off on this device.", replyNotificationsDescription(false, true)) + assertEquals("Blocked for Crumble in Android's settings.", replyNotificationsDescription(true, false)) + assertEquals("Blocked for Crumble in Android's settings.", replyNotificationsDescription(false, false)) + } +} + +@OptIn(ExperimentalCoroutinesApi::class) +class HomeTests { + private fun TestScope.model(transport: SettingsTransport) = + AppModel(client = APIClient(SERVER, "session", transport), scope = backgroundScope) + + @Test + fun theStatusLineLeadsWithWork() { + val bot = Agent(id = "a", enabled = true, description = "Reads the mail") + assertEquals("Working…", botStatusLine(bot, true)) + assertEquals("Reads the mail", botStatusLine(bot, false)) + assertEquals("Ready", botStatusLine(bot.copy(description = ""), false)) + assertEquals("Paused", botStatusLine(bot.copy(enabled = false), false)) + } + + @Test + fun startingUpStaysHomeWithoutOpeningAChat() = runTest { + val transport = SettingsTransport() + transport.responses[BOTS] = 200 to """[${agentFixture("a1")},${agentFixture("a2")}]""" + val model = model(transport) + + model.refresh() + runCurrent() + + assertNull(model.route) + assertEquals(listOf("a1", "a2"), model.agents.map { it.id }) + assertTrue(transport.requests.none { it.pathWithQuery.contains("/chat") }) + } + + @Test + fun aDeletedBotLeavesNoStaleSelectionOnHome() = runTest { + val transport = SettingsTransport() + transport.responses[BOTS] = 200 to """[${agentFixture("a2")}]""" + val model = model(transport) + model.agents = listOf(Agent(id = "a1"), Agent(id = "a2")) + model.selectAgent("a1") + model.navigate(null) + + model.refresh() + runCurrent() + + assertEquals("a2", model.selectedAgent?.id) + assertNull(model.route) + } + + @Test + fun aRefreshKeepsAnOpenChatOpen() = runTest { + val transport = SettingsTransport() + transport.responses[BOTS] = 200 to """[${agentFixture("a1")}]""" + val model = model(transport) + model.agents = listOf(Agent(id = "a1")) + model.selectAgent("a1") + + model.refresh() + runCurrent() + + assertEquals(Route.AgentChat("a1"), model.route) + } + + @Test + fun goingHomeLeavesThePage() = runTest { + val model = model(SettingsTransport()) + model.route = Route.Memory + + model.navigate(null) + + assertNull(model.route) + } + + @Test + fun homeReadsEveryBotsLiveStatus() = runTest { + val transport = SettingsTransport() + transport.responses["GET /v1/agents/a1/chat?limit=1"] = + 200 to snapshotFixture(ChatSnapshot(agentId = "a1", status = "running")) + transport.responses["GET /v1/agents/a2/chat?limit=1"] = + 200 to snapshotFixture(ChatSnapshot(agentId = "a2", status = "idle")) + val model = model(transport) + model.agents = listOf(Agent(id = "a1", enabled = true), Agent(id = "a2", enabled = true)) + + model.refreshBotStatuses() + + assertTrue(model.isWorking("a1")) + assertFalse(model.isWorking("a2")) + } +} + +class CommandPaletteTests { + private val bots = listOf( + Agent(id = "a1", name = "Atlas", enabled = true), + Agent(id = "a2", name = "Atlas", enabled = false), + Agent(id = "pending:1", name = "Saving", enabled = true), + ) + private val groups = listOf( + GroupChat("g1", "Family", listOf("a1", "a2"), "t", "t"), + GroupChat("pending:2", "Unsaved", listOf("a1", "a2"), "t", "t"), + ) + + private fun sections(agents: List = bots, admin: Boolean = false, theme: ThemeChoice = ThemeChoice.System) = + paletteSections(agents, groups, admin, theme) + + private fun titles(list: List, heading: String) = + list.firstOrNull { it.heading == heading }?.items?.map { it.title }.orEmpty() + + @Test + fun itOffersWhatTheWebsiteOffers() { + val all = sections() + assertEquals(listOf("Bots", "Group chats", "Create", "Workspace", "Settings", "Theme"), all.map { it.heading }) + assertEquals(listOf("Family"), titles(all, "Group chats")) + assertEquals(listOf("New bot", "New group chat"), titles(all, "Create")) + assertEquals("General", titles(all, "Settings").first()) + assertEquals(listOf("System theme", "Light theme", "Dark theme"), titles(all, "Theme")) + } + + @Test + fun unsavedRecordsStayOut() { + assertEquals(listOf("a1", "a2"), sections().first().items.map { (it.action as PaletteAction.OpenBot).id }) + } + + @Test + fun pausedBotsAndTheCurrentThemeAreMarked() { + val all = sections(theme = ThemeChoice.Dark) + assertEquals(listOf(null, "Paused"), all.first().items.map { it.note }) + assertEquals(listOf(null, null, "Current"), all.last().items.map { it.note }) + } + + @Test + fun usersIsForAdmins() { + assertFalse("Users" in titles(sections(), "Settings")) + assertTrue("Users" in titles(sections(admin = true), "Settings")) + } + + @Test + fun aGroupNeedsTwoBots() { + assertEquals(listOf("New bot"), titles(sections(agents = bots.take(1)), "Create")) + } + + @Test + fun equalNamesBothMatchAndCommandWordsDoNotFindBots() { + assertEquals(2, searchPalette(sections(), "atlas").single().items.size) + assertEquals(emptyList(), titles(searchPalette(sections(), "bot"), "Bots")) + } + + @Test + fun aBlankSearchKeepsEverything() { + assertEquals(sections(), searchPalette(sections(), " ")) + } + + @Test + fun lettersInOrderMatchIgnoringCase() { + assertEquals(listOf("Providers"), titles(searchPalette(sections(), "PRVD"), "Settings")) + assertTrue(searchPalette(sections(), "zzzz").isEmpty()) + } + + @Test + fun theBestMatchLeads() { + val found = searchPalette(sections(), "memory") + assertEquals("Memory", found.first().items.first().title) + val ranked = searchPalette(sections(), "web") + assertEquals(listOf("Settings"), ranked.map { it.heading }.take(1)) + assertEquals("Web search", ranked.first().items.first().title) + } + + @Test + fun theWebsitesWordsFindTheirAndroidPages() { + assertEquals(listOf("Automations"), titles(searchPalette(sections(), "automations"), "Workspace")) + assertEquals(listOf("Dark theme"), titles(searchPalette(sections(), "theme dark"), "Theme")) + assertEquals(listOf("Dark theme"), titles(searchPalette(sections(), "dark theme"), "Theme")) + assertEquals("Providers", titles(searchPalette(sections(), "settings prov"), "Settings").first()) + } +} + +@OptIn(ExperimentalCoroutinesApi::class) +class CommandPaletteActionTests { + private fun TestScope.model(): AppModel { + val model = AppModel(client = APIClient(SERVER, "session", SettingsTransport()), scope = backgroundScope) + model.showingPalette = true + return model + } + + @Test + fun aPageOpensAndThePaletteCloses() = runTest { + val model = model() + model.runPalette(PaletteAction.OpenPage(Route.Activity)) + assertEquals(Route.Activity, model.route) + assertFalse(model.showingPalette) + } + + @Test + fun generalOpensItsSettingsPage() = runTest { + val model = model() + model.runPalette(PaletteAction.OpenPage(Route.General)) + assertEquals(Route.General, model.route) + } + + @Test + fun creatingOpensTheForms() = runTest { + val model = model() + model.runPalette(PaletteAction.NewBot) + assertTrue(model.agentDraft?.isNew == true) + model.runPalette(PaletteAction.NewGroup) + assertEquals(Route.NewGroup, model.route) + } + + @Test + fun aThemeChangesInPlace() = runTest { + val model = model() + model.runPalette(PaletteAction.SetTheme(ThemeChoice.Dark)) + assertEquals(ThemeChoice.Dark, model.theme) + assertFalse(model.showingPalette) + } +} diff --git a/app/src/test/java/dev/crumble/android/GeneratedContractTests.kt b/app/src/test/java/dev/crumble/android/GeneratedContractTests.kt index 1a1478e..d6dd87f 100644 --- a/app/src/test/java/dev/crumble/android/GeneratedContractTests.kt +++ b/app/src/test/java/dev/crumble/android/GeneratedContractTests.kt @@ -64,7 +64,7 @@ class GeneratedContractTests { assertEquals(status, error.statusCode) assertEquals("DELETE", error.method) assertEquals("/v1/agents/a1", error.path) - assertEquals(if (status == 401) "Authentication failed. Check the server token in Settings." else "Invalid request: Choose a bot", friendlyError(error)) + assertEquals(if (status == 401) "Authentication failed. Sign in again in Settings." else "Invalid request: Choose a bot", friendlyError(error)) assertEquals("Bearer owner", transport.requests.single().headers["Authorization"]) } } diff --git a/app/src/test/java/dev/crumble/android/GroupChatTests.kt b/app/src/test/java/dev/crumble/android/GroupChatTests.kt new file mode 100644 index 0000000..f98bc0a --- /dev/null +++ b/app/src/test/java/dev/crumble/android/GroupChatTests.kt @@ -0,0 +1,799 @@ +package dev.crumble.android + +import dev.crumble.android.generated.GroupActivity +import dev.crumble.android.generated.GroupChat +import dev.crumble.android.generated.GroupMemberActivity +import dev.crumble.android.model.ActivityEvent +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.ChatHistoryResponse +import dev.crumble.android.model.ChatRow +import dev.crumble.android.model.CrumbleJson +import dev.crumble.android.model.GroupConversation +import dev.crumble.android.model.GroupDraft +import dev.crumble.android.model.GroupSnapshot +import dev.crumble.android.model.Message +import dev.crumble.android.model.MessageDeliveryState +import dev.crumble.android.model.MessageOrigin +import dev.crumble.android.model.MessageSource +import dev.crumble.android.model.NotificationContext +import dev.crumble.android.model.PendingAttachment +import dev.crumble.android.model.Route +import dev.crumble.android.model.groupReactions +import dev.crumble.android.model.groupReplyLabel +import dev.crumble.android.model.groupSourcesOf +import dev.crumble.android.model.groupStatusLine +import dev.crumble.android.model.isGroupRunning +import dev.crumble.android.model.isValidGroup +import dev.crumble.android.model.memberStatusLabel +import dev.crumble.android.model.membersOf +import dev.crumble.android.model.notification +import dev.crumble.android.model.shownInGroup +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import dev.crumble.android.push.parsePushReplyData +import java.io.ByteArrayInputStream +import java.nio.charset.StandardCharsets +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test + +private const val G1 = "11111111-1111-4111-8111-111111111111" +private const val G2 = "22222222-2222-4222-8222-222222222222" +private const val BASE = "/v1/group-chats" +private const val RECONNECTING = "Reconnecting…" + +private fun groupJson(id: String = G1, name: String = "Team", members: List = listOf("a1", "a2")) = + """{"id":"$id","name":"$name","memberIds":[${members.joinToString(",") { "\"$it\"" }}],"createdAt":"t","updatedAt":"t"}""" + +private fun row(entry: Int, group: String = G1, role: String = "user", text: String = "m$entry", requestId: String? = null) = + """{"id":"$group:$entry:0","entryId":"$group:$entry","role":"$role","content":"$text"${requestId?.let { ",\"requestId\":\"$it\"" } ?: ""}}""" + +private fun snapshotJson( + rows: List = emptyList(), + group: String = groupJson(), + hasMore: Boolean = false, + oldest: String? = null, + members: String = "", +) = """{"messages":[${rows.joinToString(",")}],"hasMore":$hasMore,"oldestEntryId":${oldest?.let { "\"$it\"" } ?: "null"},"groupChat":$group,"activity":{"paused":false,"botTurns":0,"members":[$members]},"updatedAt":1}""" + +private fun bodyOf(request: HttpRequestData) = + CrumbleJson.parseToJsonElement(request.body!!.toString(StandardCharsets.UTF_8)).jsonObject + +/** Answers by "METHOD path", holding back any request whose key is in `held`; streams end at once. */ +private class GroupTransport : HttpTransport { + val requests = mutableListOf() + val held = mutableMapOf>() + val responses = mutableMapOf>( + "GET $BASE" to (200 to "[${groupJson()}]"), + "GET $BASE/$G1/chat" to (200 to snapshotJson()), + "POST $BASE/$G1/messages" to (201 to """{"requestId":"r","entryId":"e"}"""), + "POST $BASE/$G1/stop" to (204 to ""), + "DELETE $BASE/$G1" to (204 to ""), + ) + var bytes = ByteArray(0) + var stream: Pair = 200 to "" + val streams = mutableListOf() + var closedStreams = 0 + + private fun key(request: HttpRequestData) = "${request.method} ${request.pathWithQuery}" + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + requests.add(request) + val key = key(request) + held[key]?.await() + if (bytes.isNotEmpty() && "/attachments/" in key) return HttpResponseData(200, bytes) + val (status, body) = responses[key] ?: (500 to """{"error":"unscripted $key"}""") + return HttpResponseData(status, body.toByteArray(StandardCharsets.UTF_8)) + } + + override suspend fun openStream(request: HttpRequestData): HttpStreamResponse { + streams.add(request.pathWithQuery) + return HttpStreamResponse(stream.first, ByteArrayInputStream(stream.second.toByteArray(StandardCharsets.UTF_8))) { closedStreams += 1 } + } + + fun sent(key: String) = requests.filter { key(it) == key } +} + +private val bots = listOf(Agent(id = "a1", name = "Ada", enabled = true), Agent(id = "a2", name = "Kev", enabled = true)) + +private fun activity(vararg members: Pair) = + GroupActivity(false, 0.0, members.map { GroupMemberActivity(it.first, it.second, null) }) + +private fun snapshot(vararg ids: String, hasMore: Boolean = false, oldest: String? = null) = GroupSnapshot( + ids.map { Message(id = it, entryId = it, role = "user") }, hasMore, oldest, + GroupChat(G1, "Team", listOf("a1", "a2"), "t", "t"), activity(), +) + +@OptIn(ExperimentalCoroutinesApi::class) +class GroupChatTests { + private fun model(scope: TestScope, transport: GroupTransport) = AppModel( + client = APIClient("http://example.com", "token", transport), + scope = scope.backgroundScope, + ).also { it.agents = bots } + + // Streams read on the IO dispatcher. Blocking here matters: a suspended test body lets virtual time run on. + private fun TestScope.until(condition: () -> Boolean) { + repeat(5_000) { + runCurrent() + if (condition()) return + Thread.sleep(1) + } + fail("condition never held") + } + + /** Opens G1, then waits out one stream: it sends the same snapshot and ends, so the model waits to reconnect. */ + private fun TestScope.opened(transport: GroupTransport, rows: List = emptyList()): AppModel { + transport.responses["GET $BASE/$G1/chat"] = 200 to snapshotJson(rows) + transport.stream = 200 to "event: snapshot\ndata: ${snapshotJson(rows)}\n\n" + val app = model(this, transport) + app.groupChats = listOf(GroupChat(G1, "Team", listOf("a1", "a2"), "t", "t")) + app.openGroupChat(G1) + until { app.groupConversation?.streamStatus == RECONNECTING } + return app + } + + /** Lets the model reconnect once and receive `snapshot`. */ + private fun TestScope.nextStream(app: AppModel, transport: GroupTransport, snapshot: String) { + val closed = transport.closedStreams + transport.stream = 200 to "event: snapshot\ndata: $snapshot\n\n" + testScheduler.advanceTimeBy(600) + until { transport.closedStreams > closed && app.groupConversation?.streamStatus == RECONNECTING } + } + + @Test + fun everyOperationUsesItsContractPath() = runTest { + val transport = GroupTransport().apply { + responses["POST $BASE"] = 201 to groupJson() + responses["GET $BASE/$G1"] = 200 to groupJson() + responses["PATCH $BASE/$G1"] = 200 to groupJson(name = "New") + responses["GET $BASE/$G1/history?limit=100&before=e%3A1"] = 200 to """{"messages":[],"hasMore":false,"oldestEntryId":null}""" + stream = 404 to """{"error":"gone"}""" + bytes = byteArrayOf(1, 2) + } + val api = APIClient("http://example.com", "token", transport) + + assertEquals(listOf(G1), api.groupChats().map { it.id }) + assertEquals(G1, api.groupChat(G1).id) + api.createGroupChat("Team", listOf("a1", "a2")) + assertEquals(setOf("name", "memberIds"), bodyOf(transport.sent("POST $BASE").single()).keys) + assertEquals("New", api.updateGroupChat(G1, "New", listOf("a1", "a2")).name) + assertEquals(setOf("name", "memberIds"), bodyOf(transport.sent("PATCH $BASE/$G1").single()).keys) + api.deleteGroupChat(G1) + assertEquals(G1, api.groupSnapshot(G1).groupChat.id) + assertEquals(false, api.groupHistory(G1, "e:1", 100).hasMore) + api.sendGroupMessage(G1, "hi", "r1", "e1") + val sent = bodyOf(transport.sent("POST $BASE/$G1/messages").single()) + assertEquals("r1", sent["requestId"]!!.jsonPrimitive.content) + assertEquals("e1", sent["replyTo"]!!.jsonPrimitive.content) + assertArrayEquals(byteArrayOf(1, 2), api.groupAttachment(G1, "e:1", 0)) + assertEquals("/v1/group-chats/$G1/attachments/e%3A1/0", transport.requests.last().pathWithQuery) + api.stopGroupChat(G1) + val failure = runCatching { api.groupChatEvents(G1) {} }.exceptionOrNull() + assertEquals(404, (failure as dev.crumble.android.network.APIError).statusCode) + assertEquals(listOf("$BASE/$G1/events"), transport.streams) + } + + @Test + fun streamDeliversSnapshotsWithoutAnAgentAndSkipsHeartbeats() = runTest { + val transport = GroupTransport().apply { + stream = 200 to "event: heartbeat\ndata: {}\n\nevent: snapshot\ndata: ${snapshotJson(listOf(row(1)))}\n\n" + } + val received = mutableListOf() + runCatching { APIClient("http://example.com", "token", transport).groupChatEvents(G1) { received.add(it) } } + assertEquals(listOf("$G1:1:0"), received.single().messages.map { it.id }) + } + + @Test + fun liveSnapshotsReachTheOpenChat() = runTest { + val transport = GroupTransport() + val app = opened(transport, listOf(row(1))) + assertEquals(Route.GroupChat(G1), app.route) + assertEquals(listOf("$G1:1:0"), app.groupConversation?.messages?.map { it.id }) + + nextStream(app, transport, snapshotJson(listOf(row(1), row(2)), members = """{"agentId":"a1","status":"running","error":null}""")) + + assertEquals(listOf("$G1:1:0", "$G1:2:0"), app.groupConversation?.messages?.map { it.id }) + assertTrue(isGroupRunning(app.groupConversation?.activity)) + } + + @Test + fun refreshOnGroupRouteDoesNotOpenABotChat() = runTest { + val transport = GroupTransport() + transport.responses["GET /v1/agents"] = 200 to """[${agentFixture("a1")}]""" + val app = opened(transport) + + app.refresh() + runCurrent() + + assertEquals(Route.GroupChat(G1), app.route) + assertNotNull(app.groupConversation) + } + + @Test + fun aDeletedGroupLeavesTheChat() = runTest { + val transport = GroupTransport().apply { responses["GET $BASE/$G1/chat"] = 404 to """{"error":"gone"}""" } + val app = model(this, transport) + app.agents = emptyList() + app.groupChats = listOf(GroupChat(G1, "Team", listOf("a1", "a2"), "t", "t")) + app.updateGroupComposer(G1) { it.copy(draft = "kept") } + app.openGroupChat(G1) + runCurrent() + + assertNull(app.route) + assertNull(app.groupConversation) + assertTrue(app.groupChats.isEmpty()) + assertEquals("", app.groupComposer(G1).draft) + } + + @Test + fun aStreamThatEndsReconnectsAndReportsIt() = runTest { + val transport = GroupTransport() + val app = opened(transport) + assertEquals(RECONNECTING, app.liveStatus) + } + + @Test + fun anExpiredSessionStopsFollowing() = runTest { + val transport = GroupTransport() + val app = opened(transport) + transport.stream = 401 to """{"error":"no"}""" + testScheduler.advanceTimeBy(1_100) + until { app.groupConversation?.streamStatus == "Disconnected" } + assertEquals("Authentication failed. Sign in again in Settings.", app.errorText) + } + + @Test + fun aGroupDeletedElsewhereEndsTheStreamAndLeaves() = runTest { + val transport = GroupTransport() + val app = opened(transport) + app.agents = emptyList() + transport.stream = 404 to """{"error":"gone"}""" + testScheduler.advanceTimeBy(1_100) + until { app.groupConversation == null } + assertNull(app.route) + assertTrue(app.groupChats.isEmpty()) + } + + @Test + fun openingFailureShowsTheErrorAndTheStreamStillRecovers() = runTest { + val transport = GroupTransport().apply { + responses["GET $BASE/$G1/chat"] = 500 to """{"error":"boom"}""" + stream = 200 to "event: snapshot\ndata: ${snapshotJson()}\n\n" + } + val app = model(this, transport) + app.openGroupChat(G1) + until { app.groupConversation?.group != null } + assertNull(app.groupConversation?.loadError) + assertEquals("Team", app.groupConversation?.group?.name) + } + + @Test + fun aLateSnapshotReadIsDroppedAfterLeaving() = runTest { + val gate = CompletableDeferred() + val transport = GroupTransport().apply { held["GET $BASE/$G1/chat"] = gate } + val app = model(this, transport) + app.openGroupChat(G1) + runCurrent() + app.openPanel(Route.Tasks) + gate.complete(Unit) + runCurrent() + + assertEquals(Route.Tasks, app.route) + assertNull(app.groupConversation) + assertTrue(transport.streams.isEmpty()) + } + + @Test + fun createShowsTheGroupAtOnceAndSwapsInTheServerRow() = runTest { + val gate = CompletableDeferred() + val transport = GroupTransport().apply { + held["POST $BASE"] = gate + responses["POST $BASE"] = 201 to groupJson() + stream = 200 to "event: snapshot\ndata: ${snapshotJson()}\n\n" + } + val app = model(this, transport) + app.groupDraft = GroupDraft(name = " Team ", memberIDs = listOf("a1", "a2")) + app.saveGroup() + + assertNull(app.groupDraft) + assertTrue(app.groupChats.single().id.startsWith("pending:")) + assertEquals("Team", app.groupChats.single().name) + + app.refresh() + runCurrent() + assertTrue("a refresh must not drop the pending row", app.groupChats.any { it.id.startsWith("pending:") }) + + gate.complete(Unit) + runCurrent() + assertEquals(listOf(G1), app.groupChats.map { it.id }) + assertEquals(Route.GroupChat(G1), app.route) + } + + @Test + fun aLateCreateKeepsNewerNavigation() = runTest { + val gate = CompletableDeferred() + val transport = GroupTransport().apply { + held["POST $BASE"] = gate + responses["POST $BASE"] = 201 to groupJson() + } + val app = model(this, transport) + app.groupDraft = GroupDraft(name = "Team", memberIDs = listOf("a1", "a2")) + app.saveGroup() + app.openPanel(Route.Activity) + + gate.complete(Unit) + runCurrent() + + assertEquals(Route.Activity, app.route) + assertEquals(listOf(G1), app.groupChats.map { it.id }) + } + + @Test + fun aFailedCreateRemovesTheRowAndRestoresTheForm() = runTest { + val transport = GroupTransport().apply { responses["POST $BASE"] = 400 to """{"error":"List each bot once"}""" } + val app = model(this, transport) + val draft = GroupDraft(name = "Team", memberIDs = listOf("a1", "a2")) + app.groupDraft = draft + app.saveGroup() + runCurrent() + + assertTrue(app.groupChats.isEmpty()) + assertEquals(draft, app.groupDraft) + assertEquals("List each bot once", app.errorText) + } + + @Test + fun anInvalidFormDoesNotSave() = runTest { + val transport = GroupTransport() + val app = model(this, transport) + app.groupDraft = GroupDraft(name = " ", memberIDs = listOf("a1", "a2")) + app.saveGroup() + app.groupDraft = GroupDraft(name = "Team", memberIDs = listOf("a1")) + app.saveGroup() + runCurrent() + assertTrue(transport.requests.isEmpty()) + assertTrue(app.groupChats.isEmpty()) + } + + @Test + fun editAppliesAtOnceAndASnapshotCannotRevertIt() = runTest { + val gate = CompletableDeferred() + val transport = GroupTransport() + val app = opened(transport) + transport.held["PATCH $BASE/$G1"] = gate + transport.responses["PATCH $BASE/$G1"] = 200 to groupJson(name = "Saved", members = listOf("a1", "a2")) + app.groupDraft = GroupDraft(groupID = G1, name = "Renamed", memberIDs = listOf("a1", "a2")) + app.saveGroup() + + assertEquals("Renamed", app.groupChats.single().name) + assertEquals("Renamed", app.groupConversation?.group?.name) + + nextStream(app, transport, snapshotJson()) + assertEquals(2, transport.streams.size) + assertEquals("Renamed", app.groupConversation?.group?.name) + + gate.complete(Unit) + runCurrent() + assertEquals("Saved", app.groupChats.single().name) + assertEquals("Saved", app.groupConversation?.group?.name) + } + + @Test + fun aFailedEditRestoresTheGroupAndTheForm() = runTest { + val transport = GroupTransport() + val app = opened(transport) + transport.responses["PATCH $BASE/$G1"] = 500 to """{"error":"nope"}""" + val draft = GroupDraft(groupID = G1, name = "Renamed", memberIDs = listOf("a1", "a2")) + app.groupDraft = draft + app.saveGroup() + runCurrent() + + assertEquals("Team", app.groupChats.single().name) + assertEquals("Team", app.groupConversation?.group?.name) + assertEquals(draft, app.groupDraft) + assertEquals("nope", app.errorText) + } + + @Test + fun theEditorMovesToTheServerVersionUnlessTheOwnerTyped() = runTest { + val transport = GroupTransport() + val app = opened(transport) + transport.responses["GET $BASE/$G1"] = 200 to groupJson(name = "Elsewhere", members = listOf("a1", "a2", "a3")) + + app.openGroupEditor(G1) + assertEquals("Team", app.groupDraft?.name) + runCurrent() + assertEquals("Elsewhere", app.groupDraft?.name) + assertEquals(listOf("a1", "a2", "a3"), app.groupDraft?.memberIDs) + + val gate = CompletableDeferred() + transport.held["GET $BASE/$G1"] = gate + app.openGroupEditor(G1) + app.groupDraft = app.groupDraft!!.copy(name = "Mine") + gate.complete(Unit) + runCurrent() + assertEquals("Mine", app.groupDraft?.name) + } + + @Test + fun memberTogglesStopAtTheLimit() = runTest { + val app = model(this, GroupTransport()) + app.groupDraft = GroupDraft(memberIDs = listOf("1", "2", "3", "4", "5", "6")) + app.toggleGroupMember("7", true) + assertEquals(6, app.groupDraft!!.memberIDs.size) + app.toggleGroupMember("1", false) + app.toggleGroupMember("7", true) + assertEquals(listOf("2", "3", "4", "5", "6", "7"), app.groupDraft!!.memberIDs) + } + + @Test + fun deleteLeavesAtOnceAndFailureBringsItBack() = runTest { + val gate = CompletableDeferred() + val transport = GroupTransport() + val app = opened(transport) + transport.held["DELETE $BASE/$G1"] = gate + transport.responses["DELETE $BASE/$G1"] = 500 to """{"error":"nope"}""" + app.agents = emptyList() + + app.deleteGroup(G1) + assertTrue(app.groupChats.isEmpty()) + assertNull(app.route) + assertNull(app.groupConversation) + + gate.complete(Unit) + runCurrent() + assertEquals(listOf(G1), app.groupChats.map { it.id }) + assertEquals(Route.GroupChat(G1), app.route) + assertNotNull(app.groupConversation) + assertEquals("nope", app.errorText) + } + + @Test + fun aConfirmedDeleteForgetsTheGroupsLocalState() = runTest { + val transport = GroupTransport() + val app = opened(transport) + app.agents = emptyList() + app.updateGroupComposer(G1) { it.copy(draft = "unsent") } + app.deleteGroup(G1) + runCurrent() + assertTrue(app.groupChats.isEmpty()) + assertEquals("", app.groupComposer(G1).draft) + } + + @Test + fun aSentMessageWaitsForItsSnapshotWithoutDuplicates() = runTest { + val gate = CompletableDeferred() + val transport = GroupTransport() + val app = opened(transport, listOf(row(1))) + val reply = app.groupConversation!!.messages.single() + transport.held["POST $BASE/$G1/messages"] = gate + app.updateGroupComposer(G1) { it.copy(draft = " hello ", replyTo = reply) } + app.sendGroupMessage() + runCurrent() + + assertEquals("", app.groupComposer(G1).draft) + assertNull(app.groupComposer(G1).replyTo) + val pending = app.groupOutgoing[G1]!!.single() + assertEquals("hello", pending.text) + assertEquals(MessageDeliveryState.sending, pending.deliveryState) + assertEquals("m1", pending.replyPreview) + val requestID = pending.requestId!! + assertEquals(reply.entryId, bodyOf(transport.sent("POST $BASE/$G1/messages").single())["replyTo"]!!.jsonPrimitive.content) + + // The confirming snapshot can beat the POST's response. + nextStream(app, transport, snapshotJson(listOf(row(1), row(2, requestId = requestID)))) + assertTrue(app.groupOutgoing[G1].orEmpty().isEmpty()) + assertEquals(2, app.groupConversation!!.messages.size) + + gate.complete(Unit) + runCurrent() + assertTrue(app.groupOutgoing[G1].orEmpty().isEmpty()) + assertNull(app.groupConversation?.sendError) + } + + @Test + fun aTimedOutPostDoesNotReportAMessageTheSnapshotConfirmed() = runTest { + val gate = CompletableDeferred() + val transport = GroupTransport() + val app = opened(transport) + transport.held["POST $BASE/$G1/messages"] = gate + transport.responses["POST $BASE/$G1/messages"] = 500 to """{"error":"timed out"}""" + app.updateGroupComposer(G1) { it.copy(draft = "hello") } + app.sendGroupMessage() + runCurrent() + val requestID = app.groupOutgoing[G1]!!.single().requestId!! + + nextStream(app, transport, snapshotJson(listOf(row(1, requestId = requestID)))) + gate.complete(Unit) + runCurrent() + + assertNull(app.groupConversation?.sendError) + assertTrue(app.groupOutgoing[G1].orEmpty().isEmpty()) + } + + @Test + fun aFailedSendCanBeRetriedWithTheSameRequestAndFiles() = runTest { + val transport = GroupTransport() + val app = opened(transport) + transport.responses["POST $BASE/$G1/messages"] = 500 to """{"error":"down"}""" + val file = PendingAttachment(name = "a.png", mimeType = "image/png", data = byteArrayOf(1)) + app.updateGroupComposer(G1) { it.copy(draft = "hello") } + app.addGroupAttachment(G1, file) + app.sendGroupMessage() + runCurrent() + + val failed = app.groupOutgoing[G1]!!.single() + assertEquals(MessageDeliveryState.failed, failed.deliveryState) + assertEquals("Message was not confirmed: down", app.groupConversation?.sendError) + assertArrayEquals(byteArrayOf(1), app.groupAttachmentImageBytes(failed, 0)) + + transport.responses["POST $BASE/$G1/messages"] = 201 to """{"requestId":"r","entryId":"e"}""" + app.retryGroupMessage(failed) + assertEquals(MessageDeliveryState.sending, app.groupOutgoing[G1]!!.single().deliveryState) + assertNull(app.groupConversation?.sendError) + runCurrent() + + val sends = transport.sent("POST $BASE/$G1/messages").map { bodyOf(it) } + assertEquals(2, sends.size) + assertEquals(sends[0]["requestId"], sends[1]["requestId"]) + assertEquals("a.png", sends[1]["attachments"]!!.jsonArray[0].jsonObject["name"]!!.jsonPrimitive.content) + } + + @Test + fun outgoingMessagesAndDraftsStayScopedToTheirGroup() = runTest { + val gate = CompletableDeferred() + val transport = GroupTransport().apply { + held["POST $BASE/$G1/messages"] = gate + responses["GET $BASE/$G2/chat"] = 200 to snapshotJson(group = groupJson(id = G2, name = "Other")) + } + val app = opened(transport) + app.updateGroupComposer(G1) { it.copy(draft = "to one") } + app.sendGroupMessage() + app.updateGroupComposer(G1) { it.copy(draft = "half written") } + runCurrent() + + transport.stream = 200 to "event: snapshot\ndata: ${snapshotJson(group = groupJson(id = G2, name = "Other"))}\n\n" + app.openGroupChat(G2) + until { app.groupConversation?.group != null } + assertEquals("Other", app.groupConversation?.group?.name) + assertTrue(app.groupOutgoing[G2].orEmpty().isEmpty()) + assertEquals("", app.groupComposer(G2).draft) + + transport.responses["POST $BASE/$G1/messages"] = 500 to """{"error":"down"}""" + gate.complete(Unit) + runCurrent() + assertEquals(MessageDeliveryState.failed, app.groupOutgoing[G1]!!.single().deliveryState) + assertNull(app.groupConversation?.sendError) + + assertEquals("half written", app.groupComposer(G1).draft) + } + + @Test + fun stopShowsPendingAndReportsFailure() = runTest { + val gate = CompletableDeferred() + val transport = GroupTransport() + val app = opened(transport) + transport.held["POST $BASE/$G1/stop"] = gate + transport.responses["POST $BASE/$G1/stop"] = 500 to """{"error":"nope"}""" + + app.stopGroupChat() + assertTrue("group-stop:$G1" in app.pendingMutations) + assertEquals("Stopping…", app.notice) + app.stopGroupChat() + runCurrent() + assertEquals("a pending stop is not sent twice", 1, transport.sent("POST $BASE/$G1/stop").size) + + gate.complete(Unit) + runCurrent() + assertFalse("group-stop:$G1" in app.pendingMutations) + assertEquals("nope", app.errorText) + } + + private fun TestScope.openedWithOlderRows(transport: GroupTransport): AppModel { + val live = snapshotJson(listOf(row(5)), hasMore = true, oldest = "$G1:5") + transport.responses["GET $BASE/$G1/chat"] = 200 to live + transport.stream = 200 to "event: snapshot\ndata: $live\n\n" + val app = model(this, transport) + app.openGroupChat(G1) + until { app.groupConversation?.streamStatus == RECONNECTING } + return app + } + + private val historyPage = "GET $BASE/$G1/history?limit=100&before=11111111-1111-4111-8111-111111111111%3A5" + + @Test + fun historyPrependsOlderRowsOnce() = runTest { + val transport = GroupTransport() + val app = openedWithOlderRows(transport) + transport.responses[historyPage] = 200 to """{"messages":[${row(4)}],"hasMore":false,"oldestEntryId":"$G1:4"}""" + val gate = CompletableDeferred() + transport.held[historyPage] = gate + + app.loadEarlierGroupMessages() + assertTrue(app.groupConversation!!.loadingOlder) + app.loadEarlierGroupMessages() + runCurrent() + assertEquals(1, transport.sent(historyPage).size) + + gate.complete(Unit) + runCurrent() + assertEquals(listOf("$G1:4:0", "$G1:5:0"), app.groupConversation!!.messages.map { it.id }) + assertFalse(app.groupConversation!!.hasMore) + } + + @Test + fun aLateHistoryPageIsDroppedAfterLeaving() = runTest { + val transport = GroupTransport() + val app = openedWithOlderRows(transport) + transport.responses[historyPage] = 200 to """{"messages":[${row(4)}],"hasMore":false,"oldestEntryId":"$G1:4"}""" + val gate = CompletableDeferred() + transport.held[historyPage] = gate + transport.stream = 200 to "event: snapshot\ndata: ${snapshotJson(listOf(row(5)), hasMore = true, oldest = "$G1:5")}\n\n" + + app.loadEarlierGroupMessages() + runCurrent() + app.openGroupChat(G1) + runCurrent() + gate.complete(Unit) + until { app.groupConversation?.group != null } + + val conversation = app.groupConversation!! + assertEquals(listOf("$G1:5:0"), conversation.messages.map { it.id }) + assertFalse(conversation.loadingOlder) + } + + @Test + fun aFailedHistoryPageCanBeLoadedAgain() = runTest { + val transport = GroupTransport() + val app = openedWithOlderRows(transport) + + app.loadEarlierGroupMessages() + runCurrent() + assertFalse(app.groupConversation!!.loadingOlder) + assertTrue(app.errorText.isNotEmpty()) + assertTrue(app.groupConversation!!.hasMore) + } + + @Test + fun snapshotsKeepOlderPagesAndTheirCursor() { + val paged = GroupConversation(G1).merging(snapshot("g:5:0", hasMore = true, oldest = "g:5")) + .adding(ChatHistoryResponse(listOf(Message(id = "g:4:0", role = "user")), true, "g:4")) + val next = paged.merging(snapshot("g:5:0", "g:6:0", hasMore = true, oldest = "g:5")) + assertEquals(listOf("g:4:0", "g:5:0", "g:6:0"), next.messages.map { it.id }) + assertEquals("g:4", next.oldestEntryID) + } + + @Test + fun aSnapshotBeyondAGapRestartsFromTheLivePage() { + val paged = GroupConversation(G1).merging(snapshot("g:5:0", hasMore = true, oldest = "g:5")) + .adding(ChatHistoryResponse(listOf(Message(id = "g:4:0", role = "user")), true, "g:4")) + val resumed = paged.merging(snapshot("g:90:0", hasMore = true, oldest = "g:90")) + assertEquals(listOf("g:90:0"), resumed.messages.map { it.id }) + assertEquals("g:90", resumed.oldestEntryID) + assertFalse(resumed.olderLoaded) + } + + @Test + fun groupImagesComeFromTheGroupAttachmentRoute() = runTest { + val transport = GroupTransport().apply { bytes = byteArrayOf(9) } + val app = opened(transport) + app.loadGroupAttachmentImage("$G1:1", 0) + assertEquals("/v1/group-chats/$G1/attachments/11111111-1111-4111-8111-111111111111%3A1/0", transport.requests.last().pathWithQuery) + assertArrayEquals(byteArrayOf(9), app.groupAttachmentImageBytes(Message(entryId = "$G1:1"), 0)) + } + + @Test + fun aFailedListKeepsItsRowsAndSaysSo() = runTest { + val transport = GroupTransport() + val app = model(this, transport) + app.loadGroupChats() + runCurrent() + assertEquals(listOf(G1), app.groupChats.map { it.id }) + + transport.responses["GET $BASE"] = 503 to """{"error":"Group chats are unavailable"}""" + app.loadGroupChats() + runCurrent() + assertTrue(app.groupsFailed) + assertEquals(listOf(G1), app.groupChats.map { it.id }) + assertEquals("", app.errorText) + } + + @Test + fun botMessagesWithoutBlocksShowWhileToolActivityDoesNot() { + val bot = Message(id = "g:1:0", entryId = "g:1", role = "assistant", content = JsonPrimitive("hi")) + val tool = Message(id = "g:2:0", role = "toolResult", content = JsonPrimitive("Reacted")) + val file = Message(id = "g:3:0", role = "user", content = JsonPrimitive(""), attachments = listOf(dev.crumble.android.model.AttachmentInfo(name = "a"))) + assertFalse("the bot chat filter needs blocks", ChatRow.shownInChat(bot)) + assertTrue(shownInGroup(bot)) + assertFalse(shownInGroup(tool)) + assertTrue(shownInGroup(file)) + val rows = ChatRow.rows(listOf(bot, tool, file), null, false, ::shownInGroup) + assertEquals(listOf("g:1:0", "g:3:0"), rows.map { it.id }) + } + + @Test + fun reactionsSourcesAndLabelsFollowTheWeb() { + val emoji = buildJsonObject { put("emoji", "👍") } + val reactions = groupReactions( + listOf( + Message(role = "toolResult", toolName = "react", replyTo = "e1", origin = MessageOrigin("bot", "Ada", "a1"), toolDetails = emoji), + Message(role = "toolResult", toolName = "react", replyTo = "e1", toolDetails = emoji), + Message(role = "toolResult", toolName = "react", replyTo = "e2", isError = true, toolDetails = emoji), + Message(role = "toolResult", toolName = "react", toolDetails = emoji), + ), + ) + assertEquals(mapOf("e1" to listOf("Ada 👍", "👍")), reactions) + + val sources = groupSourcesOf(Message(sources = listOf(MessageSource("https://example.com/a/", "A"), MessageSource("ftp://x", "X")))) + assertEquals(mapOf("example.com/a" to "A"), sources) + assertNull(groupSourcesOf(Message())) + + assertEquals("You", groupReplyLabel(Message(role = "user"))) + assertEquals("Ada", groupReplyLabel(Message(role = "assistant", origin = MessageOrigin("bot", "Ada")))) + assertEquals("a bot", groupReplyLabel(Message(role = "assistant"))) + } + + @Test + fun theHeaderSaysWhoIsDoingWhat() { + val group = GroupChat(G1, "Team", listOf("a1", "gone", "a2"), "t", "t") + assertEquals(bots, membersOf(group, bots)) + assertEquals("Ada, Kev", groupStatusLine(bots, null)) + assertEquals("Ada is answering · Kev answers next", groupStatusLine(bots, activity("a1" to "running", "a2" to "queued"))) + assertEquals("Ada, Kev", groupStatusLine(bots, activity("a1" to "disabled", "a2" to "idle"))) + assertEquals("Ada is disabled and skipped", memberStatusLabel(bots[0], "disabled")) + assertEquals("Ada is here", memberStatusLabel(bots[0], "idle")) + assertTrue(isGroupRunning(activity("a1" to "queued"))) + assertFalse(isGroupRunning(activity("a1" to "idle"))) + assertFalse(isGroupRunning(null)) + } + + @Test + fun formValidityMatchesTheServerLimits() { + assertTrue(isValidGroup("Team", listOf("1", "2"))) + assertTrue(isValidGroup("Team", List(6) { "$it" })) + assertFalse(isValidGroup("Team", listOf("1"))) + assertFalse(isValidGroup("Team", List(7) { "$it" })) + assertFalse(isValidGroup(" ", listOf("1", "2"))) + } + + @Test + fun groupRepliesNameTheGroupAndStayQuietOnlyInThatGroup() { + val reply = ActivityEvent(type = "reply", agentId = "a1", agentName = "Ada", origin = "group", preview = "hi", groupId = G1, groupName = "Team") + assertEquals("Ada in Team", notification(reply, NotificationContext(true, null))?.title) + assertEquals("Ada in a group", notification(reply.copy(groupName = ""), NotificationContext(true, null))?.title) + assertNull(notification(reply, NotificationContext(true, Route.GroupChat(G1)))) + assertNotNull("the bot's own chat is not the group", notification(reply, NotificationContext(true, Route.AgentChat("a1")))) + assertNotNull(notification(reply, NotificationContext(false, Route.GroupChat(G1)))) + } + + @Test + fun pushRepliesCarryTheirGroup() { + val event = parsePushReplyData( + mapOf("type" to "reply", "eventId" to "e", "serverId" to "s", "agentId" to "a1", "agentName" to "Ada", "preview" to "hi", "groupId" to G1, "groupName" to "Team"), + ) + assertEquals(G1, event?.groupId) + assertEquals("Team", event?.groupName) + val direct = parsePushReplyData(mapOf("type" to "reply", "eventId" to "e", "serverId" to "s", "agentId" to "a1", "agentName" to "Ada", "preview" to "hi")) + assertNull(direct?.groupId) + } +} diff --git a/app/src/test/java/dev/crumble/android/NavigationTests.kt b/app/src/test/java/dev/crumble/android/NavigationTests.kt new file mode 100644 index 0000000..e3e114f --- /dev/null +++ b/app/src/test/java/dev/crumble/android/NavigationTests.kt @@ -0,0 +1,33 @@ +package dev.crumble.android + +import dev.crumble.android.model.Route +import dev.crumble.android.model.SETTINGS_PAGES +import dev.crumble.android.model.WORKSPACE_PAGES +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class NavigationTests { + @Test + fun theWorkspaceHoldsOnlyTheWebsiteSidebarPages() { + assertEquals(listOf(Route.Memory, Route.Tasks, Route.Activity), WORKSPACE_PAGES) + assertTrue(WORKSPACE_PAGES.none { it in SETTINGS_PAGES }) + } + + @Test + fun settingsPagesReturnToTheSettingsList() { + SETTINGS_PAGES.forEach { assertEquals(Route.Settings, it.parent) } + assertEquals(Route.MessageGateways, Route.MessageGateway("telegram").parent) + } + + @Test + fun workspacePagesAndSettingsReturnToTheAccountMenu() { + (WORKSPACE_PAGES + Route.Settings).forEach { assertEquals(Route.Account, it.parent) } + } + + @Test + fun chatsAndTheAccountMenuReturnHome() { + listOf(Route.Account, Route.AgentChat("a1"), Route.GroupChat("g1")).forEach { assertNull(it.parent) } + } +} diff --git a/app/src/test/java/dev/crumble/android/RecurrenceTests.kt b/app/src/test/java/dev/crumble/android/RecurrenceTests.kt new file mode 100644 index 0000000..eece0ce --- /dev/null +++ b/app/src/test/java/dev/crumble/android/RecurrenceTests.kt @@ -0,0 +1,137 @@ +package dev.crumble.android + +import dev.crumble.android.model.NextRun +import dev.crumble.android.model.Recurrence +import dev.crumble.android.model.TaskDraft +import dev.crumble.android.model.TaskWhen +import dev.crumble.android.model.choice +import dev.crumble.android.model.choosing +import dev.crumble.android.model.cronOf +import dev.crumble.android.model.humanRun +import dev.crumble.android.model.inTimezone +import dev.crumble.android.model.minuteChoices +import dev.crumble.android.model.nextRunOf +import dev.crumble.android.model.recurrenceOf +import dev.crumble.android.model.runningAt +import dev.crumble.android.model.timezoneChoices +import dev.crumble.android.model.wallClock +import dev.crumble.android.model.weekdayName +import java.time.Instant +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.format.TextStyle +import java.util.Locale +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class RecurrenceTests { + private fun draft() = TaskDraft(scheduleID = "", agentID = "a1", timezone = "UTC") + private val now = Instant.parse("2026-11-05T10:00:00Z") + + @Test + fun cronReadsBackIntoThePicker() { + assertEquals(Recurrence(TaskWhen.Hourly, minute = 5), recurrenceOf("5 * * * *")) + assertEquals(Recurrence(TaskWhen.Daily, 30, 8), recurrenceOf(" 30 8 * * * ")) + assertEquals(Recurrence(TaskWhen.Weekdays, 0, 9), recurrenceOf("0 9 * * 1-5")) + assertEquals(Recurrence(TaskWhen.Weekly, 0, 9, listOf(1, 3)), recurrenceOf("0 9 * * 1,3")) + assertEquals(Recurrence(TaskWhen.Weekly, 0, 9, listOf(0)), recurrenceOf("0 9 * * 7,0")) + assertEquals(Recurrence(TaskWhen.Monthly, 0, 9, day = 15), recurrenceOf("0 9 15 * *")) + } + + @Test + fun cronsThePickerCannotShowStayCustom() { + for (cron in listOf("*/5 * * * *", "0 9 * 1 *", "60 * * * *", "0 24 * * *", "0 9 32 * *", "0 9 0 * *", "99999999999 * * * *", "")) { + assertNull(cron, recurrenceOf(cron)) + } + } + + @Test + fun everyPickerStateRoundTrips() { + val recurrences = listOf( + Recurrence(TaskWhen.Hourly, minute = 10), + Recurrence(TaskWhen.Daily, 5, 6), + Recurrence(TaskWhen.Weekdays, 5, 6), + Recurrence(TaskWhen.Weekly, 5, 6, listOf(0, 2)), + Recurrence(TaskWhen.Monthly, 5, 6, day = 31), + ) + for (recurrence in recurrences) assertEquals(recurrence, recurrenceOf(cronOf(recurrence))) + assertEquals("5 6 * * 0,2,5", cronOf(Recurrence(TaskWhen.Weekly, 5, 6, listOf(5, 0, 2)))) + } + + @Test + fun switchingKindKeepsTheTimeAndLeavesCustomAlone() { + val daily = draft().copy(repeats = true, cron = "30 7 * * *") + assertEquals("30 7 * * 1", daily.choosing(TaskWhen.Weekly).cron) + assertEquals("30 7 1 * *", daily.choosing(TaskWhen.Monthly).cron) + assertEquals("30 * * * *", daily.choosing(TaskWhen.Hourly).cron) + assertEquals("0 9 * * 1-5", draft().copy(repeats = true, cron = "*/5 * * * *").choosing(TaskWhen.Weekdays).cron) + + val custom = daily.choosing(TaskWhen.Custom) + assertEquals(TaskWhen.Custom, custom.choice) + assertEquals("30 7 * * *", custom.cron) + assertEquals(TaskWhen.Daily, custom.choosing(TaskWhen.Daily).choice) + assertEquals(TaskWhen.Once, custom.choosing(TaskWhen.Once).choice) + assertFalse(custom.choosing(TaskWhen.Once).customCron) + } + + @Test + fun aHandWrittenMinuteStaysSelectable() { + assertEquals(12, minuteChoices(10).size) + assertTrue(7 in minuteChoices(7)) + } + + @Test + fun weekdayNamesCountSundayAsZero() { + assertEquals("Sunday", weekdayName(0, TextStyle.FULL, Locale.US)) + assertEquals("Mon", weekdayName(1, TextStyle.SHORT, Locale.US)) + } + + @Test + fun changingTheZoneKeepsTheChosenClockTime() { + val picked = draft().runningAt(LocalDateTime.of(2026, 12, 1, 9, 0)) + val moved = picked.inTimezone("America/New_York") + assertEquals(LocalDateTime.of(2026, 12, 1, 9, 0), moved.wallClock) + assertEquals(Instant.parse("2026-12-01T14:00:00Z"), moved.runDate) + } + + @Test + fun timezoneChoicesSearchAndKeepTheCurrentZone() { + val zones = setOf("Europe/Berlin", "America/New_York", "UTC", "Etc/GMT+1", "EST5EDT") + assertEquals(listOf("America/New_York", "Europe/Berlin", "UTC"), timezoneChoices("", "UTC", zones)) + assertEquals(listOf("America/New_York"), timezoneChoices("new york", "UTC", zones)) + assertTrue("Mars/Base" in timezoneChoices("", "Mars/Base", zones)) + } + + @Test + fun runsReadRelativeToTheTasksZone() { + val zone = ZoneId.of("UTC") + fun at(text: String) = humanRun(Instant.parse(text), zone, now, Locale.UK) + assertEquals("today at 12:00", at("2026-11-05T12:00:00Z")) + assertEquals("tomorrow at 09:00", at("2026-11-06T09:00:00Z")) + assertEquals("Monday at 09:00", at("2026-11-09T09:00:00Z")) + assertEquals("Mon, Nov 16 at 09:00", humanRun(Instant.parse("2026-11-16T09:00:00Z"), zone, now, Locale.US).replace(' ', ' ').replace(" AM", "").replace("9:00", "09:00")) + } + + @Test + fun theDayBoundaryIsTheTasksNotTheDevices() { + assertEquals("tomorrow at 00:30", humanRun(Instant.parse("2026-11-05T15:30:00Z"), ZoneId.of("Asia/Tokyo"), now, Locale.UK)) + } + + @Test + fun previewMatchesTheEditorStates() { + val repeating = draft().copy(repeats = true, cron = "0 9 * * *") + assertEquals(NextRun.At("Next run", "tomorrow at 09:00", "UTC"), nextRunOf(repeating, now, Locale.UK)) + assertEquals(NextRun.Never, nextRunOf(repeating.copy(cron = "0 0 31 2 *"), now)) + assertEquals(NextRun.Never, nextRunOf(repeating.copy(cron = "nonsense"), now)) + assertEquals(NextRun.Never, nextRunOf(repeating.copy(cron = ""), now)) + assertEquals(NextRun.Never, nextRunOf(repeating.copy(timezone = "Not/AZone"), now)) + assertEquals(NextRun.Unknown, nextRunOf(repeating.copy(cron = "H * * * *"), now)) + + val once = draft().copy(runDate = Instant.parse("2026-11-05T12:00:00Z")) + assertEquals(NextRun.At("Runs", "today at 12:00", "UTC"), nextRunOf(once, now, Locale.UK)) + assertEquals(NextRun.Passed, nextRunOf(once.copy(runDate = now.minusSeconds(60)), now)) + } +} diff --git a/app/src/test/java/dev/crumble/android/ReplyMarkdownTests.kt b/app/src/test/java/dev/crumble/android/ReplyMarkdownTests.kt new file mode 100644 index 0000000..5d3ba26 --- /dev/null +++ b/app/src/test/java/dev/crumble/android/ReplyMarkdownTests.kt @@ -0,0 +1,267 @@ +package dev.crumble.android + +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.LinkAnnotation +import androidx.compose.ui.text.font.FontStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextDecoration +import dev.crumble.android.model.ChatRow +import dev.crumble.android.model.Message +import dev.crumble.android.model.MessageOrigin +import dev.crumble.android.model.isNotice +import dev.crumble.android.model.messageLabel +import dev.crumble.android.model.noticeTitle +import dev.crumble.android.ui.MarkdownBlock +import dev.crumble.android.ui.inlineMarkdown +import kotlinx.serialization.json.JsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +private fun AnnotatedString.links() = getLinkAnnotations(0, length).map { range -> + text.substring(range.start, range.end) to (range.item as LinkAnnotation.Url).url +} + +private fun AnnotatedString.styled(match: (androidx.compose.ui.text.SpanStyle) -> Boolean) = + spanStyles.filter { match(it.item) }.map { text.substring(it.start, it.end) } + +class ReplyMarkdownTests { + // Links + + @Test + fun aMarkdownLinkShowsItsLabelAndOpensItsTarget() { + val reply = inlineMarkdown("See [the docs](https://example.com/a) now") + + assertEquals("See the docs now", reply.text) + assertEquals(listOf("the docs" to "https://example.com/a"), reply.links()) + } + + @Test + fun aLinkMayCarryATitleAngleBracketsOrParentheses() { + assertEquals("https://a.dev", inlineMarkdown("[a](https://a.dev \"Home\")").links().single().second) + assertEquals("https://a.dev/x", inlineMarkdown("[a]()").links().single().second) + assertEquals("https://a.dev/w_(x)", inlineMarkdown("[a](https://a.dev/w_(x))").links().single().second) + } + + @Test + fun aLabelKeepsItsInlineMarkdown() { + val reply = inlineMarkdown("[**bold** text](https://a.dev)") + + assertEquals("bold text", reply.text) + assertEquals(listOf("bold text" to "https://a.dev"), reply.links()) + assertEquals(listOf("bold"), reply.styled { it.fontWeight == FontWeight.Bold }) + } + + @Test + fun aBoldLinkStaysALink() { + assertEquals(listOf("a" to "https://a.dev"), inlineMarkdown("**[a](https://a.dev)**").links()) + assertEquals(listOf("https://a.dev" to "https://a.dev"), inlineMarkdown("*https://a.dev*").links()) + } + + @Test + fun onlyWebLinksCanBeTapped() { + for (target in listOf("javascript:alert(1)", "intent://x#Intent;end", "mailto:a@b.dev", "file:///etc/passwd", "/relative")) { + val reply = inlineMarkdown("[label]($target)") + assertEquals(target, "label", reply.text) + assertTrue(target, reply.links().isEmpty()) + } + } + + @Test + fun uppercaseSchemesAreWebLinks() { + assertEquals(listOf("a" to "HTTPS://a.dev"), inlineMarkdown("[a](HTTPS://a.dev)").links()) + } + + @Test + fun anUnfinishedLinkStaysText() { + assertEquals("[half](", inlineMarkdown("[half](").text) + assertEquals("[not a link]", inlineMarkdown("[not a link]").text) + assertTrue(inlineMarkdown("[half](").links().isEmpty()) + } + + @Test + fun aBareUrlLinksWithoutItsSentencePunctuation() { + val reply = inlineMarkdown("Read https://example.com/page, then https://a.dev.") + + assertEquals("Read https://example.com/page, then https://a.dev.", reply.text) + assertEquals( + listOf("https://example.com/page" to "https://example.com/page", "https://a.dev" to "https://a.dev"), + reply.links(), + ) + } + + @Test + fun aBareUrlKeepsParenthesesItOpenedAndDropsOnesItDidNot() { + assertEquals("https://a.dev/w_(x)", inlineMarkdown("https://a.dev/w_(x)").links().single().second) + assertEquals("https://a.dev/x", inlineMarkdown("(https://a.dev/x)").links().single().second) + } + + @Test + fun aUrlInsideAWordOrCodeSpanIsNotLinked() { + assertTrue(inlineMarkdown("xhttps://a.dev").links().isEmpty()) + assertTrue(inlineMarkdown("`https://a.dev`").links().isEmpty()) + assertTrue(inlineMarkdown("https://").links().isEmpty()) + } + + @Test + fun anAutolinkDropsItsAngleBrackets() { + val reply = inlineMarkdown("Go to now") + + assertEquals("Go to https://a.dev/x now", reply.text) + assertEquals(listOf("https://a.dev/x" to "https://a.dev/x"), reply.links()) + assertEquals("", inlineMarkdown("").text) + } + + @Test + fun aUrlInALabelDoesNotNestALink() { + assertEquals( + listOf("https://inner.dev" to "https://outer.dev"), + inlineMarkdown("[https://inner.dev](https://outer.dev)").links(), + ) + } + + @Test + fun aBackslashKeepsPunctuationLiteral() { + val reply = inlineMarkdown("\\[a\\](https://a.dev) \\~\\~b\\~\\~") + + assertEquals("[a](https://a.dev) ~~b~~", reply.text) + } + + // Strikethrough + + @Test + fun tildesStrikeThrough() { + val struck = { source: String -> + inlineMarkdown(source).styled { it.textDecoration == TextDecoration.LineThrough } + } + + assertEquals(listOf("gone"), struck("~~gone~~ kept")) + assertEquals(listOf("gone"), struck("~gone~ kept")) + assertEquals(emptyList(), struck("about ~5 min and ~ 6")) + assertEquals(emptyList(), struck("~~~gone~~~")) + } + + @Test + fun anOpenStrikeShowsItsTildes() { + assertEquals("~~half", inlineMarkdown("~~half").text) + } + + @Test + fun strikethroughNestsWithOtherMarks() { + val reply = inlineMarkdown("~~*both*~~") + + assertEquals("both", reply.text) + assertEquals(listOf("both"), reply.styled { it.fontStyle == FontStyle.Italic }) + assertEquals(listOf("both"), reply.styled { it.textDecoration == TextDecoration.LineThrough }) + } + + // Tables + + private fun table(source: String) = MarkdownBlock.parse(source).single() as MarkdownBlock.Table + + @Test + fun aTableKeepsItsHeaderRowsAndAlignment() { + val parsed = table("| Name | Cost | Note |\n| :--- | ---: | :-: |\n| Ada | 1 | ok |\n| Kev | 2 | fine |") + + assertEquals(listOf("Name", "Cost", "Note"), parsed.header) + assertEquals(listOf(TextAlign.Start, TextAlign.End, TextAlign.Center), parsed.align) + assertEquals(listOf(listOf("Ada", "1", "ok"), listOf("Kev", "2", "fine")), parsed.rows) + } + + @Test + fun outerPipesAreOptionalAndEscapedPipesStayInTheCell() { + val parsed = table("a | b\n--|--\n1 \\| 2 | 3") + + assertEquals(listOf("a", "b"), parsed.header) + assertEquals(listOf(listOf("1 | 2", "3")), parsed.rows) + } + + @Test + fun rowsAreFittedToTheHeader() { + val parsed = table("| a | b |\n|---|---|\n| 1 |\n| 1 | 2 | 3 |") + + assertEquals(listOf(listOf("1", ""), listOf("1", "2")), parsed.rows) + } + + @Test + fun aTableEndsAtABlankLineOrAnotherBlockAndInterruptsAParagraph() { + val blocks = MarkdownBlock.parse("Before\n| a |\n|---|\n| 1 |\n# Next\n\n| b |\n|---|\n\nAfter") + + assertEquals( + listOf( + MarkdownBlock.Paragraph("Before"), + MarkdownBlock.Table(listOf("a"), listOf(TextAlign.Start), listOf(listOf("1"))), + MarkdownBlock.Heading(1, "Next"), + MarkdownBlock.Table(listOf("b"), listOf(TextAlign.Start), emptyList()), + MarkdownBlock.Paragraph("After"), + ), + blocks, + ) + } + + @Test + fun aMismatchedDelimiterIsNotATable() { + assertEquals(listOf(MarkdownBlock.Paragraph("a | b\n---")), MarkdownBlock.parse("a | b\n---")) + assertEquals(listOf(MarkdownBlock.Paragraph("| a | b |")), MarkdownBlock.parse("| a | b |")) + assertEquals(listOf(MarkdownBlock.Paragraph("x\n---")), MarkdownBlock.parse("x\n---")) + } + + @Test + fun aStreamingHeaderStaysTextUntilItsDelimiterIsComplete() { + assertEquals(listOf(MarkdownBlock.Paragraph("| a | b |\n|--")), MarkdownBlock.parse("| a | b |\n|--")) + assertTrue(MarkdownBlock.parse("| a | b |\n|--|--").single() is MarkdownBlock.Table) + } + + @Test + fun tablesInsideCodeStayCode() { + assertEquals(listOf(MarkdownBlock.Code("| a |\n|---|")), MarkdownBlock.parse("```\n| a |\n|---|\n```")) + } + + @Test + fun aMermaidDiagramStaysACodeBlock() { + assertEquals(listOf(MarkdownBlock.Code("graph TD\n A --> B")), MarkdownBlock.parse("```mermaid\ngraph TD\n A --> B\n```")) + } + + // Notices + + private fun user(kind: String?, name: String? = null, source: String? = null) = Message( + id = "m", + role = "user", + content = JsonPrimitive("Run the report"), + origin = kind?.let { MessageOrigin(kind = it, name = name, source = source) }, + ) + + @Test + fun messagesTheOwnerDidNotWriteCollapseUnderTheirOrigin() { + assertEquals("Automation · Digest", noticeTitle(user("task", "Digest"))) + assertEquals("Automation · Deploy, event from GitHub", noticeTitle(user("event", "Deploy", "GitHub"))) + assertEquals("Automation · Deploy, event from a deleted source", noticeTitle(user("event", "Deploy"))) + assertEquals("Script automation · Nightly", noticeTitle(user("script", "Nightly"))) + assertEquals("Credential · ACME_TOKEN", noticeTitle(user("credential", "ACME_TOKEN"))) + assertEquals("Bot request", noticeTitle(user("bot_request"))) + assertEquals("From Kev", noticeTitle(user("bot", "Kev"))) + listOf("task", "event", "script", "credential", "bot_request", "bot").forEach { assertTrue(it, isNotice(user(it, "x"))) } + } + + @Test + fun theOwnersOwnMessagesAreNotNotices() { + assertFalse(isNotice(user(null))) + assertFalse(isNotice(user("owner"))) + assertNull(noticeTitle(user("owner"))) + assertEquals("You", messageLabel(user("owner"))) + } + + @Test + fun onlyUserRowsAreNotices() { + assertFalse(isNotice(user("task", "Digest").copy(role = "assistant"))) + } + + @Test + fun noticesStayInTheChatButJobMessagesDoNot() { + assertTrue(ChatRow.shownInChat(user("task", "Digest"))) + assertFalse(ChatRow.shownInChat(user("coding", "fix"))) + } +} diff --git a/app/src/test/java/dev/crumble/android/SecretsTests.kt b/app/src/test/java/dev/crumble/android/SecretsTests.kt new file mode 100644 index 0000000..40132a1 --- /dev/null +++ b/app/src/test/java/dev/crumble/android/SecretsTests.kt @@ -0,0 +1,1102 @@ +package dev.crumble.android + +import dev.crumble.android.generated.Credential +import dev.crumble.android.generated.CredentialRequest +import dev.crumble.android.generated.Credentials +import dev.crumble.android.generated.Login +import dev.crumble.android.generated.LoginFields +import dev.crumble.android.generated.LoginRequest +import dev.crumble.android.generated.Logins +import dev.crumble.android.generated.PasswordManager +import dev.crumble.android.generated.Provider +import dev.crumble.android.generated.ProviderExternalAuth +import dev.crumble.android.generated.ProviderLoginMethod +import dev.crumble.android.generated.SecretStatus +import dev.crumble.android.generated.TranscriptMessage +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.ChatRow +import dev.crumble.android.model.ChatSnapshot +import dev.crumble.android.model.CredentialForm +import dev.crumble.android.model.CrumbleJson +import dev.crumble.android.model.LoginForm +import dev.crumble.android.model.LoginMode +import dev.crumble.android.model.ManagerTokenForm +import dev.crumble.android.model.Message +import dev.crumble.android.model.ProviderKeyForm +import dev.crumble.android.model.Route +import dev.crumble.android.model.SKILLS_ALL +import dev.crumble.android.model.SecretDraft +import dev.crumble.android.model.SecretInput +import dev.crumble.android.model.SecretKind +import dev.crumble.android.model.SecretRequestRef +import dev.crumble.android.model.SecretRequestState +import dev.crumble.android.model.SecretRow +import dev.crumble.android.model.credentialFields +import dev.crumble.android.model.credentialForm +import dev.crumble.android.model.credentialReadKey +import dev.crumble.android.model.hostList +import dev.crumble.android.model.isWebLink +import dev.crumble.android.model.keepPlaceholder +import dev.crumble.android.model.loginFields +import dev.crumble.android.model.loginForm +import dev.crumble.android.model.matchingProviders +import dev.crumble.android.model.providerStatus +import dev.crumble.android.model.restored +import dev.crumble.android.model.secretBotsShown +import dev.crumble.android.model.secretDraft +import dev.crumble.android.model.secretKey +import dev.crumble.android.model.secretRequestState +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import dev.crumble.android.network.domain +import dev.crumble.android.storage.CredentialStore +import java.nio.charset.StandardCharsets +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.jsonObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +private const val SECRET = "s3cret-value" + +private fun bodyOf(request: HttpRequestData) = + CrumbleJson.parseToJsonElement(request.body!!.toString(StandardCharsets.UTF_8)).jsonObject + +private fun bodyText(request: HttpRequestData) = request.body?.toString(StandardCharsets.UTF_8).orEmpty() + +/** Answers by "METHOD path", holding back any request whose key has a gate. */ +private class SecretTransport : HttpTransport { + val requests = mutableListOf() + val held = mutableMapOf>() + val responses = mutableMapOf>() + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + requests.add(request) + val key = "${request.method} ${request.pathWithQuery}" + held[key]?.await() + val (status, body) = responses[key] ?: (503 to """{"error":"unscripted $key"}""") + return HttpResponseData(status, body.toByteArray(StandardCharsets.UTF_8)) + } + + override suspend fun openStream(request: HttpRequestData): HttpStreamResponse = + throw UnsupportedOperationException("streams are not used here") + + fun sent(key: String) = requests.filter { "${it.method} ${it.pathWithQuery}" == key } +} + +private class RecordingStore : CredentialStore { + val written = mutableListOf() + override fun read(account: String): String? = null + override fun write(account: String, value: String) { + written.add(value) + } + + override fun delete(account: String) = Unit + override fun deletePrefixed(prefix: String) = Unit +} + +private fun hostsJson(hosts: List) = hosts.joinToString(",") { "\"$it\"" } + +private fun credentialJson(name: String = "ACME_TOKEN", hosts: List = listOf("api.acme.com"), updated: String = "2026-11-05T10:00:00Z") = + """{"name":"$name","hosts":[${hostsJson(hosts)}],"secret":{"configured":true,"passwordManager":null,"reference":null},"createdAt":"$updated","updatedAt":"$updated","lastUsedAt":null,"lastError":null,"github":false}""" + +private fun credentialRequestJson(name: String = "ACME_TOKEN", at: String = "t1") = + """{"name":"$name","hosts":["api.acme.com"],"reason":"Deploys","requestedAt":"$at"}""" + +private fun credentialsJson(items: List = emptyList(), requests: List = emptyList()) = + """{"credentials":[${items.joinToString(",")}],"requests":[${requests.joinToString(",")}]}""" + +private fun loginJson(name: String = "github") = + """{"name":"$name","hosts":["github.com"],"fields":{"username":{"configured":true,"passwordManager":null,"reference":null},"password":{"configured":true,"passwordManager":null,"reference":null}},"createdAt":"t","updatedAt":"t","lastUsedAt":null,"lastError":null}""" + +private fun loginsJson(items: List = emptyList(), requests: List = emptyList()) = + """{"logins":[${items.joinToString(",")}],"requests":[${requests.joinToString(",")}]}""" + +private fun managerJson(id: String = "1password", connected: Boolean = true, usedBy: String = "") = + """{"id":"$id","name":"1Password","connected":$connected,"connectedAt":${if (connected) "\"t\"" else "null"},"usedBy":[$usedBy]}""" + +private fun providerJson(id: String = "openai", credentialType: String? = null, activeLogin: String? = null, configured: Boolean = credentialType != null) = + """{"provider":"$id","name":"OpenAI","configured":$configured,"authMethods":[{"type":"api_key","label":"Key","subscription":false},{"type":"oauth","label":"ChatGPT","subscription":true}],"credentialType":${credentialType?.let { "\"$it\"" } ?: "null"},"apiKey":{"configured":${credentialType == "api_key"},"passwordManager":null,"reference":null},"activeLoginId":${activeLogin?.let { "\"$it\"" } ?: "null"},"externalAuth":null}""" + +private fun sessionJson(status: String = "pending", prompt: String = "null", events: String = "") = + """{"id":"l1","provider":"openai","method":"oauth","status":"$status","createdAt":1,"expiresAt":2,"prompt":$prompt,"events":[$events],"failure":null}""" + +private fun promptJson(id: String = "p1", type: String = "secret") = + """{"id":"$id","type":"$type","message":"Paste the code"}""" + +private val credential = Credential("ACME_TOKEN", listOf("api.acme.com"), null, "t", "t", null, null, false) + +private val provider = Provider( + provider = "openai", name = "OpenAI", configured = false, + authMethods = listOf(ProviderLoginMethod("oauth", "ChatGPT", true)), + credentialType = null, apiKey = SecretStatus(false, null, null), activeLoginId = null, externalAuth = null, +) + +private const val CREDENTIALS = "/v1/agents/a1/credentials" +private const val LOGINS = "/v1/agents/a1/logins" +private const val PUT_CREDENTIAL = "PUT $CREDENTIALS/ACME_TOKEN" +private const val PUT_LOGIN = "PUT $LOGINS/github" +private const val MANAGERS = "GET /v1/password-managers" +private const val SESSION = "GET /v1/provider-logins/l1" + +private fun credentialMessage(requestedAt: String? = "t1") = + Message(id = "t1", entryId = "t", role = "toolResult", credentialRequest = SecretRequestRef("ACME_TOKEN", listOf("api.acme.com"), requestedAt)) + +private fun loginMessage() = Message(id = "t2", entryId = "t2", role = "toolResult", loginRequest = SecretRequestRef("github", listOf("github.com"), "t1")) + +@OptIn(ExperimentalCoroutinesApi::class) +class SecretsTests { + private fun modelWith(transport: SecretTransport, scope: TestScope, store: CredentialStore? = null): AppModel { + val client = APIClient(baseURL = "https://example.test", token = "session", transport = transport) + val model = if (store == null) AppModel(client = client, scope = scope) else AppModel(client = client, credentials = store, scope = scope) + return model.also { it.agents = listOf(Agent(id = "a1", name = "Atlas"), Agent(id = "a2", name = "Scout")) } + } + + private fun scripted() = SecretTransport().apply { + responses["GET /v1/agents"] = 200 to "[${agentFixture("a1")}]" + responses["GET $CREDENTIALS"] = 200 to credentialsJson() + responses["GET /v1/agents/a2/credentials"] = 200 to credentialsJson() + responses["GET $LOGINS"] = 200 to loginsJson() + responses["GET /v1/agents/a2/logins"] = 200 to loginsJson() + responses[MANAGERS] = 200 to """{"passwordManagers":[${managerJson()}]}""" + responses["GET /v1/providers"] = 200 to "[${providerJson()}]" + } + + private fun newCredential(model: AppModel, value: SecretDraft = SecretDraft(text = SECRET)) { + model.openCredentialForm("a1") + model.credentialForm = model.credentialForm!!.copy(name = "ACME_TOKEN", hosts = "API.acme.com, *.acme.com", secret = value) + } + + @Test + fun hostsSplitOnCommasSpacesAndLines() { + assertEquals(listOf("api.acme.com", "*.acme.com", "b.io"), hostList(" API.acme.com, *.acme.com\nb.io ")) + assertEquals(emptyList(), hostList(" , ")) + } + + @Test + fun secretDraftsNeverPrintTheirValue() { + val draft = SecretDraft(text = SECRET) + val form = CredentialForm(botID = "a1", owner = "a1", name = "A", hosts = "a.io", secret = draft) + val login = LoginForm(botID = "a1", owner = "a1", password = draft) + val token = ManagerTokenForm(PasswordManager("1password", "1Password", false, null, emptyList()), draft) + val key = ProviderKeyForm(provider, draft) + for (text in listOf(draft, form, login, token, key, draft.input)) { + assertFalse(text.toString().contains(SECRET)) + } + } + + @Test + fun aSavedReferenceStartsTheDraftAndStaysUnchangedUntilEdited() { + val saved = secretDraft(SecretStatus(true, "1password", "op://v/i/f")) + assertEquals("op://v/i/f", saved.text) + assertFalse(saved.changed) + assertTrue(saved.copy(text = " op://v/i/g ").changed) + assertEquals(SecretInput.Reference("1password", "op://v/i/g"), saved.copy(text = " op://v/i/g ").input) + assertEquals("", secretDraft(SecretStatus(true, null, null)).text) + assertNull(saved.source(null).input) + } + + @Test + fun credentialFormChecksItsFieldsLikeTheWeb() { + val form = credentialForm("a1", emptyList()) + assertFalse(form.copy(name = "acme", hosts = "a.io", secret = SecretDraft(text = "v")).ready) + assertTrue(form.copy(name = "acme").nameInvalid) + assertFalse(form.copy(name = "ACME", hosts = "", secret = SecretDraft(text = "v")).ready) + assertFalse(form.copy(name = "ACME", hosts = "a.io").ready) + assertTrue(form.copy(name = "ACME", hosts = "a.io", secret = SecretDraft(text = "v")).ready) + assertTrue(credentialForm("a1", emptyList(), existing = credential).ready) + } + + @Test + fun aRequestLocksItsNameAndKeepsItsHosts() { + val request = CredentialRequest("ACME_TOKEN", listOf("a.io", "b.io"), "Deploys", "t") + val form = credentialForm(null, listOf(Agent(id = "a1", name = "Atlas")), request = request) + assertEquals("a1", form.owner) + assertNull(form.botID) + assertTrue(form.locked) + assertEquals("a.io, b.io", form.hosts) + } + + @Test + fun loginRequestAsksForTheOneTimeCode() { + val form = loginForm("a1", emptyList(), request = LoginRequest("github", listOf("github.com"), "Sign in", true, "t")) + assertTrue(form.hasCode) + val filled = form.copy(username = SecretDraft(text = "u"), password = SecretDraft(text = "p")) + assertFalse(filled.ready) + assertTrue(filled.copy(code = SecretDraft(text = "c")).ready) + } + + @Test + fun aSavedCredentialKeepsItsSecretUnlessChanged() { + val existing = credential.copy(secret = dev.crumble.android.generated.CredentialSecret(true, "1password", "op://v/i/f")) + val form = credentialForm("a1", emptyList(), existing = existing) + assertFalse("secret" in credentialFields(form)) + assertFalse(form.readsPasswordManager) + assertNull(keepPlaceholder(existing)) + val moved = form.copy(secret = form.secret.source("bitwarden").copy(text = "id")) + assertTrue(moved.readsPasswordManager) + assertEquals( + JsonObject(mapOf("reference" to JsonObject(mapOf("passwordManager" to JsonPrimitive("bitwarden"), "reference" to JsonPrimitive("id"))))), + credentialFields(moved)["secret"], + ) + } + + @Test + fun turningOffTheCodeRemovesOnlyASavedOne() { + val saved = Login( + "github", listOf("github.com"), + LoginFields(SecretStatus(true, null, null), SecretStatus(true, null, null), SecretStatus(true, null, null)), + "t", "t", null, null, + ) + val form = loginForm("a1", emptyList(), existing = saved) + val off = loginFields(form.copy(hasCode = false))["fields"] as JsonObject + assertEquals(JsonNull, off["one_time_code"]) + assertEquals(setOf("one_time_code"), off.keys) + val untouched = loginFields(form)["fields"] as JsonObject + assertTrue(untouched.isEmpty()) + val plain = loginFields(loginForm("a1", emptyList()).copy(username = SecretDraft(text = "u")))["fields"] as JsonObject + assertEquals(setOf("username"), plain.keys) + } + + @Test + fun aOnePasswordItemFillsEveryField() { + val form = loginForm("a1", emptyList()).copy(name = "github", hosts = "github.com", mode = LoginMode.item, item = " op://vault/item ") + assertTrue(form.ready) + assertTrue(form.readsPasswordManager) + assertFalse(form.copy(item = "op://vault/item/field").ready) + val body = loginFields(form) + assertFalse("fields" in body) + assertEquals(JsonPrimitive("op://vault/item"), (body["item"] as JsonObject)["reference"]) + assertEquals(JsonPrimitive("1password"), (body["item"] as JsonObject)["passwordManager"]) + } + + @Test + fun cardStateNeedsAFreshReadToCallARequestAnswered() { + fun state(request: String?, listed: Boolean = true, saved: Boolean = false, fresh: Boolean = true, failed: Boolean = false) = + secretRequestState(request, listed, saved, fresh, failed) + assertEquals(SecretRequestState.Loading, state(null, listed = false)) + assertEquals(SecretRequestState.Unavailable, state(null, listed = false, failed = true)) + assertEquals(SecretRequestState.Loading, state(null, fresh = false)) + assertEquals(SecretRequestState.Waiting("r"), state("r", fresh = false)) + assertEquals(SecretRequestState.Saved, state(null, saved = true)) + assertEquals(SecretRequestState.Declined, state(null)) + } + + @Test + fun anAskFromALaterRequestDoesNotAnswerAnOlderCard() { + val ref = SecretRequestRef("ACME_TOKEN", requestedAt = "t1") + assertTrue(ref.answers("ACME_TOKEN", "t1")) + assertFalse(ref.answers("ACME_TOKEN", "t2")) + assertTrue(SecretRequestRef("ACME_TOKEN").answers("ACME_TOKEN", "t2")) + } + + @Test + fun onlyBotsWithMatchesOrFailuresGetAFrameAcrossAllBots() { + val rows = mapOf("a1" to listOf(SecretRow("ACME", listOf("api.acme.com"), null, null)), "a2" to emptyList()) + val ids = listOf("a1", "a2", "a3") + assertEquals(listOf("a1", "a3"), secretBotsShown(ids, SKILLS_ALL, "", { rows[it].orEmpty() }, { it == "a3" })) + assertEquals(listOf("a1"), secretBotsShown(ids, SKILLS_ALL, "acme.com", { rows[it].orEmpty() }, { false })) + assertEquals(listOf("a2"), secretBotsShown(ids, "a2", "zzz", { rows[it].orEmpty() }, { false })) + } + + @Test + fun providerStatusFollowsTheWeb() { + val manager = PasswordManager("1password", "1Password", true, "t", emptyList()) + assertEquals("Signed in", providerStatus(provider.copy(credentialType = "oauth"), emptyList())) + assertEquals("Key saved", providerStatus(provider.copy(credentialType = "api_key"), emptyList())) + val referenced = provider.copy(credentialType = "api_key", apiKey = SecretStatus(true, "1password", "op://a/b/c")) + assertEquals("Key in 1Password", providerStatus(referenced, listOf(manager))) + assertEquals("Key in a password manager", providerStatus(referenced, emptyList())) + assertEquals("From environment", providerStatus(provider.copy(configured = true), emptyList())) + assertEquals("Signing in…", providerStatus(provider.copy(activeLoginId = "l1"), emptyList())) + assertNull(providerStatus(provider, emptyList())) + val external = ProviderExternalAuth("cli_missing", null, null, null, "Install it") + assertEquals("Not installed", providerStatus(provider.copy(externalAuth = external), emptyList())) + } + + @Test + fun providersSortByNameAndSearchNameOrID() { + val zeta = provider.copy(provider = "zeta", name = "Zeta") + val acme = provider.copy(provider = "acme", name = "Acme") + assertEquals(listOf("acme", "zeta"), matchingProviders(listOf(zeta, acme), "").map { it.provider }) + assertEquals(listOf("zeta"), matchingProviders(listOf(zeta, acme), "zet").map { it.provider }) + } + + @Test + fun onlyWebPagesLeaveTheApp() { + assertTrue(isWebLink("https://auth.example.com/device")) + assertTrue(isWebLink("HTTP://auth.example.com")) + assertFalse(isWebLink("intent://scan#Intent;end")) + assertFalse(isWebLink("javascript:alert(1)")) + } + + @Test + fun rollbackPutsARecordBackInPlaceAndKeepsOtherChanges() { + val a = credential.copy(name = "A") + val b = credential.copy(name = "B") + val c = credential.copy(name = "C") + val before = Credentials(listOf(a, b, c), emptyList()) + val after = Credentials(listOf(a, c, credential.copy(name = "D")), emptyList()) + assertEquals(listOf("A", "B", "C", "D"), after.restored(before, "B").credentials.map { it.name }) + assertEquals(listOf("A", "C", "D"), Credentials(listOf(a, c, credential.copy(name = "D")), emptyList()).restored(Credentials(emptyList(), emptyList()), "B").credentials.map { it.name }) + assertTrue(Logins(emptyList(), emptyList()).restored(Logins(emptyList(), emptyList()), "x").logins.isEmpty()) + } + + @Test + fun transcriptResultsBecomeRequestCards() { + fun message(tool: String, isError: Boolean = false) = CrumbleJson.decodeFromString( + TranscriptMessage.serializer(), + """{"id":"m","entryId":"e","role":"toolResult","content":"","toolName":"$tool","isError":$isError,"toolDetails":{"name":"ACME","hosts":["a.io"],"requestedAt":"t1"}}""", + ).domain() + assertEquals(SecretRequestRef("ACME", listOf("a.io"), "t1"), message("request_credential").credentialRequest) + assertEquals(SecretRequestRef("ACME", listOf("a.io"), "t1"), message("request_login").loginRequest) + assertNull(message("request_credential", isError = true).credentialRequest) + assertNull(message("other").credentialRequest) + assertTrue(ChatRow.shownInChat(message("request_login"))) + } + + @Test + fun savingAValueShowsTheRowAtOnceAndForgetsTheSecret() = runTest { + val transport = scripted() + transport.responses[PUT_CREDENTIAL] = 200 to credentialJson(hosts = listOf("api.acme.com", "*.acme.com"), updated = "server") + val gate = CompletableDeferred().also { transport.held[PUT_CREDENTIAL] = it } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.botCredentials = mapOf("a1" to Credentials(emptyList(), emptyList())) + newCredential(model) + + model.saveCredential() + testScheduler.runCurrent() + + assertNull(model.credentialForm) + val shown = model.botCredentials["a1"]!!.credentials.single() + assertEquals("", shown.updatedAt) + assertEquals(listOf("api.acme.com", "*.acme.com"), shown.hosts) + assertTrue(secretKey("credential", "a1", "ACME_TOKEN") in model.pendingMutations) + val body = bodyOf(transport.sent(PUT_CREDENTIAL).single()) + assertEquals(JsonPrimitive(SECRET), (body["secret"] as JsonObject)["value"]) + assertEquals(JsonArray(listOf(JsonPrimitive("api.acme.com"), JsonPrimitive("*.acme.com"))), body["hosts"]) + + transport.responses["GET $CREDENTIALS"] = 200 to credentialsJson(listOf(credentialJson(updated = "server"))) + gate.complete(Unit) + testScheduler.runCurrent() + + assertEquals(listOf("server"), model.botCredentials["a1"]!!.credentials.map { it.updatedAt }) + assertTrue(model.pendingMutations.isEmpty()) + } + + @Test + fun aLateListDoesNotReplaceAPendingSave() = runTest { + val transport = scripted() + transport.responses[PUT_CREDENTIAL] = 200 to credentialJson(updated = "server") + val list = CompletableDeferred().also { transport.held["GET $CREDENTIALS"] = it } + val save = CompletableDeferred().also { transport.held[PUT_CREDENTIAL] = it } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.openPanel(Route.Credentials) + testScheduler.runCurrent() + model.botCredentials = mapOf("a1" to Credentials(emptyList(), emptyList())) + newCredential(model) + model.saveCredential() + testScheduler.runCurrent() + + list.complete(Unit) + testScheduler.runCurrent() + + assertEquals("", model.botCredentials["a1"]!!.credentials.single().updatedAt) + transport.responses["GET $CREDENTIALS"] = 200 to credentialsJson(listOf(credentialJson(updated = "server"))) + save.complete(Unit) + testScheduler.runCurrent() + assertEquals("server", model.botCredentials["a1"]!!.credentials.single().updatedAt) + } + + @Test + fun aFailedSaveRemovesTheRowAndReopensTheFormWithTheEntries() = runTest { + val transport = scripted() + transport.responses[PUT_CREDENTIAL] = 400 to """{"error":"bad hosts"}""" + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.route = Route.Credentials + model.botCredentials = mapOf("a1" to Credentials(emptyList(), emptyList())) + newCredential(model) + + model.saveCredential() + testScheduler.runCurrent() + + assertTrue(model.botCredentials["a1"]!!.credentials.isEmpty()) + val form = model.credentialForm!! + assertEquals("bad hosts", form.error) + assertEquals(SECRET, form.secret.text) + assertEquals("", model.errorText) + + transport.responses[PUT_CREDENTIAL] = 200 to credentialJson() + transport.responses["GET $CREDENTIALS"] = 200 to credentialsJson(listOf(credentialJson())) + model.saveCredential() + testScheduler.runCurrent() + assertNull(model.credentialForm) + assertEquals(1, model.botCredentials["a1"]!!.credentials.size) + } + + @Test + fun aFailureAfterLeavingDropsTheSecretAndReportsIt() = runTest { + val transport = scripted() + transport.responses[PUT_CREDENTIAL] = 400 to """{"error":"bad hosts"}""" + val gate = CompletableDeferred().also { transport.held[PUT_CREDENTIAL] = it } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.route = Route.Credentials + model.botCredentials = mapOf("a1" to Credentials(emptyList(), emptyList())) + newCredential(model) + model.saveCredential() + testScheduler.runCurrent() + + model.openPanel(Route.Logins) + testScheduler.runCurrent() + gate.complete(Unit) + testScheduler.runCurrent() + + assertNull(model.credentialForm) + assertEquals("bad hosts", model.errorText) + assertTrue(model.botCredentials["a1"]!!.credentials.isEmpty()) + } + + @Test + fun aReferenceStaysPendingUntilThePasswordManagerAnswers() = runTest { + val transport = scripted() + transport.responses[PUT_CREDENTIAL] = 200 to credentialJson() + val gate = CompletableDeferred().also { transport.held[PUT_CREDENTIAL] = it } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.botCredentials = mapOf("a1" to Credentials(emptyList(), emptyList())) + newCredential(model, SecretDraft(manager = "1password", text = "op://v/i/f")) + + model.saveCredential() + testScheduler.runCurrent() + + assertTrue(model.credentialForm!!.saving) + assertFalse(model.credentialForm!!.ready) + assertTrue(model.botCredentials["a1"]!!.credentials.isEmpty()) + + transport.responses["GET $CREDENTIALS"] = 200 to credentialsJson(listOf(credentialJson())) + gate.complete(Unit) + testScheduler.runCurrent() + assertNull(model.credentialForm) + assertEquals(1, model.botCredentials["a1"]!!.credentials.size) + } + + @Test + fun aRefusedReferenceKeepsTheFormOpenWithItsError() = runTest { + val transport = scripted() + transport.responses[PUT_CREDENTIAL] = 400 to """{"error":"cannot read it"}""" + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.botCredentials = mapOf("a1" to Credentials(emptyList(), emptyList())) + newCredential(model, SecretDraft(manager = "1password", text = "op://v/i/f")) + + model.saveCredential() + testScheduler.runCurrent() + + val form = model.credentialForm!! + assertFalse(form.saving) + assertEquals("cannot read it", form.error) + assertEquals("op://v/i/f", form.secret.text) + } + + @Test + fun cardLoadsThenSavesAnswerAtOnceAndNeverStoresIt() = runTest { + val transport = scripted() + val store = RecordingStore() + transport.responses["GET $CREDENTIALS"] = 200 to credentialsJson(requests = listOf(credentialRequestJson())) + transport.responses[PUT_CREDENTIAL] = 200 to credentialJson() + val gate = CompletableDeferred().also { transport.held[PUT_CREDENTIAL] = it } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope, store) + model.selectAgent("a1") + model.applySnapshot(ChatSnapshot(agentId = "a1", messages = listOf(credentialMessage()))) + testScheduler.runCurrent() + + val request = model.botCredentials["a1"]!!.requests.single() + assertTrue(credentialReadKey(credentialMessage().credentialRequest!!) in model.freshSecretRequests) + model.openCredentialForm("a1", request = request) + model.credentialForm = model.credentialForm!!.copy(secret = SecretDraft(text = SECRET)) + model.saveCredential() + testScheduler.runCurrent() + + assertNull(model.credentialForm) + assertTrue(model.botCredentials["a1"]!!.requests.isEmpty()) + assertEquals(1, model.botCredentials["a1"]!!.credentials.size) + + transport.responses["GET $CREDENTIALS"] = 200 to credentialsJson(listOf(credentialJson())) + gate.complete(Unit) + testScheduler.runCurrent() + + assertEquals(1, model.botCredentials["a1"]!!.credentials.size) + assertTrue(transport.sent(PUT_CREDENTIAL).single().let(::bodyText).contains(SECRET)) + assertFalse(store.written.any { it.contains(SECRET) }) + } + + @Test + fun aFailedCardAnswerComesBackWithItsErrorAndKeepsPolling() = runTest { + val transport = scripted() + transport.responses["GET $CREDENTIALS"] = 200 to credentialsJson(requests = listOf(credentialRequestJson())) + transport.responses[PUT_CREDENTIAL] = 503 to """{"error":"down"}""" + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.selectAgent("a1") + model.applySnapshot(ChatSnapshot(agentId = "a1", messages = listOf(credentialMessage()))) + testScheduler.runCurrent() + val request = model.botCredentials["a1"]!!.requests.single() + model.openCredentialForm("a1", request = request) + model.credentialForm = model.credentialForm!!.copy(secret = SecretDraft(text = SECRET)) + + model.saveCredential() + testScheduler.runCurrent() + + assertEquals(SECRET, model.credentialForm?.secret?.text) + assertEquals("down", model.credentialForm?.error) + assertEquals(listOf(request), model.botCredentials["a1"]!!.requests) + assertTrue(model.botCredentials["a1"]!!.credentials.isEmpty()) + + val reads = transport.sent("GET $CREDENTIALS").size + testScheduler.advanceTimeBy(5_100) + testScheduler.runCurrent() + assertTrue(transport.sent("GET $CREDENTIALS").size > reads) + model.cancelStream() + } + + @Test + fun decliningACardSettlesItAtOnceAndRestoresItOnFailure() = runTest { + val transport = scripted() + transport.responses["GET $LOGINS"] = 200 to loginsJson(requests = listOf("""{"name":"github","hosts":["github.com"],"reason":"Sign in","oneTimeCode":false,"requestedAt":"t1"}""")) + val decline = "POST $LOGINS/github/decline" + transport.responses[decline] = 503 to """{"error":"down"}""" + val gate = CompletableDeferred().also { transport.held[decline] = it } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.selectAgent("a1") + model.applySnapshot(ChatSnapshot(agentId = "a1", messages = listOf(loginMessage()))) + testScheduler.runCurrent() + assertEquals(1, model.botLogins["a1"]!!.requests.size) + + model.declineLoginRequest("a1", "github") + testScheduler.runCurrent() + assertTrue(model.botLogins["a1"]!!.requests.isEmpty()) + + gate.complete(Unit) + testScheduler.runCurrent() + assertEquals(1, model.botLogins["a1"]!!.requests.size) + assertEquals("down", model.decisionErrors[secretKey("login", "a1", "github")]) + model.cancelStream() + } + + @Test + fun switchingBotsDropsTheOpenRequestForm() = runTest { + val transport = scripted() + transport.responses["GET /v1/agents/a2/chat"] = 503 to "" + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.selectAgent("a1") + model.openCredentialForm("a1") + model.selectAgent("a1") + assertNotNull(model.credentialForm) + model.selectAgent("a2") + assertNull(model.credentialForm) + } + + @Test + fun theChatRequestOpensTheEditableSheetWithTheBotsHosts() = runTest { + val transport = scripted() + transport.responses["GET $CREDENTIALS"] = 200 to credentialsJson(requests = listOf(credentialRequestJson())) + transport.responses[PUT_CREDENTIAL] = 200 to credentialJson() + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.selectAgent("a1") + model.applySnapshot(ChatSnapshot(agentId = "a1", messages = listOf(credentialMessage()))) + testScheduler.runCurrent() + val request = model.botCredentials["a1"]!!.requests.single() + + model.openCredentialForm("a1", request = request) + val form = model.credentialForm!! + assertEquals("a1", form.botID) + assertEquals(request, form.request) + assertEquals(request.hosts.joinToString(", "), form.hosts) + assertTrue(form.locked) + + model.credentialForm = form.copy(hosts = "api.acme.dev", secret = SecretDraft(text = SECRET)) + model.saveCredential() + testScheduler.runCurrent() + + val body = bodyText(transport.sent(PUT_CREDENTIAL).single()) + assertTrue(body.contains("api.acme.dev")) + assertFalse(request.hosts.any { body.contains(it) }) + assertEquals(Route.AgentChat("a1"), model.route) + model.cancelStream() + } + + @Test + fun aChatRequestAnsweredFromAPasswordManagerWaitsForTheServer() = runTest { + val transport = scripted() + transport.responses["GET $CREDENTIALS"] = 200 to credentialsJson(requests = listOf(credentialRequestJson())) + transport.responses[PUT_CREDENTIAL] = 200 to credentialJson() + val gate = CompletableDeferred().also { transport.held[PUT_CREDENTIAL] = it } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.selectAgent("a1") + model.applySnapshot(ChatSnapshot(agentId = "a1", messages = listOf(credentialMessage()))) + testScheduler.runCurrent() + val request = model.botCredentials["a1"]!!.requests.single() + + model.openCredentialForm("a1", request = request) + val form = model.credentialForm!! + model.credentialForm = form.copy(secret = SecretDraft(manager = "onepassword", text = "op://vault/item")) + model.saveCredential() + testScheduler.runCurrent() + + assertTrue(model.credentialForm!!.saving) + assertEquals(listOf(request), model.botCredentials["a1"]!!.requests) + + gate.complete(Unit) + testScheduler.runCurrent() + assertNull(model.credentialForm) + model.cancelStream() + } + + @Test + fun leavingAScreenDropsItsForms() = runTest { + val transport = scripted() + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + newCredential(model) + model.openLoginForm("a1") + model.openProviderKey(provider) + model.tokenForm = ManagerTokenForm(PasswordManager("1password", "1Password", false, null, emptyList()), SecretDraft(text = SECRET)) + model.navigate(Route.PasswordManagers) + assertNull(model.credentialForm) + assertNull(model.loginForm) + assertNull(model.providerKeyForm) + assertNull(model.tokenForm) + } + + @Test + fun savingALoginWithValuesShowsTheRowAndClearsTheForm() = runTest { + val transport = scripted() + transport.responses[PUT_LOGIN] = 200 to loginJson() + val gate = CompletableDeferred().also { transport.held[PUT_LOGIN] = it } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.botLogins = mapOf("a1" to Logins(emptyList(), emptyList())) + model.openLoginForm("a1") + model.loginForm = model.loginForm!!.copy(name = "github", hosts = "github.com", username = SecretDraft(text = "kev"), password = SecretDraft(text = SECRET)) + + model.saveLogin() + testScheduler.runCurrent() + + assertNull(model.loginForm) + val shown = model.botLogins["a1"]!!.logins.single() + assertNotNull(shown.fields.password) + assertNull(shown.fields.one_time_code) + val fields = bodyOf(transport.sent(PUT_LOGIN).single())["fields"] as JsonObject + assertEquals(JsonPrimitive(SECRET), (fields["password"] as JsonObject)["value"]) + + transport.responses["GET $LOGINS"] = 200 to loginsJson(listOf(loginJson())) + gate.complete(Unit) + testScheduler.runCurrent() + assertEquals("t", model.botLogins["a1"]!!.logins.single().createdAt) + } + + @Test + fun aOnePasswordItemWaitsForTheServerAndKeepsItsErrorInTheForm() = runTest { + val transport = scripted() + transport.responses[PUT_LOGIN] = 400 to """{"error":"cannot read the item"}""" + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.botLogins = mapOf("a1" to Logins(emptyList(), emptyList())) + model.openLoginForm("a1") + model.loginForm = model.loginForm!!.copy(name = "github", hosts = "github.com", mode = LoginMode.item, item = "op://vault/item") + + model.saveLogin() + assertTrue(model.loginForm!!.saving) + testScheduler.runCurrent() + + assertEquals("cannot read the item", model.loginForm!!.error) + assertTrue(model.botLogins["a1"]!!.logins.isEmpty()) + } + + @Test + fun deletingAppliesAtOnceAndRestoresTheRowInPlaceOnFailure() = runTest { + val transport = scripted() + val delete = "DELETE $CREDENTIALS/B" + transport.responses[delete] = 503 to """{"error":"down"}""" + val gate = CompletableDeferred().also { transport.held[delete] = it } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.route = Route.Credentials + model.botCredentials = mapOf("a1" to Credentials(listOf("A", "B", "C").map { credential.copy(name = it) }, emptyList())) + + model.deleteCredential("a1", "B") + testScheduler.runCurrent() + assertEquals(listOf("A", "C"), model.botCredentials["a1"]!!.credentials.map { it.name }) + + gate.complete(Unit) + testScheduler.runCurrent() + assertEquals(listOf("A", "B", "C"), model.botCredentials["a1"]!!.credentials.map { it.name }) + assertEquals("down", model.errorText) + } + + @Test + fun usesPageByTheLastRowUntilAShortPage() = runTest { + val transport = scripted() + val first = (1..50).joinToString(",") { """{"id":"u$it","at":"t","method":"GET","host":"a.io","path":"/x","status":${if (it == 1) "null" else "200"},"error":null}""" } + transport.responses["GET $CREDENTIALS/ACME_TOKEN/uses?limit=50"] = 200 to "[$first]" + transport.responses["GET $CREDENTIALS/ACME_TOKEN/uses?limit=50&before=u50"] = 200 to """[{"id":"u51","at":"t","method":"POST","host":"a.io","path":"/y","status":201,"error":null}]""" + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + + model.openSecretUses(SecretKind.credential, "a1", "ACME_TOKEN") + testScheduler.runCurrent() + val view = model.secretUses!! + assertEquals(50, view.rows.size) + assertTrue(view.hasMore) + assertEquals("GET a.io/x", view.rows[0].detail) + assertEquals("failed", view.rows[0].note) + + model.loadMoreSecretUses() + testScheduler.runCurrent() + assertEquals(51, model.secretUses!!.rows.size) + assertFalse(model.secretUses!!.hasMore) + } + + @Test + fun fillsNameTheFieldAndALateReplyIsDroppedOnceClosed() = runTest { + val transport = scripted() + val path = "GET $LOGINS/github/uses?limit=50" + transport.responses[path] = 200 to """[{"id":"u1","at":"t","host":"github.com","field":"one_time_code","error":"expired"}]""" + val gate = CompletableDeferred().also { transport.held[path] = it } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.openSecretUses(SecretKind.login, "a1", "github") + testScheduler.runCurrent() + model.closeSecretUses() + gate.complete(Unit) + testScheduler.runCurrent() + assertNull(model.secretUses) + + transport.held.remove(path) + model.openSecretUses(SecretKind.login, "a1", "github") + testScheduler.runCurrent() + assertEquals("One-time code on github.com", model.secretUses!!.rows.single().detail) + assertEquals("expired", model.secretUses!!.rows.single().note) + } + + @Test + fun connectingAPasswordManagerStaysPendingAndClearsTheToken() = runTest { + val transport = scripted() + val connect = "PUT /v1/password-managers/1password" + transport.responses[MANAGERS] = 200 to """{"passwordManagers":[${managerJson(connected = false)}]}""" + transport.responses[connect] = 200 to managerJson() + val gate = CompletableDeferred().also { transport.held[connect] = it } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.loadPasswordManagers() + testScheduler.runCurrent() + val manager = model.passwordManagers.single() + model.openManagerToken(manager) + model.tokenForm = model.tokenForm!!.copy(token = SecretDraft(text = " $SECRET ")) + + model.saveManagerToken() + testScheduler.runCurrent() + assertTrue(model.tokenForm!!.saving) + assertFalse(model.passwordManagers.single().connected) + assertEquals(JsonPrimitive(SECRET), bodyOf(transport.sent(connect).single())["token"]) + + transport.responses[MANAGERS] = 200 to """{"passwordManagers":[${managerJson()}]}""" + gate.complete(Unit) + testScheduler.runCurrent() + assertNull(model.tokenForm) + assertTrue(model.passwordManagers.single().connected) + } + + @Test + fun aRefusedTokenStaysInTheFormWithTheError() = runTest { + val transport = scripted() + transport.responses["PUT /v1/password-managers/1password"] = 400 to """{"error":"1Password rejected the token"}""" + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.openManagerToken(PasswordManager("1password", "1Password", false, null, emptyList())) + model.tokenForm = model.tokenForm!!.copy(token = SecretDraft(text = SECRET)) + + model.saveManagerToken() + testScheduler.runCurrent() + + assertEquals("1Password rejected the token", model.tokenForm!!.error) + assertEquals(SECRET, model.tokenForm!!.token.text) + assertFalse(model.tokenForm!!.saving) + } + + @Test + fun disconnectingAppliesAtOnceAndRollsBackWhenRefused() = runTest { + val transport = scripted() + val disconnect = "DELETE /v1/password-managers/1password" + transport.responses[disconnect] = 409 to """{"error":"1 secret still read from this password manager"}""" + val gate = CompletableDeferred().also { transport.held[disconnect] = it } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.loadPasswordManagers() + testScheduler.runCurrent() + + model.disconnectManager(model.passwordManagers.single()) + testScheduler.runCurrent() + assertFalse(model.passwordManagers.single().connected) + + gate.complete(Unit) + testScheduler.runCurrent() + assertTrue(model.passwordManagers.single().connected) + assertEquals("1 secret still read from this password manager", model.errorText) + } + + @Test + fun aManagerInUseCannotBeDisconnected() = runTest { + val transport = scripted() + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.disconnectManager(PasswordManager("1password", "1Password", true, "t", listOf("secret"))) + testScheduler.runCurrent() + assertTrue(transport.sent("DELETE /v1/password-managers/1password").isEmpty()) + } + + @Test + fun providerKeySavesAtOnceAndComesBackOnFailure() = runTest { + val transport = scripted() + val put = "PUT /v1/providers/openai" + transport.responses[put] = 503 to """{"error":"down"}""" + val gate = CompletableDeferred().also { transport.held[put] = it } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.route = Route.Providers + model.loadProviders() + testScheduler.runCurrent() + val account = model.providerAccounts.single() + model.openProviderKey(account) + model.providerKeyForm = model.providerKeyForm!!.copy(key = SecretDraft(text = SECRET)) + + model.saveProviderAccountKey() + testScheduler.runCurrent() + assertNull(model.providerKeyForm) + assertEquals("Key saved", providerStatus(model.providerAccounts.single(), emptyList())) + assertEquals(JsonPrimitive(SECRET), bodyOf(transport.sent(put).single())["value"]) + + gate.complete(Unit) + testScheduler.runCurrent() + assertEquals(account, model.providerAccounts.single()) + assertEquals(SECRET, model.providerKeyForm!!.key.text) + assertEquals("down", model.providerKeyForm!!.error) + } + + @Test + fun aProviderKeyReferenceWaitsAndRefreshesModels() = runTest { + val transport = scripted() + val put = "PUT /v1/providers/openai" + transport.responses[put] = 200 to """{"provider":"openai","configured":true}""" + val gate = CompletableDeferred().also { transport.held[put] = it } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.loadProviders() + testScheduler.runCurrent() + model.openProviderKey(model.providerAccounts.single()) + model.providerKeyForm = model.providerKeyForm!!.copy(key = SecretDraft(manager = "1password", text = "op://v/i/f")) + + model.saveProviderAccountKey() + testScheduler.runCurrent() + assertTrue(model.providerKeyForm!!.saving) + assertNull(model.providerAccounts.single().credentialType) + val reference = bodyOf(transport.sent(put).single())["reference"] as JsonObject + assertEquals(JsonPrimitive("op://v/i/f"), reference["reference"]) + + transport.responses["GET /v1/providers"] = 200 to "[${providerJson(credentialType = "api_key")}]" + gate.complete(Unit) + testScheduler.runCurrent() + assertNull(model.providerKeyForm) + assertEquals("api_key", model.providerAccounts.single().credentialType) + } + + @Test + fun signOutAppliesAtOnceAndRollsBackOnFailure() = runTest { + val transport = scripted() + transport.responses["GET /v1/providers"] = 200 to "[${providerJson(credentialType = "oauth")}]" + val delete = "DELETE /v1/providers/openai" + transport.responses[delete] = 503 to """{"error":"down"}""" + val gate = CompletableDeferred().also { transport.held[delete] = it } + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + model.loadProviders() + testScheduler.runCurrent() + val account = model.providerAccounts.single() + + model.removeProviderCredential(account) + testScheduler.runCurrent() + assertNull(model.providerAccounts.single().credentialType) + + gate.complete(Unit) + testScheduler.runCurrent() + assertEquals(account, model.providerAccounts.single()) + assertEquals("down", model.errorText) + } + + private fun startedLogin(transport: SecretTransport, scope: TestScope): AppModel { + val model = modelWith(transport, scope) + transport.responses["POST /v1/providers/openai/login"] = 201 to sessionJson() + transport.responses[SESSION] = 200 to sessionJson(prompt = promptJson()) + return model + } + + @Test + fun signInShowsSuccessOnlyOnceTheServerConfirms() = runTest { + val transport = scripted() + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = startedLogin(transport, scope) + val gate = CompletableDeferred().also { transport.held["POST /v1/providers/openai/login"] = it } + + model.openProviderLogin(provider) + model.startProviderLogin() + testScheduler.runCurrent() + assertTrue(model.providerLogin!!.starting) + assertNull(model.providerLogin!!.session) + + gate.complete(Unit) + testScheduler.runCurrent() + assertEquals("l1", model.providerLogin!!.sessionID) + assertEquals("p1", model.providerLogin!!.session!!.prompt!!.id) + assertEquals(JsonPrimitive("oauth"), bodyOf(transport.sent("POST /v1/providers/openai/login").single())["method"]) + + model.providerLogin = model.providerLogin!!.copy(answer = SecretDraft(text = SECRET)) + val answer = "POST /v1/provider-logins/l1/responses" + transport.responses[answer] = 200 to sessionJson(prompt = promptJson("p2", "text")) + val answerGate = CompletableDeferred().also { transport.held[answer] = it } + model.answerProviderLogin(SECRET) + testScheduler.runCurrent() + assertTrue(model.providerLogin!!.answering) + + // A read from before the answer must not bring the old prompt back. + testScheduler.advanceTimeBy(1_100) + testScheduler.runCurrent() + answerGate.complete(Unit) + testScheduler.runCurrent() + assertEquals("p2", model.providerLogin!!.session!!.prompt!!.id) + assertEquals("", model.providerLogin!!.answer.text) + val body = bodyOf(transport.sent(answer).single()) + assertEquals(JsonPrimitive("p1"), body["promptId"]) + assertEquals(JsonPrimitive(SECRET), body["value"]) + + transport.responses[SESSION] = 200 to sessionJson(status = "succeeded") + transport.responses["GET /v1/providers"] = 200 to "[${providerJson(credentialType = "oauth")}]" + testScheduler.advanceTimeBy(1_100) + testScheduler.runCurrent() + assertEquals("succeeded", model.providerLogin!!.session!!.status) + assertEquals("oauth", model.providerAccounts.single().credentialType) + model.hideProviderLogin() + testScheduler.advanceTimeBy(5_000) + testScheduler.runCurrent() + } + + @Test + fun aFailedAnswerKeepsTheEntryAndTheSignIn() = runTest { + val transport = scripted() + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = startedLogin(transport, scope) + transport.responses["POST /v1/provider-logins/l1/responses"] = 400 to """{"error":"wrong code"}""" + model.openProviderLogin(provider.copy(activeLoginId = "l1")) + testScheduler.runCurrent() + model.providerLogin = model.providerLogin!!.copy(answer = SecretDraft(text = SECRET)) + + model.answerProviderLogin(SECRET) + testScheduler.runCurrent() + + assertEquals("wrong code", model.providerLogin!!.answerError) + assertEquals(SECRET, model.providerLogin!!.answer.text) + assertFalse(model.providerLogin!!.answering) + model.hideProviderLogin() + } + + @Test + fun aNewPromptDropsTheOldEntry() = runTest { + val transport = scripted() + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = startedLogin(transport, scope) + model.openProviderLogin(provider.copy(activeLoginId = "l1")) + testScheduler.runCurrent() + model.providerLogin = model.providerLogin!!.copy(answer = SecretDraft(text = SECRET)) + + transport.responses[SESSION] = 200 to sessionJson(prompt = promptJson("p2")) + testScheduler.advanceTimeBy(1_100) + testScheduler.runCurrent() + + assertEquals("", model.providerLogin!!.answer.text) + model.hideProviderLogin() + } + + @Test + fun aLostSignInStopsReadingAndSaysSo() = runTest { + val transport = scripted() + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = modelWith(transport, scope) + transport.responses[SESSION] = 410 to """{"error":"gone"}""" + model.openProviderLogin(provider.copy(activeLoginId = "l1")) + testScheduler.runCurrent() + assertTrue(model.providerLogin!!.gone) + val reads = transport.sent(SESSION).size + testScheduler.advanceTimeBy(3_000) + testScheduler.runCurrent() + assertEquals(reads, transport.sent(SESSION).size) + } + + @Test + fun cancellingClosesEvenWhenTheServerFailsAndHidingStopsReading() = runTest { + val transport = scripted() + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = startedLogin(transport, scope) + transport.responses["DELETE /v1/provider-logins/l1"] = 503 to """{"error":"down"}""" + model.openProviderLogin(provider.copy(activeLoginId = "l1")) + testScheduler.runCurrent() + + model.cancelProviderLogin() + testScheduler.runCurrent() + assertNull(model.providerLogin) + val reads = transport.sent(SESSION).size + testScheduler.advanceTimeBy(3_000) + testScheduler.runCurrent() + assertEquals(reads, transport.sent(SESSION).size) + } + + @Test + fun aLateSignInReplyIsDroppedAfterHiding() = runTest { + val transport = scripted() + val scope = TestScope(StandardTestDispatcher(testScheduler)) + val model = startedLogin(transport, scope) + val gate = CompletableDeferred().also { transport.held["POST /v1/providers/openai/login"] = it } + model.openProviderLogin(provider) + model.startProviderLogin() + testScheduler.runCurrent() + model.hideProviderLogin() + gate.complete(Unit) + testScheduler.runCurrent() + assertNull(model.providerLogin) + assertTrue(transport.sent(SESSION).isEmpty()) + } +} diff --git a/app/src/test/java/dev/crumble/android/SignOutTests.kt b/app/src/test/java/dev/crumble/android/SignOutTests.kt new file mode 100644 index 0000000..634b0fd --- /dev/null +++ b/app/src/test/java/dev/crumble/android/SignOutTests.kt @@ -0,0 +1,110 @@ +package dev.crumble.android + +import dev.crumble.android.model.AppModel +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import dev.crumble.android.storage.InMemoryCredentialStore +import java.nio.charset.StandardCharsets +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +private class SignOutTransport(private val status: Int) : HttpTransport { + val requests = mutableListOf() + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + requests.add(request) + return HttpResponseData(status, "{}".toByteArray(StandardCharsets.UTF_8)) + } + + override suspend fun openStream(request: HttpRequestData): HttpStreamResponse = + throw UnsupportedOperationException("streams are not used here") +} + +@OptIn(ExperimentalCoroutinesApi::class) +class SignOutTests { + private fun store() = InMemoryCredentialStore( + mapOf( + "server-url" to "https://crumble.example", + "server-token" to "session", + "account-email" to "me@example.com", + "recent-chat:abc:a1" to "{}", + "push-state-v1" to "{}", + ), + ) + + @Test + fun signOutRevokesTheSessionThenForgetsIt() = runTest { + val transport = SignOutTransport(200) + val credentials = store() + val order = mutableListOf() + val model = AppModel( + client = APIClient("https://crumble.example", "session", transport), + credentials = credentials, + scope = this, + transport = transport, + onSignOut = { order.add("push ${transport.requests.size}") }, + ) + model.token = "session" + model.password = "typed" + model.signOut() + runCurrent() + + assertEquals(listOf("push 0"), order) + assertEquals("POST /api/auth/sign-out", transport.requests.single().let { "${it.method} ${it.pathWithQuery}" }) + assertEquals("Bearer session", transport.requests.single().headers["Authorization"]) + assertNull(credentials.read("server-token")) + assertNull(credentials.read("account-email")) + assertNull(credentials.read("recent-chat:abc:a1")) + assertEquals("https://crumble.example", credentials.read("server-url")) + assertEquals("{}", credentials.read("push-state-v1")) + assertEquals("", model.token) + assertEquals("", model.client?.token) + assertEquals("", model.password) + assertEquals("Signed out", model.notice) + } + + @Test + fun signOutStillForgetsTheSessionWhenTheServerFails() = runTest { + val transport = SignOutTransport(503) + val credentials = store() + val model = AppModel( + client = APIClient("https://crumble.example", "session", transport), + credentials = credentials, + scope = this, + transport = transport, + ) + model.token = "session" + model.signOut() + runCurrent() + + assertNull(credentials.read("server-token")) + assertEquals("", model.token) + assertEquals( + "Signed out of this device. The server couldn't be reached, so the session may stay active there.", + model.errorText, + ) + } + + @Test + fun anAlreadyExpiredSessionCountsAsSignedOut() = runTest { + val transport = SignOutTransport(401) + val model = AppModel( + client = APIClient("https://crumble.example", "session", transport), + credentials = store(), + scope = this, + transport = transport, + ) + model.token = "session" + model.signOut() + runCurrent() + + assertEquals("Signed out", model.notice) + } +} diff --git a/app/src/test/java/dev/crumble/android/SkillsMemoryAvatarTests.kt b/app/src/test/java/dev/crumble/android/SkillsMemoryAvatarTests.kt new file mode 100644 index 0000000..1b9db48 --- /dev/null +++ b/app/src/test/java/dev/crumble/android/SkillsMemoryAvatarTests.kt @@ -0,0 +1,888 @@ +package dev.crumble.android + +import dev.crumble.android.generated.BotAvatarDefinition +import dev.crumble.android.generated.LearnedChange +import dev.crumble.android.generated.MemorySource +import dev.crumble.android.model.ActivityRecord +import dev.crumble.android.model.Agent +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.BulkAction +import dev.crumble.android.model.CrumbleJson +import dev.crumble.android.model.DiffLine +import dev.crumble.android.model.Memory +import dev.crumble.android.model.Route +import dev.crumble.android.model.SKILLS_SHARED +import dev.crumble.android.model.SharedSkill +import dev.crumble.android.model.SkillDraft +import dev.crumble.android.model.SkillInstallForm +import dev.crumble.android.model.applyBulkAction +import dev.crumble.android.model.diff +import dev.crumble.android.model.lineDiff +import dev.crumble.android.model.memoryAge +import dev.crumble.android.model.memoryLine +import dev.crumble.android.model.memorySourceLabel +import dev.crumble.android.model.revertPrompt +import dev.crumble.android.model.selectionCatalog +import dev.crumble.android.model.skillGlimpse +import dev.crumble.android.model.skippedNote +import dev.crumble.android.model.visibleIn +import dev.crumble.android.network.APIClient +import dev.crumble.android.network.HttpRequestData +import dev.crumble.android.network.HttpResponseData +import dev.crumble.android.network.HttpStreamResponse +import dev.crumble.android.network.HttpTransport +import dev.crumble.android.ui.placeholderAvatar +import java.io.ByteArrayInputStream +import java.nio.charset.StandardCharsets +import java.time.Instant +import java.util.Collections +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.jsonObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +private const val TIME = "2026-10-18T10:00:00Z" + +private fun packageJson( + id: String, + agentId: String? = "a1", + name: String = "Triage", + instructions: String = "Sort things", + pinned: Boolean = false, + origin: String? = null, +) = """{"id":"$id","name":"$name","instructions":"$instructions","createdAt":"$TIME","updatedAt":"$TIME","agentId":${agentId?.let { "\"$it\"" } ?: "null"},"description":"","documents":[{"path":"ref.md","content":"Doc"}],"createdBy":"owner","sourceExecutionId":null,"useCount":0,"lastUsedAt":null,"state":"active","pinned":$pinned${origin?.let { ",\"origin\":$it" } ?: ""}}""" + +private const val ORIGIN = """{"repository":"owner/repo","branch":"main","path":"skills/triage","commit":"abcdef123456","digest":"d"}""" + +private fun sharedRow(id: String, update: String = "null", origin: String = ORIGIN) = + """{"id":"$id","name":"$id","instructions":"Do it","createdAt":"$TIME","updatedAt":"$TIME","source":"shared","description":"Short","origin":$origin,"update":$update}""" + +private fun skillJson(id: String, name: String = "Saved") = + """{"id":"$id","name":"$name","instructions":"Do it","createdAt":"$TIME","updatedAt":"$TIME"}""" + +private fun memoryJson(id: String, content: String, agentId: String? = null, source: String = "null") = + """{"id":"$id","agentId":${agentId?.let { "\"$it\"" } ?: "null"},"content":"$content","source":$source,"createdAt":"$TIME","updatedAt":"$TIME"}""" + +private fun changeJson(id: String, before: String = "null", after: String = "null", target: String = "memory", targetId: String = "m1", agentId: String? = null, action: String = "update") = + """{"id":"$id","agentId":${agentId?.let { "\"$it\"" } ?: "null"},"actor":"bot","target":"$target","targetId":"$targetId","action":"$action","before":$before,"after":$after,"source":null,"revertsId":null,"createdAt":"$TIME"}""" + +private fun listing(vararg rows: String) = + """{"repository":"owner/repo","branch":"main","commit":"c1","path":"","skills":[${rows.joinToString(",")}],"omitted":0}""" + +private fun candidate(path: String, status: String = "new") = + """{"path":"$path","name":"$path","description":"","status":"$status","problem":null,"skipped":[],"skillId":null}""" + +private fun changeOf(json: String) = CrumbleJson.decodeFromString(LearnedChange.serializer(), json) + +/** Answers by "METHOD path", holding back any request whose key is in `held`. */ +private class Script : HttpTransport { + val requests: MutableList = Collections.synchronizedList(mutableListOf()) + val held = mutableMapOf>() + val responses = mutableMapOf>() + /** Answers before `responses`, for requests told apart by their body. */ + var override: (HttpRequestData) -> Pair? = { null } + var running = 0 + var mostRunning = 0 + + override suspend fun execute(request: HttpRequestData): HttpResponseData { + val key = "${request.method} ${request.pathWithQuery}" + requests.add(request) + synchronized(this) { + running += 1 + mostRunning = maxOf(mostRunning, running) + } + delay(1) + held[key]?.await() + synchronized(this) { running -= 1 } + val (status, body) = override(request) ?: responses[key] ?: (500 to """{"error":"unscripted $key"}""") + return HttpResponseData(status, body.toByteArray(StandardCharsets.UTF_8)) + } + + override suspend fun openStream(request: HttpRequestData) = + HttpStreamResponse(404, ByteArrayInputStream(ByteArray(0))) + + fun hold(key: String) = CompletableDeferred().also { held[key] = it } + fun sent(key: String) = requests.filter { "${it.method} ${it.pathWithQuery}" == key } + fun bodyOf(key: String) = sent(key).single().body!!.toString(StandardCharsets.UTF_8).let { CrumbleJson.parseToJsonElement(it).jsonObject } +} + +private val BOTS = listOf(Agent(id = "a1", name = "Ada", enabled = true), Agent(id = "a2", name = "Kev", enabled = true)) + +@OptIn(ExperimentalCoroutinesApi::class) +class SkillsMemoryAvatarTests { + private fun model(scope: TestScope, transport: Script) = AppModel( + client = APIClient("http://example.com", "token", transport), + scope = scope.backgroundScope, + ).also { it.agents = BOTS } + + private fun TestScope.settle() { + testScheduler.advanceTimeBy(50) + runCurrent() + } + + // Skills page + + @Test + fun personalSkillsLoadPerBotAndOneFailureKeepsTheRest() = runTest { + val transport = Script().apply { + responses["GET /v1/agents"] = 200 to "[${agentFixture("a1", "Ada")},${agentFixture("a2", "Kev")}]" + responses["GET /v1/skills"] = 200 to "[${sharedRow("s1")}]" + responses["GET /v1/agents/a1/skills"] = 200 to "[${packageJson("p1")}]" + responses["GET /v1/agents/a2/skills"] = 500 to """{"error":"busy"}""" + } + val app = model(this, transport) + + app.openPanel(Route.Skills) + settle() + + assertEquals(listOf("p1"), app.agentSkills["a1"]?.map { it.id }) + assertEquals("busy", app.agentSkillErrors["a2"]) + assertEquals(listOf("s1"), app.sharedSkills.map { it.id }) + assertEquals("Short", app.sharedSkills.single().description) + assertEquals("owner/repo", app.sharedSkills.single().origin?.repository) + } + + @Test + fun aDelayedPersonalSkillShowsAtOnceAndReconcilesWithoutDuplicates() = runTest { + val transport = Script().apply { responses["POST /v1/agents/a1/skills"] = 201 to packageJson("p9", name = "New") } + val gate = transport.hold("POST /v1/agents/a1/skills") + val app = model(this, transport) + app.skillDraft = SkillDraft(skillID = "", agentID = "a1", name = "New", instructions = "Do") + + app.saveSkill() + settle() + assertEquals(listOf("New"), app.agentSkills["a1"]?.map { it.name }) + assertTrue(app.agentSkills["a1"]!!.single().id.startsWith("pending-")) + assertNull(app.skillDraft) + app.agents = app.agents.map { it.copy(description = "Newer") } + + gate.complete(Unit) + settle() + + assertEquals(listOf("p9"), app.agentSkills["a1"]?.map { it.id }) + assertEquals(listOf("New"), app.agents.first().skills?.map { it.name }) + assertEquals("Newer", app.agents.first().description) + assertEquals(setOf("name", "instructions"), transport.bodyOf("POST /v1/agents/a1/skills").keys) + } + + @Test + fun editingAPersonalSkillRestoresItsPlaceAndTheDraftOnFailure() = runTest { + val transport = Script().apply { responses["PATCH /v1/agents/a1/skills/p1"] = 500 to """{"error":"no"}""" } + val gate = transport.hold("PATCH /v1/agents/a1/skills/p1") + val app = model(this, transport) + app.route = Route.Skills + app.agentSkills = mapOf("a1" to listOf(packageOf("p1", "One"), packageOf("p2", "Two"))) + app.openSkillForm("p1", "a1") + app.skillDraft = app.skillDraft!!.copy(name = "Edited") + + app.saveSkill() + settle() + assertEquals(listOf("Edited", "Two"), app.agentSkills["a1"]?.map { it.name }) + gate.complete(Unit) + settle() + + assertEquals(listOf("One", "Two"), app.agentSkills["a1"]?.map { it.name }) + assertEquals("Edited", app.skillDraft?.name) + assertEquals("no", app.errorText) + } + + private fun packageOf(id: String, name: String, pinned: Boolean = false) = + CrumbleJson.decodeFromString(dev.crumble.android.generated.SkillPackage.serializer(), packageJson(id, name = name, pinned = pinned)) + + @Test + fun pinAndDeleteApplyAtOnceAndRollBack() = runTest { + val transport = Script().apply { + responses["PATCH /v1/agents/a1/skills/p1"] = 500 to """{"error":"no"}""" + responses["DELETE /v1/agents/a1/skills/p2"] = 500 to """{"error":"no"}""" + } + val pinGate = transport.hold("PATCH /v1/agents/a1/skills/p1") + val deleteGate = transport.hold("DELETE /v1/agents/a1/skills/p2") + val app = model(this, transport) + app.agentSkills = mapOf("a1" to listOf(packageOf("p1", "One"), packageOf("p2", "Two"))) + + app.toggleSkillPin("a1", "p1") + app.deleteAgentSkill("a1", "p2") + settle() + assertEquals(listOf(true), app.agentSkills["a1"]?.map { it.pinned }) + assertEquals("""{"pinned":true}""", transport.sent("PATCH /v1/agents/a1/skills/p1").single().body!!.toString(StandardCharsets.UTF_8)) + + pinGate.complete(Unit) + deleteGate.complete(Unit) + settle() + + assertEquals(listOf("p1", "p2"), app.agentSkills["a1"]?.map { it.id }) + assertEquals(listOf(false, false), app.agentSkills["a1"]?.map { it.pinned }) + } + + @Test + fun aNewSharedSkillAssignsItsBotsAndAFailedAssignmentLeavesTheSkillSaved() = runTest { + val transport = Script().apply { + responses["POST /v1/skills"] = 201 to skillJson("s9", "New") + responses["POST /v1/skills/s9/assignment"] = 500 to """{"error":"full"}""" + } + val gate = transport.hold("POST /v1/skills") + val app = model(this, transport) + app.skillDraft = SkillDraft(skillID = "", agentID = null, name = "New", instructions = "Do", usedBy = setOf("a1")) + + app.saveSkill() + settle() + val provisional = app.sharedSkills.single().id + assertTrue(provisional.startsWith("pending-")) + assertEquals(listOf(provisional), app.agents.first().sharedSkills) + + gate.complete(Unit) + settle() + + assertEquals(listOf("s9"), app.sharedSkills.map { it.id }) + assertEquals(emptyList(), app.agents.first().sharedSkills) + assertEquals("full", app.errorText) + assertNull(app.skillDraft) + } + + @Test + fun editingUsedByAssignsAndUnassignsOnlyBotsThatDiffer() = runTest { + val transport = Script().apply { + responses["PATCH /v1/skills/s1"] = 200 to skillJson("s1") + responses["POST /v1/skills/s1/assignment"] = 200 to """{"skipped":false}""" + } + val app = model(this, transport) + app.sharedSkills = listOf(SharedSkill(id = "s1", name = "Old", instructions = "Do", source = "shared", description = "Keep")) + app.agents = listOf(BOTS[0].copy(sharedSkills = listOf("s1")), BOTS[1].copy(sharedSkills = emptyList())) + app.openSkillForm("s1") + assertEquals(setOf("a1"), app.skillDraft?.usedBy) + app.skillDraft = app.skillDraft!!.copy(usedBy = setOf("a2")) + + app.saveSkill() + settle() + + assertEquals(listOf(emptyList(), listOf("s1")), app.agents.map { it.sharedSkills }) + assertEquals(2, transport.sent("POST /v1/skills/s1/assignment").size) + assertEquals("Keep", app.sharedSkills.single().description) + } + + @Test + fun copyingAnInstalledSkillSendsItsDocumentsAndDropsTheOriginAndRecovers() = runTest { + val transport = Script().apply { + responses["GET /v1/skills/s1"] = 200 to packageJson("s1", agentId = null, name = "Triage", origin = ORIGIN) + responses["POST /v1/skills"] = 201 to skillJson("s2", "Triage copy") + } + val gate = transport.hold("POST /v1/skills") + val app = model(this, transport) + app.sharedSkills = listOf(SharedSkill(id = "s1", name = "Triage", source = "shared")) + + app.copySkill("s1") + settle() + assertEquals(listOf("Triage", "Triage copy"), app.sharedSkills.map { it.name }) + assertNull(app.sharedSkills.last().origin) + gate.complete(Unit) + settle() + assertEquals(listOf("s1", "s2"), app.sharedSkills.map { it.id }) + val body = transport.bodyOf("POST /v1/skills") + assertEquals("\"Triage copy\"", body["name"].toString()) + assertEquals("""[{"path":"ref.md","content":"Doc"}]""", body["documents"].toString()) + + transport.responses["GET /v1/skills/s1"] = 500 to """{"error":"gone"}""" + app.copySkill("s1") + settle() + assertEquals(listOf("s1", "s2"), app.sharedSkills.map { it.id }) + assertEquals("gone", app.errorText) + } + + @Test + fun updateCheckStaysPendingUntilAnsweredAndReportsFailures() = runTest { + val transport = Script().apply { + responses["POST /v1/skills/updates/check"] = 200 to """{"failed":[{"repository":"o/r","branch":"main","message":"404"}]}""" + responses["GET /v1/agents"] = 200 to "[]" + responses["GET /v1/skills"] = 200 to "[]" + } + val gate = transport.hold("POST /v1/skills/updates/check") + val app = model(this, transport) + + app.checkSkillUpdates() + app.checkSkillUpdates() + settle() + assertTrue(app.checkingSkillUpdates) + gate.complete(Unit) + settle() + + assertFalse(app.checkingSkillUpdates) + assertEquals(listOf("Couldn't check o/r (main): 404"), app.skillCheckFailures) + assertEquals(1, transport.sent("POST /v1/skills/updates/check").size) + } + + // GitHub install + + @Test + fun aLateBrowseAnswerNeverReplacesWhatWasTypedSince() = runTest { + val transport = Script().apply { responses["POST /v1/skills/github/browse"] = 200 to listing(candidate("a")) } + val gate = transport.hold("POST /v1/skills/github/browse") + val app = model(this, transport) + app.openSkillInstall() + app.changeSkillLocation("owner/repo") + + app.findSkills() + settle() + assertTrue(app.skillInstall?.browsing == true) + app.changeSkillLocation("owner/other") + gate.complete(Unit) + settle() + + assertEquals("owner/other", app.skillInstall?.location) + assertNull(app.skillInstall?.listing) + assertFalse(app.skillInstall?.browsing == true) + } + + @Test + fun browsingChecksOnlyNewSkillsAndAFailureStaysInTheSheet() = runTest { + val transport = Script().apply { + responses["POST /v1/skills/github/browse"] = 200 to listing(candidate("a"), candidate("b", "installed")) + } + val app = model(this, transport) + app.openSkillInstall() + app.changeSkillLocation(" owner/repo ") + + app.findSkills() + settle() + assertEquals(setOf("a"), app.skillInstall?.picked) + assertEquals("\"owner/repo\"", transport.bodyOf("POST /v1/skills/github/browse")["location"].toString()) + + transport.responses["POST /v1/skills/github/browse"] = 502 to """{"error":"GitHub is down"}""" + app.findSkills() + settle() + assertEquals("GitHub is down", app.skillInstall?.error) + } + + @Test + fun installStaysPendingUntilConfirmedAndKeepsPicksOnFailure() = runTest { + val transport = Script().apply { + responses["POST /v1/skills/github/install"] = 502 to """{"error":"Rate limited"}""" + responses["GET /v1/agents"] = 200 to "[]" + responses["GET /v1/skills"] = 200 to "[${sharedRow("s1")}]" + } + val gate = transport.hold("POST /v1/skills/github/install") + val app = model(this, transport) + app.skillInstall = SkillInstallForm( + location = "owner/repo", + listing = CrumbleJson.decodeFromString(dev.crumble.android.generated.SkillListing.serializer(), listing(candidate("a"), candidate("b"))), + picked = setOf("b"), + botIDs = setOf("a2"), + ) + + app.installSkills() + settle() + assertTrue(app.skillInstall?.installing == true) + assertTrue(app.sharedSkills.isEmpty()) + gate.complete(Unit) + settle() + + assertEquals("Rate limited", app.skillInstall?.error) + assertEquals(setOf("b"), app.skillInstall?.picked) + assertFalse(app.skillInstall?.installing == true) + val body = transport.bodyOf("POST /v1/skills/github/install") + assertEquals("""["b"]""", body["paths"].toString()) + assertEquals("""["a2"]""", body["botIds"].toString()) + assertEquals("\"c1\"", body["commit"].toString()) + + transport.responses["POST /v1/skills/github/install"] = 200 to "[${packageJson("s1", agentId = null, origin = ORIGIN)}]" + transport.held.clear() + app.installSkills() + settle() + assertNull(app.skillInstall) + assertEquals(listOf("s1"), app.sharedSkills.map { it.id }) + } + + @Test + fun applyingAnUpdateChangesTheRowOnlyOnceConfirmed() = runTest { + val pendingJson = """{"commit":"c2","name":"Triage","description":"","instructions":"New line","documents":[],"skipped":["big.bin"]}""" + val transport = Script().apply { + responses["GET /v1/skills/s1"] = 200 to packageJson("s1", agentId = null, origin = ORIGIN) + responses["GET /v1/skills/s1/update"] = 200 to pendingJson + responses["POST /v1/skills/s1/update"] = 500 to """{"error":"Conflict"}""" + responses["GET /v1/agents"] = 200 to "[]" + responses["GET /v1/skills"] = 200 to "[${sharedRow("s1")}]" + } + val gate = transport.hold("POST /v1/skills/s1/update") + val app = model(this, transport) + app.sharedSkills = listOf(SharedSkill(id = "s1", name = "Triage", instructions = "Old", source = "shared")) + + app.openSkillUpdate("s1") + settle() + assertEquals(listOf("big.bin"), app.skillUpdate?.pending?.skipped) + assertNotNull(app.skillUpdate?.current) + + app.applySkillUpdate() + settle() + assertTrue(app.skillUpdate?.applying == true) + assertEquals("Old", app.sharedSkills.single().instructions) + gate.complete(Unit) + settle() + assertEquals("Conflict", app.skillUpdate?.error) + assertEquals("Old", app.sharedSkills.single().instructions) + + transport.held.clear() + transport.responses["POST /v1/skills/s1/update"] = 200 to packageJson("s1", agentId = null, instructions = "New line", origin = ORIGIN) + app.applySkillUpdate() + settle() + assertNull(app.skillUpdate) + } + + // Bulk actions + + private fun catalog(app: AppModel) = selectionCatalog(app.sharedSkills, app.agents, app.agentSkills) + + @Test + fun defaultSkillsNeverEnterTheSelectionAndScopesFilterIt() = runTest { + val app = model(this, Script()) + app.sharedSkills = listOf( + SharedSkill(id = "d1", name = "Tasks", source = "bundled"), + SharedSkill(id = "s1", name = "Shared", source = "shared"), + ) + app.agentSkills = mapOf("a1" to listOf(packageOf("p1", "Own"))) + + val skills = catalog(app) + + assertEquals(listOf("s1", "p1"), skills.map { it.id }) + assertEquals(listOf("s1"), skills.visibleIn(SKILLS_SHARED, "").map { it.id }) + assertEquals(listOf("p1"), skills.visibleIn("a1", "").map { it.id }) + assertEquals(listOf("p1"), skills.visibleIn("all", "own").map { it.id }) + } + + @Test + fun bulkDeleteRemovesAtOnceAndRestoresOnlyFailuresWhichStaySelected() = runTest { + val transport = Script().apply { + responses["DELETE /v1/skills/s1"] = 204 to "" + responses["DELETE /v1/agents/a1/skills/p1"] = 500 to """{"error":"locked"}""" + responses["GET /v1/agents"] = 200 to "[${agentFixture("a1", "Ada")}]" + responses["GET /v1/skills"] = 200 to "[]" + responses["GET /v1/agents/a1/skills"] = 200 to "[${packageJson("p1")}]" + } + val gate = transport.hold("DELETE /v1/agents/a1/skills/p1") + val app = model(this, transport) + app.sharedSkills = listOf(SharedSkill(id = "s1", name = "One", source = "shared")) + app.agents = listOf(BOTS[0].copy(sharedSkills = listOf("s1")), BOTS[1]) + app.agentSkills = mapOf("a1" to listOf(packageOf("p1", "Own"))) + app.selectedSkills = setOf("s1", "p1") + + app.runBulkAction(BulkAction.delete) + settle() + assertTrue(app.sharedSkills.isEmpty()) + assertTrue(app.agentSkills["a1"]!!.isEmpty()) + assertEquals(emptyList(), app.agents.first().sharedSkills) + assertTrue("skills:bulk" in app.pendingMutations) + + gate.complete(Unit) + settle() + + assertEquals(listOf("p1"), app.agentSkills["a1"]?.map { it.id }) + assertTrue(app.sharedSkills.isEmpty()) + assertEquals(setOf("p1"), app.selectedSkills) + assertEquals( + listOf("1 of 2 skills processed; 1 failed and remain selected.", "Failed Own (Ada): locked"), + app.bulkReport.map { it.text }, + ) + } + + @Test + fun bulkDeleteRestoresASharedSkillToTheBotsThatUsedIt() = runTest { + val transport = Script().apply { responses["DELETE /v1/skills/s1"] = 500 to """{"error":"no"}""" } + val app = model(this, transport) + app.sharedSkills = listOf(SharedSkill(id = "s1", name = "One", source = "shared")) + app.agents = listOf(BOTS[0].copy(sharedSkills = listOf("s1"))) + app.selectedSkills = setOf("s1") + + app.runBulkAction(BulkAction.delete) + settle() + + assertEquals(listOf("s1"), app.sharedSkills.map { it.id }) + assertEquals(listOf("s1"), app.agents.first().sharedSkills) + } + + @Test + fun bulkAssignAppliesAtOnceAndReportsSkippedBots() = runTest { + val transport = Script().apply { + responses["POST /v1/skills/s1/assignment"] = 200 to """{"skipped":true}""" + responses["GET /v1/agents"] = 500 to """{"error":"later"}""" + responses["GET /v1/skills"] = 200 to "[]" + } + val app = model(this, transport) + app.sharedSkills = listOf(SharedSkill(id = "s1", name = "One", source = "shared")) + app.agents = BOTS.map { it.copy(sharedSkills = emptyList()) } + app.selectedSkills = setOf("s1") + + app.runBulkAction(BulkAction.assign, setOf("a1", "a2")) + runCurrent() + assertEquals(listOf(listOf("s1"), listOf("s1")), app.agents.map { it.sharedSkills }) + settle() + + assertEquals(emptySet(), app.selectedSkills) + assertEquals( + listOf( + "1 of 1 skills processed.", + "Skipped One (Shared) → Ada: already in the requested state.", + "Skipped One (Shared) → Kev: already in the requested state.", + ), + app.bulkReport.map { it.text }, + ) + assertEquals("""{"botId":"a1","assigned":true}""", transport.requests.first { it.body != null }.body!!.toString(StandardCharsets.UTF_8)) + } + + @Test + fun bulkAssignRollsBackOnlyTheFailedBot() = runTest { + val transport = Script().apply { + responses["POST /v1/skills/s1/assignment"] = 200 to """{"skipped":false}""" + override = { request -> + if (request.body?.toString(StandardCharsets.UTF_8)?.contains("a2") == true) 500 to """{"error":"full"}""" else null + } + } + val app = model(this, transport) + app.sharedSkills = listOf(SharedSkill(id = "s1", name = "One", source = "shared")) + app.agents = BOTS.map { it.copy(sharedSkills = emptyList()) } + app.selectedSkills = setOf("s1") + + app.runBulkAction(BulkAction.assign, setOf("a1", "a2")) + settle() + + assertEquals(listOf(listOf("s1"), emptyList()), app.agents.map { it.sharedSkills }) + assertEquals(setOf("s1"), app.selectedSkills) + assertEquals("Failed One (Shared) → Kev: full", app.bulkReport.last().text) + } + + @Test + fun bulkAssignKeepsFailedSkillsSelectedAndCapsConcurrency() = runTest { + val transport = Script().apply { responses["POST /v1/skills/s1/assignment"] = 500 to """{"error":"full"}""" } + val app = model(this, transport) + val many = (1..6).map { Agent(id = "b$it", name = "B$it", enabled = true, sharedSkills = emptyList()) } + app.agents = many + app.sharedSkills = listOf(SharedSkill(id = "s1", name = "One", source = "shared")) + app.selectedSkills = setOf("s1") + + app.runBulkAction(BulkAction.assign, many.map { it.id }.toSet()) + settle() + + assertEquals(setOf("s1"), app.selectedSkills) + assertEquals(4, transport.mostRunning) + assertTrue(app.agents.all { it.sharedSkills == emptyList() }) + assertEquals("0 of 1 skills processed; 1 failed and remain selected.", app.bulkReport.first().text) + } + + @Test + fun bulkUpdateSkipsWhatItCannotUpdateAndAppliesOnlySelected() = runTest { + val transport = Script().apply { + responses["POST /v1/skills/updates/check"] = 200 to """{"failed":[]}""" + responses["GET /v1/skills"] = 200 to "[${sharedRow("s1", """{"commit":"c","removed":false}""")},${sharedRow("s2")},${sharedRow("s3", """{"commit":"c","removed":false}""")}]" + responses["POST /v1/skills/s1/update"] = 200 to packageJson("s1", agentId = null) + } + val api = APIClient("http://example.com", "token", transport) + val picked = selectionCatalog( + listOf( + SharedSkill(id = "s1", name = "One", source = "shared", origin = origin()), + SharedSkill(id = "s2", name = "Two", source = "shared", origin = origin()), + SharedSkill(id = "p", name = "Plain", source = "shared"), + ), + emptyList(), + emptyMap(), + ) + + val result = applyBulkAction(api, BulkAction.update, picked, emptyList()) + + assertEquals(emptySet(), result.failed) + assertEquals( + listOf( + "3 of 3 skills processed.", + "Skipped Two (Shared): already up to date.", + "Skipped Plain (Shared): not installed from GitHub.", + ), + result.messages.map { it.text }, + ) + assertEquals(1, transport.requests.count { it.pathWithQuery.endsWith("/update") }) + } + + @Test + fun bulkUpdateFailsSkillsWhoseRepositoryCheckFailed() = runTest { + val transport = Script().apply { + responses["POST /v1/skills/updates/check"] = 200 to """{"failed":[{"repository":"owner/repo","branch":"main","message":"404"}]}""" + responses["GET /v1/skills"] = 200 to "[${sharedRow("s1", """{"commit":"c","removed":false}""")}]" + } + val api = APIClient("http://example.com", "token", transport) + val picked = selectionCatalog(listOf(SharedSkill(id = "s1", name = "One", source = "shared", origin = origin())), emptyList(), emptyMap()) + + val result = applyBulkAction(api, BulkAction.update, picked, emptyList()) + + assertEquals(setOf("s1"), result.failed) + assertEquals("Failed One (Shared): 404", result.messages.last().text) + } + + private fun origin() = CrumbleJson.decodeFromString(dev.crumble.android.generated.SkillOrigin.serializer(), ORIGIN) + + @Test + fun skillTextHelpersMatchTheWebsite() { + assertEquals("Triage", skillGlimpse("\n## Triage\nSort")) + assertEquals("No instructions.", skillGlimpse(" \n")) + assertNull(skippedNote(emptyList())) + assertEquals("Skips a, b", skippedNote(listOf("a", "b"))) + assertEquals("Skips a, b, c and 2 more", skippedNote(listOf("a", "b", "c", "d", "e"))) + } + + // Memory + + @Test + fun memoriesLoadPerOwnerAndAFailureStaysWithItsGroup() = runTest { + val source = """{"kind":"task","name":"Standup"}""" + val transport = Script().apply { + responses["GET /v1/agents"] = 200 to "[${agentFixture("a1", "Ada")},${agentFixture("a2", "Kev")}]" + responses["GET /v1/memories"] = 200 to "[${memoryJson("m1", "Shared", source = source)}]" + responses["GET /v1/agents/a1/memories"] = 500 to """{"error":"busy"}""" + responses["GET /v1/agents/a2/memories"] = 200 to "[${memoryJson("m2", "Kev", "a2")}]" + } + val app = model(this, transport) + app.agentMemories = mapOf("a1" to listOf(Memory(id = "old", content = "Kept"))) + + app.openPanel(Route.Memory) + settle() + + assertEquals(mapOf("a1" to "busy"), app.memoryErrors) + assertEquals(listOf("old"), app.agentMemories["a1"]?.map { it.id }) + assertEquals(listOf("m2"), app.agentMemories["a2"]?.map { it.id }) + val memory = app.sharedMemories.single() + assertEquals("From the automation Standup", memorySourceLabel(memory)) + assertEquals(TIME, memory.updatedAt) + } + + @Test + fun aFailedMemoryEditKeepsItsPlaceAndSource() = runTest { + val transport = Script().apply { responses["PATCH /v1/memories/m1"] = 500 to """{"error":"no"}""" } + val gate = transport.hold("PATCH /v1/memories/m1") + val app = model(this, transport) + app.route = Route.Memory + val source = MemorySource(kind = "owner") + app.sharedMemories = listOf(Memory(id = "m1", content = "One", source = source), Memory(id = "m2", content = "Two")) + app.openMemoryForm("m1") + app.memoryDraft = app.memoryDraft!!.copy(content = "Edited") + + app.saveMemory() + settle() + assertEquals(source, app.sharedMemories.first().source) + assertEquals("Edited", app.sharedMemories.first().content) + gate.complete(Unit) + settle() + + assertEquals(listOf("One", "Two"), app.sharedMemories.map { it.content }) + assertEquals("Edited", app.memoryDraft?.content) + } + + @Test + fun memorySourceAndAgeReadLikeTheWebsite() { + val now = Instant.parse("2026-10-21T10:00:00Z") + assertEquals("From the bot chat", memorySourceLabel(Memory(source = MemorySource("chat")))) + assertEquals("Added by you", memorySourceLabel(Memory(source = MemorySource("owner")))) + assertEquals("From a request by a bot", memorySourceLabel(Memory(source = MemorySource("bot")))) + assertEquals("From the group chat Team", memorySourceLabel(Memory(source = MemorySource("group", name = "Team")))) + assertNull(memorySourceLabel(Memory())) + assertEquals("3 days ago", memoryAge(TIME, now)) + assertEquals("yesterday", memoryAge("2026-10-20T10:00:00Z", now)) + assertEquals("this minute", memoryAge("2026-10-21T09:59:40Z", now)) + assertEquals("2 hours ago", memoryAge("2026-10-21T08:00:00Z", now)) + assertNull(memoryAge("nonsense", now)) + assertEquals("Added by you · 3 days ago", memoryLine(Memory(source = MemorySource("owner"), updatedAt = TIME), now)) + assertEquals("", memoryLine(Memory(), now)) + } + + // Change history + + @Test + fun diffsAreLineBasedLikeTheWebsite() { + assertEquals( + listOf(DiffLine(' ', "a"), DiffLine('-', "b"), DiffLine('+', "x"), DiffLine('+', "y"), DiffLine(' ', "c")), + lineDiff(listOf("a", "b", "c"), listOf("a", "x", "y", "c")), + ) + val skill = changeOf(changeJson("c1", before = "null", after = packageJson("p1", name = "New"), target = "skill", targetId = "p1", agentId = "a1", action = "create")) + assertEquals( + listOf("# New", "", "", "Sort things", "", "--- ref.md", "Doc"), + skill.diff().map { it.text }, + ) + assertTrue(skill.diff().all { it.kind == '+' }) + assertEquals("The skill is deleted again. The revert is recorded, so you can undo it too.", revertPrompt(skill)) + val memory = changeOf(changeJson("c2", before = memoryJson("m1", "Old"), after = memoryJson("m1", "New"))) + assertEquals(listOf(DiffLine('-', "Old"), DiffLine('+', "New")), memory.diff()) + assertTrue(revertPrompt(memory).startsWith("The memory goes back")) + } + + @Test + fun changesPageWithTheLastIDAndStopAtAShortPage() = runTest { + val page = (1..50).joinToString(",") { changeJson("c$it") } + val transport = Script().apply { + responses["GET /v1/changes?limit=50"] = 200 to "[$page]" + responses["GET /v1/changes?limit=50&before=c50"] = 200 to "[${changeJson("c51")}]" + } + val app = model(this, transport) + + app.openChanges() + settle() + assertTrue(app.changesHasMore) + app.loadMoreChanges() + settle() + + assertEquals(51, app.changes.size) + assertFalse(app.changesHasMore) + } + + @Test + fun aFailedHistoryLoadReports() = runTest { + val transport = Script().apply { responses["GET /v1/changes?limit=50"] = 500 to """{"error":"down"}""" } + val app = model(this, transport) + + app.openChanges() + settle() + + assertEquals("down", app.changesError) + assertFalse(app.changesLoading) + } + + @Test + fun revertingRestoresTheRecordAtOnceAndRollsBackOnFailure() = runTest { + val change = changeOf(changeJson("c1", before = memoryJson("m1", "Before"), after = memoryJson("m1", "After"))) + val transport = Script().apply { responses["POST /v1/changes/c1/revert"] = 500 to """{"error":"no"}""" } + val gate = transport.hold("POST /v1/changes/c1/revert") + val app = model(this, transport) + app.sharedMemories = listOf(Memory(id = "m1", content = "After"), Memory(id = "m2", content = "Other")) + + app.revertChange(change) + settle() + assertEquals(listOf("Before", "Other"), app.sharedMemories.map { it.content }) + assertTrue("change:c1" in app.pendingMutations) + app.sharedMemories = app.sharedMemories.map { if (it.id == "m2") it.copy(content = "Newer") else it } + gate.complete(Unit) + settle() + + assertEquals(listOf("After", "Newer"), app.sharedMemories.map { it.content }) + assertEquals("no", app.errorText) + } + + @Test + fun revertingACreationDeletesTheRecordAndConfirmsWithTheRevertChange() = runTest { + val change = changeOf(changeJson("c1", after = packageJson("p1"), target = "skill", targetId = "p1", agentId = "a1", action = "create")) + val transport = Script().apply { + responses["POST /v1/changes/c1/revert"] = 201 to changeJson("c2", before = packageJson("p1"), target = "skill", targetId = "p1", agentId = "a1", action = "revert") + } + val app = model(this, transport) + app.agentSkills = mapOf("a1" to listOf(packageOf("p1", "One"))) + app.agents = app.agents.map { it.copy(skills = emptyList()) } + app.changes = listOf(change) + + app.revertChange(change) + runCurrent() + assertTrue(app.agentSkills["a1"]!!.isEmpty()) + settle() + + assertEquals(listOf("c2", "c1"), app.changes.map { it.id }) + } + + @Test + fun revertingADeletedSharedSkillBringsItBack() = runTest { + val change = changeOf(changeJson("c1", before = packageJson("s1", agentId = null, name = "Back"), target = "skill", targetId = "s1", action = "delete")) + val transport = Script().apply { responses["POST /v1/changes/c1/revert"] = 500 to """{"error":"no"}""" } + val app = model(this, transport) + + app.revertChange(change) + runCurrent() + assertEquals(listOf("Back"), app.sharedSkills.map { it.name }) + settle() + assertTrue(app.sharedSkills.isEmpty()) + } + + @Test + fun activityFeedKeepsChangesTypedForDiffAndRevert() = runTest { + val body = """{"activities":[{"id":"c1","agentId":null,"agentName":null,"timestamp":1,"kind":"change","change":${changeJson("c1", before = memoryJson("m1", "Old"), after = memoryJson("m1", "New"))}}],"hasMore":false,"nextCursor":null}""" + val transport = Script().apply { responses["GET /v1/activity/feed?limit=50"] = 200 to body } + val app = model(this, transport) + + app.openPanel(Route.Activity) + settle() + + val record: ActivityRecord = app.activities.single() + assertEquals("c1", record.change?.id) + } + + // Avatars + + @Test + fun savingAnAvatarAppliesAtOnceLocksThePageAndConfirms() = runTest { + val transport = Script().apply { responses["PATCH /v1/agents/a1"] = 200 to agentFixture("a1", "Ada") } + val gate = transport.hold("PATCH /v1/agents/a1") + val app = model(this, transport) + val edited: BotAvatarDefinition = placeholderAvatar("x").copy(color = "#123456") + app.pickAvatarBot("a1") + app.changeAvatar(edited) + + app.saveAvatar() + settle() + assertTrue(app.avatarPage.saving) + assertFalse(app.avatarPage.saved) + assertEquals("#123456", app.agents.first().avatar?.color) + app.changeAvatar(edited.copy(color = "#000000")) + app.pickAvatarBot("a2") + assertEquals("#123456", app.avatarPage.value.color) + assertEquals("a1", app.avatarPage.botID) + + gate.complete(Unit) + settle() + + assertTrue(app.avatarPage.saved) + assertFalse(app.avatarPage.saving) + assertEquals("#38bdf8", app.agents.first().avatar?.color) + val sent = transport.bodyOf("PATCH /v1/agents/a1") + assertEquals(setOf("avatar"), sent.keys) + assertEquals("\"#123456\"", sent["avatar"]!!.jsonObject["color"].toString()) + app.changeAvatar(edited) + assertFalse(app.avatarPage.saved) + } + + @Test + fun aFailedAvatarSaveRestoresTheBotAndKeepsTheDraft() = runTest { + val transport = Script().apply { responses["PATCH /v1/agents/a1"] = 500 to """{"error":"no"}""" } + val gate = transport.hold("PATCH /v1/agents/a1") + val app = model(this, transport) + val original = placeholderAvatar("o") + val edited = placeholderAvatar("x").copy(color = "#123456") + app.agents = listOf(BOTS[0].copy(avatar = original), BOTS[1]) + app.pickAvatarBot("a1") + assertEquals(original, app.avatarPage.value) + app.changeAvatar(edited) + + app.saveAvatar() + settle() + app.agents = app.agents.map { it.copy(description = "Newer") } + gate.complete(Unit) + settle() + + assertEquals(original, app.agents.first().avatar) + assertEquals("Newer", app.agents.first().description) + assertEquals(edited, app.avatarPage.value) + assertFalse(app.avatarPage.saving) + assertFalse(app.avatarPage.saved) + assertEquals("no", app.errorText) + } + + @Test + fun previewOnlyCannotSave() = runTest { + val transport = Script() + val app = model(this, transport) + val value = app.avatarPage.value + + app.saveAvatar() + app.pickAvatarBot("") + settle() + + assertEquals(value, app.avatarPage.value) + assertTrue(transport.requests.isEmpty()) + } +} diff --git a/app/src/test/resources/cron-reference.json b/app/src/test/resources/cron-reference.json new file mode 100644 index 0000000..3160271 --- /dev/null +++ b/app/src/test/resources/cron-reference.json @@ -0,0 +1 @@ +{"from":[["2026-11-05T10:00:00.000Z","UTC"],["2026-03-08T06:30:00.000Z","America/New_York"],["2026-11-01T05:40:00.000Z","America/New_York"],["2026-10-25T00:30:00.000Z","Europe/Berlin"],["2026-03-29T00:30:00.000Z","Europe/Berlin"],["2026-12-31T23:59:30.000Z","Asia/Tokyo"]],"out":[{"c":"0 9 * * *","word":"At 09:00","next":["2026-11-06T09:00:00.000Z","2026-03-08T13:00:00.000Z","2026-11-01T14:00:00.000Z","2026-10-25T08:00:00.000Z","2026-03-29T07:00:00.000Z","2027-01-01T00:00:00.000Z"]},{"c":"0 9 * * 1-5","word":"At 09:00, Monday through Friday","next":["2026-11-06T09:00:00.000Z","2026-03-09T13:00:00.000Z","2026-11-02T14:00:00.000Z","2026-10-26T08:00:00.000Z","2026-03-30T07:00:00.000Z","2027-01-01T00:00:00.000Z"]},{"c":"30 14 * * 1,3,5","word":"At 14:30, only on Monday, Wednesday, and Friday","next":["2026-11-06T14:30:00.000Z","2026-03-09T18:30:00.000Z","2026-11-02T19:30:00.000Z","2026-10-26T13:30:00.000Z","2026-03-30T12:30:00.000Z","2027-01-01T05:30:00.000Z"]},{"c":"0 9 1 * *","word":"At 09:00, on day 1 of the month","next":["2026-12-01T09:00:00.000Z","2026-04-01T13:00:00.000Z","2026-11-01T14:00:00.000Z","2026-11-01T08:00:00.000Z","2026-04-01T07:00:00.000Z","2027-01-01T00:00:00.000Z"]},{"c":"5 * * * *","word":"At 5 minutes past the hour","next":["2026-11-05T10:05:00.000Z","2026-03-08T07:05:00.000Z","2026-11-01T06:05:00.000Z","2026-10-25T01:05:00.000Z","2026-03-29T01:05:00.000Z","2027-01-01T00:05:00.000Z"]},{"c":"0 * * * *","word":"Every hour","next":["2026-11-05T11:00:00.000Z","2026-03-08T07:00:00.000Z","2026-11-01T06:00:00.000Z","2026-10-25T01:00:00.000Z","2026-03-29T01:00:00.000Z","2027-01-01T00:00:00.000Z"]},{"c":"* * * * *","word":"Every minute","next":["2026-11-05T10:01:00.000Z","2026-03-08T06:31:00.000Z","2026-11-01T05:41:00.000Z","2026-10-25T00:31:00.000Z","2026-03-29T00:31:00.000Z","2027-01-01T00:00:00.000Z"]},{"c":"*/5 * * * *","word":"Every 5 minutes","next":["2026-11-05T10:05:00.000Z","2026-03-08T06:35:00.000Z","2026-11-01T05:45:00.000Z","2026-10-25T00:35:00.000Z","2026-03-29T00:35:00.000Z","2027-01-01T00:00:00.000Z"]},{"c":"*/1 * * * *","word":"Every minute","next":["2026-11-05T10:01:00.000Z","2026-03-08T06:31:00.000Z","2026-11-01T05:41:00.000Z","2026-10-25T00:31:00.000Z","2026-03-29T00:31:00.000Z","2027-01-01T00:00:00.000Z"]},{"c":"0/15 * * * *","word":"Every 15 minutes","next":["2026-11-05T10:15:00.000Z","2026-03-08T06:45:00.000Z","2026-11-01T05:45:00.000Z","2026-10-25T00:45:00.000Z","2026-03-29T00:45:00.000Z","2027-01-01T00:00:00.000Z"]},{"c":"10/20 * * * *","word":"Every 20 minutes, starting at 10 minutes past the hour","next":["2026-11-05T10:10:00.000Z","2026-03-08T06:50:00.000Z","2026-11-01T05:50:00.000Z","2026-10-25T00:50:00.000Z","2026-03-29T00:50:00.000Z","2027-01-01T00:10:00.000Z"]},{"c":"0 */2 * * *","word":"On the hour, every 2 hours","next":["2026-11-05T12:00:00.000Z","2026-03-08T07:00:00.000Z","2026-11-01T07:00:00.000Z","2026-10-25T03:00:00.000Z","2026-03-29T01:00:00.000Z","2027-01-01T01:00:00.000Z"]},{"c":"15 */3 * * *","word":"At 15 minutes past the hour, every 3 hours","next":["2026-11-05T12:15:00.000Z","2026-03-08T07:15:00.000Z","2026-11-01T08:15:00.000Z","2026-10-25T02:15:00.000Z","2026-03-29T01:15:00.000Z","2027-01-01T00:15:00.000Z"]},{"c":"0 9-17 * * *","word":"Every hour, between 09:00 and 17:00","next":["2026-11-05T11:00:00.000Z","2026-03-08T13:00:00.000Z","2026-11-01T14:00:00.000Z","2026-10-25T08:00:00.000Z","2026-03-29T07:00:00.000Z","2027-01-01T00:00:00.000Z"]},{"c":"30 9-17 * * 1-5","word":"At 30 minutes past the hour, between 09:00 and 17:59, Monday through Friday","next":["2026-11-05T10:30:00.000Z","2026-03-09T13:30:00.000Z","2026-11-02T14:30:00.000Z","2026-10-26T08:30:00.000Z","2026-03-30T07:30:00.000Z","2027-01-01T00:30:00.000Z"]},{"c":"*/10 9-17 * * *","word":"Every 10 minutes, between 09:00 and 17:59","next":["2026-11-05T10:10:00.000Z","2026-03-08T13:00:00.000Z","2026-11-01T14:00:00.000Z","2026-10-25T08:00:00.000Z","2026-03-29T07:00:00.000Z","2027-01-01T00:00:00.000Z"]},{"c":"0 9,12,18 * * *","word":"At 09:00, 12:00 and 18:00","next":["2026-11-05T12:00:00.000Z","2026-03-08T13:00:00.000Z","2026-11-01T14:00:00.000Z","2026-10-25T08:00:00.000Z","2026-03-29T07:00:00.000Z","2027-01-01T00:00:00.000Z"]},{"c":"15 9,12 * * *","word":"At 09:15 and 12:15","next":["2026-11-05T12:15:00.000Z","2026-03-08T13:15:00.000Z","2026-11-01T14:15:00.000Z","2026-10-25T08:15:00.000Z","2026-03-29T07:15:00.000Z","2027-01-01T00:15:00.000Z"]},{"c":"0-30 9 * * *","word":"Every minute between 09:00 and 09:30","next":["2026-11-06T09:00:00.000Z","2026-03-08T13:00:00.000Z","2026-11-01T14:00:00.000Z","2026-10-25T08:00:00.000Z","2026-03-29T07:00:00.000Z","2027-01-01T00:00:00.000Z"]},{"c":"0 0 1 1 *","word":"At 00:00, on day 1 of the month, only in January","next":["2027-01-01T00:00:00.000Z","2027-01-01T05:00:00.000Z","2027-01-01T05:00:00.000Z","2026-12-31T23:00:00.000Z","2026-12-31T23:00:00.000Z","2027-12-31T15:00:00.000Z"]},{"c":"0 0 1,15 * *","word":"At 00:00, on day 1 and 15 of the month","next":["2026-11-15T00:00:00.000Z","2026-03-15T04:00:00.000Z","2026-11-15T05:00:00.000Z","2026-10-31T23:00:00.000Z","2026-03-31T22:00:00.000Z","2027-01-14T15:00:00.000Z"]},{"c":"0 0 1-7 * *","word":"At 00:00, between day 1 and 7 of the month","next":["2026-11-06T00:00:00.000Z","2026-04-01T04:00:00.000Z","2026-11-02T05:00:00.000Z","2026-10-31T23:00:00.000Z","2026-03-31T22:00:00.000Z","2027-01-01T15:00:00.000Z"]},{"c":"0 0 */2 * *","word":"At 00:00, every 2 days in a month","next":["2026-11-07T00:00:00.000Z","2026-03-09T04:00:00.000Z","2026-11-03T05:00:00.000Z","2026-10-26T23:00:00.000Z","2026-03-30T22:00:00.000Z","2027-01-02T15:00:00.000Z"]},{"c":"0 0 1/3 * *","word":"At 00:00, every 3 days in a month","next":["2026-11-07T00:00:00.000Z","2026-03-10T04:00:00.000Z","2026-11-04T05:00:00.000Z","2026-10-27T23:00:00.000Z","2026-03-30T22:00:00.000Z","2027-01-03T15:00:00.000Z"]},{"c":"0 12 * JAN *","word":"At 12:00, only in January","next":["2027-01-01T12:00:00.000Z","2027-01-01T17:00:00.000Z","2027-01-01T17:00:00.000Z","2027-01-01T11:00:00.000Z","2027-01-01T11:00:00.000Z","2027-01-01T03:00:00.000Z"]},{"c":"0 12 * JAN,JUL *","word":"At 12:00, only in January and July","next":["2027-01-01T12:00:00.000Z","2026-07-01T16:00:00.000Z","2027-01-01T17:00:00.000Z","2027-01-01T11:00:00.000Z","2026-07-01T10:00:00.000Z","2027-01-01T03:00:00.000Z"]},{"c":"0 12 * JAN-MAR *","word":"At 12:00, January through March","next":["2027-01-01T12:00:00.000Z","2026-03-08T16:00:00.000Z","2027-01-01T17:00:00.000Z","2027-01-01T11:00:00.000Z","2026-03-29T10:00:00.000Z","2027-01-01T03:00:00.000Z"]},{"c":"0 12 * */3 *","word":"At 12:00, every 3 months","next":["2027-01-01T12:00:00.000Z","2026-04-01T16:00:00.000Z","2027-01-01T17:00:00.000Z","2026-10-25T11:00:00.000Z","2026-04-01T10:00:00.000Z","2027-01-01T03:00:00.000Z"]},{"c":"0 12 * 1/2 *","word":"At 12:00, every 2 months","next":["2026-11-05T12:00:00.000Z","2026-03-08T16:00:00.000Z","2026-11-01T17:00:00.000Z","2026-11-01T11:00:00.000Z","2026-03-29T10:00:00.000Z","2027-01-01T03:00:00.000Z"]},{"c":"0 12 * 2/2 *","word":"At 12:00, every 2 months, February through December","next":["2026-12-01T12:00:00.000Z","2026-04-01T16:00:00.000Z","2026-12-01T17:00:00.000Z","2026-10-25T11:00:00.000Z","2026-04-01T10:00:00.000Z","2027-02-01T03:00:00.000Z"]},{"c":"0 8 * * MON","word":"At 08:00, only on Monday","next":["2026-11-09T08:00:00.000Z","2026-03-09T12:00:00.000Z","2026-11-02T13:00:00.000Z","2026-10-26T07:00:00.000Z","2026-03-30T06:00:00.000Z","2027-01-03T23:00:00.000Z"]},{"c":"0 8 * * mon-fri","word":"At 08:00, Monday through Friday","next":["2026-11-06T08:00:00.000Z","2026-03-09T12:00:00.000Z","2026-11-02T13:00:00.000Z","2026-10-26T07:00:00.000Z","2026-03-30T06:00:00.000Z","2027-01-03T23:00:00.000Z"]},{"c":"0 8 * * SAT,SUN","word":"At 08:00, only on Saturday and Sunday","next":["2026-11-07T08:00:00.000Z","2026-03-08T12:00:00.000Z","2026-11-01T13:00:00.000Z","2026-10-25T07:00:00.000Z","2026-03-29T06:00:00.000Z","2027-01-01T23:00:00.000Z"]},{"c":"0 8 * * 0","word":"At 08:00, only on Sunday","next":["2026-11-08T08:00:00.000Z","2026-03-08T12:00:00.000Z","2026-11-01T13:00:00.000Z","2026-10-25T07:00:00.000Z","2026-03-29T06:00:00.000Z","2027-01-02T23:00:00.000Z"]},{"c":"0 8 * * 7","word":"At 08:00, only on Sunday","next":["2026-11-08T08:00:00.000Z","2026-03-08T12:00:00.000Z","2026-11-01T13:00:00.000Z","2026-10-25T07:00:00.000Z","2026-03-29T06:00:00.000Z","2027-01-02T23:00:00.000Z"]},{"c":"0 8 * * 1-7","word":"At 08:00, Monday through Sunday","next":["2026-11-06T08:00:00.000Z","2026-03-08T12:00:00.000Z","2026-11-01T13:00:00.000Z","2026-10-25T07:00:00.000Z","2026-03-29T06:00:00.000Z","2027-01-01T23:00:00.000Z"]},{"c":"0 8 * * */2","word":"At 08:00, every 2 days of the week","next":["2026-11-07T08:00:00.000Z","2026-03-08T12:00:00.000Z","2026-11-01T13:00:00.000Z","2026-10-25T07:00:00.000Z","2026-03-29T06:00:00.000Z","2027-01-01T23:00:00.000Z"]},{"c":"0 8 * * 1-5/2","word":"At 08:00, every 2 days of the week, Monday through Friday","next":["2026-11-06T08:00:00.000Z","2026-03-09T12:00:00.000Z","2026-11-02T13:00:00.000Z","2026-10-26T07:00:00.000Z","2026-03-30T06:00:00.000Z","2027-01-03T23:00:00.000Z"]},{"c":"0 8 ? * 1","word":"At 08:00, only on Monday","next":["2026-11-09T08:00:00.000Z","2026-03-09T12:00:00.000Z","2026-11-02T13:00:00.000Z","2026-10-26T07:00:00.000Z","2026-03-30T06:00:00.000Z","2027-01-03T23:00:00.000Z"]},{"c":"0 0 0 * * *","word":"At 00:00","next":["2026-11-06T00:00:00.000Z","2026-03-09T04:00:00.000Z","2026-11-02T05:00:00.000Z","2026-10-25T23:00:00.000Z","2026-03-29T22:00:00.000Z","2027-01-01T15:00:00.000Z"]},{"c":"0 30 9 * * *","word":"At 09:30","next":["2026-11-06T09:30:00.000Z","2026-03-08T13:30:00.000Z","2026-11-01T14:30:00.000Z","2026-10-25T08:30:00.000Z","2026-03-29T07:30:00.000Z","2027-01-01T00:30:00.000Z"]},{"c":"15 30 9 * * *","word":"At 09:30:15","next":["2026-11-06T09:30:15.000Z","2026-03-08T13:30:15.000Z","2026-11-01T14:30:15.000Z","2026-10-25T08:30:15.000Z","2026-03-29T07:30:15.000Z","2027-01-01T00:30:15.000Z"]},{"c":"@daily","word":"At 00:00","next":["2026-11-06T00:00:00.000Z","2026-03-09T04:00:00.000Z","2026-11-02T05:00:00.000Z","2026-10-25T23:00:00.000Z","2026-03-29T22:00:00.000Z","2027-01-01T15:00:00.000Z"]},{"c":"@hourly","word":"Every hour","next":["2026-11-05T11:00:00.000Z","2026-03-08T07:00:00.000Z","2026-11-01T06:00:00.000Z","2026-10-25T01:00:00.000Z","2026-03-29T01:00:00.000Z","2027-01-01T00:00:00.000Z"]},{"c":"@weekly","word":"At 00:00, only on Sunday","next":["2026-11-08T00:00:00.000Z","2026-03-15T04:00:00.000Z","2026-11-08T05:00:00.000Z","2026-10-31T23:00:00.000Z","2026-04-04T22:00:00.000Z","2027-01-02T15:00:00.000Z"]},{"c":"@monthly","word":"At 00:00, on day 1 of the month","next":["2026-12-01T00:00:00.000Z","2026-04-01T04:00:00.000Z","2026-12-01T05:00:00.000Z","2026-10-31T23:00:00.000Z","2026-03-31T22:00:00.000Z","2027-01-31T15:00:00.000Z"]},{"c":"@yearly","word":"At 00:00, on day 1 of the month, only in January","next":["2027-01-01T00:00:00.000Z","2027-01-01T05:00:00.000Z","2027-01-01T05:00:00.000Z","2026-12-31T23:00:00.000Z","2026-12-31T23:00:00.000Z","2027-12-31T15:00:00.000Z"]},{"c":"@weekdays","word":null,"next":["2026-11-06T00:00:00.000Z","2026-03-09T04:00:00.000Z","2026-11-02T05:00:00.000Z","2026-10-25T23:00:00.000Z","2026-03-29T22:00:00.000Z","2027-01-03T15:00:00.000Z"]},{"c":"@midnight","word":"At 00:00","next":[null,null,null,null,null,null]},{"c":"1,5,10 * * * *","word":"At 1, 5, and 10 minutes past the hour","next":["2026-11-05T10:01:00.000Z","2026-03-08T07:01:00.000Z","2026-11-01T06:01:00.000Z","2026-10-25T01:01:00.000Z","2026-03-29T01:01:00.000Z","2027-01-01T00:01:00.000Z"]},{"c":"1,5-10 * * * *","word":"At 1 and 5 through 10 minutes past the hour","next":["2026-11-05T10:01:00.000Z","2026-03-08T07:01:00.000Z","2026-11-01T06:01:00.000Z","2026-10-25T01:01:00.000Z","2026-03-29T01:01:00.000Z","2027-01-01T00:01:00.000Z"]},{"c":"1-5,10-20/2 * * * *","word":"1 through 5 and every 2 minutes, minutes 10 through 20 past the hour","next":["2026-11-05T10:01:00.000Z","2026-03-08T07:01:00.000Z","2026-11-01T06:01:00.000Z","2026-10-25T01:01:00.000Z","2026-03-29T01:01:00.000Z","2027-01-01T00:01:00.000Z"]},{"c":"0 1-3,5 * * *","word":"Every hour, at 01:00 through 03:00 and 05:00","next":["2026-11-06T01:00:00.000Z","2026-03-08T07:00:00.000Z","2026-11-01T07:00:00.000Z","2026-10-25T02:00:00.000Z","2026-03-29T01:00:00.000Z","2027-01-01T16:00:00.000Z"]},{"c":"0 0 31 2 *","word":"At 00:00, on day 31 of the month, only in February","next":[null,null,null,null,null,null]},{"c":"0 0 30 2 *","word":"At 00:00, on day 30 of the month, only in February","next":[null,null,null,null,null,null]},{"c":"0 0 29 2 *","word":"At 00:00, on day 29 of the month, only in February","next":["2028-02-29T00:00:00.000Z","2028-02-29T05:00:00.000Z","2028-02-29T05:00:00.000Z","2028-02-28T23:00:00.000Z","2028-02-28T23:00:00.000Z","2028-02-28T15:00:00.000Z"]},{"c":"0 0 L * *","word":"At 00:00, on the last day of the month","next":["2026-11-30T00:00:00.000Z","2026-03-31T04:00:00.000Z","2026-11-30T05:00:00.000Z","2026-10-30T23:00:00.000Z","2026-03-30T22:00:00.000Z","2027-01-30T15:00:00.000Z"]},{"c":"0 0 * * 5L","word":"At 00:00, on the last Friday of the month","next":["2026-11-27T00:00:00.000Z","2026-03-27T04:00:00.000Z","2026-11-27T05:00:00.000Z","2026-10-29T23:00:00.000Z","2026-04-23T22:00:00.000Z","2027-01-28T15:00:00.000Z"]},{"c":"0 0 * * 1#2","word":"At 00:00, on the second Monday of the month","next":["2026-11-09T00:00:00.000Z","2026-03-09T04:00:00.000Z","2026-11-09T05:00:00.000Z","2026-11-08T23:00:00.000Z","2026-04-12T22:00:00.000Z","2027-01-10T15:00:00.000Z"]},{"c":"0 0 * * L","word":"At 00:00, only on Saturday","next":[null,null,null,null,null,null]},{"c":"0 0 15 * 1","word":"At 00:00, on day 15 of the month, and on Monday","next":["2026-11-09T00:00:00.000Z","2026-03-09T04:00:00.000Z","2026-11-02T05:00:00.000Z","2026-10-25T23:00:00.000Z","2026-03-29T22:00:00.000Z","2027-01-03T15:00:00.000Z"]},{"c":"60 * * * *","word":null,"next":[null,null,null,null,null,null]},{"c":"* 24 * * *","word":null,"next":[null,null,null,null,null,null]},{"c":"0 0 0 * *","word":null,"next":[null,null,null,null,null,null]},{"c":"0 0 32 * *","word":null,"next":[null,null,null,null,null,null]},{"c":"0 0 * 13 *","word":null,"next":[null,null,null,null,null,null]},{"c":"0 0 * * 8","word":null,"next":[null,null,null,null,null,null]},{"c":"1 2 3","word":null,"next":["2027-02-01T00:00:00.000Z","2027-02-01T05:00:00.000Z","2027-02-01T05:00:00.000Z","2027-01-31T23:00:00.000Z","2027-01-31T23:00:00.000Z","2027-01-31T15:00:00.000Z"]},{"c":"bad cron here x","word":null,"next":[null,null,null,null,null,null]},{"c":"*/0 * * * *","word":null,"next":[null,null,null,null,null,null]},{"c":"1-2-3 * * * *","word":"Minutes 1 through 2 past the hour","next":["2026-11-05T10:01:00.000Z","2026-03-08T07:01:00.000Z","2026-11-01T06:01:00.000Z","2026-10-25T01:01:00.000Z","2026-03-29T01:01:00.000Z","2027-01-01T00:01:00.000Z"]},{"c":"5-1 * * * *","word":"Minutes 5 through 1 past the hour","next":[null,null,null,null,null,null]},{"c":"H * * * *","word":null,"next":["2026-11-05T10:05:00.000Z","2026-03-08T07:25:00.000Z","2026-11-01T05:53:00.000Z","2026-10-25T01:04:00.000Z","2026-03-29T00:58:00.000Z","2027-01-01T00:13:00.000Z"]},{"c":"0 0 * FOO *","word":null,"next":[null,null,null,null,null,null]},{"c":"0 12 ? * ?","word":"At 12:00","next":["2026-11-05T12:00:00.000Z","2026-03-08T16:00:00.000Z","2026-11-01T17:00:00.000Z","2026-10-25T11:00:00.000Z","2026-03-29T10:00:00.000Z","2027-01-01T03:00:00.000Z"]},{"c":"0 0 2,1 * *","word":"At 00:00, on day 1 and 2 of the month","next":["2026-12-01T00:00:00.000Z","2026-04-01T04:00:00.000Z","2026-11-02T05:00:00.000Z","2026-10-31T23:00:00.000Z","2026-03-31T22:00:00.000Z","2027-01-01T15:00:00.000Z"]},{"c":"3,1,2 * * * *","word":"At 1, 2, and 3 minutes past the hour","next":["2026-11-05T10:01:00.000Z","2026-03-08T07:01:00.000Z","2026-11-01T06:01:00.000Z","2026-10-25T01:01:00.000Z","2026-03-29T01:01:00.000Z","2027-01-01T00:01:00.000Z"]},{"c":"0 0 * * 3,1","word":"At 00:00, only on Monday and Wednesday","next":["2026-11-09T00:00:00.000Z","2026-03-09T04:00:00.000Z","2026-11-02T05:00:00.000Z","2026-10-25T23:00:00.000Z","2026-03-29T22:00:00.000Z","2027-01-03T15:00:00.000Z"]},{"c":"30 1 * * *","word":"At 01:30","next":["2026-11-06T01:30:00.000Z","2026-03-09T05:30:00.000Z","2026-11-02T06:30:00.000Z","2026-10-26T00:30:00.000Z","2026-03-29T23:30:00.000Z","2027-01-01T16:30:00.000Z"]},{"c":"50 1 * * *","word":"At 01:50","next":["2026-11-06T01:50:00.000Z","2026-03-08T06:50:00.000Z","2026-11-01T05:50:00.000Z","2026-10-26T00:50:00.000Z","2026-03-29T00:50:00.000Z","2027-01-01T16:50:00.000Z"]},{"c":"0 2 * * *","word":"At 02:00","next":["2026-11-06T02:00:00.000Z","2026-03-08T07:00:00.000Z","2026-11-01T07:00:00.000Z","2026-10-26T01:00:00.000Z","2026-03-29T01:00:00.000Z","2027-01-01T17:00:00.000Z"]},{"c":"30 2 * * *","word":"At 02:30","next":["2026-11-06T02:30:00.000Z","2026-03-08T07:30:00.000Z","2026-11-01T07:30:00.000Z","2026-10-26T01:30:00.000Z","2026-03-29T01:30:00.000Z","2027-01-01T17:30:00.000Z"]}]} diff --git a/contract/assets/CHANGELOG.md b/contract/assets/CHANGELOG.md index 01e2469..7c9c9f4 100644 --- a/contract/assets/CHANGELOG.md +++ b/contract/assets/CHANGELOG.md @@ -1,5 +1,3 @@ -# Contract 1.0.0 +# Contract 6.0.0 -- Publish the initial independently versioned HTTP API and snapshot, activity, and heartbeat event schemas. -- Include checksums, this contract changelog excerpt, and the source commit in every contract bundle. -- Encode nullable resource responses as unions and require every path parameter. +- Local export from the bot checkout. The bot repository no longer publishes contract releases. diff --git a/contract/assets/SHA256SUMS b/contract/assets/SHA256SUMS index 70b7a1f..ac96184 100644 --- a/contract/assets/SHA256SUMS +++ b/contract/assets/SHA256SUMS @@ -1,6 +1,6 @@ -a0075a753628fc939e4599991ba3906f3ffaa403dda047266e096f923cb3ea3b CHANGELOG.md -1f225a65f4e80470da9e8230da3a355dc60cb711f9e61a186249ed3dd6e6e9f7 activity-event.schema.json -0af60b3c79a62a0b9780ef716e4db77b33701d1c5d8a0a372d77593adf2a936c chat-snapshot.schema.json +f1b51f5a2371989fb0a961e8d2097879a0fb90fc4d44a7554e32555ade38da32 CHANGELOG.md +4fa4a524cf635a837b53a322f2bdcbcccba75bc24b33260863ea8124f96ee21e activity-event.schema.json +eb4fc4fea61127a93e78b09eb7223a1ed730b49bc7a9a3dedfbf0fa70c3932c6 chat-snapshot.schema.json e1fc21c5ca3e658bfbfbb5005a0d1dfec2be6e720b5a1ff86f699a13cc5db221 heartbeat.schema.json -1cb17d9cdc18c7c33e17f22491963f48e4a24c612ed150344ad258df6847ad1e openapi.json -ec0e70b63f6836d6bd251e14dc92b2b2b7455d35dc681c5cec14ba3f607e5189 source-commit.txt +3f389004678290cd63833233a48f17b321bb1157ae62956f72ae882b034a0c84 openapi.json +139de61622a3ef9a8c0112ca42971afcc5b5da9613f6604b2c64a37166a623e3 source-commit.txt diff --git a/contract/assets/activity-event.schema.json b/contract/assets/activity-event.schema.json index 105190b..5539c0f 100644 --- a/contract/assets/activity-event.schema.json +++ b/contract/assets/activity-event.schema.json @@ -37,6 +37,23 @@ }, "executionId": { "type": "string" + }, + "jobName": { + "type": "string" + }, + "groupId": { + "type": "string" + }, + "groupName": { + "type": "string" + }, + "waitingFor": { + "type": "string", + "enum": [ + "approval", + "credential", + "login" + ] } }, "required": [ diff --git a/contract/assets/chat-snapshot.schema.json b/contract/assets/chat-snapshot.schema.json index f89beb1..7374638 100644 --- a/contract/assets/chat-snapshot.schema.json +++ b/contract/assets/chat-snapshot.schema.json @@ -49,6 +49,12 @@ }, "agentId": { "type": "string" + }, + "via": { + "type": "string" + }, + "source": { + "type": "string" } }, "required": [ @@ -94,6 +100,51 @@ ], "additionalProperties": true }, + "jobQuestion": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "job": { + "type": "string" + }, + "options": { + "type": "array", + "items": { + "type": "string" + } + }, + "multiple": { + "type": "boolean" + } + }, + "required": [ + "id", + "kind", + "job" + ], + "additionalProperties": true + }, + "heldAction": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "job": { + "type": "string" + } + }, + "required": [ + "id", + "job" + ], + "additionalProperties": true + }, "attachments": { "type": "array", "items": { @@ -134,7 +185,26 @@ "isError": { "type": "boolean" }, - "toolDetails": {} + "toolDetails": {}, + "sources": { + "type": "array", + "items": { + "type": "object", + "properties": { + "url": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": [ + "url", + "title" + ], + "additionalProperties": true + } + } }, "required": [ "id", diff --git a/contract/assets/openapi.json b/contract/assets/openapi.json index ace8741..7d57ba5 100644 --- a/contract/assets/openapi.json +++ b/contract/assets/openapi.json @@ -2,14 +2,21 @@ "openapi": "3.1.0", "info": { "title": "Crumble API", - "version": "1.0.0", + "version": "6.0.0", "description": "Shared HTTP contract for Crumble clients. Provider availability and cross-field business rules are validated at runtime." }, "components": { "securitySchemes": { "BearerAuth": { "type": "http", - "scheme": "bearer" + "scheme": "bearer", + "description": "Better Auth session token from /api/auth/sign-in/email. The legacy server token is not accepted." + }, + "SessionCookie": { + "type": "apiKey", + "in": "cookie", + "name": "better-auth.session_token", + "description": "Better Auth session cookie. HTTPS deployments use the __Secure- prefix. Cookie-authenticated writes require the configured Origin." } }, "schemas": { @@ -41,7 +48,8 @@ ] }, "origin": { - "type": "string" + "type": "string", + "description": "What the bot answered: owner (a message from the owner), task (a scheduled task), script (a script task's result), bot (another bot's request), group (a group chat turn), or coding or desktop (a job's report; jobName names the job). Clients may receive other values later." }, "preview": { "type": "string" @@ -51,6 +59,26 @@ }, "executionId": { "type": "string" + }, + "jobName": { + "type": "string", + "description": "The job whose report the bot answered, for origin coding or desktop. A desktop job's report often asks for the owner; clients may open the bot desktop." + }, + "groupId": { + "type": "string", + "description": "Set when a bot answered in a group chat; open the group rather than the bot chat." + }, + "groupName": { + "type": "string" + }, + "waitingFor": { + "type": "string", + "enum": [ + "approval", + "credential", + "login" + ], + "description": "Set when the bot waits for the owner's answer: approval (a desktop job action held by an intent check), credential, or login (a request the owner saves or declines). Clients may receive other values later." } }, "required": [ @@ -112,6 +140,74 @@ } } }, + "LearnedEvent": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "learned" + ] + }, + "agentId": { + "type": "string" + }, + "agentName": { + "type": "string" + }, + "executionId": { + "type": "string" + }, + "changes": { + "type": "array", + "items": { + "type": "object", + "properties": { + "changeId": { + "type": "string" + }, + "target": { + "type": "string", + "enum": [ + "skill", + "memory" + ] + }, + "action": { + "type": "string", + "enum": [ + "create", + "update", + "delete", + "revert" + ] + }, + "name": { + "type": "string" + } + }, + "required": [ + "changeId", + "target", + "action", + "name" + ] + } + }, + "createdAt": { + "type": "string" + } + }, + "required": [ + "type", + "agentId", + "agentName", + "executionId", + "changes", + "createdAt" + ], + "description": "A bot's review of one of its turns changed its skills or memory, sent as the `learned` event on /v1/events. Clients show a short notice in the bot chat and link to the change record." + }, "Health": { "type": "object", "properties": { @@ -139,10 +235,23 @@ "coding": { "type": "boolean", "description": "Whether bots can be given the coding tool on this server." + }, + "desktop": { + "type": "boolean", + "description": "Whether bots can be given the desktop tool, and with it a bot desktop, on this server." + }, + "jobKinds": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The kinds of background job bots can be given on this server, such as `coding` and `desktop`." } }, "required": [ - "coding" + "coding", + "desktop", + "jobKinds" ] }, "Error": { @@ -231,626 +340,950 @@ "remoteDelivery" ] }, - "AgentPreview": { + "AdminUser": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "email": { + "type": "string" + }, + "name": { + "type": "string" + }, + "role": { + "type": "string", + "enum": [ + "admin", + "user" + ] + }, + "createdAt": { + "type": "string" + } + }, + "required": [ + "id", + "email", + "name", + "role", + "createdAt" + ] + }, + "Invite": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "createdAt": { + "type": "string" + } + }, + "required": [ + "id", + "createdAt" + ] + }, + "CreatedInvite": { "allOf": [ { - "$ref": "#/components/schemas/Agent" + "$ref": "#/components/schemas/Invite" }, { "type": "object", "properties": { - "lastMessage": { + "url": { "type": "string" } - } + }, + "required": [ + "url" + ] } ] }, - "Agent": { + "ServerSettings": { + "type": "object", + "properties": { + "signUpOpen": { + "type": "boolean" + }, + "workspaceCpus": { + "type": "integer", + "minimum": 1, + "maximum": 64 + }, + "workspaceMemoryMib": { + "type": "integer", + "minimum": 512, + "maximum": 262144 + }, + "codingImage": { + "type": [ + "string", + "null" + ], + "pattern": "^[a-z0-9][\\w.\\-/:@]{0,254}$", + "description": "Image new workspaces boot from, such as `ghcr.io/owner/image:tag`; null uses the server's `CRUMBLE_WORKSPACE_IMAGE`." + }, + "questionGraceMinutes": { + "type": "integer", + "minimum": 0, + "maximum": 1440, + "description": "How long a coding job waiting on the owner's answer keeps its workspace running." + } + }, + "required": [ + "signUpOpen", + "workspaceCpus", + "workspaceMemoryMib", + "codingImage", + "questionGraceMinutes" + ] + }, + "GitHubApp": { "type": "object", "properties": { "id": { "type": "string" }, - "name": { + "slug": { "type": "string" }, - "avatar": { + "name": { "type": "string" }, - "description": { - "type": "string" + "login": { + "type": "string", + "description": "The name commits and pull requests show, such as `scout[bot]`." }, - "instructions": { + "htmlUrl": { "type": "string" }, - "provider": { + "installUrl": { "type": "string" }, - "model": { - "type": "string" + "account": { + "type": [ + "string", + "null" + ], + "description": "The GitHub user or organization whose repositories the App works on." }, - "enabled": { + "installed": { "type": "boolean" }, - "tools": { - "type": "array", - "items": { - "type": "string" - } + "clientSecret": { + "$ref": "#/components/schemas/SecretStatus" }, - "skills": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "instructions": { - "type": "string" - } - }, - "required": [ - "name", - "instructions" - ] - } + "user": { + "type": [ + "string", + "null" + ], + "description": "The owner's GitHub login when signed in through the App; its bots then act as the owner, with the App's badge." }, - "sharedSkills": { + "botIds": { "type": "array", "items": { "type": "string" } }, - "sharedMemory": { + "createdAt": { + "type": "string" + } + }, + "required": [ + "id", + "slug", + "name", + "login", + "htmlUrl", + "installUrl", + "account", + "installed", + "clientSecret", + "user", + "botIds", + "createdAt" + ] + }, + "SecretStatus": { + "type": "object", + "properties": { + "configured": { "type": "boolean" }, - "mcpServers": { - "type": "array", - "items": { - "type": "string" - } + "passwordManager": { + "type": [ + "string", + "null" + ], + "enum": [ + "1password", + "bitwarden", + null + ], + "description": "The password manager the value is read from; null for a value stored in Crumble or no value." }, - "delegates": { + "reference": { + "type": [ + "string", + "null" + ], + "description": "Where in `passwordManager` the value is read from." + } + }, + "required": [ + "configured", + "passwordManager", + "reference" + ], + "description": "A secret the owner entered; its value is never returned." + }, + "GitHubAccount": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "login": { + "type": "string", + "description": "The GitHub user its bots act and commit as." + }, + "htmlUrl": { + "type": "string" + }, + "botIds": { "type": "array", "items": { "type": "string" } }, - "inference": { - "type": "object", - "properties": { - "thinkingLevel": { - "type": "string", - "enum": [ - "off", - "minimal", - "low", - "medium", - "high", - "xhigh", - "max" - ] - }, - "temperature": { - "type": "number" - }, - "maxOutputTokens": { - "type": "number" - } - } + "token": { + "$ref": "#/components/schemas/SecretStatus" }, - "createdAt": { - "type": "string" + "signingKey": { + "type": "string", + "description": "The OpenSSH public key the account's commits are signed with. Add it on GitHub as the user's signing key so its commits show as verified." }, - "updatedAt": { + "createdAt": { "type": "string" } }, "required": [ "id", - "name", - "avatar", - "description", - "instructions", - "provider", - "model", - "enabled", - "tools", - "skills", - "mcpServers", - "delegates", - "createdAt", - "updatedAt" + "login", + "htmlUrl", + "botIds", + "token", + "signingKey", + "createdAt" ] }, - "ChatSnapshot": { - "allOf": [ - { - "$ref": "#/components/schemas/TranscriptPage" - }, - { - "type": "object", + "JudgeModel": { + "type": "object", + "properties": { + "judgeModel": { + "type": [ + "object", + "null" + ], "properties": { - "conversationId": { - "type": "string" - }, - "agentId": { + "provider": { "type": "string" }, - "conversation": { - "$ref": "#/components/schemas/Conversation" - }, - "live": { - "description": "Pi Durable live progress state. In-flight assistant message content is omitted." - }, - "partial": { + "model": { "type": "string" - }, - "usage": { - "description": "Pi Durable usage document." - }, - "status": { - "type": "string", - "enum": [ - "idle", - "running", - "failed" - ] - }, - "updatedAt": { - "type": "number" - }, - "error": { - "type": [ - "string", - "null" - ] } }, "required": [ - "conversationId", - "agentId", - "conversation", - "partial", - "status", - "updatedAt", - "error" - ] + "provider", + "model" + ], + "description": "The owner's classifier; null uses the default, GPT-6 Luna through OpenAI Decisions." + }, + "effective": { + "$ref": "#/components/schemas/JudgeChoice" + }, + "choices": { + "type": "array", + "items": { + "$ref": "#/components/schemas/JudgeChoice" + }, + "description": "The classifier models the account's provider keys reach." } + }, + "required": [ + "judgeModel", + "effective", + "choices" ] }, - "TranscriptMessage": { - "type": "object", + "JudgeChoice": { + "type": [ + "object", + "null" + ], "properties": { - "id": { - "type": "string" - }, - "entryId": { - "type": "string" - }, - "requestId": { - "type": "string" - }, - "role": { + "provider": { "type": "string" }, - "content": { + "model": { "type": "string" }, - "blocks": { - "description": "Provider content blocks, with inline image bytes removed." - }, - "stopReason": { + "name": { "type": "string" }, - "timestamp": { - "type": "number" - }, "kind": { - "type": "string" - }, - "replyTo": { - "type": "string" - }, - "replyPreview": { - "type": "string" - }, - "origin": { - "$ref": "#/components/schemas/MessageOrigin" - }, - "communication": { - "$ref": "#/components/schemas/BotCommunication" - }, - "attachments": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AttachmentInfo" - } - }, - "toolCallId": { - "type": "string" - }, - "toolName": { - "type": "string" - }, - "isError": { - "type": "boolean" - }, - "toolDetails": { - "description": "Provider-specific tool details, including nested code-mode calls." + "type": "string", + "enum": [ + "classifier", + "chat" + ] } }, "required": [ - "id", - "entryId", - "role", - "content" - ] + "provider", + "model", + "name", + "kind" + ], + "description": "The model that judges now: a classifier, or a small chat model when no key reaches one. Null when no model is available; then only commit points are held." }, - "MessageOrigin": { + "VisionModel": { "type": "object", "properties": { - "kind": { - "type": "string" - }, - "name": { - "type": "string" + "visionModel": { + "type": [ + "object", + "null" + ], + "properties": { + "provider": { + "type": "string" + }, + "model": { + "type": "string" + } + }, + "required": [ + "provider", + "model" + ], + "description": "The model that describes images for bots whose model can't read them. Null when off: such bots refuse images in their chat and get only an image's name in group chats." }, - "agentId": { - "type": "string" + "choices": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VisionChoice" + }, + "description": "The chat models that read images and that the account's provider keys reach." } }, "required": [ - "kind" + "visionModel", + "choices" ] }, - "BotCommunication": { + "VisionChoice": { "type": "object", "properties": { - "executionId": { - "type": "string" - }, - "fromAgentId": { - "type": "string" - }, - "fromName": { + "provider": { "type": "string" }, - "toAgentId": { + "model": { "type": "string" }, - "toName": { + "name": { "type": "string" - }, - "status": { - "type": "string", - "enum": [ - "sent", - "done", - "failed", - "cancelled" - ] } }, "required": [ - "executionId", - "fromAgentId", - "fromName", - "toAgentId", - "toName", - "status" + "provider", + "model", + "name" ] }, - "AttachmentInfo": { + "AgentPreview": { + "allOf": [ + { + "$ref": "#/components/schemas/Agent" + }, + { + "type": "object", + "properties": { + "lastMessage": { + "type": "string" + } + } + } + ] + }, + "BotAvatarDefinition": { "type": "object", "properties": { - "name": { - "type": "string" - }, - "mimeType": { - "type": "string" + "definition": { + "type": "object", + "properties": { + "version": { + "type": "number", + "enum": [ + 1 + ] + }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 40 + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 40 + }, + "body": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 6000 + } + }, + "required": [ + "path" + ], + "additionalProperties": false + }, + "eyes": { + "type": "object", + "properties": { + "x": { + "type": "number" + }, + "y": { + "type": "number" + }, + "spacing": { + "type": "number" + }, + "scale": { + "type": "number" + } + }, + "required": [ + "x", + "y", + "spacing", + "scale" + ], + "additionalProperties": false + } + }, + "required": [ + "version", + "id", + "name", + "body", + "eyes" + ], + "additionalProperties": false }, - "size": { - "type": "number" + "color": { + "type": "string", + "pattern": "^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" }, - "kind": { + "eyeColor": { "type": "string", - "enum": [ - "image", - "text" - ] + "pattern": "^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" } }, "required": [ - "name", - "mimeType", - "size", - "kind" - ] + "definition", + "color", + "eyeColor" + ], + "description": "Open Bot Avatar v1 geometry in a 0 0 100 100 viewBox, body color and eye color." }, - "Conversation": { + "Agent": { "type": "object", "properties": { "id": { "type": "string" }, - "agentId": { + "name": { "type": "string" }, - "title": { + "avatar": { + "$ref": "#/components/schemas/BotAvatarDefinition" + }, + "description": { "type": "string" }, - "createdAt": { + "instructions": { "type": "string" }, - "updatedAt": { + "provider": { "type": "string" }, - "archived": { - "type": "boolean" - } - }, - "required": [ - "id", - "agentId", - "title", - "createdAt", - "updatedAt" - ] - }, - "TranscriptPage": { - "type": "object", - "properties": { - "messages": { - "type": "array", - "items": { - "$ref": "#/components/schemas/TranscriptMessage" - } - }, - "hasMore": { - "type": "boolean" + "model": { + "type": "string" }, - "oldestEntryId": { + "webSearchProvider": { "type": [ "string", "null" + ], + "enum": [ + "mixed", + "exa", + null ] - } - }, - "required": [ - "messages", - "hasMore", - "oldestEntryId" - ] - }, - "CodingJobs": { - "type": "object", - "properties": { - "jobs": { + }, + "enabled": { + "type": "boolean" + }, + "tools": { "type": "array", "items": { - "$ref": "#/components/schemas/CodingJob" + "type": "string" }, - "description": "Oldest job first." + "description": "The bot's tools; always includes `schedule` and `codemode`." + }, + "skills": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "instructions": { + "type": "string" + } + }, + "required": [ + "name", + "instructions" + ] + } + }, + "sharedSkills": { + "type": "array", + "items": { + "type": "string" + } + }, + "sharedMemory": { + "type": "boolean", + "description": "True whenever `tools` includes `memory`; the server ignores it in input." + }, + "mcpServers": { + "type": "array", + "items": { + "type": "string" + } + }, + "delegates": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Every other bot; with `delegate` in `tools` this bot may message any of them. The server ignores it in input." + }, + "inference": { + "type": "object", + "properties": { + "thinkingLevel": { + "type": "string", + "enum": [ + "off", + "minimal", + "low", + "medium", + "high", + "xhigh", + "max" + ] + }, + "temperature": { + "type": "number" + }, + "maxOutputTokens": { + "type": "number" + } + } + }, + "desktopModel": { + "type": "object", + "properties": { + "provider": { + "type": "string" + }, + "model": { + "type": "string" + } + }, + "required": [ + "provider", + "model" + ], + "description": "The model for this bot's desktop jobs; unset, they use the bot's own model." + }, + "review": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "skillThreshold": { + "type": "integer" + }, + "memoryThreshold": { + "type": "integer" + }, + "maxInputTokens": { + "type": "integer" + } + }, + "required": [ + "enabled", + "skillThreshold", + "memoryThreshold" + ], + "description": "How the bot reviews its turns to learn: whether at all, after how many tool-activity rounds for skills and memory, and how much of a turn a review reads. Unset means enabled with thresholds of 10." + }, + "reviewModel": { + "type": "object", + "properties": { + "provider": { + "type": "string" + }, + "model": { + "type": "string" + } + }, + "required": [ + "provider", + "model" + ], + "description": "The model that runs this bot's reviews; unset, they use the bot's own model." + }, + "createdAt": { + "type": "string" + }, + "updatedAt": { + "type": "string" } }, "required": [ - "jobs" + "id", + "name", + "avatar", + "description", + "instructions", + "provider", + "model", + "enabled", + "tools", + "skills", + "mcpServers", + "delegates", + "createdAt", + "updatedAt" ] }, - "CodingJob": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "conversationId": { - "type": "string" + "ChatSnapshot": { + "allOf": [ + { + "$ref": "#/components/schemas/TranscriptPage" }, - "status": { - "type": "string", - "enum": [ - "working", - "idle" + { + "type": "object", + "properties": { + "conversationId": { + "type": "string" + }, + "agentId": { + "type": "string" + }, + "conversation": { + "$ref": "#/components/schemas/Conversation" + }, + "live": { + "description": "Pi Durable live progress state. In-flight assistant message content is omitted." + }, + "partial": { + "type": "string" + }, + "usage": { + "description": "Pi Durable usage document." + }, + "status": { + "type": "string", + "enum": [ + "idle", + "running", + "failed" + ] + }, + "updatedAt": { + "type": "number" + }, + "error": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "conversationId", + "agentId", + "conversation", + "partial", + "status", + "updatedAt", + "error" ] } - }, - "required": [ - "name", - "conversationId", - "status" ] }, - "Execution": { + "TranscriptMessage": { "type": "object", "properties": { "id": { "type": "string" }, - "agentId": { + "entryId": { "type": "string" }, - "conversationId": { + "requestId": { "type": "string" }, - "scheduleId": { - "type": [ - "string", - "null" - ] + "role": { + "type": "string" }, - "submissionId": { - "type": [ - "string", - "null" - ] + "content": { + "type": "string" }, - "requestId": { + "blocks": { + "description": "Provider content blocks, with inline image bytes removed." + }, + "stopReason": { "type": "string" }, - "prompt": { + "timestamp": { + "type": "number" + }, + "kind": { "type": "string" }, "replyTo": { - "type": [ - "string", - "null" - ] + "type": "string" }, - "attachmentsDigest": { - "type": [ - "string", - "null" - ] + "replyPreview": { + "type": "string" }, - "status": { - "type": "string", - "enum": [ - "pending", - "running", - "done", - "failed", - "cancelled" - ] + "origin": { + "$ref": "#/components/schemas/MessageOrigin" }, - "error": { - "type": [ - "string", - "null" - ] + "communication": { + "$ref": "#/components/schemas/BotCommunication" }, - "createdAt": { + "jobQuestion": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "job": { + "type": "string" + }, + "options": { + "type": "array", + "items": { + "type": "string" + } + }, + "multiple": { + "type": "boolean" + } + }, + "required": [ + "id", + "kind", + "job" + ], + "description": "On a `job-question` event: the job that asked the owner the question in `content`. Whether it still waits is the job's `question` in its listing." + }, + "heldAction": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "job": { + "type": "string" + } + }, + "required": [ + "id", + "job" + ], + "description": "On a `held-action` event: the desktop job action waiting for the owner. Its state is under `/v1/agents/{id}/held-actions`." + }, + "attachments": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AttachmentInfo" + } + }, + "toolCallId": { "type": "string" }, - "updatedAt": { + "toolName": { "type": "string" + }, + "isError": { + "type": "boolean" + }, + "toolDetails": { + "description": "Provider-specific tool details, including nested code-mode calls. A successful `desktop_screenshot` result has `{ mimeType, size }`; read its image from `GET /v1/agents/{id}/attachments/{entryId}/0`." + }, + "sources": { + "type": "array", + "items": { + "type": "object", + "properties": { + "url": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": [ + "url", + "title" + ] + }, + "description": "In a group chat, the pages the sending bot searched or read in the turn that wrote the message." } }, "required": [ "id", - "agentId", - "conversationId", - "scheduleId", - "submissionId", - "requestId", - "prompt", - "status", - "error", - "createdAt", - "updatedAt" + "entryId", + "role", + "content" ] }, - "Compaction": { + "MessageOrigin": { "type": "object", "properties": { - "taskId": { + "kind": { + "type": "string", + "description": "Where the message came from: owner, task, event (an event automation's prompt), script (a script task's result), credential, bot, or group. Clients may receive other values later." + }, + "name": { + "type": "string" + }, + "agentId": { "type": "string" + }, + "via": { + "type": "string", + "description": "On an owner message sent through a message gateway: the gateway's ID, such as `discord`." + }, + "source": { + "type": "string", + "description": "On an event automation's message: the name of the event source whose event started it." } }, "required": [ - "taskId" + "kind" ] }, - "Memory": { + "BotCommunication": { "type": "object", "properties": { - "id": { + "executionId": { "type": "string" }, - "agentId": { - "type": [ - "string", - "null" - ] + "fromAgentId": { + "type": "string" }, - "content": { + "fromName": { "type": "string" }, - "createdAt": { + "toAgentId": { "type": "string" }, - "updatedAt": { + "toName": { "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "sent", + "done", + "failed", + "cancelled" + ] } }, "required": [ - "id", - "agentId", - "content", - "createdAt", - "updatedAt" + "executionId", + "fromAgentId", + "fromName", + "toAgentId", + "toName", + "status" ] }, - "ListedSkill": { - "oneOf": [ - { - "allOf": [ - { - "$ref": "#/components/schemas/Skill" - }, - { - "type": "object", - "properties": { - "source": { - "type": "string", - "enum": [ - "shared" - ] - } - }, - "required": [ - "source" - ] - } - ] + "AttachmentInfo": { + "type": "object", + "properties": { + "name": { + "type": "string" }, - { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "description": { - "type": "string" - }, - "instructions": { - "type": "string" - }, - "path": { - "type": "string" - }, - "source": { - "type": "string", - "enum": [ - "bundled" - ] - } - }, - "required": [ - "id", - "name", - "instructions", - "path", - "source" + "mimeType": { + "type": "string" + }, + "size": { + "type": "number" + }, + "kind": { + "type": "string", + "enum": [ + "image", + "text" ] } + }, + "required": [ + "name", + "mimeType", + "size", + "kind" ] }, - "Skill": { + "Conversation": { "type": "object", "properties": { "id": { "type": "string" }, - "name": { + "agentId": { "type": "string" }, - "instructions": { + "title": { "type": "string" }, "createdAt": { @@ -858,94 +1291,274 @@ }, "updatedAt": { "type": "string" + }, + "archived": { + "type": "boolean" } }, "required": [ "id", - "name", - "instructions", + "agentId", + "title", "createdAt", "updatedAt" ] }, - "Schedule": { + "TranscriptPage": { "type": "object", "properties": { - "id": { - "type": "string" - }, - "agentId": { - "type": "string" - }, - "name": { - "type": "string" + "messages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TranscriptMessage" + } }, - "prompt": { - "type": "string" + "hasMore": { + "type": "boolean" }, - "cron": { + "oldestEntryId": { "type": [ "string", "null" ] + } + }, + "required": [ + "messages", + "hasMore", + "oldestEntryId" + ] + }, + "CodingJobs": { + "type": "object", + "properties": { + "jobs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CodingJob" + }, + "description": "Oldest job first." + } + }, + "required": [ + "jobs" + ] + }, + "CodingJob": { + "type": "object", + "properties": { + "name": { + "type": "string" }, - "timezone": { + "conversationId": { "type": "string" }, - "runAt": { - "type": [ - "string", - "null" + "status": { + "type": "string", + "enum": [ + "working", + "idle" ] }, - "enabled": { - "type": "boolean" + "model": { + "type": "object", + "properties": { + "provider": { + "type": "string" + }, + "model": { + "type": "string" + } + }, + "required": [ + "provider", + "model" + ], + "description": "The model the job runs with. Absent when the job has none of its own and uses the server's default." }, - "nextRunAt": { - "type": [ - "string", - "null" - ] + "usage": { + "description": "Pi Durable usage document of the job's own conversation: tokens and cost per model and tool. Absent before its first request." }, - "createdAt": { + "question": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "text": { + "type": "string" + }, + "askedAt": { + "type": "number" + }, + "options": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Answers the owner can pick; any other text is an answer too." + }, + "multiple": { + "type": "boolean", + "description": "Whether several options can be picked; the answer lists each." + } + }, + "required": [ + "id", + "text", + "askedAt" + ], + "description": "The question the job asked the owner and waits on. Answer it with the job's `answer` route." + } + }, + "required": [ + "name", + "conversationId", + "status" + ] + }, + "DesktopJobs": { + "type": "object", + "properties": { + "jobs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DesktopJob" + }, + "description": "Oldest job first." + } + }, + "required": [ + "jobs" + ] + }, + "DesktopJob": { + "type": "object", + "properties": { + "name": { "type": "string" }, - "createdByAgentId": { - "type": [ - "string", - "null" + "conversationId": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "working", + "idle" ] + }, + "model": { + "type": "object", + "properties": { + "provider": { + "type": "string" + }, + "model": { + "type": "string" + } + }, + "required": [ + "provider", + "model" + ], + "description": "The model the job runs with. Absent when the job has none of its own and uses the server's default." + }, + "usage": { + "description": "Pi Durable usage document of the job's own conversation: tokens and cost per model and tool. Absent before its first request." + }, + "question": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "text": { + "type": "string" + }, + "askedAt": { + "type": "number" + }, + "options": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Answers the owner can pick; any other text is an answer too." + }, + "multiple": { + "type": "boolean", + "description": "Whether several options can be picked; the answer lists each." + } + }, + "required": [ + "id", + "text", + "askedAt" + ], + "description": "The question the job asked the owner and waits on. Answer it with the job's `answer` route." } }, "required": [ - "id", - "agentId", "name", - "prompt", - "cron", - "timezone", - "runAt", - "enabled", - "nextRunAt", - "createdAt", - "createdByAgentId" + "conversationId", + "status" ] }, - "ScheduleRun": { + "DesktopControl": { "type": "object", "properties": { - "admitted": { - "type": "boolean" + "holder": { + "type": "string", + "enum": [ + "bot", + "owner" + ], + "description": "Who operates the bot desktop. While the owner holds control, the bot's desktop job pauses and only the owner's viewer input reaches the bot desktop." }, - "result": { - "$ref": "#/components/schemas/ScheduleRunResult" + "changes": { + "type": "integer", + "description": "How often control changed hands. A desktop job refuses actions it planned before a change." + }, + "updatedAt": { + "type": "string" } }, "required": [ - "admitted" + "holder", + "changes", + "updatedAt" ] }, - "ScheduleRunResult": { + "DesktopStatus": { + "type": "object", + "properties": { + "running": { + "type": "boolean", + "description": "Whether the bot's machine runs its bot desktop now, so a passive viewer can connect. Always false for a bot without a bot desktop." + } + }, + "required": [ + "running" + ] + }, + "DesktopViewer": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Server-relative URL of the viewer page, a noVNC client of the bot desktop. Load it in a web view; it works once and expires at expiresAt unless its connection has started by then." + }, + "expiresAt": { + "type": "string" + } + }, + "required": [ + "path", + "expiresAt" + ] + }, + "Execution": { "type": "object", "properties": { "id": { @@ -988,7 +1601,14 @@ ] }, "status": { - "type": "string" + "type": "string", + "enum": [ + "pending", + "running", + "done", + "failed", + "cancelled" + ] }, "error": { "type": [ @@ -1003,229 +1623,16006 @@ "type": "string" } }, - "additionalProperties": {} + "required": [ + "id", + "agentId", + "conversationId", + "scheduleId", + "submissionId", + "requestId", + "prompt", + "status", + "error", + "createdAt", + "updatedAt" + ] }, - "ActivityFeed": { + "Compaction": { "type": "object", "properties": { - "activities": { - "type": "array", - "items": { - "$ref": "#/components/schemas/OperationalActivity" - } - }, - "hasMore": { - "type": "boolean" + "taskId": { + "type": "string" } }, "required": [ - "activities", - "hasMore" + "taskId" ] }, - "OperationalActivity": { + "GroupChat": { "type": "object", "properties": { "id": { "type": "string" }, - "agentId": { + "name": { "type": "string" }, - "agentName": { - "type": "string" + "memberIds": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Member bots in the order they joined." }, - "entryId": { + "createdAt": { "type": "string" }, - "timestamp": { - "type": "number" - }, - "kind": { - "type": "string", - "enum": [ - "tool-call", - "tool-result", - "mcp-call", - "bot-message" - ] - }, - "details": { - "type": "object", - "additionalProperties": {} + "updatedAt": { + "type": "string" } }, "required": [ "id", - "agentId", - "agentName", - "entryId", - "kind", - "details" + "name", + "memberIds", + "createdAt", + "updatedAt" ] }, - "Provider": { - "type": "object", + "GroupChatSnapshot": { + "allOf": [ + { + "$ref": "#/components/schemas/TranscriptPage" + }, + { + "type": "object", + "properties": { + "groupChat": { + "$ref": "#/components/schemas/GroupChat" + }, + "activity": { + "$ref": "#/components/schemas/GroupActivity" + }, + "updatedAt": { + "type": "number" + } + }, + "required": [ + "groupChat", + "activity", + "updatedAt" + ] + } + ] + }, + "GroupActivity": { + "type": "object", "properties": { - "provider": { - "type": "string" + "paused": { + "type": "boolean", + "description": "Bot-started turns used up the turn budget; the owner's next message resumes the group." }, - "name": { - "type": "string" + "botTurns": { + "type": "number", + "description": "Bot-started turns since the owner's last message." }, - "configured": { - "type": "boolean" + "members": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GroupMemberActivity" + } } }, "required": [ - "provider", - "name", - "configured" + "paused", + "botTurns", + "members" ] }, - "Model": { + "GroupMemberActivity": { "type": "object", "properties": { - "provider": { - "type": "string" - }, - "id": { - "type": "string" - }, - "name": { + "agentId": { "type": "string" }, - "contextWindow": { - "type": "number" + "status": { + "type": "string", + "enum": [ + "idle", + "queued", + "running", + "disabled" + ] }, - "reasoning": { - "type": "boolean" + "error": { + "type": [ + "string", + "null" + ], + "description": "Why the member's latest turn failed." } }, "required": [ - "provider", - "id", - "name", - "contextWindow", - "reasoning" + "agentId", + "status", + "error" ] }, - "ProviderConfigured": { + "GroupMessageReceipt": { "type": "object", "properties": { - "provider": { + "requestId": { "type": "string" }, - "configured": { - "type": "boolean" + "entryId": { + "type": "string" } }, "required": [ - "provider", - "configured" + "requestId", + "entryId" ] }, - "McpServerStatus": { - "allOf": [ - { - "$ref": "#/components/schemas/McpServer" + "Credentials": { + "type": "object", + "properties": { + "credentials": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Credential" + } }, - { - "type": "object", - "properties": { - "auth": { - "type": "string", - "enum": [ - "oauth", - "token", - "none" - ] - }, - "authenticated": { - "type": "boolean" - } - }, - "required": [ - "auth", - "authenticated" - ] + "requests": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CredentialRequest" + } } + }, + "required": [ + "credentials", + "requests" ] }, - "McpServer": { + "Credential": { "type": "object", "properties": { - "id": { - "type": "string" - }, "name": { "type": "string" }, - "url": { + "hosts": { + "type": "array", + "items": { + "type": "string" + } + }, + "secret": { + "allOf": [ + { + "$ref": "#/components/schemas/SecretStatus" + }, + { + "type": [ + "object", + "null" + ], + "description": "Null when `github` is true." + } + ] + }, + "createdAt": { "type": "string" }, - "enabled": { - "type": "boolean" + "updatedAt": { + "type": "string" }, - "agentId": { + "lastUsedAt": { "type": [ "string", "null" ] + }, + "lastError": { + "type": [ + "string", + "null" + ], + "description": "Why the newest use couldn't read the value from its password manager; null when it could." + }, + "github": { + "type": "boolean", + "description": "The value is a GitHub token: from the bot's GitHub App, minted for the App or for the owner signed in through it, or its machine account's personal access token. It has no secret here." } }, "required": [ - "id", "name", - "url", - "enabled", - "agentId" + "hosts", + "secret", + "createdAt", + "updatedAt", + "lastUsedAt", + "lastError", + "github" ] }, - "McpOAuthStart": { - "anyOf": [ - { + "CredentialRequest": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "hosts": { + "type": "array", + "items": { + "type": "string" + } + }, + "reason": { + "type": "string" + }, + "requestedAt": { + "type": "string" + } + }, + "required": [ + "name", + "hosts", + "reason", + "requestedAt" + ] + }, + "BotRequest": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "agentId": { + "type": "string" + }, + "proposal": { "type": "object", "properties": { - "authorizationUrl": { - "type": "string" + "name": { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + "avatar": { + "type": "object", + "properties": { + "definition": { + "type": "object", + "properties": { + "version": { + "type": "number", + "enum": [ + 1 + ] + }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 40 + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 40 + }, + "body": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 6000 + } + }, + "required": [ + "path" + ], + "additionalProperties": false + }, + "eyes": { + "type": "object", + "properties": { + "x": { + "type": "number" + }, + "y": { + "type": "number" + }, + "spacing": { + "type": "number" + }, + "scale": { + "type": "number" + } + }, + "required": [ + "x", + "y", + "spacing", + "scale" + ], + "additionalProperties": false + } + }, + "required": [ + "version", + "id", + "name", + "body", + "eyes" + ], + "additionalProperties": false + }, + "color": { + "type": "string", + "pattern": "^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" + }, + "eyeColor": { + "type": "string", + "pattern": "^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" + } + }, + "required": [ + "definition", + "color", + "eyeColor" + ] + }, + "description": { + "type": "string", + "maxLength": 1000, + "default": "" + }, + "instructions": { + "type": "string", + "maxLength": 32000, + "default": "You are a thoughtful, capable personal assistant." + }, + "provider": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-z0-9-]+$", + "default": "openai" + }, + "model": { + "type": "string", + "minLength": 1, + "maxLength": 200, + "default": "gpt-4.1" + }, + "webSearchProvider": { + "type": [ + "string", + "null" + ], + "enum": [ + "mixed", + "exa", + null + ] + }, + "enabled": { + "type": "boolean", + "default": true + }, + "tools": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "maxItems": 100, + "default": [ + "memory" + ] + }, + "skills": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "instructions": { + "type": "string", + "maxLength": 32000 + } + }, + "required": [ + "name", + "instructions" + ] + }, + "maxItems": 100, + "default": [] + }, + "sharedSkills": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 100 + }, + "sharedMemory": { + "type": "boolean" + }, + "mcpServers": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 30, + "default": [] + }, + "delegates": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 30, + "default": [] + }, + "inference": { + "type": "object", + "properties": { + "thinkingLevel": { + "type": "string", + "enum": [ + "off", + "minimal", + "low", + "medium", + "high", + "xhigh", + "max" + ], + "default": "off" + }, + "temperature": { + "type": "number", + "minimum": 0, + "maximum": 2 + }, + "maxOutputTokens": { + "type": "integer", + "minimum": 1, + "maximum": 1000000 + } + } + }, + "review": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "default": true + }, + "skillThreshold": { + "type": "integer", + "minimum": 1, + "maximum": 1000, + "default": 10 + }, + "memoryThreshold": { + "type": "integer", + "minimum": 1, + "maximum": 1000, + "default": 10 + }, + "maxInputTokens": { + "type": "integer", + "minimum": 1000, + "maximum": 2000000 + } + } + }, + "reviewModel": { + "type": [ + "object", + "null" + ], + "properties": { + "provider": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-z0-9-]+$" + }, + "model": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "provider", + "model" + ] + }, + "desktopModel": { + "type": [ + "object", + "null" + ], + "properties": { + "provider": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-z0-9-]+$" + }, + "model": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "provider", + "model" + ] + } + }, + "required": [ + "name" + ] + }, + "reason": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "pending", + "approved", + "declined" + ] + }, + "createdAgentId": { + "type": [ + "string", + "null" + ] + }, + "requestedAt": { + "type": "string" + }, + "decidedAt": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "id", + "agentId", + "proposal", + "reason", + "status", + "createdAgentId", + "requestedAt", + "decidedAt" + ] + }, + "CredentialUse": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "at": { + "type": "string" + }, + "method": { + "type": "string" + }, + "host": { + "type": "string" + }, + "path": { + "type": "string" + }, + "status": { + "type": [ + "integer", + "null" + ] + }, + "error": { + "type": [ + "string", + "null" + ], + "description": "Why the value couldn't be read from its password manager; the request was never sent." + } + }, + "required": [ + "id", + "at", + "method", + "host", + "path", + "status", + "error" + ] + }, + "Logins": { + "type": "object", + "properties": { + "logins": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Login" + } + }, + "requests": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LoginRequest" + } + } + }, + "required": [ + "logins", + "requests" + ] + }, + "Login": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "hosts": { + "type": "array", + "items": { + "type": "string" + } + }, + "fields": { + "type": "object", + "properties": { + "username": { + "$ref": "#/components/schemas/SecretStatus" + }, + "password": { + "$ref": "#/components/schemas/SecretStatus" + }, + "one_time_code": { + "$ref": "#/components/schemas/SecretStatus" + } + }, + "description": "Where each field's value is read from. A login always has a username and a password; `one_time_code` only when it has one." + }, + "createdAt": { + "type": "string" + }, + "updatedAt": { + "type": "string" + }, + "lastUsedAt": { + "type": [ + "string", + "null" + ] + }, + "lastError": { + "type": [ + "string", + "null" + ], + "description": "Why the newest fill couldn't read its value; null when it could." + } + }, + "required": [ + "name", + "hosts", + "fields", + "createdAt", + "updatedAt", + "lastUsedAt", + "lastError" + ] + }, + "LoginRequest": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "hosts": { + "type": "array", + "items": { + "type": "string" + } + }, + "reason": { + "type": "string" + }, + "oneTimeCode": { + "type": "boolean", + "description": "Whether the bot says the site asks for a one-time code." + }, + "requestedAt": { + "type": "string" + } + }, + "required": [ + "name", + "hosts", + "reason", + "oneTimeCode", + "requestedAt" + ] + }, + "LoginUse": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "at": { + "type": "string" + }, + "host": { + "type": "string" + }, + "field": { + "type": "string", + "enum": [ + "username", + "password", + "one_time_code" + ] + }, + "error": { + "type": [ + "string", + "null" + ], + "description": "Why the value couldn't be read; nothing was typed." + } + }, + "required": [ + "id", + "at", + "host", + "field", + "error" + ] + }, + "HeldAction": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "job": { + "type": "string", + "description": "The desktop job's name." + }, + "action": { + "type": "string", + "description": "The action in plain words." + }, + "page": { + "type": [ + "string", + "null" + ], + "description": "The URL of the page the job read last." + }, + "ownerMessages": { + "type": "array", + "items": { + "type": "object", + "properties": { + "requestId": { + "type": "string" + }, + "text": { + "type": "string" + }, + "from": { + "type": "string", + "enum": [ + "owner", + "automation" + ] + } + }, + "required": [ + "requestId", + "text", + "from" + ] + }, + "description": "The owner messages the action was checked against." + }, + "reason": { + "type": "string", + "description": "Why the intent check held it." + }, + "status": { + "type": "string", + "enum": [ + "pending", + "approved", + "declined", + "expired" + ] + }, + "declineReason": { + "type": [ + "string", + "null" + ] + }, + "heldAt": { + "type": "string" + }, + "decidedAt": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "id", + "job", + "action", + "page", + "ownerMessages", + "reason", + "status", + "declineReason", + "heldAt", + "decidedAt" + ] + }, + "Memory": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "agentId": { + "type": [ + "string", + "null" + ] + }, + "content": { + "type": "string" + }, + "source": { + "anyOf": [ + { + "$ref": "#/components/schemas/MemorySource" + }, + { + "type": "null" + } + ] + }, + "createdAt": { + "type": "string" + }, + "updatedAt": { + "type": "string" + } + }, + "required": [ + "id", + "agentId", + "content", + "source", + "createdAt", + "updatedAt" + ] + }, + "MemorySource": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "chat", + "owner", + "task", + "bot", + "group" + ] + }, + "name": { + "type": "string", + "description": "The task, bot, or group chat, as named when the memory was saved." + }, + "scheduleId": { + "type": "string", + "description": "For `task`." + }, + "agentId": { + "type": "string", + "description": "For `bot`." + }, + "groupId": { + "type": "string", + "description": "For `group`." + } + }, + "required": [ + "kind" + ], + "description": "Where the memory was saved: the owner's bot chat, the owner directly, a scheduled task, another bot's request, or a group chat." + }, + "SkillPackage": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "instructions": { + "type": "string" + }, + "createdAt": { + "type": "string" + }, + "updatedAt": { + "type": "string" + }, + "agentId": { + "type": [ + "string", + "null" + ] + }, + "description": { + "type": "string" + }, + "documents": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SkillDocument" + } + }, + "createdBy": { + "type": "string", + "enum": [ + "owner", + "bot" + ] + }, + "sourceExecutionId": { + "type": [ + "string", + "null" + ] + }, + "useCount": { + "type": "integer" + }, + "lastUsedAt": { + "type": [ + "string", + "null" + ] + }, + "state": { + "type": "string", + "enum": [ + "active", + "stale", + "archived" + ] + }, + "pinned": { + "type": "boolean" + }, + "copiedFromSkillId": { + "type": [ + "string", + "null" + ], + "format": "uuid" + }, + "origin": { + "$ref": "#/components/schemas/SkillOrigin" + } + }, + "required": [ + "id", + "name", + "instructions", + "createdAt", + "updatedAt", + "agentId", + "description", + "documents", + "createdBy", + "sourceExecutionId", + "useCount", + "lastUsedAt", + "state", + "pinned" + ] + }, + "SkillDocument": { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "content": { + "type": "string" + } + }, + "required": [ + "path", + "content" + ] + }, + "SkillOrigin": { + "type": [ + "object", + "null" + ], + "properties": { + "repository": { + "type": "string", + "description": "`owner/repo`." + }, + "branch": { + "type": "string" + }, + "path": { + "type": "string", + "description": "The skill's folder; empty for the root." + }, + "commit": { + "type": "string" + }, + "digest": { + "type": "string", + "description": "Fingerprint of the imported files; an update is available when upstream's differs." + } + }, + "required": [ + "repository", + "branch", + "path", + "commit", + "digest" + ], + "description": "Where an installed skill came from. Installed skills are read-only." + }, + "ReviewResult": { + "type": "object", + "properties": { + "executionId": { + "type": "string" + }, + "agentId": { + "type": "string" + }, + "createdAt": { + "type": "string" + }, + "changes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LearnedChange" + } + } + }, + "required": [ + "executionId", + "agentId", + "createdAt", + "changes" + ] + }, + "LearnedChange": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "agentId": { + "type": [ + "string", + "null" + ] + }, + "actor": { + "type": "string", + "enum": [ + "owner", + "bot", + "review", + "curator" + ] + }, + "target": { + "type": "string", + "enum": [ + "skill", + "memory" + ] + }, + "targetId": { + "type": "string" + }, + "action": { + "type": "string", + "enum": [ + "create", + "update", + "delete", + "revert" + ] + }, + "before": { + "anyOf": [ + { + "$ref": "#/components/schemas/SkillPackage" + }, + { + "$ref": "#/components/schemas/Memory" + }, + { + "type": "null" + } + ] + }, + "after": { + "anyOf": [ + { + "$ref": "#/components/schemas/SkillPackage" + }, + { + "$ref": "#/components/schemas/Memory" + }, + { + "type": "null" + } + ] + }, + "source": { + "anyOf": [ + { + "$ref": "#/components/schemas/ChangeSource" + }, + { + "type": "null" + } + ] + }, + "revertsId": { + "type": [ + "string", + "null" + ] + }, + "createdAt": { + "type": "string" + } + }, + "required": [ + "id", + "agentId", + "actor", + "target", + "targetId", + "action", + "before", + "after", + "source", + "revertsId", + "createdAt" + ] + }, + "ChangeSource": { + "type": "object", + "properties": { + "executionId": { + "type": [ + "string", + "null" + ] + }, + "conversationId": { + "type": [ + "string", + "null" + ] + }, + "groupId": { + "type": [ + "string", + "null" + ] + } + } + }, + "ListedSkill": { + "oneOf": [ + { + "allOf": [ + { + "$ref": "#/components/schemas/Skill" + }, + { + "type": "object", + "properties": { + "source": { + "type": "string", + "enum": [ + "shared" + ] + }, + "description": { + "type": "string" + }, + "origin": { + "$ref": "#/components/schemas/SkillOrigin" + }, + "update": { + "$ref": "#/components/schemas/SkillUpdate" + } + }, + "required": [ + "source" + ] + } + ] + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "instructions": { + "type": "string" + }, + "path": { + "type": "string" + }, + "source": { + "type": "string", + "enum": [ + "bundled" + ] + } + }, + "required": [ + "id", + "name", + "instructions", + "path", + "source" + ] + } + ] + }, + "SkillUpdate": { + "type": [ + "object", + "null" + ], + "properties": { + "commit": { + "type": "string" + }, + "removed": { + "type": "boolean", + "description": "The skill's folder is gone from the branch." + } + }, + "required": [ + "commit", + "removed" + ], + "description": "The newer upstream commit of an installed skill." + }, + "Skill": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "instructions": { + "type": "string" + }, + "createdAt": { + "type": "string" + }, + "updatedAt": { + "type": "string" + } + }, + "required": [ + "id", + "name", + "instructions", + "createdAt", + "updatedAt" + ] + }, + "SkillListing": { + "type": "object", + "properties": { + "repository": { + "type": "string" + }, + "branch": { + "type": "string" + }, + "commit": { + "type": "string" + }, + "path": { + "type": "string" + }, + "skills": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SkillCandidate" + } + }, + "omitted": { + "type": "integer", + "description": "Skills beyond the first hundred, not listed." + } + }, + "required": [ + "repository", + "branch", + "commit", + "path", + "skills", + "omitted" + ] + }, + "SkillCandidate": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "The skill's folder; empty for the root." + }, + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "new", + "installed", + "update", + "clash", + "invalid" + ] + }, + "problem": { + "type": [ + "string", + "null" + ], + "description": "Why a `clash` or `invalid` skill can't be installed." + }, + "skipped": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Files in the folder that won't be imported: only SKILL.md and references/*.md are." + }, + "skillId": { + "type": [ + "string", + "null" + ], + "description": "The installed skill, for `installed` and `update`." + } + }, + "required": [ + "path", + "name", + "description", + "status", + "problem", + "skipped", + "skillId" + ] + }, + "SkillCheck": { + "type": "object", + "properties": { + "failed": { + "type": "array", + "items": { + "type": "object", + "properties": { + "repository": { + "type": "string" + }, + "branch": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "repository", + "branch", + "message" + ] + } + } + }, + "required": [ + "failed" + ] + }, + "PendingSkillUpdate": { + "type": "object", + "properties": { + "commit": { + "type": "string" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "instructions": { + "type": "string" + }, + "documents": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SkillDocument" + } + }, + "skipped": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "commit", + "name", + "description", + "instructions", + "documents", + "skipped" + ] + }, + "Schedule": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "agentId": { + "type": "string" + }, + "name": { + "type": "string" + }, + "prompt": { + "type": "string" + }, + "kind": { + "type": "string", + "enum": [ + "prompt", + "script" + ] + }, + "command": { + "type": [ + "string", + "null" + ] + }, + "timeoutSeconds": { + "type": "integer" + }, + "notify": { + "type": "boolean" + }, + "cron": { + "type": [ + "string", + "null" + ] + }, + "timezone": { + "type": "string" + }, + "runAt": { + "type": [ + "string", + "null" + ] + }, + "eventSourceId": { + "type": [ + "string", + "null" + ], + "description": "The event source whose events start this automation; set instead of `cron` and `runAt`." + }, + "enabled": { + "type": "boolean" + }, + "nextRunAt": { + "type": [ + "string", + "null" + ] + }, + "createdAt": { + "type": "string" + }, + "createdByAgentId": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "id", + "agentId", + "name", + "prompt", + "kind", + "command", + "timeoutSeconds", + "notify", + "cron", + "timezone", + "runAt", + "eventSourceId", + "enabled", + "nextRunAt", + "createdAt", + "createdByAgentId" + ] + }, + "ScheduleRun": { + "type": "object", + "properties": { + "admitted": { + "type": "boolean" + }, + "result": { + "$ref": "#/components/schemas/ScheduleRunResult" + } + }, + "required": [ + "admitted" + ] + }, + "ScheduleRunResult": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "agentId": { + "type": "string" + }, + "conversationId": { + "type": "string" + }, + "scheduleId": { + "type": [ + "string", + "null" + ] + }, + "submissionId": { + "type": [ + "string", + "null" + ] + }, + "requestId": { + "type": "string" + }, + "prompt": { + "type": "string" + }, + "replyTo": { + "type": [ + "string", + "null" + ] + }, + "attachmentsDigest": { + "type": [ + "string", + "null" + ] + }, + "status": { + "type": "string" + }, + "error": { + "type": [ + "string", + "null" + ] + }, + "createdAt": { + "type": "string" + }, + "updatedAt": { + "type": "string" + } + }, + "additionalProperties": {} + }, + "ScriptRun": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "scheduleId": { + "type": "string" + }, + "agentId": { + "type": "string" + }, + "command": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "running", + "succeeded", + "failed", + "timed_out", + "interrupted" + ] + }, + "exitCode": { + "type": [ + "integer", + "null" + ] + }, + "output": { + "type": "string", + "description": "The last 64 KiB and 2000 lines of combined output." + }, + "droppedBytes": { + "type": "integer", + "description": "Bytes dropped from the output tail." + }, + "error": { + "type": [ + "string", + "null" + ] + }, + "startedAt": { + "type": "string" + }, + "finishedAt": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "id", + "scheduleId", + "agentId", + "command", + "status", + "exitCode", + "output", + "droppedBytes", + "error", + "startedAt", + "finishedAt" + ] + }, + "ActivityFeed": { + "type": "object", + "properties": { + "activities": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/OperationalActivity" + }, + { + "$ref": "#/components/schemas/ChangeActivity" + } + ] + } + }, + "hasMore": { + "type": "boolean" + }, + "nextCursor": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "activities", + "hasMore", + "nextCursor" + ] + }, + "OperationalActivity": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "agentId": { + "type": "string" + }, + "agentName": { + "type": "string" + }, + "entryId": { + "type": "string" + }, + "timestamp": { + "type": "number" + }, + "kind": { + "type": "string", + "enum": [ + "tool-call", + "tool-result", + "mcp-call", + "bot-message" + ] + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "id", + "agentId", + "agentName", + "entryId", + "kind", + "details" + ] + }, + "ChangeActivity": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "agentId": { + "type": [ + "string", + "null" + ] + }, + "agentName": { + "type": [ + "string", + "null" + ] + }, + "timestamp": { + "type": "number" + }, + "kind": { + "type": "string", + "enum": [ + "change" + ] + }, + "change": { + "$ref": "#/components/schemas/LearnedChange" + } + }, + "required": [ + "id", + "agentId", + "agentName", + "timestamp", + "kind", + "change" + ] + }, + "Provider": { + "type": "object", + "properties": { + "provider": { + "type": "string" + }, + "name": { + "type": "string" + }, + "configured": { + "type": "boolean" + }, + "authMethods": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ProviderLoginMethod" + } + }, + "credentialType": { + "type": [ + "string", + "null" + ], + "enum": [ + "api_key", + "oauth", + null + ] + }, + "apiKey": { + "$ref": "#/components/schemas/SecretStatus" + }, + "activeLoginId": { + "type": [ + "string", + "null" + ] + }, + "externalAuth": { + "$ref": "#/components/schemas/ProviderExternalAuth" + } + }, + "required": [ + "provider", + "name", + "configured", + "authMethods", + "credentialType", + "apiKey", + "activeLoginId", + "externalAuth" + ] + }, + "ProviderLoginMethod": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "api_key", + "oauth" + ] + }, + "label": { + "type": "string" + }, + "subscription": { + "type": "boolean" + } + }, + "required": [ + "type", + "label", + "subscription" + ] + }, + "ProviderExternalAuth": { + "type": [ + "object", + "null" + ], + "properties": { + "status": { + "type": "string", + "enum": [ + "signed_in", + "signed_out", + "cli_missing", + "error" + ] + }, + "cliVersion": { + "type": [ + "string", + "null" + ] + }, + "signInCommand": { + "type": [ + "string", + "null" + ] + }, + "signOutCommand": { + "type": [ + "string", + "null" + ] + }, + "message": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "status", + "cliVersion", + "signInCommand", + "signOutCommand", + "message" + ] + }, + "Model": { + "type": "object", + "properties": { + "provider": { + "type": "string" + }, + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "contextWindow": { + "type": "number" + }, + "reasoning": { + "type": "boolean" + }, + "thinkingLevels": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "off", + "minimal", + "low", + "medium", + "high", + "xhigh", + "max" + ] + }, + "description": "The thinking levels this model takes, from lowest to highest. A bot's level outside them runs at the nearest one." + } + }, + "required": [ + "provider", + "id", + "name", + "contextWindow", + "reasoning", + "thinkingLevels" + ] + }, + "ProviderConfigured": { + "type": "object", + "properties": { + "provider": { + "type": "string" + }, + "configured": { + "type": "boolean" + } + }, + "required": [ + "provider", + "configured" + ] + }, + "ProviderLoginSession": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "provider": { + "type": "string" + }, + "method": { + "type": "string", + "enum": [ + "api_key", + "oauth" + ] + }, + "status": { + "type": "string", + "enum": [ + "pending", + "succeeded", + "failed", + "cancelled", + "expired" + ] + }, + "createdAt": { + "type": "number" + }, + "expiresAt": { + "type": "number" + }, + "prompt": { + "type": [ + "object", + "null" + ], + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "text", + "secret", + "select", + "manual_code" + ] + }, + "message": { + "type": "string" + }, + "placeholder": { + "type": "string" + }, + "options": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "label": { + "type": "string" + }, + "description": { + "type": "string" + } + }, + "required": [ + "id", + "label" + ] + } + } + }, + "required": [ + "id", + "type", + "message" + ] + }, + "events": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ProviderLoginEvent" + } + }, + "failure": { + "type": [ + "object", + "null" + ], + "properties": { + "code": { + "type": "string", + "enum": [ + "provider_failure", + "callback_unavailable", + "storage_failure" + ] + }, + "message": { + "type": "string" + } + }, + "required": [ + "code", + "message" + ] + } + }, + "required": [ + "id", + "provider", + "method", + "status", + "createdAt", + "expiresAt", + "prompt", + "events", + "failure" + ] + }, + "ProviderLoginEvent": { + "oneOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "info" + ] + }, + "message": { + "type": "string" + }, + "links": { + "type": "array", + "items": { + "type": "object", + "properties": { + "url": { + "type": "string" + }, + "label": { + "type": "string" + } + }, + "required": [ + "url" + ] + } + } + }, + "required": [ + "type", + "message" + ] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "auth_url" + ] + }, + "url": { + "type": "string" + }, + "instructions": { + "type": "string" + } + }, + "required": [ + "type", + "url" + ] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "device_code" + ] + }, + "userCode": { + "type": "string" + }, + "verificationUri": { + "type": "string" + }, + "intervalSeconds": { + "type": "number" + }, + "expiresInSeconds": { + "type": "number" + } + }, + "required": [ + "type", + "userCode", + "verificationUri" + ] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "progress" + ] + }, + "message": { + "type": "string" + } + }, + "required": [ + "type", + "message" + ] + } + ] + }, + "PasswordManagers": { + "type": "object", + "properties": { + "passwordManagers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PasswordManager" + } + } + }, + "required": [ + "passwordManagers" + ] + }, + "PasswordManager": { + "type": "object", + "properties": { + "id": { + "type": "string", + "enum": [ + "1password", + "bitwarden" + ] + }, + "name": { + "type": "string" + }, + "connected": { + "type": "boolean" + }, + "connectedAt": { + "type": [ + "string", + "null" + ] + }, + "usedBy": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The keys of the secrets that read their value from this password manager, such as `mcp:`; it can't be disconnected while any remain." + } + }, + "required": [ + "id", + "name", + "connected", + "connectedAt", + "usedBy" + ] + }, + "PluginSettings": { + "type": "object", + "properties": { + "plugins": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "contributes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "providers", + "jobKinds", + "webSearchProviders", + "chatAdapters" + ] + }, + "description": "What the plugin adds to the server, so a client can show its settings where those are chosen." + }, + "settings": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PluginSetting" + } + } + }, + "required": [ + "id", + "contributes", + "settings" + ] + } + } + }, + "required": [ + "plugins" + ] + }, + "PluginSetting": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "kind": { + "type": "string", + "enum": [ + "secret" + ], + "description": "A secret is written once and never returned." + }, + "label": { + "type": "string" + }, + "whenMissing": { + "type": "string", + "description": "The status to show while the setting has no value." + }, + "secret": { + "$ref": "#/components/schemas/SecretStatus" + } + }, + "required": [ + "key", + "kind", + "label", + "whenMissing", + "secret" + ] + }, + "McpServerStatus": { + "allOf": [ + { + "$ref": "#/components/schemas/McpServer" + }, + { + "type": "object", + "properties": { + "auth": { + "type": "string", + "enum": [ + "oauth", + "token", + "none" + ] + }, + "error": { + "type": [ + "string", + "null" + ], + "description": "Why the server's tools were left out of a bot's last turn, such as a missing sign-in; null once it connects again." + }, + "authenticated": { + "type": "boolean" + } + }, + "required": [ + "auth", + "error", + "authenticated" + ] + } + ] + }, + "McpServer": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "url": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "agentId": { + "type": [ + "string", + "null" + ] + }, + "oauthClientId": { + "type": [ + "string", + "null" + ], + "description": "The client ID of an OAuth app the owner registered with the server's authorization server, used instead of registering Crumble." + }, + "token": { + "$ref": "#/components/schemas/SecretStatus" + }, + "oauthClientSecret": { + "$ref": "#/components/schemas/SecretStatus" + } + }, + "required": [ + "id", + "name", + "url", + "enabled", + "agentId", + "oauthClientId", + "token", + "oauthClientSecret" + ] + }, + "McpOAuthStart": { + "anyOf": [ + { + "type": "object", + "properties": { + "authorizationUrl": { + "type": "string" + } + }, + "required": [ + "authorizationUrl" + ] + }, + { + "type": "object", + "properties": { + "authorized": { + "type": "boolean", + "enum": [ + true + ] + } + }, + "required": [ + "authorized" + ] + } + ] + } + }, + "parameters": {} + }, + "paths": { + "/health": { + "get": { + "operationId": "getHealth", + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Health" + } + } + } + } + } + } + }, + "/v1/capabilities": { + "get": { + "operationId": "getCapabilities", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Capabilities" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/push": { + "get": { + "operationId": "getPushStatus", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PushStatus" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/push/devices/{installationId}": { + "put": { + "operationId": "putPushDevice", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string", + "format": "uuid" + }, + "required": true, + "name": "installationId", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "platform": { + "type": "string", + "enum": [ + "macos", + "ios", + "android" + ] + }, + "transport": { + "type": "string", + "enum": [ + "apns", + "fcm" + ] + }, + "token": { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + "environment": { + "type": "string", + "enum": [ + "development", + "production" + ] + }, + "bundleId": { + "type": "string", + "minLength": 1, + "maxLength": 255 + }, + "enabled": { + "type": "boolean" + } + }, + "required": [ + "platform", + "transport", + "token", + "environment", + "enabled" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PushDeviceRegistration" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "delete": { + "operationId": "deletePushDevice", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string", + "format": "uuid" + }, + "required": true, + "name": "installationId", + "in": "path" + } + ], + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/push/devices/{installationId}/presence": { + "put": { + "operationId": "putPushPresence", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string", + "format": "uuid" + }, + "required": true, + "name": "installationId", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "active": { + "type": "boolean" + }, + "agentId": { + "type": [ + "string", + "null" + ], + "format": "uuid" + } + }, + "required": [ + "active", + "agentId" + ] + } + } + } + }, + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/admin/users": { + "get": { + "operationId": "listUsers", + "description": "Every account on the server, oldest first. Admins only.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "users": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminUser" + } + } + }, + "required": [ + "users" + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/admin/users/{id}": { + "patch": { + "operationId": "setUserRole", + "description": "Makes the account an admin or a regular user. 409 when it would leave the server without an admin. Admins only.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "role": { + "type": "string", + "enum": [ + "admin", + "user" + ] + } + }, + "required": [ + "role" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdminUser" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "delete": { + "operationId": "removeUser", + "description": "Removes the account, its sessions, and all its data, bots included. 409 for the caller's own account. Admins only.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/admin/invites": { + "get": { + "operationId": "listInvites", + "description": "Invite links not yet used or revoked, newest first. Admins only.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "invites": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Invite" + } + } + }, + "required": [ + "invites" + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "post": { + "operationId": "createInvite", + "description": "Makes a one-time invite link. Only its hash is stored, so the link is shown once. Admins only.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreatedInvite" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/admin/invites/{id}": { + "delete": { + "operationId": "revokeInvite", + "description": "Revokes an invite link. Admins only.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/admin/workspaces/outdated": { + "get": { + "operationId": "listOutdatedWorkspaces", + "description": "Running workspaces whose machine has another image than the server's settings name. Each switches at its next idle stop, keeping its files; stopped workspaces switch when they next start. Admins only.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "workspaces": { + "type": "array", + "items": { + "type": "object", + "properties": { + "userId": { + "type": "string" + }, + "agentId": { + "type": "string" + } + }, + "required": [ + "userId", + "agentId" + ] + } + } + }, + "required": [ + "workspaces" + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/admin/settings": { + "get": { + "operationId": "getServerSettings", + "description": "The server's settings. Admins only.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServerSettings" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "patch": { + "operationId": "updateServerSettings", + "description": "Changes the given settings. New workspace size and image apply to workspaces as they boot. Admins only.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "signUpOpen": { + "type": "boolean" + }, + "workspaceCpus": { + "type": "integer", + "minimum": 1, + "maximum": 64 + }, + "workspaceMemoryMib": { + "type": "integer", + "minimum": 512, + "maximum": 262144 + }, + "codingImage": { + "type": [ + "string", + "null" + ], + "pattern": "^[a-z0-9][\\w.\\-/:@]{0,254}$", + "description": "Image new workspaces boot from, such as `ghcr.io/owner/image:tag`; null uses the server's `CRUMBLE_WORKSPACE_IMAGE`." + }, + "questionGraceMinutes": { + "type": "integer", + "minimum": 0, + "maximum": 1440, + "description": "How long a coding job waiting on the owner's answer keeps its workspace running." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServerSettings" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/message-gateways": { + "get": { + "operationId": "messageGateways", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "gateways": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "label": { + "type": "string" + }, + "secretKey": { + "type": "string" + }, + "tokenConfigured": { + "type": "boolean" + }, + "config": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "defaultBotId": { + "type": [ + "string", + "null" + ], + "format": "uuid" + }, + "ownerId": { + "type": [ + "string", + "null" + ], + "minLength": 1, + "maxLength": 200, + "pattern": "^[^\\s,]+$/u" + }, + "allowedChannelIds": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "maxItems": 1000 + }, + "allowDirectMessages": { + "type": "boolean" + }, + "aliases": { + "type": "array", + "items": { + "type": "object", + "properties": { + "handle": { + "type": "string", + "minLength": 1, + "maxLength": 100, + "pattern": "^[\\p{L}\\p{N}_-]+$/u" + }, + "botId": { + "type": "string", + "format": "uuid" + } + }, + "required": [ + "handle", + "botId" + ] + }, + "maxItems": 1000 + } + }, + "required": [ + "enabled", + "defaultBotId", + "ownerId", + "allowedChannelIds", + "allowDirectMessages", + "aliases" + ], + "additionalProperties": false + }, + "status": { + "type": "string", + "enum": [ + "disconnected", + "connecting", + "connected", + "error" + ] + }, + "error": { + "type": [ + "string", + "null" + ] + }, + "pendingCount": { + "type": "integer", + "minimum": 0 + }, + "failedCount": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "id", + "label", + "secretKey", + "tokenConfigured", + "config", + "status", + "error", + "pendingCount", + "failedCount" + ] + } + } + }, + "required": [ + "gateways" + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/message-gateways/{id}": { + "put": { + "operationId": "updateMessageGateway", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "defaultBotId": { + "type": [ + "string", + "null" + ], + "format": "uuid" + }, + "ownerId": { + "type": [ + "string", + "null" + ], + "minLength": 1, + "maxLength": 200, + "pattern": "^[^\\s,]+$/u" + }, + "allowedChannelIds": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "maxItems": 1000 + }, + "allowDirectMessages": { + "type": "boolean" + }, + "aliases": { + "type": "array", + "items": { + "type": "object", + "properties": { + "handle": { + "type": "string", + "minLength": 1, + "maxLength": 100, + "pattern": "^[\\p{L}\\p{N}_-]+$/u" + }, + "botId": { + "type": "string", + "format": "uuid" + } + }, + "required": [ + "handle", + "botId" + ] + }, + "maxItems": 1000 + } + }, + "required": [ + "enabled", + "defaultBotId", + "ownerId", + "allowedChannelIds", + "allowDirectMessages", + "aliases" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "label": { + "type": "string" + }, + "secretKey": { + "type": "string" + }, + "tokenConfigured": { + "type": "boolean" + }, + "config": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "defaultBotId": { + "type": [ + "string", + "null" + ], + "format": "uuid" + }, + "ownerId": { + "type": [ + "string", + "null" + ], + "minLength": 1, + "maxLength": 200, + "pattern": "^[^\\s,]+$/u" + }, + "allowedChannelIds": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "maxItems": 1000 + }, + "allowDirectMessages": { + "type": "boolean" + }, + "aliases": { + "type": "array", + "items": { + "type": "object", + "properties": { + "handle": { + "type": "string", + "minLength": 1, + "maxLength": 100, + "pattern": "^[\\p{L}\\p{N}_-]+$/u" + }, + "botId": { + "type": "string", + "format": "uuid" + } + }, + "required": [ + "handle", + "botId" + ] + }, + "maxItems": 1000 + } + }, + "required": [ + "enabled", + "defaultBotId", + "ownerId", + "allowedChannelIds", + "allowDirectMessages", + "aliases" + ], + "additionalProperties": false + }, + "status": { + "type": "string", + "enum": [ + "disconnected", + "connecting", + "connected", + "error" + ] + }, + "error": { + "type": [ + "string", + "null" + ] + }, + "pendingCount": { + "type": "integer", + "minimum": 0 + }, + "failedCount": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "id", + "label", + "secretKey", + "tokenConfigured", + "config", + "status", + "error", + "pendingCount", + "failedCount" + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/event-relay": { + "get": { + "operationId": "getEventRelay", + "description": "The account's event relay: its URL, whether the Doorstep account token is set (plugin setting `doorstep:token`), and the connection status.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "url": { + "type": [ + "string", + "null" + ] + }, + "tokenConfigured": { + "type": "boolean" + }, + "status": { + "type": "string", + "enum": [ + "disconnected", + "connecting", + "connected", + "error" + ] + }, + "error": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "url", + "tokenConfigured", + "status", + "error" + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "put": { + "operationId": "updateEventRelay", + "description": "Sets the event relay URL, or removes it with `null`, which disconnects the relay.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "url": { + "type": [ + "string", + "null" + ], + "maxLength": 2000, + "format": "uri" + } + }, + "required": [ + "url" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "url": { + "type": [ + "string", + "null" + ] + }, + "tokenConfigured": { + "type": "boolean" + }, + "status": { + "type": "string", + "enum": [ + "disconnected", + "connecting", + "connected", + "error" + ] + }, + "error": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "url", + "tokenConfigured", + "status", + "error" + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/github-apps": { + "get": { + "operationId": "listGithubApps", + "description": "The account's GitHub Apps, each the GitHub identity its bots act through in one GitHub account's repositories.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "apps": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GitHubApp" + } + } + }, + "required": [ + "apps" + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/github-apps/manifest": { + "post": { + "operationId": "createGithubAppManifest", + "description": "Starts creating a private GitHub App. The client posts `manifest` as a form field to `url`; GitHub then sends the owner to `{origin}/github-app/callback` with a code and state.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 34 + }, + "origin": { + "type": "string", + "maxLength": 2000, + "format": "uri" + }, + "organization": { + "type": "string", + "pattern": "^[A-Za-z0-9-]{1,39}$" + } + }, + "required": [ + "name", + "origin" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "url": { + "type": "string" + }, + "manifest": { + "type": "string" + } + }, + "required": [ + "url", + "manifest" + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/github-apps/complete": { + "post": { + "operationId": "completeGithubApp", + "description": "Exchanges the code GitHub redirected back with for the App's keys, within an hour of starting. 400 for a stale or reused state.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "code": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "state": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "code", + "state" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GitHubApp" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/github-apps/{id}/connect": { + "post": { + "operationId": "connectGithubApp", + "description": "Finds the App's installation on its account and gives its bots the GH_TOKEN credential. 409 until the owner installs the App.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GitHubApp" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/github-apps/{id}/bots": { + "put": { + "operationId": "setGithubAppBots", + "description": "Replaces the bots that act through the App. A bot uses at most one App per GitHub account; 409 when a bot already uses another App for this App's account.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "botIds": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "maxItems": 200 + } + }, + "required": [ + "botIds" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GitHubApp" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/github-apps/{id}": { + "delete": { + "operationId": "deleteGithubApp", + "description": "Forgets the App, signs the owner out of it, and takes GH_TOKEN from bots left without an installed App. The App stays on GitHub until the owner deletes it there.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/github-apps/{id}/sign-in": { + "post": { + "operationId": "signInGithubApp", + "description": "Starts signing the owner in to GitHub through the App, so its bots act as the owner. The client opens `url`; GitHub sends the owner to the App's callback URL, `{origin}/github-app/authorized`, or `{origin}/ui/github-app/authorized` for Apps created before the web UI moved to `/`, with a code and state. `origin` is no longer used. 409 without a client secret.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "origin": { + "type": "string", + "maxLength": 2000, + "format": "uri" + } + }, + "required": [ + "origin" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "url": { + "type": "string" + } + }, + "required": [ + "url" + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/github-apps/sign-in/complete": { + "post": { + "operationId": "completeGithubAppSignIn", + "description": "Exchanges the code GitHub sent the owner back with for the owner's tokens, within ten minutes of starting. 400 for a stale or reused state or a refused sign-in.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "code": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "state": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "code", + "state" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GitHubApp" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/github-apps/{id}/user": { + "delete": { + "operationId": "signOutGithubApp", + "description": "Revokes and forgets the owner's sign-in through the App; its bots act as the App again.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GitHubApp" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/github-apps/{id}/client-secret": { + "put": { + "operationId": "setGithubAppClientSecret", + "description": "Stores a client secret generated in the App's GitHub settings, for an App created before Crumble kept it.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "value": { + "type": "string", + "minLength": 1, + "maxLength": 16000 + }, + "reference": { + "type": "object", + "properties": { + "passwordManager": { + "type": "string", + "enum": [ + "1password", + "bitwarden" + ] + }, + "reference": { + "type": "string", + "minLength": 1, + "maxLength": 1000 + } + }, + "required": [ + "passwordManager", + "reference" + ] + } + }, + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GitHubApp" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/github-accounts": { + "get": { + "operationId": "listGithubAccounts", + "description": "The account's machine accounts: GitHub users made for bots. A bot acts as its machine account wherever none of its GitHub Apps does.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "accounts": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GitHubAccount" + } + } + }, + "required": [ + "accounts" + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "post": { + "operationId": "addGithubAccount", + "description": "Adds the GitHub user a personal access token signs in as. 400 when GitHub refuses the token; 409 when the user is already added.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "value": { + "type": "string", + "minLength": 1, + "maxLength": 16000 + }, + "reference": { + "type": "object", + "properties": { + "passwordManager": { + "type": "string", + "enum": [ + "1password", + "bitwarden" + ] + }, + "reference": { + "type": "string", + "minLength": 1, + "maxLength": 1000 + } + }, + "required": [ + "passwordManager", + "reference" + ] + } + }, + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GitHubAccount" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/github-accounts/{id}/token": { + "put": { + "operationId": "setGithubAccountToken", + "description": "Replaces the machine account's token. 400 when GitHub refuses it or it signs in as another user.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "value": { + "type": "string", + "minLength": 1, + "maxLength": 16000 + }, + "reference": { + "type": "object", + "properties": { + "passwordManager": { + "type": "string", + "enum": [ + "1password", + "bitwarden" + ] + }, + "reference": { + "type": "string", + "minLength": 1, + "maxLength": 1000 + } + }, + "required": [ + "passwordManager", + "reference" + ] + } + }, + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GitHubAccount" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/github-accounts/{id}/bots": { + "put": { + "operationId": "setGithubAccountBots", + "description": "Replaces the bots that act as the machine account, giving them GH_TOKEN. A bot acts as at most one; 409 when a bot already acts as another.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "botIds": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "maxItems": 200 + } + }, + "required": [ + "botIds" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GitHubAccount" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/github-accounts/{id}": { + "delete": { + "operationId": "deleteGithubAccount", + "description": "Forgets the machine account and its token, and takes GH_TOKEN from bots left without an installed App. The user stays on GitHub.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/event-sources": { + "get": { + "operationId": "listEventSources", + "description": "The account's event sources, each with the number of automations that use it.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "sources": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "createdAt": { + "type": "string" + }, + "usedBy": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "id", + "name", + "createdAt", + "usedBy" + ] + } + } + }, + "required": [ + "sources" + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "post": { + "operationId": "createEventSource", + "description": "Creates a source on the event relay. The response's `address` contains the source's secret and is returned only once. 400 when the relay URL or token is missing, or the relay can't be reached or rejects the token.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "name" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "201": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "createdAt": { + "type": "string" + }, + "usedBy": { + "type": "integer", + "minimum": 0 + }, + "address": { + "type": "string" + } + }, + "required": [ + "id", + "name", + "createdAt", + "usedBy", + "address" + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/event-sources/{id}": { + "delete": { + "operationId": "deleteEventSource", + "description": "Deletes the source on the event relay and in Crumble; its address stops working. 409 while an automation uses it.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/web-search": { + "get": { + "operationId": "getWebSearch", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "defaultProvider": { + "type": "string", + "enum": [ + "mixed", + "exa" + ] + }, + "exaKeyConfigured": { + "type": "boolean" + } + }, + "required": [ + "defaultProvider", + "exaKeyConfigured" + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "put": { + "operationId": "updateWebSearch", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "defaultProvider": { + "type": "string", + "enum": [ + "mixed", + "exa" + ] + } + }, + "required": [ + "defaultProvider" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "defaultProvider": { + "type": "string", + "enum": [ + "mixed", + "exa" + ] + }, + "exaKeyConfigured": { + "type": "boolean" + } + }, + "required": [ + "defaultProvider", + "exaKeyConfigured" + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/judge-model": { + "get": { + "operationId": "getJudgeModel", + "description": "The account's judge model for desktop jobs' intent checks, and the models the account's provider keys reach.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/JudgeModel" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "put": { + "operationId": "updateJudgeModel", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "judgeModel": { + "type": [ + "object", + "null" + ], + "properties": { + "provider": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-z0-9-]+$" + }, + "model": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "provider", + "model" + ] + } + }, + "required": [ + "judgeModel" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/JudgeModel" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/vision-model": { + "get": { + "operationId": "getVisionModel", + "description": "The account's vision model, which describes images for bots whose model can't read them, and the models that read images the account's provider keys reach.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VisionModel" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "put": { + "operationId": "updateVisionModel", + "description": "Choose the account's vision model, or turn it off with null. It must be one of the choices `getVisionModel` lists.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "visionModel": { + "type": [ + "object", + "null" + ], + "properties": { + "provider": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-z0-9-]+$" + }, + "model": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "provider", + "model" + ] + } + }, + "required": [ + "visionModel" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VisionModel" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents": { + "get": { + "operationId": "listAgents", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AgentPreview" + } + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "post": { + "operationId": "createAgent", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + "avatar": { + "type": "object", + "properties": { + "definition": { + "type": "object", + "properties": { + "version": { + "type": "number", + "enum": [ + 1 + ] + }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 40 + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 40 + }, + "body": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 6000 + } + }, + "required": [ + "path" + ], + "additionalProperties": false + }, + "eyes": { + "type": "object", + "properties": { + "x": { + "type": "number" + }, + "y": { + "type": "number" + }, + "spacing": { + "type": "number" + }, + "scale": { + "type": "number" + } + }, + "required": [ + "x", + "y", + "spacing", + "scale" + ], + "additionalProperties": false + } + }, + "required": [ + "version", + "id", + "name", + "body", + "eyes" + ], + "additionalProperties": false + }, + "color": { + "type": "string", + "pattern": "^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" + }, + "eyeColor": { + "type": "string", + "pattern": "^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" + } + }, + "required": [ + "definition", + "color", + "eyeColor" + ] + }, + "description": { + "type": "string", + "maxLength": 1000, + "default": "" + }, + "instructions": { + "type": "string", + "maxLength": 32000, + "default": "You are a thoughtful, capable personal assistant." + }, + "provider": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-z0-9-]+$", + "default": "openai" + }, + "model": { + "type": "string", + "minLength": 1, + "maxLength": 200, + "default": "gpt-4.1" + }, + "webSearchProvider": { + "type": [ + "string", + "null" + ], + "enum": [ + "mixed", + "exa", + null + ] + }, + "enabled": { + "type": "boolean", + "default": true + }, + "tools": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "maxItems": 100, + "default": [ + "memory" + ] + }, + "skills": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "instructions": { + "type": "string", + "maxLength": 32000 + } + }, + "required": [ + "name", + "instructions" + ] + }, + "maxItems": 100, + "default": [] + }, + "sharedSkills": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 100 + }, + "sharedMemory": { + "type": "boolean" + }, + "mcpServers": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 30, + "default": [] + }, + "delegates": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 30, + "default": [] + }, + "inference": { + "type": "object", + "properties": { + "thinkingLevel": { + "type": "string", + "enum": [ + "off", + "minimal", + "low", + "medium", + "high", + "xhigh", + "max" + ], + "default": "off" + }, + "temperature": { + "type": "number", + "minimum": 0, + "maximum": 2 + }, + "maxOutputTokens": { + "type": "integer", + "minimum": 1, + "maximum": 1000000 + } + } + }, + "review": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "default": true + }, + "skillThreshold": { + "type": "integer", + "minimum": 1, + "maximum": 1000, + "default": 10 + }, + "memoryThreshold": { + "type": "integer", + "minimum": 1, + "maximum": 1000, + "default": 10 + }, + "maxInputTokens": { + "type": "integer", + "minimum": 1000, + "maximum": 2000000 + } + } + }, + "reviewModel": { + "type": [ + "object", + "null" + ], + "properties": { + "provider": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-z0-9-]+$" + }, + "model": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "provider", + "model" + ] + }, + "desktopModel": { + "type": [ + "object", + "null" + ], + "properties": { + "provider": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-z0-9-]+$" + }, + "model": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "provider", + "model" + ] + } + }, + "required": [ + "name" + ] + } + } + } + }, + "responses": { + "201": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Agent" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}": { + "get": { + "operationId": "getAgent", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Agent" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "patch": { + "operationId": "updateAgent", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + "avatar": { + "type": "object", + "properties": { + "definition": { + "type": "object", + "properties": { + "version": { + "type": "number", + "enum": [ + 1 + ] + }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 40 + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 40 + }, + "body": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 6000 + } + }, + "required": [ + "path" + ], + "additionalProperties": false + }, + "eyes": { + "type": "object", + "properties": { + "x": { + "type": "number" + }, + "y": { + "type": "number" + }, + "spacing": { + "type": "number" + }, + "scale": { + "type": "number" + } + }, + "required": [ + "x", + "y", + "spacing", + "scale" + ], + "additionalProperties": false + } + }, + "required": [ + "version", + "id", + "name", + "body", + "eyes" + ], + "additionalProperties": false + }, + "color": { + "type": "string", + "pattern": "^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" + }, + "eyeColor": { + "type": "string", + "pattern": "^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" + } + }, + "required": [ + "definition", + "color", + "eyeColor" + ] + }, + "description": { + "type": "string", + "maxLength": 1000 + }, + "instructions": { + "type": "string", + "maxLength": 32000 + }, + "provider": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-z0-9-]+$" + }, + "model": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "webSearchProvider": { + "type": [ + "string", + "null" + ], + "enum": [ + "mixed", + "exa", + null + ] + }, + "enabled": { + "type": "boolean" + }, + "tools": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "maxItems": 100 + }, + "skills": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "instructions": { + "type": "string", + "maxLength": 32000 + } + }, + "required": [ + "name", + "instructions" + ] + }, + "maxItems": 100 + }, + "sharedSkills": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 100 + }, + "sharedMemory": { + "type": "boolean" + }, + "mcpServers": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 30 + }, + "delegates": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 30 + }, + "inference": { + "type": "object", + "properties": { + "thinkingLevel": { + "type": "string", + "enum": [ + "off", + "minimal", + "low", + "medium", + "high", + "xhigh", + "max" + ], + "default": "off" + }, + "temperature": { + "type": "number", + "minimum": 0, + "maximum": 2 + }, + "maxOutputTokens": { + "type": "integer", + "minimum": 1, + "maximum": 1000000 + } + } + }, + "review": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "default": true + }, + "skillThreshold": { + "type": "integer", + "minimum": 1, + "maximum": 1000, + "default": 10 + }, + "memoryThreshold": { + "type": "integer", + "minimum": 1, + "maximum": 1000, + "default": 10 + }, + "maxInputTokens": { + "type": "integer", + "minimum": 1000, + "maximum": 2000000 + } + } + }, + "reviewModel": { + "type": [ + "object", + "null" + ], + "properties": { + "provider": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-z0-9-]+$" + }, + "model": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "provider", + "model" + ] + }, + "desktopModel": { + "type": [ + "object", + "null" + ], + "properties": { + "provider": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-z0-9-]+$" + }, + "model": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "provider", + "model" + ] + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/Agent" + }, + { + "type": "null" + } + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "delete": { + "operationId": "deleteAgent", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/duplicate": { + "post": { + "operationId": "duplicateAgent", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "201": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/Agent" + }, + { + "type": "null" + } + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/chat": { + "get": { + "operationId": "getChat", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200 + }, + "required": false, + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChatSnapshot" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/chat/history": { + "get": { + "operationId": "getChatHistory", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200 + }, + "required": false, + "name": "limit", + "in": "query" + }, + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "required": false, + "name": "before", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TranscriptPage" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/coding-jobs": { + "get": { + "operationId": "listCodingJobs", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CodingJobs" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/coding-jobs/{name}/answer": { + "post": { + "operationId": "answerCodingJob", + "description": "Answers the coding job's open question, which resumes the job. 409 when the job no longer waits on that question.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "name", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "questionId": { + "type": "string", + "minLength": 1 + }, + "text": { + "type": "string", + "minLength": 1, + "maxLength": 32000 + } + }, + "required": [ + "questionId", + "text" + ] + } + } + } + }, + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/coding-jobs/{name}/history": { + "get": { + "operationId": "getCodingJobHistory", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "name", + "in": "path" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200 + }, + "required": false, + "name": "limit", + "in": "query" + }, + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "required": false, + "name": "before", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TranscriptPage" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/desktop-jobs": { + "get": { + "operationId": "listDesktopJobs", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DesktopJobs" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/desktop/control": { + "get": { + "operationId": "getDesktopControl", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DesktopControl" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "put": { + "operationId": "putDesktopControl", + "description": "Take control of the bot desktop (holder owner) or hand it back (holder bot). 409 when the bot has no bot desktop.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "holder": { + "type": "string", + "enum": [ + "bot", + "owner" + ] + } + }, + "required": [ + "holder" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DesktopControl" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/desktop/events": { + "get": { + "operationId": "streamDesktopEvents", + "x-sse-events": { + "control": { + "$ref": "#/components/schemas/DesktopControl" + }, + "heartbeat": { + "$ref": "#/components/schemas/HeartbeatEvent" + } + }, + "description": "Server-sent events. A control event carries the DesktopControl JSON object in data, once on connect and on every change. Heartbeat events carry {} every 15 seconds. Authenticate with the Authorization header.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "SSE stream, not a JSON array", + "content": { + "text/event-stream": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/desktop/status": { + "get": { + "operationId": "getDesktopStatus", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DesktopStatus" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/desktop/viewer": { + "post": { + "operationId": "createDesktopViewer", + "description": "Issue a single-use viewer link for the bot desktop. The page and its WebSocket live outside /v1 and need no Authorization header: the link is the credential. With passive=true the link is watch-only: it neither boots the bot's machine nor keeps it awake, and its connection ends when the machine stops. 409 when the bot has no bot desktop.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "passive", + "in": "query" + } + ], + "responses": { + "201": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DesktopViewer" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/desktop-jobs/{name}/history": { + "get": { + "operationId": "getDesktopJobHistory", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "name", + "in": "path" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200 + }, + "required": false, + "name": "limit", + "in": "query" + }, + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "required": false, + "name": "before", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TranscriptPage" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/messages": { + "post": { + "operationId": "sendMessage", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "content": { + "type": "string", + "maxLength": 32000 + }, + "requestId": { + "type": "string", + "format": "uuid" + }, + "replyTo": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "attachments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "mimeType": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "data": { + "type": "string", + "minLength": 1, + "pattern": "^[A-Za-z0-9+/]*={0,2}$" + } + }, + "required": [ + "name", + "mimeType", + "data" + ] + }, + "maxItems": 8, + "default": [] + }, + "timezone": { + "type": "string", + "minLength": 1, + "maxLength": 100 + } + }, + "required": [ + "content", + "requestId" + ] + } + } + } + }, + "responses": { + "202": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Execution" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/attachments/{entryId}/{index}": { + "get": { + "operationId": "getAttachment", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string", + "description": "An owner message's entry, or a successful `desktop_screenshot` tool result's entry." + }, + "required": true, + "description": "An owner message's entry, or a successful `desktop_screenshot` tool result's entry.", + "name": "entryId", + "in": "path" + }, + { + "schema": { + "type": [ + "integer", + "null" + ], + "minimum": 0, + "maximum": 7, + "description": "The attachment's index in the message's `attachments`, or the image's index in the tool result (0 for a desktop screenshot)." + }, + "required": true, + "description": "The attachment's index in the message's `attachments`, or the image's index in the tool result (0 for a desktop screenshot).", + "name": "index", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Attachment or screenshot bytes; Content-Type identifies the image format", + "headers": { + "Cache-Control": { + "schema": { + "type": "string" + }, + "description": "private, max-age=31536000, immutable" + } + }, + "content": { + "image/*": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/abort": { + "post": { + "operationId": "abortChat", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/compact": { + "post": { + "operationId": "compactChat", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "202": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Compaction" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/events": { + "get": { + "operationId": "streamChatEvents", + "x-sse-events": { + "snapshot": { + "$ref": "#/components/schemas/ChatSnapshot" + }, + "heartbeat": { + "$ref": "#/components/schemas/HeartbeatEvent" + } + }, + "description": "Server-sent events. Each snapshot event carries a ChatSnapshot JSON object in data. Heartbeat events carry {} every 15 seconds. Authenticate with the Authorization header. Reconnect by fetching the current snapshot; there is no Last-Event-ID replay.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200 + }, + "required": false, + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "SSE stream, not a JSON array", + "content": { + "text/event-stream": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/events": { + "get": { + "operationId": "streamActivityEvents", + "x-sse-events": { + "activity": { + "$ref": "#/components/schemas/ActivityEvent" + }, + "learned": { + "$ref": "#/components/schemas/LearnedEvent" + }, + "heartbeat": { + "$ref": "#/components/schemas/HeartbeatEvent" + } + }, + "description": "Server-sent events. Each activity event carries a ReplyEvent or ChatPreviewEvent JSON object in data. Each learned event carries a LearnedEvent: what a bot's review of one turn changed; GET /v1/agents/{id}/reviews lists them durably. Current chat previews replay on connection; finished replies and learned events are not replayed. Heartbeat events carry {} every 15 seconds. Authenticate with the Authorization header. No Last-Event-ID replay.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "SSE stream, not a JSON array", + "content": { + "text/event-stream": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/group-chats": { + "get": { + "operationId": "listGroupChats", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GroupChat" + } + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "post": { + "operationId": "createGroupChat", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + "memberIds": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "minItems": 2, + "maxItems": 6 + } + }, + "required": [ + "name", + "memberIds" + ] + } + } + } + }, + "responses": { + "201": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GroupChat" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/group-chats/{id}": { + "get": { + "operationId": "getGroupChat", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GroupChat" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "patch": { + "operationId": "updateGroupChat", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + "memberIds": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "minItems": 2, + "maxItems": 6 + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GroupChat" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "delete": { + "operationId": "deleteGroupChat", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/group-chats/{id}/chat": { + "get": { + "operationId": "getGroupChatSnapshot", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200 + }, + "required": false, + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GroupChatSnapshot" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/group-chats/{id}/history": { + "get": { + "operationId": "getGroupChatHistory", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200 + }, + "required": false, + "name": "limit", + "in": "query" + }, + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "required": false, + "name": "before", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TranscriptPage" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/group-chats/{id}/messages": { + "post": { + "operationId": "sendGroupMessage", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "content": { + "type": "string", + "maxLength": 32000 + }, + "requestId": { + "type": "string", + "format": "uuid" + }, + "replyTo": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "attachments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "mimeType": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "data": { + "type": "string", + "minLength": 1, + "pattern": "^[A-Za-z0-9+/]*={0,2}$" + } + }, + "required": [ + "name", + "mimeType", + "data" + ] + }, + "maxItems": 8, + "default": [] + } + }, + "required": [ + "content", + "requestId" + ] + } + } + } + }, + "responses": { + "201": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GroupMessageReceipt" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/group-chats/{id}/attachments/{entryId}/{index}": { + "get": { + "operationId": "getGroupAttachment", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "entryId", + "in": "path" + }, + { + "schema": { + "type": [ + "integer", + "null" + ], + "minimum": 0, + "maximum": 7 + }, + "required": true, + "name": "index", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Attachment bytes; Content-Type identifies the image or text format", + "headers": { + "Cache-Control": { + "schema": { + "type": "string" + }, + "description": "private, max-age=31536000, immutable" + } + }, + "content": { + "*/*": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/group-chats/{id}/stop": { + "post": { + "operationId": "stopGroupChat", + "description": "Ends every running bot turn in the group and drops the queued ones. The group is not paused; the next message starts turns again.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/group-chats/{id}/events": { + "get": { + "operationId": "streamGroupChatEvents", + "x-sse-events": { + "snapshot": { + "$ref": "#/components/schemas/GroupChatSnapshot" + }, + "heartbeat": { + "$ref": "#/components/schemas/HeartbeatEvent" + } + }, + "description": "Server-sent events. Each snapshot event carries a GroupChatSnapshot JSON object in data, sent on connection and after every change. Heartbeat events carry {} every 15 seconds. Authenticate with the Authorization header. Reconnect by fetching the current snapshot; there is no Last-Event-ID replay.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200 + }, + "required": false, + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "SSE stream, not a JSON array", + "content": { + "text/event-stream": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/credentials": { + "get": { + "operationId": "listAgentCredentials", + "description": "The bot's credentials and its requests for credentials the owner has not answered. Values are never returned.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Credentials" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/bot-requests": { + "get": { + "operationId": "listBotRequests", + "description": "Lists bot requests, newest first, including their current approval status.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/BotRequest" + } + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/bot-requests/{requestId}/approve": { + "post": { + "operationId": "approveBotRequest", + "description": "Approves a pending bot request, optionally saving an edited proposal and creating the new bot.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "requestId", + "in": "path" + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "proposal": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + "avatar": { + "type": "object", + "properties": { + "definition": { + "type": "object", + "properties": { + "version": { + "type": "number", + "enum": [ + 1 + ] + }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 40 + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 40 + }, + "body": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 6000 + } + }, + "required": [ + "path" + ], + "additionalProperties": false + }, + "eyes": { + "type": "object", + "properties": { + "x": { + "type": "number" + }, + "y": { + "type": "number" + }, + "spacing": { + "type": "number" + }, + "scale": { + "type": "number" + } + }, + "required": [ + "x", + "y", + "spacing", + "scale" + ], + "additionalProperties": false + } + }, + "required": [ + "version", + "id", + "name", + "body", + "eyes" + ], + "additionalProperties": false + }, + "color": { + "type": "string", + "pattern": "^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" + }, + "eyeColor": { + "type": "string", + "pattern": "^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" + } + }, + "required": [ + "definition", + "color", + "eyeColor" + ] + }, + "description": { + "type": "string", + "maxLength": 1000, + "default": "" + }, + "instructions": { + "type": "string", + "maxLength": 32000, + "default": "You are a thoughtful, capable personal assistant." + }, + "provider": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-z0-9-]+$", + "default": "openai" + }, + "model": { + "type": "string", + "minLength": 1, + "maxLength": 200, + "default": "gpt-4.1" + }, + "webSearchProvider": { + "type": [ + "string", + "null" + ], + "enum": [ + "mixed", + "exa", + null + ] + }, + "enabled": { + "type": "boolean", + "default": true + }, + "tools": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "maxItems": 100, + "default": [ + "memory" + ] + }, + "skills": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "instructions": { + "type": "string", + "maxLength": 32000 + } + }, + "required": [ + "name", + "instructions" + ] + }, + "maxItems": 100, + "default": [] + }, + "sharedSkills": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 100 + }, + "sharedMemory": { + "type": "boolean" + }, + "mcpServers": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 30, + "default": [] + }, + "delegates": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 30, + "default": [] + }, + "inference": { + "type": "object", + "properties": { + "thinkingLevel": { + "type": "string", + "enum": [ + "off", + "minimal", + "low", + "medium", + "high", + "xhigh", + "max" + ], + "default": "off" + }, + "temperature": { + "type": "number", + "minimum": 0, + "maximum": 2 + }, + "maxOutputTokens": { + "type": "integer", + "minimum": 1, + "maximum": 1000000 + } + } + }, + "review": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "default": true + }, + "skillThreshold": { + "type": "integer", + "minimum": 1, + "maximum": 1000, + "default": 10 + }, + "memoryThreshold": { + "type": "integer", + "minimum": 1, + "maximum": 1000, + "default": 10 + }, + "maxInputTokens": { + "type": "integer", + "minimum": 1000, + "maximum": 2000000 + } + } + }, + "reviewModel": { + "type": [ + "object", + "null" + ], + "properties": { + "provider": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-z0-9-]+$" + }, + "model": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "provider", + "model" + ] + }, + "desktopModel": { + "type": [ + "object", + "null" + ], + "properties": { + "provider": { + "type": "string", + "minLength": 1, + "maxLength": 80, + "pattern": "^[a-z0-9-]+$" + }, + "model": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "required": [ + "provider", + "model" + ] + } + }, + "required": [ + "name" + ] + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "request": { + "$ref": "#/components/schemas/BotRequest" + }, + "agent": { + "$ref": "#/components/schemas/Agent" + } + }, + "required": [ + "request", + "agent" + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/bot-requests/{requestId}/decline": { + "post": { + "operationId": "declineBotRequest", + "description": "Declines a pending bot request.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "requestId", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BotRequest" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/credentials/{name}": { + "put": { + "operationId": "saveAgentCredential", + "description": "Creates or updates a credential. Saving one the bot requested answers the request and starts a bot turn with a notice. A new value applies from the next request; the placeholder stays the same.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "name", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "hosts": { + "type": "array", + "items": { + "type": "string", + "maxLength": 253 + }, + "minItems": 1, + "maxItems": 20 + }, + "secret": { + "type": "object", + "properties": { + "value": { + "type": "string", + "minLength": 1, + "maxLength": 16000 + }, + "reference": { + "type": "object", + "properties": { + "passwordManager": { + "type": "string", + "enum": [ + "1password", + "bitwarden" + ] + }, + "reference": { + "type": "string", + "minLength": 1, + "maxLength": 1000 + } + }, + "required": [ + "passwordManager", + "reference" + ] + } + }, + "additionalProperties": false + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Credential" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "delete": { + "operationId": "deleteAgentCredential", + "description": "Deletes a credential and its use records, or declines a request for one, which starts a bot turn with a notice.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "name", + "in": "path" + } + ], + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/credentials/{name}/decline": { + "post": { + "operationId": "declineAgentCredential", + "description": "Declines a pending credential request without changing a saved credential.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "name", + "in": "path" + } + ], + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/credentials/{name}/uses": { + "get": { + "operationId": "listAgentCredentialUses", + "description": "Requests sent with the credential's value in the last 90 days, newest first. Page with `before` set to the last use's ID.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "name", + "in": "path" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200, + "default": 50 + }, + "required": false, + "name": "limit", + "in": "query" + }, + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "required": false, + "name": "before", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CredentialUse" + } + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/logins": { + "get": { + "operationId": "listAgentLogins", + "description": "The logins the bot's desktop jobs can fill into web pages, and its requests for logins the owner has not answered. Values are never returned.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Logins" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/logins/{name}": { + "put": { + "operationId": "saveAgentLogin", + "description": "Creates or updates a login. Saving one the bot requested answers the request and starts a bot turn with a notice. Each field is a value stored in Crumble or a password manager reference; a 1Password `item` fills every field. Every reference is read once to check it, and nothing is saved if one fails.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "name", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "hosts": { + "type": "array", + "items": { + "type": "string", + "maxLength": 253 + }, + "minItems": 1, + "maxItems": 20 + }, + "item": { + "type": "object", + "properties": { + "passwordManager": { + "type": "string", + "enum": [ + "1password" + ] + }, + "reference": { + "type": "string", + "pattern": "^op:\\/\\/[^/]+\\/[^/]+$" + } + }, + "required": [ + "passwordManager", + "reference" + ] + }, + "fields": { + "type": "object", + "properties": { + "username": { + "type": "object", + "properties": { + "value": { + "type": "string", + "minLength": 1, + "maxLength": 16000 + }, + "reference": { + "type": "object", + "properties": { + "passwordManager": { + "type": "string", + "enum": [ + "1password", + "bitwarden" + ] + }, + "reference": { + "type": "string", + "minLength": 1, + "maxLength": 1000 + } + }, + "required": [ + "passwordManager", + "reference" + ] + } + }, + "additionalProperties": false + }, + "password": { + "type": "object", + "properties": { + "value": { + "type": "string", + "minLength": 1, + "maxLength": 16000 + }, + "reference": { + "type": "object", + "properties": { + "passwordManager": { + "type": "string", + "enum": [ + "1password", + "bitwarden" + ] + }, + "reference": { + "type": "string", + "minLength": 1, + "maxLength": 1000 + } + }, + "required": [ + "passwordManager", + "reference" + ] + } + }, + "additionalProperties": false + }, + "one_time_code": { + "type": [ + "object", + "null" + ], + "properties": { + "value": { + "type": "string", + "minLength": 1, + "maxLength": 16000 + }, + "reference": { + "type": "object", + "properties": { + "passwordManager": { + "type": "string", + "enum": [ + "1password", + "bitwarden" + ] + }, + "reference": { + "type": "string", + "minLength": 1, + "maxLength": 1000 + } + }, + "required": [ + "passwordManager", + "reference" + ] + } + }, + "additionalProperties": false + } + } + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Login" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "delete": { + "operationId": "deleteAgentLogin", + "description": "Deletes a login and its fill records, or declines a request for one, which starts a bot turn with a notice.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "name", + "in": "path" + } + ], + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/logins/{name}/decline": { + "post": { + "operationId": "declineAgentLogin", + "description": "Declines a pending login request without changing a saved login.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "name", + "in": "path" + } + ], + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/logins/{name}/uses": { + "get": { + "operationId": "listAgentLoginUses", + "description": "Fills of the login's fields in the last 90 days, newest first. Page with `before` set to the last use's ID.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "name", + "in": "path" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200, + "default": 50 + }, + "required": false, + "name": "limit", + "in": "query" + }, + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "required": false, + "name": "before", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LoginUse" + } + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/held-actions": { + "get": { + "operationId": "listAgentHeldActions", + "description": "Desktop job actions an intent check held for the owner, newest first, pending and decided.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/HeldAction" + } + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/held-actions/{actionId}/approve": { + "post": { + "operationId": "approveAgentHeldAction", + "description": "Runs the held action; the job continues where it stopped. Fails with 409 once the action was decided.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "actionId", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeldAction" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/held-actions/{actionId}/decline": { + "post": { + "operationId": "declineAgentHeldAction", + "description": "Refuses the held action with an optional reason; the job reports back. Fails with 409 once the action was decided.", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "actionId", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "maxLength": 2000 + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeldAction" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/agents/{id}/memories": { + "get": { + "operationId": "listAgentMemories", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Memory" + } + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "post": { + "operationId": "createAgentMemory", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "content": { + "type": "string", + "minLength": 1, + "maxLength": 32000 + } + }, + "required": [ + "content" + ] + } + } + } + }, + "responses": { + "201": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Memory" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } } - }, - "required": [ - "authorizationUrl" - ] + } }, - { - "type": "object", - "properties": { - "authorized": { - "type": "boolean", - "enum": [ - true - ] + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } } - }, - "required": [ - "authorized" - ] - } - ] - } - }, - "parameters": {} - }, - "paths": { - "/health": { - "get": { - "operationId": "getHealth", - "security": [], - "responses": { - "200": { - "description": "Success", + } + }, + "500": { + "description": "Internal server error", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Health" + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" } } } @@ -1233,24 +17630,186 @@ } } }, - "/v1/capabilities": { - "get": { - "operationId": "getCapabilities", + "/v1/agents/{id}/memories/{memoryId}": { + "patch": { + "operationId": "updateAgentMemory", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "memoryId", + "in": "path" } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "content": { + "type": "string", + "minLength": 1, + "maxLength": 32000 + } + }, + "required": [ + "content" + ] + } + } + } + }, "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Capabilities" + "anyOf": [ + { + "$ref": "#/components/schemas/Memory" + }, + { + "type": "null" + } + ] + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" } } } + } + } + }, + "delete": { + "operationId": "deleteAgentMemory", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "memoryId", + "in": "path" + } + ], + "responses": { + "204": { + "description": "Success, no response body" }, "400": { "description": "Invalid request or operation", @@ -1263,7 +17822,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -1335,12 +17894,15 @@ } } }, - "/v1/push": { + "/v1/memories": { "get": { - "operationId": "getPushStatus", + "operationId": "listSharedMemories", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "responses": { @@ -1349,7 +17911,10 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PushStatus" + "type": "array", + "items": { + "$ref": "#/components/schemas/Memory" + } } } } @@ -1365,7 +17930,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -1435,25 +18000,15 @@ } } } - } - }, - "/v1/push/devices/{installationId}": { - "put": { - "operationId": "putPushDevice", + }, + "post": { + "operationId": "createSharedMemory", "security": [ { - "BearerAuth": [] - } - ], - "parameters": [ - { - "schema": { - "type": "string", - "format": "uuid" - }, - "required": true, - "name": "installationId", - "in": "path" + "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "requestBody": { @@ -1463,60 +18018,26 @@ "schema": { "type": "object", "properties": { - "platform": { - "type": "string", - "enum": [ - "macos", - "ios", - "android" - ] - }, - "transport": { - "type": "string", - "enum": [ - "apns", - "fcm" - ] - }, - "token": { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - "environment": { - "type": "string", - "enum": [ - "development", - "production" - ] - }, - "bundleId": { + "content": { "type": "string", "minLength": 1, - "maxLength": 255 - }, - "enabled": { - "type": "boolean" + "maxLength": 32000 } }, "required": [ - "platform", - "transport", - "token", - "environment", - "enabled" + "content" ] } } } }, "responses": { - "200": { + "201": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PushDeviceRegistration" + "$ref": "#/components/schemas/Memory" } } } @@ -1532,7 +18053,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -1602,28 +18123,66 @@ } } } - }, - "delete": { - "operationId": "deletePushDevice", + } + }, + "/v1/memories/{id}": { + "patch": { + "operationId": "updateSharedMemory", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ { "schema": { - "type": "string", - "format": "uuid" + "type": "string" }, "required": true, - "name": "installationId", + "name": "id", "in": "path" } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "content": { + "type": "string", + "minLength": 1, + "maxLength": 32000 + } + }, + "required": [ + "content" + ] + } + } + } + }, "responses": { - "204": { - "description": "Success, no response body" + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/Memory" + }, + { + "type": "null" + } + ] + } + } + } }, "400": { "description": "Invalid request or operation", @@ -1636,7 +18195,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -1706,53 +18265,27 @@ } } } - } - }, - "/v1/push/devices/{installationId}/presence": { - "put": { - "operationId": "putPushPresence", + }, + "delete": { + "operationId": "deleteSharedMemory", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ { "schema": { - "type": "string", - "format": "uuid" + "type": "string" }, "required": true, - "name": "installationId", + "name": "id", "in": "path" } ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "active": { - "type": "boolean" - }, - "agentId": { - "type": [ - "string", - "null" - ], - "format": "uuid" - } - }, - "required": [ - "active", - "agentId" - ] - } - } - } - }, "responses": { "204": { "description": "Success, no response body" @@ -1768,7 +18301,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -1840,12 +18373,26 @@ } } }, - "/v1/agents": { + "/v1/agents/{id}/skills": { "get": { - "operationId": "listAgents", + "operationId": "listAgentSkills", + "description": "The bot's own skill packages, including stale and archived ones. The agent's inline `skills` field lists the same skills by name and instructions.", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" } ], "responses": { @@ -1856,7 +18403,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/components/schemas/AgentPreview" + "$ref": "#/components/schemas/SkillPackage" } } } @@ -1873,7 +18420,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -1945,10 +18492,23 @@ } }, "post": { - "operationId": "createAgent", + "operationId": "createAgentSkill", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" } ], "requestBody": { @@ -1961,135 +18521,44 @@ "name": { "type": "string", "minLength": 1, - "maxLength": 80 - }, - "avatar": { - "type": "string", - "maxLength": 100, - "default": "bot" - }, - "description": { - "type": "string", - "maxLength": 1000, - "default": "" - }, - "instructions": { - "type": "string", - "maxLength": 32000, - "default": "You are a thoughtful, capable personal assistant." - }, - "provider": { - "type": "string", - "minLength": 1, - "maxLength": 80, - "pattern": "^[a-z0-9-]+$", - "default": "openai" - }, - "model": { - "type": "string", - "minLength": 1, - "maxLength": 200, - "default": "gpt-4.1" - }, - "enabled": { - "type": "boolean", - "default": true - }, - "tools": { - "type": "array", - "items": { - "type": "string", - "minLength": 1, - "maxLength": 200 - }, - "maxItems": 100, - "default": [ - "memory" - ] - }, - "skills": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1, - "maxLength": 100 - }, - "instructions": { - "type": "string", - "maxLength": 32000 - } - }, - "required": [ - "name", - "instructions" - ] - }, - "maxItems": 30, - "default": [] - }, - "sharedSkills": { - "type": "array", - "items": { - "type": "string", - "format": "uuid" - }, - "maxItems": 100 - }, - "sharedMemory": { - "type": "boolean" + "maxLength": 100 }, - "mcpServers": { - "type": "array", - "items": { - "type": "string", - "format": "uuid" - }, - "maxItems": 30, - "default": [] + "description": { + "type": "string", + "maxLength": 300, + "default": "" }, - "delegates": { + "instructions": { + "type": "string", + "maxLength": 32000 + }, + "documents": { "type": "array", "items": { - "type": "string", - "format": "uuid" + "type": "object", + "properties": { + "path": { + "type": "string", + "pattern": "^references\\/[a-z0-9][a-z0-9._-]{0,99}\\.md$" + }, + "content": { + "type": "string", + "minLength": 1, + "maxLength": 64000 + } + }, + "required": [ + "path", + "content" + ] }, - "maxItems": 30, + "maxItems": 20, "default": [] - }, - "inference": { - "type": "object", - "properties": { - "thinkingLevel": { - "type": "string", - "enum": [ - "off", - "minimal", - "low", - "medium", - "high", - "xhigh", - "max" - ], - "default": "off" - }, - "temperature": { - "type": "number", - "minimum": 0, - "maximum": 2 - }, - "maxOutputTokens": { - "type": "integer", - "minimum": 1, - "maximum": 1000000 - } - } } }, "required": [ - "name" + "name", + "instructions" ] } } @@ -2101,7 +18570,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Agent" + "$ref": "#/components/schemas/SkillPackage" } } } @@ -2117,7 +18586,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -2189,12 +18658,16 @@ } } }, - "/v1/agents/{id}": { - "get": { - "operationId": "getAgent", + "/v1/agents/{id}/skills/{skillId}": { + "patch": { + "operationId": "updateAgentSkill", + "description": "Changes a skill's content, restores an archived skill by setting state to active, or pins it so the curator never marks it stale or archives it.", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -2205,15 +18678,88 @@ "required": true, "name": "id", "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "skillId", + "in": "path" } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "description": { + "type": "string", + "maxLength": 300 + }, + "instructions": { + "type": "string", + "maxLength": 32000 + }, + "documents": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "pattern": "^references\\/[a-z0-9][a-z0-9._-]{0,99}\\.md$" + }, + "content": { + "type": "string", + "minLength": 1, + "maxLength": 64000 + } + }, + "required": [ + "path", + "content" + ] + }, + "maxItems": 20 + }, + "state": { + "type": "string", + "enum": [ + "active", + "stale", + "archived" + ] + }, + "pinned": { + "type": "boolean" + } + } + } + } + } + }, "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Agent" + "anyOf": [ + { + "$ref": "#/components/schemas/SkillPackage" + }, + { + "type": "null" + } + ] } } } @@ -2229,7 +18775,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -2300,11 +18846,14 @@ } } }, - "patch": { - "operationId": "updateAgent", + "delete": { + "operationId": "deleteAgentSkill", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -2315,154 +18864,19 @@ "required": true, "name": "id", "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "skillId", + "in": "path" } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1, - "maxLength": 80 - }, - "avatar": { - "type": "string", - "maxLength": 100 - }, - "description": { - "type": "string", - "maxLength": 1000 - }, - "instructions": { - "type": "string", - "maxLength": 32000 - }, - "provider": { - "type": "string", - "minLength": 1, - "maxLength": 80, - "pattern": "^[a-z0-9-]+$" - }, - "model": { - "type": "string", - "minLength": 1, - "maxLength": 200 - }, - "enabled": { - "type": "boolean" - }, - "tools": { - "type": "array", - "items": { - "type": "string", - "minLength": 1, - "maxLength": 200 - }, - "maxItems": 100 - }, - "skills": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1, - "maxLength": 100 - }, - "instructions": { - "type": "string", - "maxLength": 32000 - } - }, - "required": [ - "name", - "instructions" - ] - }, - "maxItems": 30 - }, - "sharedSkills": { - "type": "array", - "items": { - "type": "string", - "format": "uuid" - }, - "maxItems": 100 - }, - "sharedMemory": { - "type": "boolean" - }, - "mcpServers": { - "type": "array", - "items": { - "type": "string", - "format": "uuid" - }, - "maxItems": 30 - }, - "delegates": { - "type": "array", - "items": { - "type": "string", - "format": "uuid" - }, - "maxItems": 30 - }, - "inference": { - "type": "object", - "properties": { - "thinkingLevel": { - "type": "string", - "enum": [ - "off", - "minimal", - "low", - "medium", - "high", - "xhigh", - "max" - ], - "default": "off" - }, - "temperature": { - "type": "number", - "minimum": 0, - "maximum": 2 - }, - "maxOutputTokens": { - "type": "integer", - "minimum": 1, - "maximum": 1000000 - } - } - } - } - } - } - } - }, + ], "responses": { - "200": { - "description": "Success", - "content": { - "application/json": { - "schema": { - "anyOf": [ - { - "$ref": "#/components/schemas/Agent" - }, - { - "type": "null" - } - ] - } - } - } + "204": { + "description": "Success, no response body" }, "400": { "description": "Invalid request or operation", @@ -2475,7 +18889,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -2545,12 +18959,18 @@ } } } - }, - "delete": { - "operationId": "deleteAgent", + } + }, + "/v1/skills/{id}/assignment": { + "post": { + "operationId": "assignSkillBot", + "description": "Turns a shared skill on or off for one bot. For a bot-owned skill, assignment copies the full package and records its source ID; an existing linked copy is left unchanged. Removal deletes only direct linked copies, never name matches or the source. Source deletion leaves copies and their provenance intact. Default skills cannot be assigned. Each request is independent, so clients can report partial failures and retry safely.", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -2563,9 +18983,48 @@ "in": "path" } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "botId": { + "type": "string", + "format": "uuid" + }, + "assigned": { + "type": "boolean" + } + }, + "required": [ + "botId", + "assigned" + ], + "additionalProperties": false + } + } + } + }, "responses": { - "204": { - "description": "Success, no response body" + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "skipped": { + "type": "boolean" + } + }, + "required": [ + "skipped" + ] + } + } + } }, "400": { "description": "Invalid request or operation", @@ -2578,7 +19037,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -2650,12 +19109,16 @@ } } }, - "/v1/agents/{id}/duplicate": { - "post": { - "operationId": "duplicateAgent", + "/v1/agents/{id}/reviews": { + "get": { + "operationId": "listAgentReviews", + "description": "What the bot's reviews changed, newest first, one entry per reviewed execution with its changes. Clients show these as notices in the bot chat, also after reconnecting.", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -2666,22 +19129,29 @@ "required": true, "name": "id", "in": "path" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200, + "default": 50 + }, + "required": false, + "name": "limit", + "in": "query" } ], "responses": { - "201": { + "200": { "description": "Success", "content": { "application/json": { "schema": { - "anyOf": [ - { - "$ref": "#/components/schemas/Agent" - }, - { - "type": "null" - } - ] + "type": "array", + "items": { + "$ref": "#/components/schemas/ReviewResult" + } } } } @@ -2697,7 +19167,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -2769,31 +19239,57 @@ } } }, - "/v1/agents/{id}/chat": { + "/v1/changes": { "get": { - "operationId": "getChat", + "operationId": "listChanges", + "description": "Skill and memory changes by owners, bots, and reviews, newest first, with the state before and after each. Page with `before` set to the last change's ID.", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ { "schema": { - "type": "string" + "type": "integer", + "minimum": 1, + "maximum": 200, + "default": 50 }, - "required": true, - "name": "id", - "in": "path" + "required": false, + "name": "limit", + "in": "query" }, { "schema": { - "type": "integer", - "minimum": 1, - "maximum": 200 + "type": "string", + "minLength": 1, + "maxLength": 200 }, "required": false, - "name": "limit", + "name": "before", + "in": "query" + }, + { + "schema": { + "anyOf": [ + { + "type": "string", + "format": "uuid" + }, + { + "type": "string", + "enum": [ + "shared" + ] + } + ] + }, + "required": false, + "name": "agentId", "in": "query" } ], @@ -2803,7 +19299,10 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ChatSnapshot" + "type": "array", + "items": { + "$ref": "#/components/schemas/LearnedChange" + } } } } @@ -2819,7 +19318,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -2891,12 +19390,16 @@ } } }, - "/v1/agents/{id}/chat/history": { - "get": { - "operationId": "getChatHistory", + "/v1/changes/{id}/revert": { + "post": { + "operationId": "revertChange", + "description": "Restores the state before the change, whatever happened since, and records the revert as a change of its own.", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -2907,26 +19410,111 @@ "required": true, "name": "id", "in": "path" + } + ], + "responses": { + "201": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LearnedChange" + } + } + } + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/skills": { + "get": { + "operationId": "listSkills", + "security": [ { - "schema": { - "type": "integer", - "minimum": 1, - "maximum": 200 - }, - "required": false, - "name": "limit", - "in": "query" + "BearerAuth": [] }, { - "schema": { - "type": "string", - "minLength": 1, - "maxLength": 200 - }, - "required": false, - "name": "before", - "in": "query" + "SessionCookie": [] } ], "responses": { @@ -2935,7 +19523,10 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/TranscriptPage" + "type": "array", + "items": { + "$ref": "#/components/schemas/ListedSkill" + } } } } @@ -2951,7 +19542,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -3021,33 +19612,77 @@ } } } - } - }, - "/v1/agents/{id}/coding-jobs": { - "get": { - "operationId": "listCodingJobs", + }, + "post": { + "operationId": "createSkill", "security": [ { "BearerAuth": [] - } - ], - "parameters": [ + }, { - "schema": { - "type": "string" - }, - "required": true, - "name": "id", - "in": "path" + "SessionCookie": [] } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "description": { + "type": "string", + "maxLength": 300, + "default": "" + }, + "instructions": { + "type": "string", + "maxLength": 32000 + }, + "documents": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "pattern": "^references\\/[a-z0-9][a-z0-9._-]{0,99}\\.md$" + }, + "content": { + "type": "string", + "minLength": 1, + "maxLength": 64000 + } + }, + "required": [ + "path", + "content" + ] + }, + "maxItems": 20, + "default": [] + } + }, + "required": [ + "name", + "instructions" + ] + } + } + } + }, "responses": { - "200": { + "201": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CodingJobs" + "$ref": "#/components/schemas/Skill" } } } @@ -3063,7 +19698,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -3135,12 +19770,16 @@ } } }, - "/v1/agents/{id}/coding-jobs/{name}/history": { + "/v1/skills/{id}": { "get": { - "operationId": "getCodingJobHistory", + "operationId": "getSkill", + "description": "One shared skill as a full package. GET /v1/skills keeps its earlier item shapes; the full records are here and in the create and update responses.", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -3151,34 +19790,6 @@ "required": true, "name": "id", "in": "path" - }, - { - "schema": { - "type": "string" - }, - "required": true, - "name": "name", - "in": "path" - }, - { - "schema": { - "type": "integer", - "minimum": 1, - "maximum": 200 - }, - "required": false, - "name": "limit", - "in": "query" - }, - { - "schema": { - "type": "string", - "minLength": 1, - "maxLength": 200 - }, - "required": false, - "name": "before", - "in": "query" } ], "responses": { @@ -3187,7 +19798,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/TranscriptPage" + "$ref": "#/components/schemas/SkillPackage" } } } @@ -3203,7 +19814,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -3273,14 +19884,15 @@ } } } - } - }, - "/v1/agents/{id}/messages": { - "post": { - "operationId": "sendMessage", + }, + "patch": { + "operationId": "updateSkill", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -3300,70 +19912,60 @@ "schema": { "type": "object", "properties": { - "content": { + "name": { "type": "string", - "maxLength": 32000 + "minLength": 1, + "maxLength": 100 }, - "requestId": { + "description": { "type": "string", - "format": "uuid" + "maxLength": 300 }, - "replyTo": { + "instructions": { "type": "string", - "minLength": 1, - "maxLength": 200 + "maxLength": 32000 }, - "attachments": { + "documents": { "type": "array", "items": { "type": "object", "properties": { - "name": { - "type": "string", - "minLength": 1, - "maxLength": 200 - }, - "mimeType": { + "path": { "type": "string", - "minLength": 1, - "maxLength": 100 + "pattern": "^references\\/[a-z0-9][a-z0-9._-]{0,99}\\.md$" }, - "data": { + "content": { "type": "string", "minLength": 1, - "pattern": "^[A-Za-z0-9+/]*={0,2}$" + "maxLength": 64000 } }, "required": [ - "name", - "mimeType", - "data" + "path", + "content" ] }, - "maxItems": 8, - "default": [] - }, - "timezone": { - "type": "string", - "minLength": 1, - "maxLength": 100 + "maxItems": 20 } - }, - "required": [ - "content", - "requestId" - ] + } } } } }, "responses": { - "202": { + "200": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Execution" + "anyOf": [ + { + "$ref": "#/components/schemas/Skill" + }, + { + "type": "null" + } + ] } } } @@ -3379,7 +19981,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -3449,14 +20051,15 @@ } } } - } - }, - "/v1/agents/{id}/attachments/{entryId}/{index}": { - "get": { - "operationId": "getAttachment", + }, + "delete": { + "operationId": "deleteSkill", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -3467,45 +20070,135 @@ "required": true, "name": "id", "in": "path" + } + ], + "responses": { + "204": { + "description": "Success, no response body" + }, + "400": { + "description": "Invalid request or operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, expired, or invalid account session", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "Resource not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "405": { + "description": "Resource is read-only", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflicting request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Request body exceeds the size limit", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/v1/skills/github/browse": { + "post": { + "operationId": "browseSkillRepository", + "description": "Lists the skills in a public GitHub repository: every folder with a SKILL.md, and whether each can be installed.", + "security": [ { - "schema": { - "type": "string" - }, - "required": true, - "name": "entryId", - "in": "path" + "BearerAuth": [] }, { - "schema": { - "type": [ - "integer", - "null" - ], - "minimum": 0, - "maximum": 7 - }, - "required": true, - "name": "index", - "in": "path" + "SessionCookie": [] } ], - "responses": { - "200": { - "description": "Attachment bytes; Content-Type identifies the image format", - "headers": { - "Cache-Control": { - "schema": { - "type": "string" + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "type": "string", + "minLength": 1, + "maxLength": 2000 + } }, - "description": "private, max-age=31536000, immutable" + "required": [ + "location" + ], + "additionalProperties": false } - }, + } + } + }, + "responses": { + "200": { + "description": "Success", "content": { - "image/*": { + "application/json": { "schema": { - "type": "string", - "format": "binary" + "$ref": "#/components/schemas/SkillListing" } } } @@ -3521,7 +20214,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -3593,27 +20286,82 @@ } } }, - "/v1/agents/{id}/abort": { + "/v1/skills/github/install": { "post": { - "operationId": "abortChat", + "operationId": "installSkills", + "description": "Installs skills from one commit of a public GitHub repository as read-only shared skills, all or none, and turns them on for `botIds`.", "security": [ { "BearerAuth": [] - } - ], - "parameters": [ + }, { - "schema": { - "type": "string" - }, - "required": true, - "name": "id", - "in": "path" + "SessionCookie": [] } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "repository": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "branch": { + "type": "string", + "minLength": 1, + "maxLength": 255 + }, + "commit": { + "type": "string", + "pattern": "^[0-9a-f]{40}$" + }, + "paths": { + "type": "array", + "items": { + "type": "string", + "maxLength": 1000 + }, + "minItems": 1, + "maxItems": 100 + }, + "botIds": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "maxItems": 200, + "default": [] + } + }, + "required": [ + "repository", + "branch", + "commit", + "paths" + ], + "additionalProperties": false + } + } + } + }, "responses": { - "204": { - "description": "Success, no response body" + "201": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SkillPackage" + } + } + } + } }, "400": { "description": "Invalid request or operation", @@ -3626,7 +20374,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -3656,7 +20404,7 @@ } }, "409": { - "description": "Conflicting request", + "description": "A skill is already installed or its name is taken", "content": { "application/json": { "schema": { @@ -3698,31 +20446,25 @@ } } }, - "/v1/agents/{id}/compact": { + "/v1/skills/updates/check": { "post": { - "operationId": "compactChat", + "operationId": "checkSkillUpdates", + "description": "Checks every installed skill's branch for changes now. The server also checks daily; GET /v1/skills shows the results as `update`.", "security": [ { "BearerAuth": [] - } - ], - "parameters": [ + }, { - "schema": { - "type": "string" - }, - "required": true, - "name": "id", - "in": "path" + "SessionCookie": [] } ], "responses": { - "202": { + "200": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Compaction" + "$ref": "#/components/schemas/SkillCheck" } } } @@ -3738,7 +20480,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -3810,21 +20552,16 @@ } } }, - "/v1/agents/{id}/events": { + "/v1/skills/{id}/update": { "get": { - "operationId": "streamChatEvents", - "x-sse-events": { - "snapshot": { - "$ref": "#/components/schemas/ChatSnapshot" - }, - "heartbeat": { - "$ref": "#/components/schemas/HeartbeatEvent" - } - }, - "description": "Server-sent events. Each snapshot event carries a ChatSnapshot JSON object in data. Heartbeat events carry {} every 15 seconds. Authenticate with the Authorization header. Reconnect by fetching the current snapshot; there is no Last-Event-ID replay.", + "operationId": "getPendingSkillUpdate", + "description": "The upstream version an installed skill would update to.", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -3835,25 +20572,15 @@ "required": true, "name": "id", "in": "path" - }, - { - "schema": { - "type": "integer", - "minimum": 1, - "maximum": 200 - }, - "required": false, - "name": "limit", - "in": "query" } ], "responses": { "200": { - "description": "SSE stream, not a JSON array", + "description": "Success", "content": { - "text/event-stream": { + "application/json": { "schema": { - "type": "string" + "$ref": "#/components/schemas/PendingSkillUpdate" } } } @@ -3869,7 +20596,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -3939,32 +20666,35 @@ } } } - } - }, - "/v1/events": { - "get": { - "operationId": "streamActivityEvents", - "x-sse-events": { - "activity": { - "$ref": "#/components/schemas/ActivityEvent" - }, - "heartbeat": { - "$ref": "#/components/schemas/HeartbeatEvent" - } - }, - "description": "Server-sent events. Each activity event carries a ReplyEvent or ChatPreviewEvent JSON object in data. Current chat previews replay on connection; finished replies are not replayed. Heartbeat events carry {} every 15 seconds. Authenticate with the Authorization header. No Last-Event-ID replay.", + }, + "post": { + "operationId": "applySkillUpdate", + "description": "Replaces an installed skill with its upstream version, recorded as a change the owner can revert.", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" } ], "responses": { "200": { - "description": "SSE stream, not a JSON array", + "description": "Success", "content": { - "text/event-stream": { + "application/json": { "schema": { - "type": "string" + "$ref": "#/components/schemas/SkillPackage" } } } @@ -3980,7 +20710,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -4052,12 +20782,15 @@ } } }, - "/v1/agents/{id}/memories": { + "/v1/schedules": { "get": { - "operationId": "listAgentMemories", + "operationId": "listSchedules", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -4065,9 +20798,9 @@ "schema": { "type": "string" }, - "required": true, - "name": "id", - "in": "path" + "required": false, + "name": "agentId", + "in": "query" } ], "responses": { @@ -4078,7 +20811,7 @@ "schema": { "type": "array", "items": { - "$ref": "#/components/schemas/Memory" + "$ref": "#/components/schemas/Schedule" } } } @@ -4095,7 +20828,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -4167,20 +20900,13 @@ } }, "post": { - "operationId": "createAgentMemory", + "operationId": "createSchedule", "security": [ { "BearerAuth": [] - } - ], - "parameters": [ + }, { - "schema": { - "type": "string" - }, - "required": true, - "name": "id", - "in": "path" + "SessionCookie": [] } ], "requestBody": { @@ -4190,14 +20916,84 @@ "schema": { "type": "object", "properties": { - "content": { + "agentId": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "kind": { + "type": "string", + "enum": [ + "prompt", + "script" + ], + "default": "prompt" + }, + "prompt": { + "type": "string", + "maxLength": 32000, + "default": "" + }, + "command": { + "type": [ + "string", + "null" + ], + "maxLength": 8000, + "default": null + }, + "timeoutSeconds": { + "type": "integer", + "minimum": 1, + "maximum": 3600, + "default": 600 + }, + "notify": { + "type": "boolean", + "default": true + }, + "cron": { + "type": [ + "string", + "null" + ], + "maxLength": 100, + "default": null + }, + "timezone": { "type": "string", + "maxLength": 100, + "default": "UTC" + }, + "runAt": { + "type": [ + "string", + "null" + ], + "format": "date-time", + "default": null + }, + "eventSourceId": { + "type": [ + "string", + "null" + ], "minLength": 1, - "maxLength": 32000 + "maxLength": 200, + "default": null + }, + "enabled": { + "type": "boolean", + "default": true } }, "required": [ - "content" + "agentId", + "name" ] } } @@ -4209,7 +21005,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Memory" + "$ref": "#/components/schemas/Schedule" } } } @@ -4225,7 +21021,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -4234,6 +21030,16 @@ } } }, + "403": { + "description": "Script tasks need coding jobs and must stay with their creator", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, "404": { "description": "Resource not found", "content": { @@ -4297,12 +21103,15 @@ } } }, - "/v1/agents/{id}/memories/{memoryId}": { + "/v1/schedules/{id}": { "patch": { - "operationId": "updateAgentMemory", + "operationId": "updateSchedule", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -4313,14 +21122,6 @@ "required": true, "name": "id", "in": "path" - }, - { - "schema": { - "type": "string" - }, - "required": true, - "name": "memoryId", - "in": "path" } ], "requestBody": { @@ -4330,15 +21131,71 @@ "schema": { "type": "object", "properties": { - "content": { + "agentId": { + "type": "string", + "format": "uuid" + }, + "name": { "type": "string", "minLength": 1, + "maxLength": 200 + }, + "kind": { + "type": "string", + "enum": [ + "prompt", + "script" + ] + }, + "prompt": { + "type": "string", "maxLength": 32000 + }, + "command": { + "type": [ + "string", + "null" + ], + "maxLength": 8000 + }, + "timeoutSeconds": { + "type": "integer", + "minimum": 1, + "maximum": 3600 + }, + "notify": { + "type": "boolean" + }, + "cron": { + "type": [ + "string", + "null" + ], + "maxLength": 100 + }, + "timezone": { + "type": "string", + "maxLength": 100 + }, + "runAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "eventSourceId": { + "type": [ + "string", + "null" + ], + "minLength": 1, + "maxLength": 200 + }, + "enabled": { + "type": "boolean" } - }, - "required": [ - "content" - ] + } } } } @@ -4351,7 +21208,7 @@ "schema": { "anyOf": [ { - "$ref": "#/components/schemas/Memory" + "$ref": "#/components/schemas/Schedule" }, { "type": "null" @@ -4372,7 +21229,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -4381,6 +21238,16 @@ } } }, + "403": { + "description": "Script tasks need coding jobs and must stay with their creator", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, "404": { "description": "Resource not found", "content": { @@ -4444,10 +21311,13 @@ } }, "delete": { - "operationId": "deleteAgentMemory", + "operationId": "deleteSchedule", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -4458,14 +21328,6 @@ "required": true, "name": "id", "in": "path" - }, - { - "schema": { - "type": "string" - }, - "required": true, - "name": "memoryId", - "in": "path" } ], "responses": { @@ -4483,112 +21345,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", - "content": { - "text/plain": { - "schema": { - "type": "string" - } - } - } - }, - "404": { - "description": "Resource not found", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - }, - "405": { - "description": "Resource is read-only", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - }, - "409": { - "description": "Conflicting request", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - }, - "413": { - "description": "Request body exceeds the size limit", - "content": { - "text/plain": { - "schema": { - "type": "string" - } - } - } - }, - "500": { - "description": "Internal server error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - }, - "503": { - "description": "Service unavailable", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - } - } - } - }, - "/v1/memories": { - "get": { - "operationId": "listSharedMemories", - "security": [ - { - "BearerAuth": [] - } - ], - "responses": { - "200": { - "description": "Success", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Memory" - } - } - } - } - }, - "400": { - "description": "Invalid request or operation", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - }, - "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -4651,48 +21408,43 @@ "description": "Service unavailable", "content": { "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - } - } - }, - "post": { - "operationId": "createSharedMemory", - "security": [ - { - "BearerAuth": [] - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "content": { - "type": "string", - "minLength": 1, - "maxLength": 32000 - } - }, - "required": [ - "content" - ] + "schema": { + "$ref": "#/components/schemas/Error" + } } } } - }, + } + } + }, + "/v1/schedules/{id}/run": { + "post": { + "operationId": "runSchedule", + "security": [ + { + "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "id", + "in": "path" + } + ], "responses": { - "201": { + "202": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Memory" + "$ref": "#/components/schemas/ScheduleRun" } } } @@ -4708,7 +21460,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -4780,12 +21532,16 @@ } } }, - "/v1/memories/{id}": { - "patch": { - "operationId": "updateSharedMemory", + "/v1/schedules/{id}/runs": { + "get": { + "operationId": "listScriptRuns", + "description": "Script task runs from the last 90 days, newest first. Page with `before` set to the last run's ID. An unknown ID returns an empty list.", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -4796,42 +21552,39 @@ "required": true, "name": "id", "in": "path" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200, + "default": 20 + }, + "required": false, + "name": "limit", + "in": "query" + }, + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "required": false, + "name": "before", + "in": "query" } ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "content": { - "type": "string", - "minLength": 1, - "maxLength": 32000 - } - }, - "required": [ - "content" - ] - } - } - } - }, "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { - "anyOf": [ - { - "$ref": "#/components/schemas/Memory" - }, - { - "type": "null" - } - ] + "type": "array", + "items": { + "$ref": "#/components/schemas/ScriptRun" + } } } } @@ -4847,7 +21600,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -4917,12 +21670,17 @@ } } } - }, - "delete": { - "operationId": "deleteSharedMemory", + } + }, + "/v1/executions": { + "get": { + "operationId": "listExecutions", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -4930,14 +21688,24 @@ "schema": { "type": "string" }, - "required": true, - "name": "id", - "in": "path" + "required": false, + "name": "agentId", + "in": "query" } ], "responses": { - "204": { - "description": "Success, no response body" + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Execution" + } + } + } + } }, "400": { "description": "Invalid request or operation", @@ -4950,7 +21718,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -5022,12 +21790,63 @@ } } }, - "/v1/skills": { + "/v1/activity/feed": { "get": { - "operationId": "listSkills", + "operationId": "getActivityFeed", + "description": "Bots' tool calls, tool results, MCP calls, and bot messages, and skill and memory changes, newest first. Page with `cursor` set to the previous page's `nextCursor`. A page may hold fewer than `limit` items while `hasMore` is true.", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string", + "format": "uuid" + }, + "required": false, + "name": "agentId", + "in": "query" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200, + "default": 100 + }, + "required": false, + "name": "limit", + "in": "query" + }, + { + "schema": { + "type": "string", + "enum": [ + "tool-call", + "tool-result", + "mcp-call", + "bot-message", + "change" + ] + }, + "required": false, + "name": "kind", + "in": "query" + }, + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 8000 + }, + "required": false, + "name": "cursor", + "in": "query" } ], "responses": { @@ -5036,10 +21855,7 @@ "content": { "application/json": { "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ListedSkill" - } + "$ref": "#/components/schemas/ActivityFeed" } } } @@ -5055,7 +21871,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -5125,46 +21941,29 @@ } } } - }, - "post": { - "operationId": "createSkill", + } + }, + "/v1/providers": { + "get": { + "operationId": "listProviders", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1, - "maxLength": 100 - }, - "instructions": { - "type": "string", - "maxLength": 32000 - } - }, - "required": [ - "name", - "instructions" - ] - } - } - } - }, "responses": { - "201": { + "200": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Skill" + "type": "array", + "items": { + "$ref": "#/components/schemas/Provider" + } } } } @@ -5180,7 +21979,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -5252,12 +22051,15 @@ } } }, - "/v1/skills/{id}": { - "patch": { - "operationId": "updateSkill", + "/v1/models": { + "get": { + "operationId": "listModels", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -5265,46 +22067,21 @@ "schema": { "type": "string" }, - "required": true, - "name": "id", - "in": "path" + "required": false, + "name": "provider", + "in": "query" } ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1, - "maxLength": 100 - }, - "instructions": { - "type": "string", - "maxLength": 32000 - } - } - } - } - } - }, "responses": { "200": { - "description": "Success", - "content": { - "application/json": { - "schema": { - "anyOf": [ - { - "$ref": "#/components/schemas/Skill" - }, - { - "type": "null" - } - ] + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Model" + } } } } @@ -5320,7 +22097,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -5390,12 +22167,18 @@ } } } - }, - "delete": { - "operationId": "deleteSkill", + } + }, + "/v1/providers/{provider}": { + "put": { + "operationId": "putProviderKey", + "description": "Saves the provider's API key, or a password manager reference to read it from. A reference is read once to check it; 400 when it can't be read, keeping the previous credential.", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -5404,13 +22187,59 @@ "type": "string" }, "required": true, - "name": "id", + "name": "provider", "in": "path" } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "value": { + "type": "string", + "minLength": 1, + "maxLength": 16000 + }, + "reference": { + "type": "object", + "properties": { + "passwordManager": { + "type": "string", + "enum": [ + "1password", + "bitwarden" + ] + }, + "reference": { + "type": "string", + "minLength": 1, + "maxLength": 1000 + } + }, + "required": [ + "passwordManager", + "reference" + ] + } + }, + "additionalProperties": false + } + } + } + }, "responses": { - "204": { - "description": "Success, no response body" + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProviderConfigured" + } + } + } }, "400": { "description": "Invalid request or operation", @@ -5423,7 +22252,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -5493,14 +22322,16 @@ } } } - } - }, - "/v1/schedules": { - "get": { - "operationId": "listSchedules", + }, + "delete": { + "operationId": "deleteProviderKey", + "description": "Remove the provider's saved credential. 409 for a provider that signs in outside Crumble; the message names its sign-out command.", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -5508,24 +22339,14 @@ "schema": { "type": "string" }, - "required": false, - "name": "agentId", - "in": "query" + "required": true, + "name": "provider", + "in": "path" } ], "responses": { - "200": { - "description": "Success", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Schedule" - } - } - } - } + "204": { + "description": "Success, no response body" }, "400": { "description": "Invalid request or operation", @@ -5538,7 +22359,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -5608,12 +22429,27 @@ } } } - }, + } + }, + "/v1/providers/{provider}/login": { "post": { - "operationId": "createSchedule", + "operationId": "startProviderLogin", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "provider", + "in": "path" } ], "requestBody": { @@ -5623,62 +22459,28 @@ "schema": { "type": "object", "properties": { - "agentId": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string", - "minLength": 1, - "maxLength": 200 - }, - "prompt": { - "type": "string", - "minLength": 1, - "maxLength": 32000 - }, - "cron": { - "type": [ - "string", - "null" - ], - "maxLength": 100, - "default": null - }, - "timezone": { + "method": { "type": "string", - "maxLength": 100, - "default": "UTC" - }, - "runAt": { - "type": [ - "string", - "null" - ], - "format": "date-time", - "default": null - }, - "enabled": { - "type": "boolean", - "default": true + "enum": [ + "api_key", + "oauth" + ] } }, "required": [ - "agentId", - "name", - "prompt" + "method" ] } } } }, "responses": { - "201": { + "202": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Schedule" + "$ref": "#/components/schemas/ProviderLoginSession" } } } @@ -5694,7 +22496,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -5766,12 +22568,15 @@ } } }, - "/v1/schedules/{id}": { - "patch": { - "operationId": "updateSchedule", + "/v1/provider-logins/{id}": { + "get": { + "operationId": "getProviderLogin", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -5784,67 +22589,13 @@ "in": "path" } ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "agentId": { - "type": "string", - "format": "uuid" - }, - "name": { - "type": "string", - "minLength": 1, - "maxLength": 200 - }, - "prompt": { - "type": "string", - "minLength": 1, - "maxLength": 32000 - }, - "cron": { - "type": [ - "string", - "null" - ], - "maxLength": 100 - }, - "timezone": { - "type": "string", - "maxLength": 100 - }, - "runAt": { - "type": [ - "string", - "null" - ], - "format": "date-time" - }, - "enabled": { - "type": "boolean" - } - } - } - } - } - }, "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { - "anyOf": [ - { - "$ref": "#/components/schemas/Schedule" - }, - { - "type": "null" - } - ] + "$ref": "#/components/schemas/ProviderLoginSession" } } } @@ -5860,7 +22611,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -5899,6 +22650,16 @@ } } }, + "410": { + "description": "Login session ended or was lost on restart", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, "413": { "description": "Request body exceeds the size limit", "content": { @@ -5932,10 +22693,13 @@ } }, "delete": { - "operationId": "deleteSchedule", + "operationId": "cancelProviderLogin", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -5949,8 +22713,15 @@ } ], "responses": { - "204": { - "description": "Success, no response body" + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProviderLoginSession" + } + } + } }, "400": { "description": "Invalid request or operation", @@ -5963,7 +22734,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -6002,6 +22773,16 @@ } } }, + "410": { + "description": "Login session ended or was lost on restart", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, "413": { "description": "Request body exceeds the size limit", "content": { @@ -6035,12 +22816,15 @@ } } }, - "/v1/schedules/{id}/run": { + "/v1/provider-logins/{id}/responses": { "post": { - "operationId": "runSchedule", + "operationId": "answerProviderLogin", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -6052,14 +22836,38 @@ "name": "id", "in": "path" } - ], + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "promptId": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "value": { + "type": "string" + } + }, + "required": [ + "promptId", + "value" + ] + } + } + } + }, "responses": { - "202": { + "200": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ScheduleRun" + "$ref": "#/components/schemas/ProviderLoginSession" } } } @@ -6075,7 +22883,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -6114,6 +22922,16 @@ } } }, + "410": { + "description": "Login session ended or was lost on restart", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, "413": { "description": "Request body exceeds the size limit", "content": { @@ -6147,22 +22965,16 @@ } } }, - "/v1/executions": { + "/v1/password-managers": { "get": { - "operationId": "listExecutions", + "operationId": "listPasswordManagers", + "description": "Every password manager this server supports, whether it is connected, and which secrets read from it.", "security": [ { "BearerAuth": [] - } - ], - "parameters": [ + }, { - "schema": { - "type": "string" - }, - "required": false, - "name": "agentId", - "in": "query" + "SessionCookie": [] } ], "responses": { @@ -6171,10 +22983,7 @@ "content": { "application/json": { "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Execution" - } + "$ref": "#/components/schemas/PasswordManagers" } } } @@ -6190,7 +22999,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -6262,43 +23071,59 @@ } } }, - "/v1/activity/feed": { - "get": { - "operationId": "getActivityFeed", + "/v1/password-managers/{id}": { + "put": { + "operationId": "connectPasswordManager", + "description": "Signs in with the token to check it, then connects the password manager or replaces its token. A new token drops the values read with the old one. 400 when the password manager rejects the token; 503 when it can't be reached.", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ { "schema": { "type": "string", - "format": "uuid" - }, - "required": false, - "name": "agentId", - "in": "query" - }, - { - "schema": { - "type": "integer", - "minimum": 1, - "maximum": 200, - "default": 100 + "enum": [ + "1password", + "bitwarden" + ] }, - "required": false, - "name": "limit", - "in": "query" + "required": true, + "name": "id", + "in": "path" } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "token": { + "type": "string", + "minLength": 1, + "maxLength": 16000 + } + }, + "required": [ + "token" + ] + } + } + } + }, "responses": { "200": { "description": "Success", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ActivityFeed" + "$ref": "#/components/schemas/PasswordManager" } } } @@ -6314,7 +23139,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -6384,29 +23209,35 @@ } } } - } - }, - "/v1/providers": { - "get": { - "operationId": "listProviders", + }, + "delete": { + "operationId": "disconnectPasswordManager", + "description": "Disconnects the password manager and drops its token. 409 while any secret still reads from it; `usedBy` in the list names them.", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string", + "enum": [ + "1password", + "bitwarden" + ] + }, + "required": true, + "name": "id", + "in": "path" } ], "responses": { - "200": { - "description": "Success", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Provider" - } - } - } - } + "204": { + "description": "Success, no response body" }, "400": { "description": "Invalid request or operation", @@ -6419,7 +23250,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -6491,22 +23322,16 @@ } } }, - "/v1/models": { + "/v1/plugin-settings": { "get": { - "operationId": "listModels", + "operationId": "listPluginSettings", + "description": "Each plugin that has settings, and whether each setting has a value. Values are never returned.", "security": [ { "BearerAuth": [] - } - ], - "parameters": [ + }, { - "schema": { - "type": "string" - }, - "required": false, - "name": "provider", - "in": "query" + "SessionCookie": [] } ], "responses": { @@ -6515,10 +23340,7 @@ "content": { "application/json": { "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Model" - } + "$ref": "#/components/schemas/PluginSettings" } } } @@ -6534,7 +23356,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -6606,21 +23428,37 @@ } } }, - "/v1/providers/{provider}": { + "/v1/plugin-settings/{pluginId}/{key}": { "put": { - "operationId": "putProviderKey", + "operationId": "setPluginSetting", + "description": "Sets a plugin setting to a `value` stored in Crumble, or to a `reference` read from a connected password manager, replacing the one before; send exactly one. A reference is checked by reading it once; 400 when it can't be read. 404 for a plugin or key the server doesn't have.", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ { "schema": { - "type": "string" + "type": "string", + "minLength": 1, + "maxLength": 200 }, "required": true, - "name": "provider", + "name": "pluginId", + "in": "path" + }, + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "required": true, + "name": "key", "in": "path" } ], @@ -6631,15 +23469,34 @@ "schema": { "type": "object", "properties": { - "apiKey": { + "value": { "type": "string", "minLength": 1, "maxLength": 16000 + }, + "reference": { + "type": "object", + "properties": { + "passwordManager": { + "type": "string", + "enum": [ + "1password", + "bitwarden" + ] + }, + "reference": { + "type": "string", + "minLength": 1, + "maxLength": 1000 + } + }, + "required": [ + "passwordManager", + "reference" + ] } }, - "required": [ - "apiKey" - ] + "additionalProperties": false } } } @@ -6650,7 +23507,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ProviderConfigured" + "$ref": "#/components/schemas/PluginSetting" } } } @@ -6666,7 +23523,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -6738,25 +23595,48 @@ } }, "delete": { - "operationId": "deleteProviderKey", + "operationId": "deletePluginSetting", + "description": "Removes a plugin setting's value. 404 for a plugin or key the server doesn't have.", "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ { "schema": { - "type": "string" + "type": "string", + "minLength": 1, + "maxLength": 200 }, "required": true, - "name": "provider", + "name": "pluginId", + "in": "path" + }, + { + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "required": true, + "name": "key", "in": "path" } ], "responses": { - "204": { - "description": "Success, no response body" + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PluginSetting" + } + } + } }, "400": { "description": "Invalid request or operation", @@ -6769,7 +23649,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -6847,6 +23727,9 @@ "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "responses": { @@ -6874,7 +23757,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -6950,6 +23833,9 @@ "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "requestBody": { @@ -6973,8 +23859,82 @@ "default": true }, "token": { - "type": "string", - "maxLength": 16000 + "type": [ + "object", + "null" + ], + "properties": { + "value": { + "type": "string", + "minLength": 1, + "maxLength": 16000 + }, + "reference": { + "type": "object", + "properties": { + "passwordManager": { + "type": "string", + "enum": [ + "1password", + "bitwarden" + ] + }, + "reference": { + "type": "string", + "minLength": 1, + "maxLength": 1000 + } + }, + "required": [ + "passwordManager", + "reference" + ] + } + }, + "additionalProperties": false + }, + "oauthClientId": { + "type": [ + "string", + "null" + ], + "minLength": 1, + "maxLength": 500 + }, + "oauthClientSecret": { + "type": [ + "object", + "null" + ], + "properties": { + "value": { + "type": "string", + "minLength": 1, + "maxLength": 16000 + }, + "reference": { + "type": "object", + "properties": { + "passwordManager": { + "type": "string", + "enum": [ + "1password", + "bitwarden" + ] + }, + "reference": { + "type": "string", + "minLength": 1, + "maxLength": 1000 + } + }, + "required": [ + "passwordManager", + "reference" + ] + } + }, + "additionalProperties": false }, "agentId": { "type": [ @@ -7015,7 +23975,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -7093,6 +24053,9 @@ "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -7147,7 +24110,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -7223,6 +24186,9 @@ "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -7257,7 +24223,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -7335,6 +24301,9 @@ "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -7400,7 +24369,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -7478,6 +24447,9 @@ "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -7510,8 +24482,82 @@ "type": "boolean" }, "token": { - "type": "string", - "maxLength": 16000 + "type": [ + "object", + "null" + ], + "properties": { + "value": { + "type": "string", + "minLength": 1, + "maxLength": 16000 + }, + "reference": { + "type": "object", + "properties": { + "passwordManager": { + "type": "string", + "enum": [ + "1password", + "bitwarden" + ] + }, + "reference": { + "type": "string", + "minLength": 1, + "maxLength": 1000 + } + }, + "required": [ + "passwordManager", + "reference" + ] + } + }, + "additionalProperties": false + }, + "oauthClientId": { + "type": [ + "string", + "null" + ], + "minLength": 1, + "maxLength": 500 + }, + "oauthClientSecret": { + "type": [ + "object", + "null" + ], + "properties": { + "value": { + "type": "string", + "minLength": 1, + "maxLength": 16000 + }, + "reference": { + "type": "object", + "properties": { + "passwordManager": { + "type": "string", + "enum": [ + "1password", + "bitwarden" + ] + }, + "reference": { + "type": "string", + "minLength": 1, + "maxLength": 1000 + } + }, + "required": [ + "passwordManager", + "reference" + ] + } + }, + "additionalProperties": false } } } @@ -7547,7 +24593,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { @@ -7623,6 +24669,9 @@ "security": [ { "BearerAuth": [] + }, + { + "SessionCookie": [] } ], "parameters": [ @@ -7650,7 +24699,7 @@ } }, "401": { - "description": "Missing or invalid bearer token", + "description": "Missing, expired, or invalid account session", "content": { "text/plain": { "schema": { diff --git a/contract/assets/source-commit.txt b/contract/assets/source-commit.txt index c52a29a..c4cbfbf 100644 --- a/contract/assets/source-commit.txt +++ b/contract/assets/source-commit.txt @@ -1 +1 @@ -f05fce5117cd8041e7ea8342eaf57f79d4990512 +a3218780cf457d4377f195ef9e67d640c5158c24 diff --git a/contract/pin.json b/contract/pin.json index 4317f9f..fde3392 100644 --- a/contract/pin.json +++ b/contract/pin.json @@ -1,22 +1,22 @@ { "checksums": { - "CHANGELOG.md": "a0075a753628fc939e4599991ba3906f3ffaa403dda047266e096f923cb3ea3b", - "activity-event.schema.json": "1f225a65f4e80470da9e8230da3a355dc60cb711f9e61a186249ed3dd6e6e9f7", - "chat-snapshot.schema.json": "0af60b3c79a62a0b9780ef716e4db77b33701d1c5d8a0a372d77593adf2a936c", + "CHANGELOG.md": "f1b51f5a2371989fb0a961e8d2097879a0fb90fc4d44a7554e32555ade38da32", + "activity-event.schema.json": "4fa4a524cf635a837b53a322f2bdcbcccba75bc24b33260863ea8124f96ee21e", + "chat-snapshot.schema.json": "eb4fc4fea61127a93e78b09eb7223a1ed730b49bc7a9a3dedfbf0fa70c3932c6", "heartbeat.schema.json": "e1fc21c5ca3e658bfbfbb5005a0d1dfec2be6e720b5a1ff86f699a13cc5db221", - "openapi.json": "1cb17d9cdc18c7c33e17f22491963f48e4a24c612ed150344ad258df6847ad1e", - "source-commit.txt": "ec0e70b63f6836d6bd251e14dc92b2b2b7455d35dc681c5cec14ba3f607e5189" + "openapi.json": "3f389004678290cd63833233a48f17b321bb1157ae62956f72ae882b034a0c84", + "source-commit.txt": "139de61622a3ef9a8c0112ca42971afcc5b5da9613f6604b2c64a37166a623e3" }, "generator": { "sha256": { - "scripts/generate-contract.py": "59bf07755caefa4ae7d4f6a76dd0d7cc032bee1d022bafe42b325c9510e1c9db", + "scripts/generate-contract.py": "8563152a5691fcf7d4a59f16cb988cb6344217052780206e55a154046c7e5e74", "scripts/templates/ContractBoundary.kt": "a901de2c9518930e80192d77aaa452047b10a0e2974eef424d22f7705fdbfeca" }, - "version": "1.0.0" + "version": "1.1.0" }, - "release": "contract-v1.0.0", + "release": null, "repository": "crumble-project/bot", - "source": "github-release", - "sourceCommit": "f05fce5117cd8041e7ea8342eaf57f79d4990512", - "version": "1.0.0" + "source": "local-export", + "sourceCommit": "a3218780cf457d4377f195ef9e67d640c5158c24", + "version": "6.0.0" } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index a2137a6..b8739d4 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -21,6 +21,7 @@ androidxFragment = "1.9.1" [libraries] androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "androidxCore" } +open-bot-avatar-compose = { module = "re.leob.openbotavatar.kt:open-bot-avatar-compose", version = "0.1.0" } androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidxActivity" } androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "androidxComposeBom" } androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3"} diff --git a/scripts/contract.py b/scripts/contract.py index cf6e579..29db173 100644 --- a/scripts/contract.py +++ b/scripts/contract.py @@ -15,7 +15,7 @@ ASSETS = ("openapi.json", "chat-snapshot.schema.json", "activity-event.schema.json", "heartbeat.schema.json", "CHANGELOG.md", "source-commit.txt") GENERATED = ROOT / "app/src/main/java/dev/crumble/android/generated" GENERATOR = ("scripts/generate-contract.py", "scripts/templates/ContractBoundary.kt") -VERSION = "1.0.0" +VERSION = "1.1.0" def digest(path): diff --git a/scripts/generate-contract.py b/scripts/generate-contract.py index 56f686c..629c2d2 100644 --- a/scripts/generate-contract.py +++ b/scripts/generate-contract.py @@ -1,12 +1,12 @@ #!/usr/bin/env python3 -"""Crumble Kotlin contract generator 1.0.0; Python standard library only.""" +"""Crumble Kotlin contract generator 1.1.0; Python standard library only.""" import argparse import copy import json import pathlib import re -VERSION = "1.0.0" +VERSION = "1.1.0" ROOT = pathlib.Path(__file__).resolve().parents[1] PACKAGE = "dev.crumble.android.generated" HEADER = "// Generated by scripts/generate-contract.py " + VERSION + ". Do not edit.\npackage " + PACKAGE + "\n\n" @@ -70,7 +70,9 @@ def resolve(self, schema): result = {"type": "object", "properties": {}, "required": []} for part in schema["allOf"]: part = self.resolve(part) - if part.get("type") != "object": + if part.get("type") == ["object", "null"]: + result["type"] = ["object", "null"] + elif part.get("type") != "object": raise ValueError("allOf requires objects") for key, value in part.get("properties", {}).items(): if key in result["properties"] and result["properties"][key] != value: @@ -84,7 +86,8 @@ def validate(self, schema): unknown = set(schema) - ALLOWED if unknown: raise ValueError("unsupported schema keywords: " + str(sorted(unknown))) - if schema.get("additionalProperties") is False: + # Data classes never emit undeclared keys, so only a closed object without properties lacks a codec. + if schema.get("additionalProperties") is False and "properties" not in schema: raise ValueError("closed objects need an explicit codec; refusing to ignore additionalProperties:false") def type(self, schema, name, request=False): @@ -97,7 +100,7 @@ def type(self, schema, name, request=False): raise ValueError("unsupported reference siblings") target = "Request" + ref if request else ref self.register(target, self.schemas[ref], request) - return target + return target + ("?" if self.schemas[ref].get("type") == ["object", "null"] else "") if "allOf" in schema: schema = self.resolve(schema) kind = schema.get("type") @@ -119,7 +122,7 @@ def type(self, schema, name, request=False): if "properties" not in schema: additional = schema.get("additionalProperties", {}) return "Map" + suffix - self.register(name, schema, request) + self.register(name, dict(schema, type="object"), request) return name + suffix if kind == "array": return "List<" + self.type(schema["items"], name + "Item", request) + ">" + suffix @@ -183,7 +186,7 @@ def model(self, name, schema): for i, t in enumerate(types): lines += [" is " + name + ".Variant" + str(i + 1) + " -> output.json.encodeToJsonElement<" + t + ">(value.value)"] return "\n".join(lines + [" })", " }", "}"]) - if schema.get("type") != "object" or "properties" not in schema: + if schema.get("type") not in ("object", ["object", "null"]) or "properties" not in schema: raise ValueError("named schemas must be objects or unions: " + name) properties = schema.get("properties", {}) if not properties: @@ -245,7 +248,7 @@ def operations(self): streaming = media == "text/event-stream" if media == "application/json": t = self.type(content[media]["schema"], pascal(op) + "Response") - elif media == "image/*": + elif media in ("image/*", "*/*"): t = "ByteArray" elif media is None: t = "Unit" diff --git a/settings.gradle.kts b/settings.gradle.kts index c23ef33..12f5bc6 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -31,3 +31,9 @@ plugins { rootProject.name = "Crumble" include(":app") +sourceControl { + gitRepository(uri("https://github.com/cheetahbyte/open-bot-avatar-kt.git")) { + producesModule("re.leob.openbotavatar.kt:open-bot-avatar-core") + producesModule("re.leob.openbotavatar.kt:open-bot-avatar-compose") + } +}