From 08eadf7af8e517f0d338928cd1c7b52aac95fd48 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:27:26 -0500 Subject: [PATCH] feat(agent): OpenCode takes keys for Ollama Cloud and other providers, or any OpenAI-compatible server (#2741) * feat(agent): OpenCode takes keys for Ollama Cloud and other providers, or any OpenAI-compatible server * fix(agent): write OpenCode config atomically, check auth first, Done hides the keyboard * fix(agent): serialize OpenCode key saves and removals * fix(agent): restore the OpenCode config atomically when the key write fails * fix(agent): report a failed OpenCode config rollback * fix(agent): delete the OpenCode config with deleteIfExists, lead with the rollback warning --- .../droiddeck/launcher/agent/AgentHarness.kt | 135 +++++++++++++++--- .../droiddeck/launcher/agent/AgentSetup.kt | 52 +++++-- .../com/droiddeck/launcher/ui/AgentPanels.kt | 32 +++-- .../droiddeck/launcher/ui/AgentSetupView.kt | 81 +++++++---- .../droiddeck/launcher/ui/FrontEndScreen.kt | 4 +- app/src/main/res/values/strings.xml | 9 +- .../droiddeck/launcher/agent/OpenCodeTest.kt | 108 ++++++++++++-- 7 files changed, 340 insertions(+), 81 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentHarness.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentHarness.kt index 669a1c5503..1db8009699 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentHarness.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentHarness.kt @@ -20,13 +20,18 @@ interface AgentHarness { /** A guest command that signs in through $BROWSER. */ val signIn: List /** - * Where the user makes an API key, for a CLI whose own sign-in is a terminal prompt: [signIn] - * then only opens this page, and the key is pasted into DroidDeck and saved by [saveKey]. + * APIs the CLI reaches with a key pasted into DroidDeck, for a CLI whose own sign-in is a terminal + * prompt; empty when it signs in through [signIn]. */ - val keyPage: String? get() = null - /** Whether a key from [keyPage] is saved under [rootfs]. */ - fun hasKey(rootfs: File): Boolean = false - fun saveKey(rootfs: File, key: String) {} + val providers: List get() = emptyList() + /** Ids of the [providers] with a key saved under [rootfs]. */ + fun keys(rootfs: File): Set = emptySet() + /** + * Saves [key] for [provider]. A [Provider.custom] one also takes the [endpoint] it is served from, and + * [get] fetches a URL from the userland, with the key as a bearer token when it is not null. + */ + fun saveKey(rootfs: File, provider: Provider, key: String, endpoint: String? = null, get: (String, String?) -> String = { url, _ -> error("Cannot reach $url") }) {} + fun removeKey(rootfs: File, provider: Provider) {} /** Whether the CLI has models that need no account; [useFree] then counts as signed in. */ val free: Boolean get() = false fun useFree(rootfs: File) {} @@ -57,6 +62,9 @@ interface AgentHarness { data class Model(val id: String, val label: String) + /** An API reached with a key; [keyPage] is where the key is made, and a [custom] one is any OpenAI-compatible server. */ + data class Provider(val id: String, val name: String, val keyPage: String? = null, val custom: Boolean = false) + data class Options(val model: String? = null, val plan: Boolean = false, val brief: String? = null, val effort: String? = null) companion object { @@ -412,31 +420,117 @@ object OpenCode : AgentHarness { override val instructions = "root/.config/opencode/AGENTS.md" override val install = "curl -fsSL https://opencode.ai/install | bash -s -- --no-modify-path" private const val AUTH = "root/.local/share/opencode/auth.json" + private const val CONFIG = "root/.config/opencode/opencode.json" private const val FREE = "root/.config/opencode/.droiddeck-free" private const val MODELS = "root/.cache/droiddeck/opencode-models" + /** The provider id DroidDeck gives a server the user names, in opencode's config and auth. */ + private const val CUSTOM = "droiddeck" // `opencode models` lists only what the saved keys reach, so the check that runs it keeps the model list current. override val signedIn = listOf("sh", "-c", "mkdir -p /${MODELS.substringBeforeLast('/')}; $binary models --verbose > /$MODELS.$$ 2>/dev/null && mv -f /$MODELS.$$ /$MODELS; rm -f /$MODELS.$$; " + - "grep -q '\"type\"' /$AUTH 2>/dev/null || [ -e /$FREE ]") - override val keyPage = "https://opencode.ai/auth" - override val signIn = listOf("/root/.local/bin/android-open", keyPage) + "grep -q '\"type\"' /$AUTH 2>/dev/null || [ -e /$FREE ] || grep -q '\"$CUSTOM\"' /$CONFIG 2>/dev/null") + // Ids are opencode's own (models.dev), so a saved key is what `opencode auth login` would save for that provider. + override val providers = listOf( + AgentHarness.Provider("opencode", "OpenCode Zen", "https://opencode.ai/auth"), + AgentHarness.Provider("ollama-cloud", "Ollama Cloud", "https://ollama.com/settings/keys"), + AgentHarness.Provider("openrouter", "OpenRouter", "https://openrouter.ai/settings/keys"), + AgentHarness.Provider("openai", "OpenAI", "https://platform.openai.com/api-keys"), + AgentHarness.Provider("anthropic", "Anthropic", "https://console.anthropic.com/settings/keys"), + AgentHarness.Provider("google", "Gemini", "https://aistudio.google.com/apikey"), + AgentHarness.Provider(CUSTOM, "Other server", custom = true), + ) + override val signIn = listOf("/root/.local/bin/android-open", providers.first().keyPage!!) override val free = true override val plans = true override val efforts = listOf("low", "medium", "high") - override fun hasKey(rootfs: File) = runCatching { JSONObject(File(rootfs, AUTH).readText()).has("opencode") }.getOrDefault(false) + override fun keys(rootfs: File): Set { + val auth = runCatching { JSONObject(File(rootfs, AUTH).readText()) }.getOrNull() + val custom = runCatching { JSONObject(File(rootfs, CONFIG).readText()).optJSONObject("provider")?.has(CUSTOM) }.getOrNull() == true + return providers.filter { auth?.has(it.id) == true || (it.custom && custom) }.map { it.id }.toSet() + } - /** The key opencode's own `auth login` would save for OpenCode Zen. */ - override fun saveKey(rootfs: File, key: String) { - val file = File(rootfs, AUTH) - // An auth.json that cannot be read holds other providers' sign-ins too, so it is never replaced. - val auth = if (file.exists()) JSONObject(file.readText()) else JSONObject() - auth.put("opencode", JSONObject().put("type", "api").put("key", key.trim())) + /** + * Saves the key as opencode's own `auth login` would. A custom server also gets a provider in + * opencode's config with the models its `/models` lists, since opencode does not list them itself. + */ + override fun saveKey(rootfs: File, provider: AgentHarness.Provider, key: String, endpoint: String?, get: (String, String?) -> String) { + val token = key.trim().takeIf { it.isNotEmpty() } + // Both files are read before either is written, so one that cannot be read changes nothing. + val authFile = File(rootfs, AUTH) + val auth = readJson(authFile) + if (token != null) auth.put(provider.id, JSONObject().put("type", "api").put("key", token)) else auth.remove(provider.id) + if (!provider.custom) return writeJson(authFile, auth, private = true) + val base = endpoint(endpoint ?: "") + val configFile = File(rootfs, CONFIG) + val before = configFile.takeIf { it.exists() }?.readText() + val config = readJson(configFile) + val models = modelIds(get("$base/models", token)) + check(models.isNotEmpty()) { "No models at $base" } + if (!config.has("\$schema")) config.put("\$schema", "https://opencode.ai/config.json") + val all = config.optJSONObject("provider") ?: JSONObject().also { config.put("provider", it) } + all.put(CUSTOM, JSONObject() + .put("npm", "@ai-sdk/openai-compatible") + .put("name", runCatching { java.net.URI(base).host }.getOrNull() ?: provider.name) + .put("options", JSONObject().put("baseURL", base)) + .put("models", JSONObject().apply { models.forEach { put(it, JSONObject().put("name", it)) } })) + writeJson(configFile, config) + try { + writeJson(authFile, auth, private = true) + } catch (e: Exception) { + val undone = runCatching { + if (before != null) writeFile(configFile, before) else java.nio.file.Files.deleteIfExists(configFile.toPath()) + } + // First, since the setup row shows two lines of the message. + undone.exceptionOrNull()?.let { throw IllegalStateException("The server config could not be put back (${it.message}): ${e.message}", e) } + throw e + } + } + + override fun removeKey(rootfs: File, provider: AgentHarness.Provider) { + if (File(rootfs, AUTH).exists()) editJson(File(rootfs, AUTH), private = true) { it.remove(provider.id) } + if (provider.custom && File(rootfs, CONFIG).exists()) editJson(File(rootfs, CONFIG)) { it.optJSONObject("provider")?.remove(CUSTOM) } + } + + /** A server address as typed, made into the OpenAI-compatible base URL opencode calls. */ + @VisibleForTesting + internal fun endpoint(typed: String): String { + val url = typed.trim().trimEnd('/').let { if ("://" in it) it else "http://$it" } + require(url.substringAfter("://").isNotEmpty()) { "No server address" } + return if (url.substringAfter("://").contains('/')) url else "$url/v1" + } + + @VisibleForTesting + internal fun modelIds(body: String): List { + // The userland can print its own warnings ahead of the response. + val json = body.substring(body.indexOf('{').coerceAtLeast(0), body.lastIndexOf('}') + 1) + val data = runCatching { JSONObject(json).optJSONArray("data") }.getOrNull() ?: return emptyList() + return (0 until data.length()).mapNotNull { data.optJSONObject(it)?.optString("id")?.takeIf { id -> id.isNotEmpty() } }.distinct() + } + + // A file that cannot be read holds the user's other providers too, so it is never replaced. + private fun readJson(file: File) = if (file.exists()) JSONObject(file.readText()) else JSONObject() + + private fun editJson(file: File, private: Boolean = false, edit: (JSONObject) -> Unit) = + writeJson(file, readJson(file).also(edit), private) + + /** Writes beside [file] and moves it into place, so a write that stops partway leaves the old file. */ + private fun writeJson(file: File, json: JSONObject, private: Boolean = false) = writeFile(file, json.toString(2) + "\n", private) + + private fun writeFile(file: File, text: String, private: Boolean = false) { file.parentFile?.mkdirs() - file.writeText(auth.toString(2) + "\n") - file.setReadable(false, false) - file.setReadable(true, true) + val temp = File(file.parentFile, ".${file.name}.tmp") + try { + temp.writeText(text) + if (private) { + temp.setReadable(false, false) + temp.setReadable(true, true) + } + java.nio.file.Files.move(temp.toPath(), file.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING, java.nio.file.StandardCopyOption.ATOMIC_MOVE) + } finally { + temp.delete() + } } override fun useFree(rootfs: File) { @@ -473,7 +567,8 @@ object OpenCode : AgentHarness { runCatching { JSONObject(json.toString()) }.getOrNull()?.takeIf { it.optString("status") != "deprecated" }?.let { o -> val provider = o.optString("providerID") val label = o.optString("name").ifEmpty { current } - models += AgentHarness.Model(current, if (provider.isEmpty() || provider == "opencode") label else "$label · $provider") + val source = if (provider == "opencode" || provider == CUSTOM) "" else providers.firstOrNull { it.id == provider }?.name ?: provider + models += AgentHarness.Model(current, if (source.isEmpty()) label else "$label · $source") o.optJSONObject("limit")?.optLong("context")?.takeIf { it > 0 }?.let { windows[current] = it } } id = null diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt index a4107fa287..e917e36605 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt @@ -27,25 +27,52 @@ object AgentSetup { val detail = mutableStateMapOf() var runtimeInstalled by mutableStateOf(true) private set - /** The harness has a key from its [AgentHarness.keyPage] saved; signed in without one means its free models. */ - var keySaved by mutableStateOf(false) + /** Ids of the harness's [AgentHarness.providers] with a key saved; signed in without one means its free models. */ + var keys by mutableStateOf(emptySet()) private set + /** The provider and custom server picked in the key field, kept while a save is checked. */ + var provider by mutableStateOf(null) + var server by mutableStateOf("") /** Saves a pasted key for a harness that signs in with one, then checks the sign-in again. */ - fun saveKey(context: Context, key: String) = signInLocally(context) { harness, root -> harness.saveKey(root, key) } + fun saveKey(context: Context, provider: AgentHarness.Provider, key: String, endpoint: String? = null) = signInLocally(context) { harness, root -> + harness.saveKey(root, provider, key, endpoint) { url, token -> fetch(context.applicationContext, url, token) } + } + + fun removeKey(context: Context, provider: AgentHarness.Provider) = signInLocally(context) { harness, root -> harness.removeKey(root, provider) } + + /** A GET from the userland, which reaches the LAN servers the app's own cleartext policy does not. */ + private fun fetch(app: Context, url: String, token: String?): String { + // The key goes in on stdin, so it is never in a command line. + val process = AgentHost.guest(app, listOf("curl", "-fsSL", "--max-time", "20", "-H", "@-", url), connectAdb = false).start() + process.outputStream.bufferedWriter().use { if (token != null) it.write("Authorization: Bearer $token\n") } + val output = process.inputStream.bufferedReader().readText() + check(process.waitFor(30, TimeUnit.SECONDS) && process.exitValue() == 0) { output.trim().lines().lastOrNull()?.takeIf { it.isNotEmpty() } ?: "Cannot reach $url" } + return output + } fun useFree(context: Context) = signInLocally(context) { harness, root -> harness.useFree(root) } + private val signInLock = Any() + private fun signInLocally(context: Context, write: (AgentHarness, File) -> Unit) { val app = context.applicationContext val harness = AgentHost.harness set(Step.SIGN_IN, Status.WORKING) Thread({ - val result = runCatching { write(harness, LinuxRuntime.rootDir(app)) } + // Each write reads the files the one before it left, including across a save's model request. + val result = synchronized(signInLock) { runCatching { write(harness, LinuxRuntime.rootDir(app)) } } main.post { - status[Step.SIGN_IN] = Status.UNKNOWN - result.exceptionOrNull()?.let { detail[Step.SIGN_IN] = it.message ?: "failed" } - check(app) + // A failure stays on the row with the key field open, since the next check would clear it. + val error = result.exceptionOrNull() + if (error != null) { + status[Step.SIGN_IN] = Status.FAILED + detail[Step.SIGN_IN] = error.message ?: "failed" + } else { + status[Step.SIGN_IN] = Status.UNKNOWN + detail.remove(Step.SIGN_IN) + check(app) + } } }, "agent-sign-in").start() } @@ -75,7 +102,7 @@ object AgentSetup { if (!runtimeInstalled) return AgentHost.refresh(app) val harness = AgentHost.harness - keySaved = harness.hasKey(LinuxRuntime.rootDir(app)) + keys = harness.keys(LinuxRuntime.rootDir(app)) val probes = mutableListOf>>() for (step in Step.entries) if (status[step] != Status.WORKING) { when (step) { @@ -102,10 +129,15 @@ object AgentSetup { fun runsAsRoot(step: Step) = step == Step.INSTALL /** Runs [step]'s action. [CONNECTION] is the app's own pairing flow, so the caller opens it. */ - fun run(context: Context, step: Step) { + fun run(context: Context, step: Step) = run(context, step, null) + + /** Opens the page where a provider's key is made, as the sign-in of a harness that takes pasted keys. */ + fun openKeyPage(context: Context, page: String) = run(context, Step.SIGN_IN, listOf("/root/.local/bin/android-open", page)) + + private fun run(context: Context, step: Step, override: List?) { val app = context.applicationContext val harness = AgentHost.harness - val command = when (step) { + val command = override ?: when (step) { Step.CONNECTION -> return Step.INSTALL -> { listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " + diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt index 3fc46e09b1..1029db97ea 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt @@ -50,6 +50,11 @@ import androidx.compose.material3.Icon import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.ime +import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.ui.text.input.KeyboardType import androidx.compose.runtime.rememberCoroutineScope import kotlinx.coroutines.launch import com.droiddeck.launcher.agent.AgentTools @@ -416,14 +421,23 @@ private fun ToolsRow(title: String, detail: String, action: @Composable () -> Un } @Composable +@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) internal fun ToolsField(value: String, onValue: (String) -> Unit, hint: String, tag: String) { - val colors = MaterialTheme.colorScheme - val pal = LocalPalette.current - Box(Modifier.fillMaxWidth().clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 12.dp, vertical = 10.dp)) { - if (value.isEmpty()) Text(hint, fontSize = 14.sp, color = pal.onSurfaceVariant, maxLines = 1) - BasicTextField( - value, onValue, singleLine = true, textStyle = TextStyle(fontSize = 14.sp, fontFamily = FontFamily.Monospace, color = colors.onSurface), - cursorBrush = SolidColor(pal.primary), modifier = Modifier.fillMaxWidth().testTag(tag), - ) - } + // The launcher's pane focus group sends a Compose text field's focus back to the last tile it remembers, + // so these fields use the EditText the rest of the launcher types into. + val view = remember { androidx.compose.foundation.relocation.BringIntoViewRequester() } + var focused by remember { mutableStateOf(false) } + val window = androidx.compose.ui.platform.LocalView.current + // An EditText's focus does not scroll its Compose parent, so the field follows the keyboard as it opens. + val keyboard = WindowInsets.ime.getBottom(androidx.compose.ui.platform.LocalDensity.current) + LaunchedEffect(focused, keyboard) { if (focused) view.bringIntoView() } + AdbTextField( + value = value, onValueChange = onValue, label = hint, keyboardType = KeyboardType.Text, imeAction = ImeAction.Done, + modifier = Modifier.bringIntoViewRequester(view).testTag(tag), placeholder = hint, compact = true, showLabel = false, + onFocusChange = { focused = it }, + onDone = { + (window.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager) + ?.hideSoftInputFromWindow(window.windowToken, 0) + }, + ) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt index 653e8eedb6..00d7880937 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt @@ -4,6 +4,8 @@ import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding @@ -97,21 +99,21 @@ internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) { steps.forEachIndexed { index, step -> val status = AgentSetup.status[step] ?: Status.UNKNOWN val harness = AgentHost.harness - // A harness that signs in with a pasted key: the sign-in opens its key page and this field takes the key. - val keyed = step == Step.SIGN_IN && harness.keyPage != null + // A harness that signs in with pasted keys: this row picks the provider and takes its key. + val keyed = step == Step.SIGN_IN && harness.providers.isNotEmpty() var keyOpen by rememberSaveable(harness.id) { mutableStateOf(false) } val (title, hint) = labels(step, harness.name, keyed) val lab = AgentHost.lab?.takeIf { it.prepare && it.running } val detail = when { step == Step.PREPARE && lab != null -> stringResource(R.string.agent_prepare_progress, lab.permille / 10, clock(lab.etaSeconds.toLong().coerceAtLeast(0))) - keyed && status == Status.DONE && !AgentSetup.keySaved -> stringResource(R.string.agent_step_free_models) + keyed && status == Status.DONE && AgentSetup.detail[step] == null -> + harness.providers.filter { it.id in AgentSetup.keys }.joinToString(" · ") { it.name }.ifEmpty { stringResource(R.string.agent_step_free_models) } else -> AgentSetup.detail[step] ?: hint } // Shown while the sign-in is pending, so it is still there after a trip to the browser for the key. val pending = (status == Status.TODO || status == Status.FAILED) && AgentSetup.status[Step.INSTALL] == Status.DONE val showKey = keyed && (keyOpen || pending) && status != Status.WORKING - var key by remember(harness.id) { mutableStateOf("") } CheckRow( when (status) { Status.DONE -> CheckState.OK @@ -122,33 +124,17 @@ internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) { ) { val blocked = (step in setOf(Step.SIGN_IN, Step.GITHUB, Step.BUILD_TOOLS) && AgentSetup.status[Step.INSTALL] != Status.DONE) || (step == Step.PREPARE && AgentSetup.status[Step.BUILD_TOOLS] != Status.DONE) - val openKey = { - keyOpen = true - AgentSetup.run(context, step) - } - if ((status == Status.TODO || status == Status.FAILED) && !blocked) { + if (keyed) { + if (pending && harness.free) SecondaryButton(stringResource(R.string.agent_action_free), compact = true) { AgentSetup.useFree(context) } + else if (status == Status.DONE) SecondaryButton(stringResource(if (keyOpen) R.string.common_hide else R.string.agent_action_add_key), compact = true) { keyOpen = !keyOpen } + } else if ((status == Status.TODO || status == Status.FAILED) && !blocked) { val label = stringResource(if (status == Status.FAILED) R.string.agent_setup_retry else action(step)) - val run = { if (step == Step.CONNECTION) pair(context) else if (keyed) openKey() else AgentSetup.run(context, step) } - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - if (keyed && harness.free) SecondaryButton(stringResource(R.string.agent_action_free), compact = true) { AgentSetup.useFree(context) } - if (step.required) PrimaryButton(label, compact = true, onClick = run) else SecondaryButton(label, compact = true, onClick = run) - } - } else if (keyed && status == Status.DONE && !AgentSetup.keySaved && !keyOpen) { - SecondaryButton(stringResource(R.string.agent_action_add_key), compact = true, onClick = openKey) + val run = { if (step == Step.CONNECTION) pair(context) else AgentSetup.run(context, step) } + if (step.required) PrimaryButton(label, compact = true, onClick = run) else SecondaryButton(label, compact = true, onClick = run) } } if (showKey) { - Row( - verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), - modifier = Modifier.fillMaxWidth().padding(start = 56.dp, end = 14.dp, bottom = 10.dp), - ) { - Box(Modifier.weight(1f)) { ToolsField(key, { key = it.trim() }, stringResource(R.string.agent_key_hint), "agent-key") } - PrimaryButton(stringResource(R.string.agent_key_save), enabled = key.isNotBlank(), compact = true) { - keyOpen = false - AgentSetup.saveKey(context, key) - key = "" - } - } + KeyPanel(harness) { keyOpen = false } if (index < steps.lastIndex) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) } } @@ -167,6 +153,47 @@ internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) { } } +/** Picks one of [harness]'s providers and saves its key, or a custom server's address. */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun KeyPanel(harness: AgentHarness, onSaved: () -> Unit) { + val context = LocalContext.current + val provider = harness.providers.firstOrNull { it.id == AgentSetup.provider } ?: harness.providers.first() + var key by remember(harness.id, provider.id) { mutableStateOf("") } + val saved = provider.id in AgentSetup.keys + Column( + verticalArrangement = Arrangement.spacedBy(10.dp), + modifier = Modifier.fillMaxWidth().padding(start = 56.dp, end = 14.dp, bottom = 12.dp), + ) { + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + for (option in harness.providers) { + val name = if (option.id in AgentSetup.keys) "${option.name} ✓" else option.name + if (option == provider) PrimaryButton(name, compact = true) {} else SecondaryButton(name, compact = true) { AgentSetup.provider = option.id } + } + } + if (provider.custom) ToolsField(AgentSetup.server, { AgentSetup.server = it.trim() }, stringResource(R.string.agent_key_server_hint), "agent-key-server") + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Box(Modifier.weight(1f)) { + ToolsField( + key, { key = it.trim() }, + if (provider.custom) stringResource(R.string.agent_key_optional_hint) else stringResource(R.string.agent_key_hint, provider.name), + "agent-key", + ) + } + provider.keyPage?.let { page -> SecondaryButton(stringResource(R.string.agent_key_get), compact = true) { AgentSetup.openKeyPage(context, page) } } + if (saved) SecondaryButton(stringResource(R.string.agent_storage_remove), compact = true) { AgentSetup.removeKey(context, provider) } + PrimaryButton( + stringResource(R.string.agent_key_save), compact = true, + enabled = if (provider.custom) AgentSetup.server.isNotBlank() else key.isNotBlank(), + ) { + AgentSetup.saveKey(context, provider, key, AgentSetup.server.takeIf { provider.custom }) + key = "" + onSaved() + } + } + } +} + @Composable private fun StorageCard() { val context = LocalContext.current diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index 4d252eff36..ef414c4eb0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -754,11 +754,11 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com onRailSelect(key) }, a) CompositionLocalProvider(LocalShowSection provides { key -> selected = key }) { - val agentKeyboardOpen = railSelection == "agent" && WindowInsets.ime.getBottom(androidx.compose.ui.platform.LocalDensity.current) > 0 + val agentKeyboardOpen = openTab == "agent" && WindowInsets.ime.getBottom(androidx.compose.ui.platform.LocalDensity.current) > 0 LauncherLayout( bottomNavigation && !s.dualScreen, pal.line, Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() } - .then(if (railSelection == "agent") Modifier.imePadding() else Modifier) + .then(if (openTab == "agent") Modifier.imePadding() else Modifier) .then(if (s.dualScreen) Modifier.onKeyEvent { event -> val step = dualPageStep(event.nativeKeyEvent) ?: return@onKeyEvent false if (event.type == KeyEventType.KeyDown && !processSettingsPageVisible) { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 23b321ba28..9ba04b9f41 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1372,10 +1372,13 @@ Sign in Free models Add key - Paste your API key from opencode.ai/auth + Paste your %1$s key + API key, if the server needs one + Server address, like 192.168.1.20:11434 + Get key Save - Free models, or a Zen key from opencode.ai/auth - Free models · add a Zen key for the rest + Free models, or a key from your provider + Free models · add a key for more PR #%1$d Not built for this copy of DroidDeck Updated %1$s diff --git a/app/src/test/java/com/droiddeck/launcher/agent/OpenCodeTest.kt b/app/src/test/java/com/droiddeck/launcher/agent/OpenCodeTest.kt index f34e2ad07c..d05f5f09f3 100644 --- a/app/src/test/java/com/droiddeck/launcher/agent/OpenCodeTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/agent/OpenCodeTest.kt @@ -120,18 +120,25 @@ class OpenCodeTest { assertNull(OpenCode.usage(root, session)) } + private fun provider(id: String) = OpenCode.providers.first { it.id == id } + @Test fun aSavedKeyKeepsOtherProvidersAndFreeIsItsOwnMark() { val root = Files.createTempDirectory("rootfs").toFile() - assertFalse(OpenCode.hasKey(root)) + assertEquals(emptySet(), OpenCode.keys(root)) val auth = File(root, "root/.local/share/opencode/auth.json").apply { parentFile!!.mkdirs() } - auth.writeText("""{"openai":{"type":"oauth","refresh":"r"}}""") - assertFalse(OpenCode.hasKey(root)) - OpenCode.saveKey(root, " sk-zen \n") + auth.writeText("""{"openai-codex":{"type":"oauth","refresh":"r"}}""") + assertEquals(emptySet(), OpenCode.keys(root)) + OpenCode.saveKey(root, provider("opencode"), " sk-zen \n") + OpenCode.saveKey(root, provider("ollama-cloud"), "ol-key") val saved = JSONObject(auth.readText()) - assertEquals("r", saved.getJSONObject("openai").getString("refresh")) + assertEquals("r", saved.getJSONObject("openai-codex").getString("refresh")) assertEquals("sk-zen", saved.getJSONObject("opencode").getString("key")) - assertEquals("api", saved.getJSONObject("opencode").getString("type")) - assertTrue(OpenCode.hasKey(root)) + assertEquals("api", saved.getJSONObject("ollama-cloud").getString("type")) + assertEquals("ol-key", saved.getJSONObject("ollama-cloud").getString("key")) + assertEquals(setOf("opencode", "ollama-cloud"), OpenCode.keys(root)) + OpenCode.removeKey(root, provider("opencode")) + assertEquals(setOf("ollama-cloud"), OpenCode.keys(root)) + assertTrue(JSONObject(auth.readText()).has("openai-codex")) OpenCode.useFree(root) assertTrue(File(root, "root/.config/opencode/.droiddeck-free").exists()) } @@ -140,15 +147,96 @@ class OpenCodeTest { val root = Files.createTempDirectory("rootfs").toFile() val auth = File(root, "root/.local/share/opencode/auth.json").apply { parentFile!!.mkdirs() } auth.writeText("{not json") - assertTrue(runCatching { OpenCode.saveKey(root, "sk-zen") }.isFailure) + assertTrue(runCatching { OpenCode.saveKey(root, provider("opencode"), "sk-zen") }.isFailure) assertEquals("{not json", auth.readText()) - assertFalse(OpenCode.hasKey(root)) + assertEquals(emptySet(), OpenCode.keys(root)) + val config = File(root, "root/.config/opencode/opencode.json").apply { parentFile!!.mkdirs() } + config.writeText("""{"provider":{"droiddeck":{"options":{"baseURL":"http://a/v1"}}}}""") + assertTrue(runCatching { OpenCode.saveKey(root, provider("droiddeck"), "k", "b:1") { _, _ -> """{"data":[{"id":"m"}]}""" } }.isFailure) + assertEquals("""{"provider":{"droiddeck":{"options":{"baseURL":"http://a/v1"}}}}""", config.readText()) + assertEquals(setOf("droiddeck"), OpenCode.keys(root)) } - @Test fun signInIsTheKeyOrTheFreeMark() { + @Test fun aCustomServerBecomesAProviderWithTheModelsItLists() { + val root = Files.createTempDirectory("rootfs").toFile() + val config = File(root, "root/.config/opencode/opencode.json").apply { parentFile!!.mkdirs() } + config.writeText("""{"theme":"tokyonight","provider":{"mine":{"npm":"x"}}}""") + val asked = mutableListOf>() + OpenCode.saveKey(root, provider("droiddeck"), "", "192.168.1.20:11434/") { url, key -> + asked += url to key + """{"object":"list","data":[{"id":"qwen3:8b"},{"id":"gpt-oss:20b"},{"id":"qwen3:8b"}]}""" + } + assertEquals(listOf("http://192.168.1.20:11434/v1/models" to null), asked) + val saved = JSONObject(config.readText()) + assertEquals("tokyonight", saved.getString("theme")) + assertTrue(saved.getJSONObject("provider").has("mine")) + val custom = saved.getJSONObject("provider").getJSONObject("droiddeck") + assertEquals("@ai-sdk/openai-compatible", custom.getString("npm")) + assertEquals("192.168.1.20", custom.getString("name")) + assertEquals("http://192.168.1.20:11434/v1", custom.getJSONObject("options").getString("baseURL")) + assertEquals(setOf("qwen3:8b", "gpt-oss:20b"), custom.getJSONObject("models").keys().asSequence().toSet()) + assertEquals(setOf("droiddeck"), OpenCode.keys(root)) + assertFalse(JSONObject(File(root, "root/.local/share/opencode/auth.json").readText()).has("droiddeck")) + + OpenCode.saveKey(root, provider("droiddeck"), "sk-lan", "https://llm.example/api/v1") { url, key -> asked += url to key; """{"data":[{"id":"m"}]}""" } + assertEquals("https://llm.example/api/v1/models" to "sk-lan", asked.last()) + assertEquals("sk-lan", JSONObject(File(root, "root/.local/share/opencode/auth.json").readText()).getJSONObject("droiddeck").getString("key")) + + OpenCode.removeKey(root, provider("droiddeck")) + assertEquals(emptySet(), OpenCode.keys(root)) + assertTrue(JSONObject(config.readText()).getJSONObject("provider").has("mine")) + } + + @Test fun modelIdsSkipWhatTheUserlandPrintsFirst() { + assertEquals(listOf("m"), OpenCode.modelIds("proot warning: can't sanitize binding \"/proc/self/fd/1\"\n{\"data\":[{\"id\":\"m\"}]}\n")) + assertEquals(emptyList(), OpenCode.modelIds("curl: (7) Failed to connect")) + } + + @Test fun aFailedKeyWritePutsTheServerConfigBack() { + val root = Files.createTempDirectory("rootfs").toFile() + val config = File(root, "root/.config/opencode/opencode.json").apply { parentFile!!.mkdirs() } + val previous = """{"provider":{"droiddeck":{"options":{"baseURL":"http://a/v1"}}}}""" + config.writeText(previous) + // A folder where the key file's temporary copy goes makes that write fail after the config is written. + File(root, "root/.local/share/opencode/.auth.json.tmp").mkdirs() + assertTrue(runCatching { OpenCode.saveKey(root, provider("droiddeck"), "k", "b:1") { _, _ -> """{"data":[{"id":"m"}]}""" } }.isFailure) + assertEquals(previous, config.readText()) + assertFalse(File(root, "root/.config/opencode/.opencode.json.tmp").exists()) + + config.delete() + File(root, "root/.local/share/opencode/.auth.json.tmp").mkdirs() + assertTrue(runCatching { OpenCode.saveKey(root, provider("droiddeck"), "k", "b:1") { _, _ -> """{"data":[{"id":"m"}]}""" } }.isFailure) + assertFalse(config.exists()) + } + + @Test fun aServerWithoutModelsIsNotSaved() { + val root = Files.createTempDirectory("rootfs").toFile() + val error = runCatching { OpenCode.saveKey(root, provider("droiddeck"), "", "localhost:1234") { _, _ -> """{"data":[]}""" } }.exceptionOrNull() + assertEquals("No models at http://localhost:1234/v1", error?.message) + assertFalse(File(root, "root/.config/opencode/opencode.json").exists()) + } + + @Test fun providerModelsAreLabelledWithTheProvider() { + val (models, _) = OpenCode.listModels(""" + ollama-cloud/gpt-oss:120b + { + "providerID": "ollama-cloud", + "name": "gpt-oss:120b" + } + droiddeck/qwen3:8b + { + "providerID": "droiddeck", + "name": "qwen3:8b" + } + """.trimIndent()) + assertEquals(listOf(AgentHarness.Model("ollama-cloud/gpt-oss:120b", "gpt-oss:120b · Ollama Cloud"), AgentHarness.Model("droiddeck/qwen3:8b", "qwen3:8b")), models) + } + + @Test fun signInIsAKeyTheFreeMarkOrACustomServer() { val probe = OpenCode.signedIn.last() assertTrue(probe.contains("/root/.local/share/opencode/auth.json")) assertTrue(probe.contains("[ -e /root/.config/opencode/.droiddeck-free ]")) + assertTrue(probe.contains("grep -q '\"droiddeck\"' /root/.config/opencode/opencode.json")) assertTrue(probe.contains("models --verbose > /root/.cache/droiddeck/opencode-models.$$")) assertEquals(listOf("/root/.local/bin/android-open", "https://opencode.ai/auth"), OpenCode.signIn) }