diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c3088d..e744462 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- Remove the pages that configure the server or the account: Providers, Judge model, Vision model, Web search, Credentials, Logins, Password managers, Integrations, Coding, Message gateways, Event relay, and Users. The web app is the only client that configures them. Settings gains a Server settings row that opens the web app's settings in the browser, and the links that led to a removed page, such as Provider Settings on a failed reply, the bot editor's web search, integrations, and credentials notes, and Connect a password manager, open the matching web page. The `oauth/callback` deep link is gone with MCP sign-in. Bots' requests for credentials and logins are still answered in the chat. - Add the data layer for outside calls: the contract copy brings call requests (`request_call`), `callee` on call events, and `callsOthers` on voice lines. The app reads call requests, approves or declines them, follows them every five seconds while they are pending or calling, and reads a call's transcript every two seconds while it goes on. - Show call requests in the bot chat: a pending one reads "Wants to call for you" with the callee, number, goal and opening and has Decline and Approve; a declined one reads "Declined"; a placed one is a row with its state that opens the call, with its goal and a transcript that follows the call live. An outside call's end notice becomes the same row. - Show voice gateway calls in bot chats, as on the web: a spoken message reads "Spoken on a call" under its bubble, and a call's start and end show as centred phone markers. A call the bot placed reads "{bot} called you" with the greeting it spoke, and the "Call ended" line that wakes the bot shows the bot's reaction instead of appearing as a typed message. diff --git a/README.md b/README.md index ae40435..a66df8d 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,9 @@ 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), 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`. +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 app doesn't configure the server or the account. Providers, credentials, logins, password managers, integrations, coding, users, message gateways, and the event relay are set in the web app: **Settings** › **Server settings** opens it in the browser. ## Shared API contract diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 8b735f0..c4a1ee9 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -37,13 +37,6 @@ - - - - - - - diff --git a/app/src/main/java/dev/crumble/android/MainActivity.kt b/app/src/main/java/dev/crumble/android/MainActivity.kt index 0164ec9..38b4362 100644 --- a/app/src/main/java/dev/crumble/android/MainActivity.kt +++ b/app/src/main/java/dev/crumble/android/MainActivity.kt @@ -40,7 +40,7 @@ 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. */ +/** Web pages in the app, such as the bot desktop viewer, keep their own storage, which must not carry over to the next account. */ private fun forgetWebSessions() { runCatching { CookieManager.getInstance().removeAllCookies(null) @@ -137,7 +137,6 @@ class MainActivity : ComponentActivity() { override fun onResume() { super.onResume() model.appActive = true - model.browserReturned() model.notificationsAllowed = push.notificationsAllowed() model.client?.let { push.configure(it) } push.updatePresence(true, model.route) @@ -177,10 +176,6 @@ class MainActivity : ComponentActivity() { } else if (!agentId.isNullOrEmpty()) { model.selectAgent(agentId) } - val data = intent.data - if (data != null && data.scheme == AppModel.oauthCallbackScheme) { - model.handleOAuthCallback(data.toString()) - } } private fun requestNotificationPermissionIfNeeded() { diff --git a/app/src/main/java/dev/crumble/android/model/Admin.kt b/app/src/main/java/dev/crumble/android/model/Admin.kt deleted file mode 100644 index 6ae6974..0000000 --- a/app/src/main/java/dev/crumble/android/model/Admin.kt +++ /dev/null @@ -1,49 +0,0 @@ -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 98ebf28..f82e5cd 100644 --- a/app/src/main/java/dev/crumble/android/model/AppModel.kt +++ b/app/src/main/java/dev/crumble/android/model/AppModel.kt @@ -1,10 +1,11 @@ package dev.crumble.android.model +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.json.JsonObject import androidx.compose.runtime.Stable 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 @@ -12,31 +13,12 @@ import dev.crumble.android.generated.ScriptRun import dev.crumble.android.generated.SkillPackage import dev.crumble.android.generated.BotRequest import dev.crumble.android.generated.CallRequest -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 @@ -48,7 +30,6 @@ 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 @@ -70,10 +51,8 @@ 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 @@ -84,10 +63,7 @@ val WORKSPACE_PAGES: List get() = listOf(Route.Memory, Route.Tasks, Route /** 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), + listOf(Route.Skills, Route.Avatars), ) val SETTINGS_PAGES: List get() = SETTINGS_GROUPS.flatten() @@ -99,20 +75,7 @@ sealed class 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() @@ -124,7 +87,6 @@ sealed class Route { get() = when { this in SETTINGS_PAGES -> Settings this in WORKSPACE_PAGES || this == Settings -> Account - this is MessageGateway -> MessageGateways this == NewGroup -> NewChat else -> null } @@ -137,20 +99,7 @@ sealed class Route { Skills -> "Skills" 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" @@ -242,21 +191,6 @@ data class TaskDraft( var enabled: Boolean = true, ) -data class MCPDraft( - val id: UUID = UUID.randomUUID(), - val serverID: String, - /** The bot a new server belongs to, or null for a shared one; fixed once the server exists. */ - var agentID: String? = null, - var name: String = "", - var url: 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 { val dispatcher = try { // Test if Main dispatcher is available in this environment @@ -272,7 +206,6 @@ private const val DECISION_POLL_MS = 5_000L private const val CALL_TRANSCRIPT_POLL_MS = 2_000L private const val CALL_TRANSCRIPT_PAGE_SIZE = 200 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 @@ -290,7 +223,6 @@ 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:" @@ -585,7 +517,6 @@ class AppModel( 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 showingPalette by mutableStateOf(false) var theme by mutableStateOf(ThemeChoice.of(credentials.read(THEME_KEY)) ?: ThemeChoice.System) @@ -602,70 +533,44 @@ class AppModel( 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. */ + + /** How a bot's requests for one kind of secret are read and answered; 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) @@ -2282,10 +2187,10 @@ class AppModel( val loadedServers = serversDeferred.await() val loadedSkills = skillsDeferred.await() return@coroutineScope { - if (settledSince(revision, MCP_RECORD, SKILL_RECORD)) { + if (settledSince(revision, SKILL_RECORD)) { loadEditorLists() } else { - mcpServers = withLocalChanges(loadedServers, mcpServers, MCP_RECORD, MCPServer::id) + mcpServers = loadedServers sharedSkills = withLocalChanges(loadedSkills, sharedSkills, SKILL_RECORD, SharedSkill::id) } } @@ -2295,11 +2200,9 @@ class AppModel( fun loadProviders() { request { api -> - 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) @@ -2355,10 +2258,10 @@ class AppModel( val modelHint: String get() { - if (providers.none { it.configured }) return "No provider is set up yet. Add one in Settings." + if (providers.none { it.configured }) return "No provider is set up yet. Add one in the web app." 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." + return "Add an API key for this provider in the web app to load its models." } return if (models.isEmpty()) "Type a model ID." else "${models.size} models available." } @@ -2609,9 +2512,7 @@ class AppModel( clearSecretDrafts() memoryDraft = null taskDraft = null - mcpDraft = null skillDraft = null - gatewayForm = null } fun openPanel(panel: Route) { @@ -2627,48 +2528,8 @@ class AppModel( loadEventSources() } Route.Activity -> loadActivity() - Route.Providers -> { - loadProviders() - loadPasswordManagers() - } - Route.PasswordManagers -> loadPasswordManagers() - Route.WebSearch -> { - loadWebSearch() - loadPluginSettings() - loadPasswordManagers() - } - 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 -> { - loadPasswordManagers() - loadIntegrations() - } is Route.AgentChat, is Route.GroupChat -> Unit } } @@ -2705,26 +2566,6 @@ class AppModel( } } - 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) @@ -3291,290 +3132,6 @@ class AppModel( ) } - /** Opens a server to edit, or a new one owned by `agentID` (null for shared). */ - fun openMCPForm(id: String, agentID: String? = null) { - var form = MCPDraft(serverID = id, agentID = agentID) - val server = mcpServers.firstOrNull { it.id == id } - if (server != null) { - form = form.copy( - agentID = server.agentId, - name = server.name, - url = server.url, - enabled = server.enabled, - token = secretDraft(server.token), - clientID = server.oauthClientId.orEmpty(), - clientSecret = secretDraft(server.oauthClientSecret), - ) - } - mcpDraft = form - } - - fun saveMCP() { - val form = mcpDraft ?: return - val name = form.name.trim() - val rawURL = form.url.trim() - val validUrl = try { - val u = java.net.URI(rawURL) - !u.host.isNullOrEmpty() && (u.scheme == "http" || u.scheme == "https") - } catch (_: Exception) { - false - } - if (name.isEmpty() || !validUrl) { - errorText = "MCP name and an HTTP(S) URL are required." - return - } - val payload = LinkedHashMap().apply { - put("name", JsonPrimitive(name)) - put("url", JsonPrimitive(rawURL)) - put("enabled", JsonPrimitive(form.enabled)) - 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, - url = rawURL, - enabled = form.enabled, - agentId = form.agentID, - authenticated = false, - auth = if (tokenChanged && !waits) "token" else "none", - oauthClientId = form.clientID.trim().nilIfEmpty, - token = old?.token, - oauthClientSecret = old?.oauthClientSecret, - ) - if (old != null && (!tokenChanged || waits) && old.url == rawURL) { - provisional = provisional.copy(authenticated = old.authenticated, auth = old.auth) - } - val owner = form.agentID - 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 } - } else { - mcpServers + provisional - } - if (isNew && owner != null) { - val agentIdx = agents.indexOfFirst { it.id == owner } - if (agentIdx >= 0) { - val memberships = (agents[agentIdx].mcpServers ?: emptyList()).toMutableList() - if (!memberships.contains(provisionalID)) memberships.add(provisionalID) - agents = agents.toMutableList().also { - it[agentIdx] = it[agentIdx].copy(mcpServers = memberships) - } - } - } - }, - rollback = { - mcpServers = recordRestored(mcpServers, original, provisionalID) { it.id } - if (isNew && owner != null) { - val agentIdx = agents.indexOfFirst { it.id == owner } - if (agentIdx >= 0) { - val memberships = agents[agentIdx].mcpServers?.filterNot { it == provisionalID } - agents = agents.toMutableList().also { - it[agentIdx] = it[agentIdx].copy(mcpServers = memberships) - } - } - } - if (route == Route.Integrations && (mcpDraft == null || mcpDraft?.id == form.id)) { - mcpDraft = form - } - }, - work = { api -> - if (isNew) { - if (owner != null) payload["agentId"] = JsonPrimitive(owner) - val saved = api.createMCPServer(payload) - return@optimisticMutation { - 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 } - if (agentIdx >= 0) { - val updatedMemberships = (agents[agentIdx].mcpServers ?: emptyList()).map { - if (it == provisionalID) saved.id else it - } - agents = agents.toMutableList().also { - it[agentIdx] = it[agentIdx].copy(mcpServers = updatedMemberships) - } - } - } - } - } - 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 } - } - } - }, - ) - } - - companion object { - const val oauthCallbackScheme = BuildConfig.APPLICATION_ID - const val oauthRedirectURI = "$oauthCallbackScheme:/oauth/callback" - } - - /** Starts an OAuth sign-in flow and opens the authorization URL in the system browser. */ - fun beginMCPSignIn(id: String, openBrowser: (String) -> Unit) { - 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() && !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 } - if (idx >= 0) { - mcpServers = mcpServers.toMutableList().also { - it[idx] = it[idx].copy(authenticated = true) - } - } - signingIn = null - showNotice("Signed in") - } else { - signingIn = null - } - } catch (e: CancellationException) { - throw e - } 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 = 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 { - val result = oauthResult(callbackUri) - if (generation != genAtStart) return@launch - val saved = api.finishMCPSignIn(id, code = result.code, state = result.state, iss = result.iss) - if (generation != genAtStart) return@launch - val idx = mcpServers.indexOfFirst { it.id == id } - if (idx >= 0) { - mcpServers = mcpServers.toMutableList().also { it[idx] = saved } - } - showNotice("Signed in") - } catch (e: CancellationException) { - throw e - } catch (e: Throwable) { - if (generation != genAtStart) return@launch - errorText = friendlyError(e) - } finally { - if (generation == genAtStart && signingIn == id) { - signingIn = null - } - } - } - } - - fun signOutOfMCP(id: String) { - val index = mcpServers.indexOfFirst { it.id == id } - if (index < 0) return - val old = mcpServers[index] - val signedOut = old.copy(authenticated = false, auth = "none") - optimisticMutation( - key = "mcp:$id", - update = { - mcpServers = mcpServers.toMutableList().also { it[index] = signedOut } - }, - rollback = { - val cur = mcpServers.indexOfFirst { it.id == id } - if (cur >= 0) { - mcpServers = mcpServers.toMutableList().also { it[cur] = old } - } - }, - work = { api -> - val saved = api.signOutOfMCP(id) - return@optimisticMutation { - val cur = mcpServers.indexOfFirst { it.id == id } - if (cur >= 0) { - mcpServers = mcpServers.toMutableList().also { it[cur] = saved } - } - } - }, - ) - } - - fun deleteMCP(id: String) { - val index = mcpServers.indexOfFirst { it.id == id } - if (index < 0) return - val old = mcpServers[index] - val affectedAgents = agents.mapNotNull { agent -> - if (agent.mcpServers?.contains(id) == true) agent.id to agent.mcpServers else null - } - optimisticMutation( - key = "mcp:$id", - touches = affectedAgents.map { "$BOT_RECORD${it.first}" }.toSet(), - update = { - mcpServers = mcpServers.filterNot { it.id == id } - agents = agents.map { agent -> - if (agent.mcpServers?.contains(id) == true) { - agent.copy(mcpServers = agent.mcpServers.filterNot { it == id }) - } else { - agent - } - } - }, - rollback = { - val list = mcpServers.toMutableList() - list.add(minOf(index, list.size), old) - mcpServers = list - val restoredMap = affectedAgents.toMap() - agents = agents.map { agent -> - val origMemberships = restoredMap[agent.id] - if (origMemberships != null) agent.copy(mcpServers = origMemberships) else agent - } - }, - work = { api -> - api.deleteMCPServer(id) - null - }, - ) - } - /** Servers a bot may use: the shared ones and its own. */ fun usableServers(forAgentID: String): List = mcpServers.filter { it.agentId == null || it.agentId == forAgentID } @@ -4296,7 +3853,6 @@ class AppModel( resetPendingMessages() resetGroupChats() resetSecrets() - resetConnections() resetAccountForm() recentChats.clear() attachmentBytes = emptyMap() @@ -4349,12 +3905,9 @@ class AppModel( mcpServers = emptyList() providers = emptyList() models = emptyList() - signingIn = null - browserSignIn = null agentDraft = null memoryDraft = null taskDraft = null - mcpDraft = null skillDraft = null snapshot = null messages = emptyList() @@ -4417,26 +3970,14 @@ class AppModel( 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) { @@ -4444,26 +3985,6 @@ class AppModel( 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 @@ -4542,9 +4063,8 @@ class AppModel( ) } - 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) + fun openCredentialForm(botID: String, request: CredentialRequest) { + credentialForm = credentialForm(botID, request) loadPasswordManagers() } @@ -4570,8 +4090,8 @@ class AppModel( ) } - fun openLoginForm(botID: String?, existing: Login? = null, request: LoginRequest? = null) { - loginForm = loginForm(botID ?: loginScope.takeIf { it != SKILLS_ALL }, agents, existing, request) + fun openLoginForm(botID: String, request: LoginRequest) { + loginForm = loginForm(botID, request) loadPasswordManagers() } @@ -4602,13 +4122,7 @@ class AppModel( ) } - private fun changeSecret( - ops: SecretOps, - botID: String, - name: String, - change: (D, String) -> D, - call: suspend (APIClient, String, String) -> Unit, - ) { + private fun declineSecretRequest(ops: SecretOps, botID: String, name: String) { val key = secretKey(ops.kind, botID, name) val before = ops.lists()[botID] optimisticMutation( @@ -4616,7 +4130,7 @@ class AppModel( update = { touchSecrets(ops.kind, botID) decisionErrors = decisionErrors - key - editSecrets(ops, botID) { change(it, name) } + editSecrets(ops, botID) { ops.withoutRequest(it, name) } }, rollback = { touchSecrets(ops.kind, botID) @@ -4627,7 +4141,7 @@ class AppModel( resumeDecisions() }, work = { api -> - call(api, botID, name) + ops.decline(api, botID, name) return@optimisticMutation { touchSecrets(ops.kind, botID) reloadSecrets(ops, botID) @@ -4636,62 +4150,10 @@ class AppModel( ) } - 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 declineCredentialRequest(botID: String, name: String) = declineSecretRequest(credentialOps, botID, name) - 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)) }, - ) - } - } + fun declineLoginRequest(botID: String, name: String) = declineSecretRequest(loginOps, botID, name) // MARK: Password managers @@ -4700,1109 +4162,53 @@ class AppModel( 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) }, - ) + attempt { api.passwordManagers() }.onSuccess { if (generation == gen) passwordManagers = it } } } - fun openManagerToken(manager: PasswordManager) { - tokenForm = ManagerTokenForm(manager) + private fun loadAgentsForPanel() { + val revision = mutationRevision + request { api -> + val loaded = api.agents() + return@request { + if (settledSince(revision, BOT_RECORD)) loadAgentsForPanel() else applyBots(loaded) + } + } } - fun closeManagerToken() { - tokenForm = null - } + // MARK: Account - private fun editManager(id: String, change: (PasswordManager) -> PasswordManager) { - passwordManagers = passwordManagers.map { if (it.id == id) change(it) else it } - } + var accountMode by mutableStateOf(AccountMode.SignIn) + var accountName by mutableStateOf("") + var inviteCode by mutableStateOf("") - /** 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 switchAccountMode() { + accountMode = if (accountMode == AccountMode.SignIn) AccountMode.SignUp else AccountMode.SignIn + errorText = "" } - 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() - } - }, - ) + private fun resetAccountForm() { + accountMode = AccountMode.SignIn + accountName = "" + inviteCode = "" } - // 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, "") + private fun loadAccount() { + if (client == null) return + val changes = themeChanges confirmed( start = {}, - work = work, + work = { api -> api.accountSession() }, 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))) }, - ) + result.onSuccess { + // 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) + } + } }, ) } - - 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/BotProfile.kt b/app/src/main/java/dev/crumble/android/model/BotProfile.kt index 3241ba9..709330e 100644 --- a/app/src/main/java/dev/crumble/android/model/BotProfile.kt +++ b/app/src/main/java/dev/crumble/android/model/BotProfile.kt @@ -23,9 +23,15 @@ fun shownCapabilities(server: Capabilities?, initialTools: Set): List, current: String): List { @@ -44,7 +50,7 @@ fun botProviderOptions(providers: List, current: String): 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." + "Add an API key or sign in for this provider in the web app to load its models." modelCount > 0 -> "$modelCount models available." else -> "Type a model ID." } diff --git a/app/src/main/java/dev/crumble/android/model/CommandPalette.kt b/app/src/main/java/dev/crumble/android/model/CommandPalette.kt index 2f1f9f8..9595068 100644 --- a/app/src/main/java/dev/crumble/android/model/CommandPalette.kt +++ b/app/src/main/java/dev/crumble/android/model/CommandPalette.kt @@ -26,7 +26,6 @@ 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 { @@ -43,7 +42,7 @@ fun paletteSections( 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 { + val settings = SETTINGS_PAGES.map { PaletteItem(it.title, PaletteAction.OpenPage(it), listOf("Settings ${it.title}")) } val themes = ThemeChoice.entries.map { @@ -64,7 +63,7 @@ fun paletteSections( ).filter { it.items.isNotEmpty() } } -/** Letters in order count, like the website's search: "prv" finds "Providers". Null means no match. */ +/** Letters in order count, like the website's search: "skl" finds "Skills". Null means no match. */ internal fun matchScore(term: String, query: String): Int? { val text = term.lowercase() val at = text.indexOf(query) diff --git a/app/src/main/java/dev/crumble/android/model/Connections.kt b/app/src/main/java/dev/crumble/android/model/Connections.kt deleted file mode 100644 index 6284bce..0000000 --- a/app/src/main/java/dev/crumble/android/model/Connections.kt +++ /dev/null @@ -1,443 +0,0 @@ -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/GeneralSettings.kt b/app/src/main/java/dev/crumble/android/model/GeneralSettings.kt index 74269a1..640f725 100644 --- a/app/src/main/java/dev/crumble/android/model/GeneralSettings.kt +++ b/app/src/main/java/dev/crumble/android/model/GeneralSettings.kt @@ -1,5 +1,9 @@ package dev.crumble.android.model +import java.net.URI +import java.net.URLDecoder +import java.nio.charset.StandardCharsets + enum class ThemeChoice(val value: String, val label: String) { System("system", "System"), Light("light", "Light"), @@ -16,3 +20,24 @@ fun replyNotificationsDescription(enabled: Boolean, allowed: Boolean): String = enabled -> "Replies from chats you don't have open show as notifications." else -> "Off on this device." } + +/** The web app's settings, or one of its pages; the web app serves them from the server's origin. */ +fun webSettingsURL(baseURL: String, page: String? = null): String? { + val uri = runCatching { URI(baseURL.trim()) }.getOrNull() ?: return null + if (uri.scheme == null || uri.host == null) return null + val origin = "${uri.scheme}://${uri.host}" + if (uri.port > 0) ":${uri.port}" else "" + return "$origin/settings" + page?.let { "/$it" }.orEmpty() +} + +enum class AccountMode { SignIn, SignUp } + +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 +} 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 315d9bd..a993281 100644 --- a/app/src/main/java/dev/crumble/android/model/Models.kt +++ b/app/src/main/java/dev/crumble/android/model/Models.kt @@ -1,6 +1,5 @@ package dev.crumble.android.model -import dev.crumble.android.generated.SecretStatus import java.time.Instant import java.time.ZoneId import java.time.ZonedDateTime @@ -280,20 +279,6 @@ data class MCPServer( val enabled: Boolean = false, /** The bot the server belongs to, or null when every bot may use it. */ val agentId: String? = null, - 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. */ -@Serializable -data class OAuthStart( - val authorizationUrl: String? = null, - val authorized: Boolean? = null, ) /** One event from the server's activity stream. */ diff --git a/app/src/main/java/dev/crumble/android/model/Secrets.kt b/app/src/main/java/dev/crumble/android/model/Secrets.kt index 4fdf832..20cbae7 100644 --- a/app/src/main/java/dev/crumble/android/model/Secrets.kt +++ b/app/src/main/java/dev/crumble/android/model/Secrets.kt @@ -3,25 +3,18 @@ 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 @@ -30,7 +23,6 @@ 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. */ @@ -62,7 +54,6 @@ 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? @@ -72,66 +63,38 @@ data class SecretDraft( 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 val SecretDraft.readsPasswordManager: Boolean get() = input is SecretInput.Reference -private fun secretDraft(saved: CredentialSecret?): SecretDraft = secretDraft(saved?.passwordManager, saved?.reference) +private fun SecretDraft.body(): JsonElement? = input?.json() -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. */ +/** The answer to a bot's request for a 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 request: CredentialRequest, 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 + get() = CREDENTIAL_NAME.matches(name) && hostList(hosts).isNotEmpty() && 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, +fun credentialForm(botID: String, request: CredentialRequest) = CredentialForm( + owner = botID, request = request, - name = existing?.name ?: request?.name.orEmpty(), - hosts = (existing?.hosts ?: request?.hosts.orEmpty()).joinToString(", "), - secret = secret, + name = request.name, + hosts = request.hosts.joinToString(", "), ) fun credentialFields(form: CredentialForm): Map = buildMap { @@ -139,21 +102,12 @@ fun credentialFields(form: CredentialForm): Map = buildMap 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. */ +/** The answer to a bot's request for a login. */ data class LoginForm( - val botID: String?, val owner: String, - val existing: Login? = null, - val request: LoginRequest? = null, + val request: LoginRequest, val name: String = "", val hosts: String = "", val mode: LoginMode = LoginMode.fields, @@ -165,12 +119,10 @@ data class LoginForm( 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)) + get() = !(hasCode && code.input == null) && username.input != null && password.input != null val ready: Boolean get() = LOGIN_NAME.matches(name) && hostList(hosts).isNotEmpty() && !saving && @@ -181,17 +133,12 @@ data class LoginForm( (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, +fun loginForm(botID: String, request: LoginRequest) = LoginForm( + owner = botID, 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), + name = request.name, + hosts = request.hosts.joinToString(", "), + hasCode = request.oneTimeCode, ) fun loginFields(form: LoginForm): Map { @@ -200,41 +147,25 @@ fun loginFields(form: LoginForm): Map { 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) - } + if (form.hasCode) form.code.body()?.let { put("one_time_code", it) } } return mapOf(hosts, "fields" to JsonObject(fields)) } -internal val STORED = SecretStatus(configured = true, passwordManager = null, reference = null) +private 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, - ) -} +/** A row to show until the server answers. */ +internal fun provisionalCredential(form: CredentialForm): Credential = Credential( + name = form.name, hosts = hostList(form.hosts), secret = CredentialSecret(true, null, null), 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 provisionalLogin(form: LoginForm): Login = Login( + name = form.name, + hosts = hostList(form.hosts), + fields = LoginFields(username = STORED, password = STORED, one_time_code = STORED.takeIf { form.hasCode }), + createdAt = "", updatedAt = "", lastUsedAt = null, lastError = null, +) internal fun Credentials.withCredential(item: Credential) = copy( credentials = upserted(credentials, item.name, item) { it.name }, @@ -264,33 +195,6 @@ internal fun Logins.restored(before: Logins, name: String) = Logins( 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) { @@ -313,96 +217,6 @@ fun secretRequestState(request: R?, listed: Boolean, saved: Boolean, f 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) 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 e325217..9a9f66e 100644 --- a/app/src/main/java/dev/crumble/android/network/APIClient.kt +++ b/app/src/main/java/dev/crumble/android/network/APIClient.kt @@ -3,47 +3,22 @@ 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 @@ -51,24 +26,14 @@ 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.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 @@ -84,7 +49,6 @@ import java.net.HttpURLConnection import java.net.ProtocolException import java.net.URI import java.net.URL -import java.net.URLDecoder import java.net.URLEncoder import java.nio.charset.StandardCharsets import java.time.ZoneId @@ -117,7 +81,7 @@ 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) +data class AccountSession(val id: String, val theme: String? = null) const val INVITE_HEADER = "x-crumble-invite" @@ -328,11 +292,7 @@ class APIClient( 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, - ) + return AccountSession(id, theme = (user["theme"] as? JsonPrimitive)?.contentOrNull) } suspend fun updateTheme(theme: String) { @@ -595,92 +555,17 @@ class APIClient( } suspend fun models(provider: String): List = operations.listModels(provider).map { it.domain() } - 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() - suspend fun deleteMCPServer(id: String) = operations.deleteMcpServer(id) - suspend fun startMCPSignIn(id: String, redirectURI: String): OAuthStart = operations.startMcpOAuth(request(strings("redirectUri" to redirectURI)), id, timeoutMs = 60_000).domain() - suspend fun finishMCPSignIn(id: String, code: String, state: String, iss: String?): MCPServer { - val fields = strings("code" to code, "state" to state).toMutableMap() - iss?.let { fields["iss"] = JsonPrimitive(it) } - 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), - ) } /** @@ -752,39 +637,3 @@ fun friendlyError(error: Throwable): String { } return error.message ?: error.toString() } - -data class OAuthCallbackResult( - val code: String, - val state: String, - val iss: String?, -) - -/** Reads the code, state and issuer from a sign-in callback, or the provider's reason for refusing. */ -fun oauthResult(callbackUri: String): OAuthCallbackResult { - val uri = URI(callbackUri) - val rawQuery = uri.rawQuery ?: "" - val params = LinkedHashMap() - if (rawQuery.isNotEmpty()) { - for (pair in rawQuery.split("&")) { - val idx = pair.indexOf('=') - if (idx >= 0) { - val k = URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8.name()) - val v = URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8.name()) - params[k] = v - } else if (pair.isNotEmpty()) { - params[URLDecoder.decode(pair, StandardCharsets.UTF_8.name())] = "" - } - } - } - val error = params["error"] - if (error != null) { - val desc = params["error_description"] ?: error - throw SignInError("Sign-in was refused: $desc") - } - val code = params["code"] - val state = params["state"] - if (code.isNullOrEmpty() || state.isNullOrEmpty()) { - throw SignInError("Sign-in returned no authorization code.") - } - return OAuthCallbackResult(code = code, state = state, iss = params["iss"]) -} 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 f62710e..f3cda46 100644 --- a/app/src/main/java/dev/crumble/android/network/ContractAdapters.kt +++ b/app/src/main/java/dev/crumble/android/network/ContractAdapters.kt @@ -172,12 +172,7 @@ 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) -} +internal fun McpServerStatus.domain() = MCPServer(id, name, url, enabled, agentId) internal fun PushStatus.domain() = PushInfo(serverId, mapOf("apns" to transports.apns, "fcm" to transports.fcm)) internal fun PushDeviceRegistration.domain() = PushRegistrationResult(serverId, remoteDelivery) internal fun ActivityEventPayload.domain(): dev.crumble.android.model.ActivityEvent = when (this) { 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 56f7817..501bc9a 100644 --- a/app/src/main/java/dev/crumble/android/ui/AgentEditorSheet.kt +++ b/app/src/main/java/dev/crumble/android/ui/AgentEditorSheet.kt @@ -1,28 +1,31 @@ package dev.crumble.android.ui import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.filled.ExpandLess +import androidx.compose.material.icons.filled.ExpandMore +import androidx.compose.material3.Surface +import dev.crumble.android.model.Skill +import androidx.compose.ui.platform.LocalContext 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 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.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.Forum import androidx.compose.material.icons.filled.Language import androidx.compose.material.icons.filled.Psychology @@ -39,7 +42,6 @@ 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 @@ -58,7 +60,6 @@ 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 @@ -74,6 +75,7 @@ fun AgentEditorDialog( model: AppModel, draft: AgentDraft, ) { + val context = LocalContext.current val requestID = draft.botRequestID val complete = draft.name.isNotBlank() && draft.provider.isNotEmpty() && draft.model.isNotBlank() @@ -321,9 +323,10 @@ fun AgentEditorDialog( }, ) Text( - text = "Manage the default and Exa key in Settings → Web search.", + text = "Manage the default and Exa key in the web app's Web search settings.", style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.clickable { openWebSettings(context, model, "web-search") }, ) } } @@ -334,7 +337,15 @@ fun AgentEditorDialog( item { RowsSection(title = "Integrations") { val servers = model.usableServers(forAgentID = draft.agentID) - if (servers.isEmpty()) note("Add an MCP server under Integrations to use its tools here.") + if (servers.isEmpty()) { + row { shape -> + GroupedRow( + title = "Add an MCP server in the web app to use its tools here.", + shape = shape, + onClick = { openWebSettings(context, model, "integrations") }, + ) + } + } for (server in servers) { row { shape -> GroupedItem( @@ -379,8 +390,8 @@ fun AgentEditorDialog( if (!draft.isNew) { item { SectionCard(title = "Credentials") { - OutlinedButton(onClick = { model.openBotCredentials(draft.agentID) }) { - Text("Manage in Settings") + OutlinedButton(onClick = { openWebSettings(context, model, "credentials") }) { + Text("Manage in the web app") } } } 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 0eab3e8..a6db8bf 100644 --- a/app/src/main/java/dev/crumble/android/ui/ChatScreen.kt +++ b/app/src/main/java/dev/crumble/android/ui/ChatScreen.kt @@ -1,5 +1,6 @@ package dev.crumble.android.ui +import androidx.compose.material.icons.filled.Add import android.graphics.BitmapFactory import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult @@ -38,7 +39,6 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons 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 @@ -111,7 +111,6 @@ import dev.crumble.android.model.CallMarker 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 @@ -315,7 +314,8 @@ fun ChatRowView( style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error, ) - OutlinedButton(onClick = { model.navigate(Route.Providers) }) { + val context = LocalContext.current + OutlinedButton(onClick = { openWebSettings(context, model, "providers") }) { Text("Provider Settings…") } } diff --git a/app/src/main/java/dev/crumble/android/ui/CommandPaletteScreen.kt b/app/src/main/java/dev/crumble/android/ui/CommandPaletteScreen.kt index 31875d4..e66398c 100644 --- a/app/src/main/java/dev/crumble/android/ui/CommandPaletteScreen.kt +++ b/app/src/main/java/dev/crumble/android/ui/CommandPaletteScreen.kt @@ -1,5 +1,6 @@ package dev.crumble.android.ui +import androidx.compose.material.icons.filled.Tune import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -23,7 +24,6 @@ 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 @@ -61,8 +61,8 @@ 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) + val sections = remember(query, model.agents, model.groupChats, model.theme) { + val all = paletteSections(model.agents, model.groupChats, model.theme) searchPalette(all, query) } val focus = remember { FocusRequester() } diff --git a/app/src/main/java/dev/crumble/android/ui/ConnectionsScreen.kt b/app/src/main/java/dev/crumble/android/ui/ConnectionsScreen.kt deleted file mode 100644 index 72efb61..0000000 --- a/app/src/main/java/dev/crumble/android/ui/ConnectionsScreen.kt +++ /dev/null @@ -1,1320 +0,0 @@ -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 bf3b80d..267a2ac 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,27 @@ package dev.crumble.android.ui +import androidx.compose.foundation.layout.statusBarsPadding +import dev.crumble.android.model.WORKSPACE_PAGES +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.Home +import androidx.compose.material.icons.filled.Menu +import androidx.compose.material3.DrawerValue +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.ModalDrawerSheet +import androidx.compose.material3.ModalNavigationDrawer +import androidx.compose.material3.NavigationDrawerItem +import androidx.compose.material3.NavigationDrawerItemDefaults +import androidx.compose.material3.rememberDrawerState +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.rememberCoroutineScope +import dev.crumble.android.model.botListLine +import dev.crumble.android.model.preview +import kotlinx.coroutines.launch import androidx.compose.material.icons.filled.GroupAdd import androidx.compose.ui.graphics.RectangleShape import androidx.compose.foundation.layout.windowInsetsPadding @@ -9,10 +31,8 @@ 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,69 +43,42 @@ import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -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 import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.ModalDrawerSheet -import androidx.compose.material3.ModalNavigationDrawer -import androidx.compose.material3.NavigationDrawerItem -import androidx.compose.material3.NavigationDrawerItemDefaults import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface 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 @@ -96,13 +89,10 @@ 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 @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -174,9 +164,6 @@ fun CrumbleAppScreen(model: AppModel) { 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) } @@ -198,19 +185,6 @@ fun CrumbleAppScreen(model: AppModel) { 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) } @@ -299,8 +273,6 @@ private fun CrumbleTopBar(model: AppModel) { } } 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") } @@ -368,46 +340,12 @@ private fun CrumbleTopBar(model: AppModel) { Icon(Icons.Default.Refresh, contentDescription = "Refresh") } } - Route.Integrations -> { - IconButton(onClick = { model.openMCPForm("", agentID = null) }) { - Icon(Icons.Default.Add, contentDescription = "Add Shared MCP Server") - } - IconButton(onClick = { model.openPanel(Route.Integrations) }) { - Icon(Icons.Default.Refresh, contentDescription = "Refresh") - } - } Route.Activity -> { IconButton(onClick = { model.openPanel(Route.Activity) }) { Icon(Icons.Default.Refresh, contentDescription = "Refresh") } } - Route.Avatars, Route.WebSearch, Route.JudgeModel, Route.VisionModel -> Unit - is Route.MessageGateway -> { - IconButton(onClick = { model.loadGateways() }) { - Icon(Icons.Default.Refresh, contentDescription = "Refresh") - } - } - Route.Providers, Route.PasswordManagers, Route.Coding, Route.Users, Route.MessageGateways, Route.EventRelay -> { - IconButton(onClick = { model.openPanel(currentRoute) }) { - Icon(Icons.Default.Refresh, contentDescription = "Refresh") - } - } - 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") - } - } - 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") - } - } + Route.Avatars -> Unit } }, ) @@ -419,19 +357,7 @@ fun routeIcon(route: Route): ImageVector = when (route) { 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 @@ -525,7 +451,6 @@ fun ErrorBanner( val noSheetOpen = model.agentDraft == null && model.memoryDraft == null && model.taskDraft == null && - model.mcpDraft == null && model.skillDraft == null && model.groupDraft == null && model.route != Route.General diff --git a/app/src/main/java/dev/crumble/android/ui/Fields.kt b/app/src/main/java/dev/crumble/android/ui/Fields.kt new file mode 100644 index 0000000..0887a6d --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/Fields.kt @@ -0,0 +1,101 @@ +package dev.crumble.android.ui + +import android.content.ClipData +import android.os.PersistableBundle +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ContentCopy +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.Icon +import androidx.compose.material3.IconButton +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.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.ClipEntry +import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.font.FontFamily +import dev.crumble.android.model.ChoiceOption + +@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) + }, + ) + } + } + } +} + +// 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(), + ) +} diff --git a/app/src/main/java/dev/crumble/android/ui/NativeLook.kt b/app/src/main/java/dev/crumble/android/ui/NativeLook.kt index b60b6bb..61b81b6 100644 --- a/app/src/main/java/dev/crumble/android/ui/NativeLook.kt +++ b/app/src/main/java/dev/crumble/android/ui/NativeLook.kt @@ -1,5 +1,10 @@ package dev.crumble.android.ui +import android.content.Context +import android.content.Intent +import androidx.core.net.toUri +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.webSettingsURL import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.lazy.LazyListScope @@ -328,3 +333,9 @@ fun SearchPill( } } } + +/** Opens the web app's settings, or one of its pages, in the browser: the server is configured there. */ +internal fun openWebSettings(context: Context, model: AppModel, page: String? = null) { + val url = webSettingsURL(model.client?.baseURL ?: model.serverURL, page) ?: return + runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, url.toUri()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } +} 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 0fde6bf..3fa3071 100644 --- a/app/src/main/java/dev/crumble/android/ui/PanelScreen.kt +++ b/app/src/main/java/dev/crumble/android/ui/PanelScreen.kt @@ -1,12 +1,12 @@ package dev.crumble.android.ui +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.layout.height +import androidx.compose.ui.text.input.PasswordVisualTransformation +import dev.crumble.android.model.activityTime 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 import androidx.compose.foundation.clickable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement @@ -17,7 +17,6 @@ import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size @@ -25,16 +24,13 @@ 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.ExpandLess import androidx.compose.material.icons.filled.ExpandMore import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card -import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExposedDropdownMenuBox @@ -43,10 +39,8 @@ import androidx.compose.material3.FilterChip import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ExposedDropdownMenuAnchorType -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.runtime.Composable @@ -58,27 +52,20 @@ 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 -import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp import dev.crumble.android.model.AppModel -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.Route import dev.crumble.android.model.SkillDraft import dev.crumble.android.model.SKILLS_SHARED -import dev.crumble.android.model.activityTime -import dev.crumble.android.model.matchesMCP import dev.crumble.android.model.memoryLine import java.time.Instant @@ -95,20 +82,7 @@ fun PanelView( Route.Skills -> SkillsPanel(model) Route.Tasks -> TasksPanel(model) Route.Activity -> ActivityPanel(model) - Route.Integrations -> IntegrationsPanel(model) 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) @@ -269,143 +243,6 @@ private fun MemoryRow( } } -@Composable -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 { - OutlinedTextField( - value = search, - onValueChange = { search = it }, - label = { Text("Search MCP servers") }, - shape = CircleShape, - singleLine = true, - modifier = Modifier.fillMaxWidth(), - ) - } - - item { - 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()) note("No shared MCP servers yet.") - for (server in shared) { - 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.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()) note("No MCP servers of its own.") - for (server in own) { - row { shape -> MCPServerRow(model = model, server = server, shape = shape, onOpenBrowser = { url -> openSignInPage(appContext, url) }) } - } - add("Add MCP Server") { model.openMCPForm("", agentID = agent.id) } - } - } - } -} - -@Composable -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" - } - GroupedItem( - shape = shape, - leading = { LetterTile(server.name) }, - trailing = { - if (!server.enabled) { - Text( - text = "Disabled", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - }, - 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…") - } - } - TextButton( - onClick = { model.openMCPForm(server.id) }, - enabled = !isPending, - ) { - Text("Edit") - } - TextButton( - onClick = { confirmingDelete = true }, - enabled = !isPending, - ) { - Text("Delete", color = MaterialTheme.colorScheme.error) - } - } - }, - ) { - 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, @@ -613,153 +450,6 @@ fun MemoryFormDialog( ) } -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun MCPFormDialog( - model: AppModel, - 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 { - model.agents.firstOrNull { it.id == draft.agentID }?.name ?: "Every bot (shared)" - } - - AlertDialog( - onDismissRequest = { - model.errorText = "" - model.mcpDraft = null - }, - title = { Text(if (draft.serverID.isEmpty()) "Add MCP Server" else "Edit MCP Server") }, - text = { - Column( - modifier = Modifier.verticalScroll(rememberScrollState()), - verticalArrangement = Arrangement.spacedBy(10.dp), - ) { - SheetErrorBanner(model.errorText) - if (draft.serverID.isEmpty()) { - ExposedDropdownMenuBox( - expanded = ownerMenuExpanded, - onExpandedChange = { ownerMenuExpanded = it }, - ) { - OutlinedTextField( - value = selectedOwnerName, - onValueChange = {}, - readOnly = true, - label = { Text("Available to") }, - trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = ownerMenuExpanded) }, - modifier = Modifier - .menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable) - .fillMaxWidth(), - ) - ExposedDropdownMenu( - expanded = ownerMenuExpanded, - onDismissRequest = { ownerMenuExpanded = false }, - ) { - DropdownMenuItem( - text = { Text("Every bot (shared)") }, - onClick = { - model.mcpDraft = draft.copy(agentID = null) - ownerMenuExpanded = false - }, - ) - for (agent in model.agents) { - DropdownMenuItem( - text = { Text(agent.name) }, - onClick = { - model.mcpDraft = draft.copy(agentID = agent.id) - ownerMenuExpanded = false - }, - ) - } - } - } - } - OutlinedTextField( - value = draft.name, - onValueChange = { model.mcpDraft = draft.copy(name = it) }, - label = { Text("Name") }, - singleLine = true, - modifier = Modifier.fillMaxWidth(), - ) - OutlinedTextField( - value = draft.url, - onValueChange = { model.mcpDraft = draft.copy(url = it) }, - label = { Text("HTTP URL") }, - placeholder = { Text("https://") }, - 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.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, - horizontalArrangement = Arrangement.SpaceBetween, - ) { - Text("Enabled") - Switch( - checked = draft.enabled, - onCheckedChange = { model.mcpDraft = draft.copy(enabled = it) }, - ) - } - } - }, - confirmButton = { - Button( - onClick = { model.saveMCP() }, - enabled = !model.loading && !draft.saving, - ) { - Text("Save") - } - }, - dismissButton = { - TextButton( - onClick = { - model.errorText = "" - model.mcpDraft = null - }, - ) { - Text("Cancel") - } - }, - ) -} - @Composable @OptIn(ExperimentalMaterial3Api::class) fun SkillFormDialog( @@ -879,7 +569,3 @@ 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 deleted file mode 100644 index 9576a45..0000000 --- a/app/src/main/java/dev/crumble/android/ui/ProvidersScreen.kt +++ /dev/null @@ -1,358 +0,0 @@ -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/SecretForms.kt b/app/src/main/java/dev/crumble/android/ui/SecretForms.kt new file mode 100644 index 0000000..648e3e5 --- /dev/null +++ b/app/src/main/java/dev/crumble/android/ui/SecretForms.kt @@ -0,0 +1,291 @@ +package dev.crumble.android.ui + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +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.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.FilterChip +import androidx.compose.material3.MaterialTheme +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.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.font.FontFamily +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.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.ONE_PASSWORD +import dev.crumble.android.model.SecretDraft + +// 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") + +@Composable +private fun SecretNote(text: String) { + Text(text, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) +} + +/** A secret's value, or a password manager reference once one is connected. */ +@Composable +private fun SecretSourceField( + model: AppModel, + label: String, + draft: SecretDraft, + onChange: (SecretDraft) -> Unit, + valueDescription: String, + concealed: Boolean = true, + enabled: Boolean = true, +) { + val context = LocalContext.current + 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 = draft.manager?.let { REFERENCE_PLACEHOLDERS[it] }?.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 { openWebSettings(context, model, "password-managers") }, + ) + } + } + } +} + +@Composable +private fun SecretSheet( + noun: String, + reason: String?, + error: String, + ready: Boolean, + saving: Boolean, + onSubmit: () -> Unit, + onClose: () -> Unit, + content: @Composable () -> Unit, +) { + AlertDialog( + onDismissRequest = onClose, + title = { Text("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("Add") + } + } + }, + dismissButton = { TextButton(onClick = onClose) { Text("Cancel") } }, + ) +} + +@Composable +private fun NameAndHosts( + name: String, + hosts: String, + invalid: Boolean, + enabled: Boolean, + nameNote: String, + hostsPlaceholder: String, + hostsNote: String, + mono: Boolean, + onHosts: (String) -> Unit, +) { + OutlinedTextField( + value = name, + onValueChange = {}, + label = { Text("Name") }, + singleLine = true, + enabled = false, + 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", + reason = form.request.reason, + error = form.error, + ready = form.ready, + saving = form.saving, + onSubmit = { model.saveCredential() }, + onClose = { model.closeCredentialForm() }, + ) { + NameAndHosts( + name = form.name, + hosts = form.hosts, + invalid = form.nameInvalid, + enabled = !form.saving, + nameNote = "The environment variable coding jobs see.", + hostsPlaceholder = "api.example.com, *.example.com", + hostsNote = "The bot proposed these. The value goes only to them, so check they belong to the service.", + mono = true, + 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.", + enabled = !form.saving, + ) + } +} + +@Composable +fun LoginFormDialog(model: AppModel, form: LoginForm) { + val update = { next: LoginForm -> if (model.loginForm != null) model.loginForm = next } + SecretSheet( + noun = "Login", + reason = form.request.reason, + error = form.error, + ready = form.ready, + saving = form.saving, + onSubmit = { model.saveLogin() }, + onClose = { model.closeLoginForm() }, + ) { + NameAndHosts( + name = form.name, + hosts = form.hosts, + invalid = form.nameInvalid, + enabled = !form.saving, + nameNote = "How desktop jobs refer to it.", + hostsPlaceholder = "github.com, *.github.com", + hostsNote = "The bot proposed these. The login is filled only into https pages on them, so check they belong to the site.", + mono = false, + 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.", + 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.", + 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.", + enabled = !form.saving, + ) + } + } + } +} diff --git a/app/src/main/java/dev/crumble/android/ui/SecretsScreen.kt b/app/src/main/java/dev/crumble/android/ui/SecretsScreen.kt deleted file mode 100644 index 61d1f3b..0000000 --- a/app/src/main/java/dev/crumble/android/ui/SecretsScreen.kt +++ /dev/null @@ -1,723 +0,0 @@ -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 b289eca..11d2559 100644 --- a/app/src/main/java/dev/crumble/android/ui/SettingsSheet.kt +++ b/app/src/main/java/dev/crumble/android/ui/SettingsSheet.kt @@ -1,7 +1,10 @@ package dev.crumble.android.ui +import androidx.compose.material3.AlertDialog +import androidx.compose.ui.text.font.FontWeight import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.OpenInNew import androidx.compose.material3.SingleChoiceSegmentedButtonRow import androidx.compose.material3.SegmentedButtonDefaults import androidx.compose.material3.SegmentedButton @@ -20,7 +23,6 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme @@ -32,7 +34,6 @@ import androidx.compose.runtime.Composable 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 @@ -121,26 +122,15 @@ private fun ThemeSection(model: AppModel) { 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 context = LocalContext.current val tones = Tone.entries Column( modifier = Modifier @@ -157,8 +147,7 @@ fun SettingsPanel(model: AppModel) { tint = MaterialTheme.colorScheme.onSurfaceVariant, ) } - SETTINGS_GROUPS.forEachIndexed { groupIndex, group -> - val pages = group.filter { it != Route.Users || model.isAdmin == true } + SETTINGS_GROUPS.forEachIndexed { groupIndex, pages -> Column(verticalArrangement = Arrangement.spacedBy(ROW_GAP)) { pages.forEachIndexed { index, page -> GroupedRow( @@ -171,6 +160,15 @@ fun SettingsPanel(model: AppModel) { } } } + if (model.token.isNotEmpty()) { + GroupedRow( + title = "Server settings", + subtitle = "Opens in the browser", + shape = groupedShape(0, 1), + onClick = { openWebSettings(context, model) }, + leading = { IconTile(Icons.AutoMirrored.Filled.OpenInNew, tones[SETTINGS_GROUPS.size % tones.size]) }, + ) + } } } diff --git a/app/src/test/java/dev/crumble/android/AccountTests.kt b/app/src/test/java/dev/crumble/android/AccountTests.kt new file mode 100644 index 0000000..4f08c39 --- /dev/null +++ b/app/src/test/java/dev/crumble/android/AccountTests.kt @@ -0,0 +1,213 @@ +package dev.crumble.android + +import dev.crumble.android.model.AccountMode +import dev.crumble.android.model.AppModel +import dev.crumble.android.model.canCreateAccount +import dev.crumble.android.model.inviteToken +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 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.assertTrue +import org.junit.Test + +private const val SERVER = "https://crumble.example" +private const val ME = "user-me" +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 class AccountTransport : 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 sessionJson() = """{"session":{"id":"s","userId":"$ME"},"user":{"id":"$ME","role":"user"}}""" + +@OptIn(ExperimentalCoroutinesApi::class) +class AccountTests { + private fun scripted() = AccountTransport().apply { + answer(SESSION, body = sessionJson()) + answer("GET /v1/agents", body = "[]") + answer("GET /v1/group-chats", body = """{"groups":[]}""") + answer("GET /v1/password-managers", body = """{"passwordManagers":[]}""") + } + + private fun TestScope.signedOut(transport: AccountTransport, 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 + } + + // 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!!)) + } +} diff --git a/app/src/test/java/dev/crumble/android/AdminTests.kt b/app/src/test/java/dev/crumble/android/AdminTests.kt deleted file mode 100644 index 4f068ca..0000000 --- a/app/src/test/java/dev/crumble/android/AdminTests.kt +++ /dev/null @@ -1,619 +0,0 @@ -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/BotParityTests.kt b/app/src/test/java/dev/crumble/android/BotParityTests.kt index 14370c2..061414c 100644 --- a/app/src/test/java/dev/crumble/android/BotParityTests.kt +++ b/app/src/test/java/dev/crumble/android/BotParityTests.kt @@ -156,7 +156,7 @@ class BotParityTests { 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("Add an API key or sign in for this provider in the web app 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)) } diff --git a/app/src/test/java/dev/crumble/android/ConnectionSafetyTests.kt b/app/src/test/java/dev/crumble/android/ConnectionSafetyTests.kt index 90b9a19..7c18565 100644 --- a/app/src/test/java/dev/crumble/android/ConnectionSafetyTests.kt +++ b/app/src/test/java/dev/crumble/android/ConnectionSafetyTests.kt @@ -1,8 +1,8 @@ package dev.crumble.android +import dev.crumble.android.generated.CredentialRequest 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 @@ -32,12 +32,7 @@ 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 val CREDENTIAL_REQUEST = CredentialRequest("ACME_TOKEN", listOf("api.acme.com"), "Deploys", "t1") private class SafetyTransport : HttpTransport { val requests = mutableListOf() @@ -84,15 +79,8 @@ class ConnectionSafetyTests { 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) @@ -132,8 +120,8 @@ class ConnectionSafetyTests { val model = modelWith(SafetyTransport(), backgroundScope) model.selectAgent("a1") runCurrent() - model.openPanel(Route.Credentials) - model.openCredentialForm("a1") + model.openPanel(Route.Avatars) + model.openCredentialForm("a1", CREDENTIAL_REQUEST) assertNotNull(model.credentialForm) model.selectAgent("a1") @@ -147,7 +135,7 @@ class ConnectionSafetyTests { val model = modelWith(SafetyTransport(), backgroundScope) model.selectAgent("a1") runCurrent() - model.openCredentialForm("a1") + model.openCredentialForm("a1", CREDENTIAL_REQUEST) model.selectAgent("a1") @@ -189,132 +177,6 @@ class ConnectionSafetyTests { 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( diff --git a/app/src/test/java/dev/crumble/android/ConnectionsTests.kt b/app/src/test/java/dev/crumble/android/ConnectionsTests.kt deleted file mode 100644 index d7702ec..0000000 --- a/app/src/test/java/dev/crumble/android/ConnectionsTests.kt +++ /dev/null @@ -1,865 +0,0 @@ -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/CrumbleTests.kt b/app/src/test/java/dev/crumble/android/CrumbleTests.kt index a616628..3de4a1c 100644 --- a/app/src/test/java/dev/crumble/android/CrumbleTests.kt +++ b/app/src/test/java/dev/crumble/android/CrumbleTests.kt @@ -44,9 +44,7 @@ import dev.crumble.android.network.HttpStreamResponse import dev.crumble.android.network.HttpTransport import dev.crumble.android.network.SSEClosedError 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.MarkdownBlock import java.io.ByteArrayInputStream import java.nio.charset.StandardCharsets @@ -347,25 +345,6 @@ class CrumbleTests { assertTrue(model.errorText.contains("busy")) } - @Test - fun mcpSignInRoundTrip() = runTest { - 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,"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 "" - } - } - val start = client.startMCPSignIn("s1", redirectURI = AppModel.oauthRedirectURI) - assertTrue(start.authorizationUrl?.startsWith("https://auth.example.com/") == true) - val sent = String(stub.requests.last().body ?: ByteArray(0), StandardCharsets.UTF_8) - assertTrue(sent.contains(AppModel.oauthRedirectURI)) - val server = client.finishMCPSignIn("s1", code = "c", state = "x", iss = "https://auth.example.com") - assertEquals("oauth", server.auth) - val finished = String(stub.requests.last().body ?: ByteArray(0), StandardCharsets.UTF_8) - assertTrue(finished.contains(""""iss":"https://auth.example.com"""")) - } - @Test fun errorsCarryStatusAndBody() = runTest { val (client, _) = StubTransport.client { 401 to "bad token" } @@ -1016,29 +995,6 @@ class CrumbleTests { assertEquals("done", retained.communication?.status) } - @Test - fun signInCallbacksCarryACodeOrAReason() { - val ok = oauthResult("${AppModel.oauthRedirectURI}?code=abc&state=xyz") - assertEquals("abc", ok.code) - assertEquals("xyz", ok.state) - assertNull(ok.iss) - - val issued = oauthResult("${AppModel.oauthRedirectURI}?code=abc&state=xyz&iss=https%3A%2F%2Fexecutor.sh%2Fapi%2Fauth") - assertEquals("https://executor.sh/api/auth", issued.iss) - - try { - oauthResult("${AppModel.oauthRedirectURI}?error=access_denied&error_description=User%20declined") - fail("expected SignInError") - } catch (_: SignInError) { - } - - try { - oauthResult("${AppModel.oauthRedirectURI}") - fail("expected SignInError") - } catch (_: SignInError) { - } - } - @Test fun markdownSplitsBlocks() { val blocks = MarkdownBlock.parse("Two meetings:\n\n- 09:00 Design\n- 14:30 Call\n\n```\ncode\n```") diff --git a/app/src/test/java/dev/crumble/android/DefectRegressionTests.kt b/app/src/test/java/dev/crumble/android/DefectRegressionTests.kt index a60ab13..f477ce1 100644 --- a/app/src/test/java/dev/crumble/android/DefectRegressionTests.kt +++ b/app/src/test/java/dev/crumble/android/DefectRegressionTests.kt @@ -8,13 +8,11 @@ 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 @@ -287,23 +285,6 @@ class DefectRegressionTests { 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 @@ -353,26 +334,6 @@ class DefectRegressionTests { 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 @@ -439,18 +400,6 @@ class DefectRegressionTests { 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 diff --git a/app/src/test/java/dev/crumble/android/DraftsAndReadsTests.kt b/app/src/test/java/dev/crumble/android/DraftsAndReadsTests.kt index fdf715a..79aeb7e 100644 --- a/app/src/test/java/dev/crumble/android/DraftsAndReadsTests.kt +++ b/app/src/test/java/dev/crumble/android/DraftsAndReadsTests.kt @@ -4,8 +4,6 @@ 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 @@ -37,7 +35,6 @@ 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 @@ -519,24 +516,6 @@ class DraftsAndReadsTests { 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 { @@ -586,25 +565,6 @@ class DraftsAndReadsTests { 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 diff --git a/app/src/test/java/dev/crumble/android/GeneralSettingsTests.kt b/app/src/test/java/dev/crumble/android/GeneralSettingsTests.kt index 1997926..9ed535d 100644 --- a/app/src/test/java/dev/crumble/android/GeneralSettingsTests.kt +++ b/app/src/test/java/dev/crumble/android/GeneralSettingsTests.kt @@ -339,8 +339,8 @@ class CommandPaletteTests { 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 sections(agents: List = bots, theme: ThemeChoice = ThemeChoice.System) = + paletteSections(agents, groups, theme) private fun titles(list: List, heading: String) = list.firstOrNull { it.heading == heading }?.items?.map { it.title }.orEmpty() @@ -367,12 +367,6 @@ class CommandPaletteTests { 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")) @@ -391,7 +385,7 @@ class CommandPaletteTests { @Test fun lettersInOrderMatchIgnoringCase() { - assertEquals(listOf("Providers"), titles(searchPalette(sections(), "PRVD"), "Settings")) + assertEquals(listOf("Skills"), titles(searchPalette(sections(), "SKLS"), "Settings")) assertTrue(searchPalette(sections(), "zzzz").isEmpty()) } @@ -399,9 +393,9 @@ class CommandPaletteTests { fun theBestMatchLeads() { val found = searchPalette(sections(), "memory") assertEquals("Memory", found.first().items.first().title) - val ranked = searchPalette(sections(), "web") + val ranked = searchPalette(sections(), "avatars") assertEquals(listOf("Settings"), ranked.map { it.heading }.take(1)) - assertEquals("Web search", ranked.first().items.first().title) + assertEquals("Avatars", ranked.first().items.first().title) } @Test @@ -409,7 +403,7 @@ class CommandPaletteTests { 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()) + assertEquals("Skills", titles(searchPalette(sections(), "settings sk"), "Settings").first()) } } diff --git a/app/src/test/java/dev/crumble/android/NavigationTests.kt b/app/src/test/java/dev/crumble/android/NavigationTests.kt index e3e114f..809ae60 100644 --- a/app/src/test/java/dev/crumble/android/NavigationTests.kt +++ b/app/src/test/java/dev/crumble/android/NavigationTests.kt @@ -18,7 +18,6 @@ class NavigationTests { @Test fun settingsPagesReturnToTheSettingsList() { SETTINGS_PAGES.forEach { assertEquals(Route.Settings, it.parent) } - assertEquals(Route.MessageGateways, Route.MessageGateway("telegram").parent) } @Test diff --git a/app/src/test/java/dev/crumble/android/SecretsTests.kt b/app/src/test/java/dev/crumble/android/SecretsTests.kt index 40132a1..5f9192d 100644 --- a/app/src/test/java/dev/crumble/android/SecretsTests.kt +++ b/app/src/test/java/dev/crumble/android/SecretsTests.kt @@ -3,15 +3,8 @@ 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 @@ -21,30 +14,18 @@ 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 @@ -63,7 +44,6 @@ 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 @@ -129,32 +109,19 @@ private fun loginJson(name: String = "github") = 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 fun managerJson() = """{"id":"1password","name":"1Password","connected":true,"connectedAt":"t","usedBy":[]}""" 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 val credentialRequest = CredentialRequest("ACME_TOKEN", listOf("api.acme.com"), "Deploys", "t1") + +private val loginRequest = LoginRequest("github", listOf("github.com"), "Sign in", false, "t1") 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)) @@ -176,12 +143,11 @@ class SecretsTests { 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) + model.openCredentialForm("a1", credentialRequest) + model.credentialForm = model.credentialForm!!.copy(hosts = "API.acme.com, *.acme.com", secret = value) } @Test @@ -193,91 +159,44 @@ class SecretsTests { @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)) { + val form = CredentialForm(owner = "a1", request = credentialRequest, name = "A", hosts = "a.io", secret = draft) + val login = LoginForm(owner = "a1", request = loginRequest, password = draft) + for (text in listOf(draft, form, login, 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()) + val form = credentialForm("a1", credentialRequest) 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) + val form = credentialForm("a1", request) assertEquals("a1", form.owner) - assertNull(form.botID) - assertTrue(form.locked) + assertEquals("ACME_TOKEN", form.name) 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")) + val form = loginForm("a1", 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 ") + val form = loginForm("a1", loginRequest).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) @@ -307,38 +226,6 @@ class SecretsTests { 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")) @@ -402,38 +289,12 @@ class SecretsTests { 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) @@ -461,13 +322,13 @@ class SecretsTests { val gate = CompletableDeferred().also { transport.held[PUT_CREDENTIAL] = it } val scope = TestScope(StandardTestDispatcher(testScheduler)) val model = modelWith(transport, scope) - model.route = Route.Credentials + model.route = Route.Memory model.botCredentials = mapOf("a1" to Credentials(emptyList(), emptyList())) newCredential(model) model.saveCredential() testScheduler.runCurrent() - model.openPanel(Route.Logins) + model.openPanel(Route.Avatars) testScheduler.runCurrent() gate.complete(Unit) testScheduler.runCurrent() @@ -534,7 +395,7 @@ class SecretsTests { val request = model.botCredentials["a1"]!!.requests.single() assertTrue(credentialReadKey(credentialMessage().credentialRequest!!) in model.freshSecretRequests) - model.openCredentialForm("a1", request = request) + model.openCredentialForm("a1", request) model.credentialForm = model.credentialForm!!.copy(secret = SecretDraft(text = SECRET)) model.saveCredential() testScheduler.runCurrent() @@ -563,7 +424,7 @@ class SecretsTests { model.applySnapshot(ChatSnapshot(agentId = "a1", messages = listOf(credentialMessage()))) testScheduler.runCurrent() val request = model.botCredentials["a1"]!!.requests.single() - model.openCredentialForm("a1", request = request) + model.openCredentialForm("a1", request) model.credentialForm = model.credentialForm!!.copy(secret = SecretDraft(text = SECRET)) model.saveCredential() @@ -613,7 +474,7 @@ class SecretsTests { val scope = TestScope(StandardTestDispatcher(testScheduler)) val model = modelWith(transport, scope) model.selectAgent("a1") - model.openCredentialForm("a1") + model.openCredentialForm("a1", credentialRequest) model.selectAgent("a1") assertNotNull(model.credentialForm) model.selectAgent("a2") @@ -632,12 +493,11 @@ class SecretsTests { testScheduler.runCurrent() val request = model.botCredentials["a1"]!!.requests.single() - model.openCredentialForm("a1", request = request) + model.openCredentialForm("a1", request) val form = model.credentialForm!! - assertEquals("a1", form.botID) + assertEquals("a1", form.owner) 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() @@ -663,7 +523,7 @@ class SecretsTests { testScheduler.runCurrent() val request = model.botCredentials["a1"]!!.requests.single() - model.openCredentialForm("a1", request = request) + model.openCredentialForm("a1", request) val form = model.credentialForm!! model.credentialForm = form.copy(secret = SecretDraft(manager = "onepassword", text = "op://vault/item")) model.saveCredential() @@ -684,14 +544,10 @@ class SecretsTests { 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) + model.openLoginForm("a1", loginRequest) + model.navigate(Route.Avatars) assertNull(model.credentialForm) assertNull(model.loginForm) - assertNull(model.providerKeyForm) - assertNull(model.tokenForm) } @Test @@ -702,7 +558,7 @@ class SecretsTests { val scope = TestScope(StandardTestDispatcher(testScheduler)) val model = modelWith(transport, scope) model.botLogins = mapOf("a1" to Logins(emptyList(), emptyList())) - model.openLoginForm("a1") + model.openLoginForm("a1", loginRequest) model.loginForm = model.loginForm!!.copy(name = "github", hosts = "github.com", username = SecretDraft(text = "kev"), password = SecretDraft(text = SECRET)) model.saveLogin() @@ -728,7 +584,7 @@ class SecretsTests { val scope = TestScope(StandardTestDispatcher(testScheduler)) val model = modelWith(transport, scope) model.botLogins = mapOf("a1" to Logins(emptyList(), emptyList())) - model.openLoginForm("a1") + model.openLoginForm("a1", loginRequest) model.loginForm = model.loginForm!!.copy(name = "github", hosts = "github.com", mode = LoginMode.item, item = "op://vault/item") model.saveLogin() @@ -738,365 +594,4 @@ class SecretsTests { 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()) - } }