Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat: add email connectors (IMAP + Gmail BYO-OAuth), clock/calendar/notification enhancements

Durganshu Mishra6447efb29e81
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index ba15cee..c8e3b28 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -211,6 +211,13 @@ dependencies {
// HTML parsing for webfetch tool
implementation("org.jsoup:jsoup:1.17.2")
+ // Connectors: Custom Tabs for the BYO-OAuth consent flow
+ implementation("androidx.browser:browser:1.8.0")
+
+ // Connectors: IMAP/SMTP email (JavaMail for Android)
+ implementation("com.sun.mail:android-mail:1.6.7")
+ implementation("com.sun.mail:android-activation:1.6.7")
+
// Markdown rendering
implementation("com.halilibo.compose-richtext:richtext-ui-material3:0.17.0")
implementation("com.halilibo.compose-richtext:richtext-commonmark:0.17.0")
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index d26824c..20c76fa 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -81,6 +81,23 @@
<intent>
<action android:name="android.intent.action.DISMISS_ALARM" />
</intent>
+ <intent>
+ <action android:name="android.intent.action.SET_TIMER" />
+ </intent>
+ <intent>
+ <action android:name="android.intent.action.DISMISS_TIMER" />
+ </intent>
+ <intent>
+ <action android:name="android.intent.action.SNOOZE_ALARM" />
+ </intent>
+ <intent>
+ <action android:name="android.intent.action.SHOW_ALARMS" />
+ </intent>
+ <!-- Needed so compose_email can resolve an installed email app. -->
+ <intent>
+ <action android:name="android.intent.action.SENDTO" />
+ <data android:scheme="mailto" />
+ </intent>
</queries>
<application
diff --git a/app/src/main/assets/skills/calendar.json b/app/src/main/assets/skills/calendar.json
new file mode 100644
index 0000000..a58de30
--- /dev/null
+++ b/app/src/main/assets/skills/calendar.json
@@ -0,0 +1,7 @@
+{
+ "id": "calendar_operations",
+ "targetPackageNames": ["com.google.android.calendar"],
+ "name": "Calendar Skills",
+ "description": "Prefer the calendar connector tools over driving the Calendar app UI.",
+ "instructions": "Never automate the Calendar app's UI to view or manage events — use the dedicated tools instead, which read/write the device's calendar accounts directly:\n1. list_calendar_events supports date ranges and text search, and shows reminders and attendees per event.\n2. create_calendar_event supports all_day, calendar_name (to pick a specific account like 'Work'), attendees (real invites on a synced Google calendar), and recurrence (daily/weekly/monthly/yearly with recurrence_count or recurrence_until).\n3. edit_calendar_event updates only the fields you provide; get the event_id from list_calendar_events first.\n4. delete_calendar_event always asks the user to confirm before removing anything — irreversible.\nOnly fall back to UI automation (open_app + navigate_app) for things these tools can't do, e.g. viewing a calendar not synced to this device or the app's own settings."
+}
diff --git a/app/src/main/assets/skills/clock.json b/app/src/main/assets/skills/clock.json
new file mode 100644
index 0000000..65a3a4f
--- /dev/null
+++ b/app/src/main/assets/skills/clock.json
@@ -0,0 +1,7 @@
+{
+ "id": "clock_operations",
+ "targetPackageNames": ["com.google.android.deskclock", "com.android.deskclock"],
+ "name": "Clock Skills",
+ "description": "Prefer the alarm/timer connector tools over driving the Clock app UI.",
+ "instructions": "Never automate the Clock app's UI to set alarms or timers — use the dedicated tools instead, which work even when no clock app is open:\n1. Alarms: set_alarm, list_alarms, edit_alarm, delete_alarm. show_alarms opens the clock app's alarm list if the user wants to see it visually.\n2. Timers: set_timer (in-app by default; pass system=true to use the system clock app's timer instead), list_timers, delete_timer.\n3. snooze_alarm and dismiss_timer only affect an alarm/timer that is ringing right now — they have no effect otherwise, so only call them when the user says something is currently going off.\n4. delete_timer only removes a system-clock-app timer from this assistant's tracking; it does not stop the ringing timer — use dismiss_timer for that.\nOnly fall back to UI automation (open_app + navigate_app) for clock-app features the tools don't cover, e.g. bedtime mode or stopwatch."
+}
diff --git a/app/src/main/assets/skills/gmail.json b/app/src/main/assets/skills/gmail.json
new file mode 100644
index 0000000..d8460ec
--- /dev/null
+++ b/app/src/main/assets/skills/gmail.json
@@ -0,0 +1,7 @@
+{
+ "id": "gmail_operations",
+ "targetPackageNames": ["com.google.android.gm"],
+ "name": "Gmail Skills",
+ "description": "Prefer the email connector tools over driving the Gmail UI.",
+ "instructions": "Never automate the Gmail app's UI (tapping, scrolling, typing) to read or send email — it's slow and fragile compared to the official tools. Instead:\n1. To read, search, or check unread email: use list_emails and read_email. These work with either a connected Gmail account (Settings → Connectors → Gmail BYO OAuth) or an IMAP account.\n2. To send email: use send_email. It always shows the user a confirmation dialog with recipient/subject/body before anything is sent — you don't need to ask permission separately.\n3. If no email connector is connected, list_emails/send_email will say so — in that case use compose_email to open the user's email app with a pre-filled draft, or suggest they connect an account in Settings → Connectors for full read/write access.\n4. To mark messages read/unread, use mark_email_read with the id from list_emails.\n5. For real-time 'did I get an email from X' questions when notifications are enabled, read_notifications with app='gmail' can be faster than list_emails.\nOnly fall back to UI automation (open_app + navigate_app) for things the tools genuinely can't do, e.g. Gmail-specific settings screens."
+}
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
index 6d68f24..90a7114 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
@@ -389,6 +389,8 @@ class AgentEngine(
handleDeleteConfirm("CONFIRM_DELETE_TIMER:", "timer", call, result)
} else if (result.success && result.message.startsWith("CONFIRM_DELETE_CALENDAR_EVENT:")) {
handleDeleteConfirm("CONFIRM_DELETE_CALENDAR_EVENT:", "calendar_event", call, result)
+ } else if (result.success && result.message.startsWith("CONFIRM_SEND_EMAIL:")) {
+ handleSendEmailConfirm(call, result)
} else {
history += ChatMessage(
role = "tool",
@@ -607,6 +609,33 @@ class AgentEngine(
}
}
+ /**
+ * Handles a tool result prefixed with CONFIRM_SEND_EMAIL:base64(args).
+ * Shows the recipient/subject/body preview and, if approved, performs the send.
+ */
+ private suspend fun handleSendEmailConfirm(call: ToolCall, result: ToolResult) {
+ val payload = result.message.removePrefix("CONFIRM_SEND_EMAIL:")
+ val description = toolExecutor.describeSendEmail(payload)
+ val approved = events.awaitConfirmation(listOf("send_email"), description)
+
+ if (approved) {
+ val actualResult = toolExecutor.executeSendEmail(payload)
+ history += ChatMessage(
+ role = "tool",
+ content = JsonPrimitive(actualResult.message),
+ toolCallId = call.id
+ )
+ events.onUi(
+ if (actualResult.success) MessageKind.TOOL else MessageKind.ERROR,
+ "${call.function.name}: ${actualResult.message}"
+ )
+ } else {
+ val msg = "User declined to send the email."
+ history += ChatMessage(role = "tool", content = JsonPrimitive(msg), toolCallId = call.id)
+ events.onUi(MessageKind.TOOL, "${call.function.name}: $msg")
+ }
+ }
+
private suspend fun handleDeleteConfirm(confirmPrefix: String, kind: String, call: ToolCall, result: ToolResult) {
val body = result.message.removePrefix(confirmPrefix)
val parts = body.split(":", limit = 2)
diff --git a/app/src/main/java/com/gotcha/connectors/Connector.kt b/app/src/main/java/com/gotcha/connectors/Connector.kt
new file mode 100644
index 0000000..cd4ef7e
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/Connector.kt
@@ -0,0 +1,31 @@
+package com.gotcha.connectors
+
+/**
+ * A connector integrates an external service (Gmail, IMAP, ...) via its official
+ * API instead of accessibility UI-driving. Connectors own their credentials,
+ * network clients, and connection state; the tools built on them stay in the
+ * existing ToolDefinitions/ToolRegistry/ToolCategories plumbing and are routed
+ * by [ConnectorRegistry.toolHandler].
+ */
+interface Connector {
+ /** Stable id used as the credential-store key (e.g. "imap", "google"). */
+ val id: String
+
+ /** Human name shown on the Settings card (e.g. "Email (IMAP)"). */
+ val displayName: String
+
+ /** One-line description of what connecting enables. */
+ val description: String
+
+ /** Names of the tools that depend on this connector (shown on its card). */
+ val toolNames: Set<String>
+
+ /** True when credentials are stored and the connector is usable. */
+ fun isConnected(): Boolean
+
+ /** Short status line for the Settings card (e.g. "Connected as [email protected]"). */
+ fun statusLine(): String
+
+ /** Clear stored credentials and any cached clients/sessions. */
+ fun disconnect()
+}
diff --git a/app/src/main/java/com/gotcha/connectors/ConnectorCredentialStore.kt b/app/src/main/java/com/gotcha/connectors/ConnectorCredentialStore.kt
new file mode 100644
index 0000000..cc35108
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/ConnectorCredentialStore.kt
@@ -0,0 +1,44 @@
+package com.gotcha.connectors
+
+import android.content.Context
+import android.content.SharedPreferences
+import androidx.security.crypto.EncryptedSharedPreferences
+import androidx.security.crypto.MasterKey
+
+/** Raw per-connector blob storage, implemented by the encrypted prod store and by test fakes. */
+interface CredentialStore {
+ fun loadRaw(connectorId: String): String?
+ fun saveRaw(connectorId: String, blob: String)
+ fun clear(connectorId: String)
+}
+
+/**
+ * Encrypted storage for connector credentials, kept in a separate file from
+ * app settings. One JSON blob per connector id; each connector encodes/decodes
+ * its own @Serializable credential class. Never logged.
+ */
+class ConnectorCredentialStore(context: Context) : CredentialStore {
+
+ private val prefs: SharedPreferences by lazy {
+ val masterKey = MasterKey.Builder(context.applicationContext)
+ .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
+ .build()
+ EncryptedSharedPreferences.create(
+ context.applicationContext,
+ "gotcha_connectors",
+ masterKey,
+ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
+ EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
+ )
+ }
+
+ override fun loadRaw(connectorId: String): String? = prefs.getString(connectorId, null)
+
+ override fun saveRaw(connectorId: String, blob: String) {
+ prefs.edit().putString(connectorId, blob).apply()
+ }
+
+ override fun clear(connectorId: String) {
+ prefs.edit().remove(connectorId).apply()
+ }
+}
diff --git a/app/src/main/java/com/gotcha/connectors/ConnectorRegistry.kt b/app/src/main/java/com/gotcha/connectors/ConnectorRegistry.kt
new file mode 100644
index 0000000..7ad7162
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/ConnectorRegistry.kt
@@ -0,0 +1,56 @@
+package com.gotcha.connectors
+
+import android.content.Context
+import com.gotcha.connectors.google.GoogleConnector
+import com.gotcha.connectors.imap.ImapConnector
+import com.gotcha.connectors.mail.EmailTools
+import com.gotcha.tools.ToolResult
+import kotlinx.serialization.json.JsonObject
+
+/**
+ * Central registry of all connectors and the tool routers built on them.
+ * Initialized lazily from ToolExecutor and SettingsScreen; [init] is idempotent
+ * so either can call it first.
+ */
+object ConnectorRegistry {
+
+ @Volatile
+ private var connectors: List<Connector> = emptyList()
+
+ @Volatile
+ private var emailTools: EmailTools? = null
+
+ @Volatile
+ private var initialized = false
+
+ fun init(context: Context) {
+ if (initialized) return
+ synchronized(this) {
+ if (initialized) return
+ val appContext = context.applicationContext
+ val store = ConnectorCredentialStore(appContext)
+ val imap = ImapConnector(store)
+ val google = GoogleConnector(store)
+ connectors = listOf(imap, google)
+ emailTools = EmailTools(appContext, imap, google)
+ initialized = true
+ }
+ }
+
+ fun all(): List<Connector> = connectors
+
+ fun byId(id: String): Connector? = connectors.firstOrNull { it.id == id }
+
+ /** Email tool router (null before [init]). Used by the send-confirmation flow. */
+ fun email(): EmailTools? = emailTools
+
+ /**
+ * Returns a handler for [name] if a connector-backed router owns that tool,
+ * else null. ToolExecutor calls this first; null falls through to the
+ * built-in dispatch.
+ */
+ fun toolHandler(name: String): (suspend (String, JsonObject) -> ToolResult)? {
+ val email = emailTools ?: return null
+ return if (name in email.toolNames) email::execute else null
+ }
+}
diff --git a/app/src/main/java/com/gotcha/connectors/google/GmailApi.kt b/app/src/main/java/com/gotcha/connectors/google/GmailApi.kt
new file mode 100644
index 0000000..d84d26e
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/google/GmailApi.kt
@@ -0,0 +1,133 @@
+package com.gotcha.connectors.google
+
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.add
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.put
+import kotlinx.serialization.json.putJsonArray
+import okhttp3.HttpUrl.Companion.toHttpUrl
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+import java.io.IOException
+import java.util.concurrent.TimeUnit
+
+/** Non-2xx Gmail API response, with a user-actionable message. */
+class GmailApiException(val code: Int, message: String) : IOException(message)
+
+/**
+ * Thin OkHttp wrapper over the Gmail REST API. Stateless: every call takes the
+ * Bearer token so [GoogleConnector] can own refresh/retry. JVM-testable via a
+ * MockWebServer [baseUrl].
+ */
+class GmailApi(
+ private val client: OkHttpClient = OkHttpClient.Builder()
+ .connectTimeout(20, TimeUnit.SECONDS)
+ .readTimeout(30, TimeUnit.SECONDS)
+ .build(),
+ private val baseUrl: String = "https://gmail.googleapis.com/gmail/v1/users/me"
+) {
+
+ private val json = Json { ignoreUnknownKeys = true }
+ private val jsonMediaType = "application/json; charset=utf-8".toMediaType()
+
+ /** messages.list — returns message ids (possibly empty). */
+ suspend fun listMessageIds(
+ accessToken: String,
+ query: String?,
+ unreadOnly: Boolean,
+ max: Int
+ ): List<String> {
+ val effectiveQuery = listOfNotNull(
+ query?.takeIf { it.isNotBlank() },
+ "is:unread".takeIf { unreadOnly }
+ ).joinToString(" ")
+ val url = "$baseUrl/messages".toHttpUrl().newBuilder()
+ .addQueryParameter("maxResults", max.toString())
+ .apply { if (effectiveQuery.isNotBlank()) addQueryParameter("q", effectiveQuery) }
+ .build()
+ val obj = get(url.toString(), accessToken)
+ return obj["messages"]?.jsonArray?.mapNotNull {
+ it.jsonObject["id"]?.jsonPrimitive?.contentOrNull
+ } ?: emptyList()
+ }
+
+ /** messages.get?format=metadata — headers + snippet + labels. */
+ suspend fun getMessageMetadata(accessToken: String, id: String): JsonObject {
+ val url = "$baseUrl/messages/$id".toHttpUrl().newBuilder()
+ .addQueryParameter("format", "metadata")
+ .addQueryParameter("metadataHeaders", "From")
+ .addQueryParameter("metadataHeaders", "To")
+ .addQueryParameter("metadataHeaders", "Subject")
+ .addQueryParameter("metadataHeaders", "Date")
+ .build()
+ return get(url.toString(), accessToken)
+ }
+
+ /** messages.get?format=full — complete payload for body extraction. */
+ suspend fun getMessageFull(accessToken: String, id: String): JsonObject =
+ get("$baseUrl/messages/$id?format=full", accessToken)
+
+ /** messages.send with a base64url raw RFC 2822 message; returns the new message id. */
+ suspend fun sendRaw(accessToken: String, rawBase64Url: String): String {
+ val body = buildJsonObject { put("raw", rawBase64Url) }
+ val obj = post("$baseUrl/messages/send", accessToken, body)
+ return obj["id"]?.jsonPrimitive?.contentOrNull ?: "(unknown id)"
+ }
+
+ /** messages.modify — add/remove the UNREAD label. */
+ suspend fun setUnread(accessToken: String, id: String, unread: Boolean) {
+ val body = buildJsonObject {
+ putJsonArray(if (unread) "addLabelIds" else "removeLabelIds") { add("UNREAD") }
+ }
+ post("$baseUrl/messages/$id/modify", accessToken, body)
+ }
+
+ /** users.getProfile — the connected account's email address. */
+ suspend fun profileEmail(accessToken: String): String {
+ val obj = get("$baseUrl/profile", accessToken)
+ return obj["emailAddress"]?.jsonPrimitive?.contentOrNull ?: "(unknown)"
+ }
+
+ private suspend fun get(url: String, accessToken: String): JsonObject =
+ execute(Request.Builder().url(url).header("Authorization", "Bearer $accessToken").build())
+
+ private suspend fun post(url: String, accessToken: String, body: JsonObject): JsonObject =
+ execute(
+ Request.Builder()
+ .url(url)
+ .header("Authorization", "Bearer $accessToken")
+ .post(body.toString().toRequestBody(jsonMediaType))
+ .build()
+ )
+
+ private suspend fun execute(request: Request): JsonObject = withContext(Dispatchers.IO) {
+ client.newCall(request).execute().use { response ->
+ val body = response.body?.string().orEmpty()
+ if (!response.isSuccessful) throw mapError(response.code, body)
+ if (body.isBlank()) buildJsonObject {} else json.parseToJsonElement(body).jsonObject
+ }
+ }
+
+ private fun mapError(code: Int, body: String): GmailApiException {
+ val detail = runCatching {
+ json.parseToJsonElement(body).jsonObject["error"]
+ ?.jsonObject?.get("message")?.jsonPrimitive?.contentOrNull
+ }.getOrNull() ?: body.take(200)
+ val message = when (code) {
+ 401 -> "Gmail auth expired (401): $detail"
+ 403, 429 -> "Gmail API rate/quota limit (HTTP $code) — try again later. $detail"
+ 400 -> "Gmail API rejected the request (400): $detail"
+ else -> "Gmail API error (HTTP $code): $detail"
+ }
+ return GmailApiException(code, message)
+ }
+}
diff --git a/app/src/main/java/com/gotcha/connectors/google/GmailMessageParser.kt b/app/src/main/java/com/gotcha/connectors/google/GmailMessageParser.kt
new file mode 100644
index 0000000..f265c07
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/google/GmailMessageParser.kt
@@ -0,0 +1,46 @@
+package com.gotcha.connectors.google
+
+import com.gotcha.connectors.mail.MailBodyExtractor
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+
+/** Pure helpers for pulling readable fields out of a Gmail API message JSON payload. */
+internal object GmailMessageParser {
+
+ fun stripPrefix(id: String): String = id.removePrefix("gmail:")
+
+ fun headerMap(message: JsonObject): Map<String, String> =
+ message["payload"]?.jsonObject?.get("headers")?.jsonArray
+ ?.mapNotNull { h ->
+ val obj = h.jsonObject
+ val name = obj["name"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null
+ val value = obj["value"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null
+ name.lowercase() to value
+ }?.toMap() ?: emptyMap()
+
+ fun labelIds(message: JsonObject): List<String> =
+ message["labelIds"]?.jsonArray?.mapNotNull { it.jsonPrimitive.contentOrNull } ?: emptyList()
+
+ /** Prefer text/plain parts; fall back to stripped text/html; recurse into multiparts. */
+ fun extractBody(payload: JsonObject?): String {
+ payload ?: return ""
+ val mimeType = payload["mimeType"]?.jsonPrimitive?.contentOrNull.orEmpty()
+ val data = payload["body"]?.jsonObject?.get("data")?.jsonPrimitive?.contentOrNull
+ if (data != null && (mimeType.startsWith("text/") || mimeType.isEmpty())) {
+ val decoded = decodeBase64Url(data)
+ return if (mimeType == "text/html") MailBodyExtractor.htmlToText(decoded) else decoded
+ }
+ val parts = payload["parts"]?.jsonArray?.map { it.jsonObject } ?: return ""
+ parts.firstOrNull { it["mimeType"]?.jsonPrimitive?.contentOrNull == "text/plain" }
+ ?.let { extractBody(it).takeIf { body -> body.isNotBlank() }?.let { body -> return body } }
+ return parts.asSequence().map { extractBody(it) }.firstOrNull { it.isNotBlank() } ?: ""
+ }
+
+ private fun decodeBase64Url(data: String): String =
+ runCatching {
+ String(java.util.Base64.getUrlDecoder().decode(data), Charsets.UTF_8)
+ }.getOrDefault("")
+}
diff --git a/app/src/main/java/com/gotcha/connectors/google/GoogleConnector.kt b/app/src/main/java/com/gotcha/connectors/google/GoogleConnector.kt
new file mode 100644
index 0000000..8487655
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/google/GoogleConnector.kt
@@ -0,0 +1,245 @@
+package com.gotcha.connectors.google
+
+import com.gotcha.connectors.Connector
+import com.gotcha.connectors.CredentialStore
+import com.gotcha.connectors.mail.EmailFull
+import com.gotcha.connectors.mail.EmailSummary
+import com.gotcha.connectors.mail.MailBackend
+import com.gotcha.connectors.mail.MailBodyExtractor
+import com.gotcha.connectors.mail.OutgoingEmail
+import com.gotcha.connectors.oauth.OAuth2Config
+import com.gotcha.connectors.oauth.OAuth2Helper
+import com.gotcha.connectors.oauth.OAuthInvalidGrant
+import com.gotcha.connectors.oauth.TokenSet
+import com.gotcha.tools.MimeMessageBuilder
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.decodeFromString
+import kotlinx.serialization.encodeToString
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+
+@Serializable
+data class GoogleCredentials(
+ val clientId: String,
+ val clientSecret: String,
+ val refreshToken: String,
+ val accountEmail: String,
+ val scopes: List<String>,
+ /** Set when refresh hit invalid_grant (e.g. 7-day testing-status expiry). */
+ val needsReconnect: Boolean = false
+)
+
+/**
+ * n8n-style Bring-Your-Own-OAuth Google connector: the user pastes credentials
+ * of a Desktop-type OAuth client from their own Google Cloud project, so
+ * restricted scopes need no CASA verification. One credential is shared by all
+ * Google services; v1 requests only gmail.modify and backs the email tools.
+ */
+class GoogleConnector(
+ private val store: CredentialStore,
+ private val api: GmailApi = GmailApi(),
+ private val oauth: OAuth2Helper = OAuth2Helper(),
+ private val tokenUrl: String = TOKEN_URL,
+ private val clock: () -> Long = System::currentTimeMillis
+) : Connector, MailBackend {
+
+ private val json = Json { ignoreUnknownKeys = true }
+
+ companion object {
+ const val AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"
+ const val TOKEN_URL = "https://oauth2.googleapis.com/token"
+ const val SCOPE_GMAIL_MODIFY = "https://www.googleapis.com/auth/gmail.modify"
+ private const val EXPIRY_SKEW_MILLIS = 60_000L
+ }
+
+ override val id = "google"
+ override val displayName = "Google (BYO OAuth)"
+ override val description =
+ "Full Gmail access via your own Google Cloud OAuth client (no app passwords)."
+ override val toolNames =
+ setOf("list_emails", "read_email", "send_email", "mark_email_read")
+ override val idPrefix = "gmail"
+
+ @Volatile
+ private var credentials: GoogleCredentials? = store.loadRaw(id)?.let { blob ->
+ runCatching { json.decodeFromString<GoogleCredentials>(blob) }.getOrNull()
+ }
+
+ // In-memory access token cache; never persisted.
+ @Volatile
+ private var accessToken: String? = null
+
+ @Volatile
+ private var accessTokenExpiresAt: Long = 0
+
+ private fun persist(creds: GoogleCredentials) {
+ store.saveRaw(id, json.encodeToString(creds))
+ credentials = creds
+ }
+
+ fun credentials(): GoogleCredentials? = credentials
+
+ fun needsReconnect(): Boolean = credentials?.needsReconnect == true
+
+ fun hasScope(scope: String): Boolean = credentials?.scopes?.contains(scope) == true
+
+ override fun isConnected(): Boolean = credentials?.needsReconnect == false
+
+ override fun statusLine(): String = when {
+ credentials == null -> "Not connected"
+ credentials?.needsReconnect == true ->
+ "Reconnect needed — the saved sign-in expired (consent screens in " +
+ "\"Testing\" status expire every 7 days; publish to production to stop this)."
+ else -> "Connected as ${credentials?.accountEmail}"
+ }
+
+ override fun disconnect() {
+ // Best-effort revoke so the grant disappears from the user's Google account.
+ credentials?.refreshToken?.let { revokeQuietly(it) }
+ store.clear(id)
+ credentials = null
+ accessToken = null
+ accessTokenExpiresAt = 0
+ }
+
+ private fun revokeQuietly(token: String) {
+ Thread {
+ runCatching {
+ val client = okhttp3.OkHttpClient()
+ val body = okhttp3.FormBody.Builder().add("token", token).build()
+ client.newCall(
+ okhttp3.Request.Builder()
+ .url("https://oauth2.googleapis.com/revoke")
+ .post(body)
+ .build()
+ ).execute().close()
+ }
+ }.start()
+ }
+
+ fun oauthConfig(clientId: String, clientSecret: String) = OAuth2Config(
+ authUrl = AUTH_URL,
+ tokenUrl = tokenUrl,
+ clientId = clientId,
+ clientSecret = clientSecret,
+ scopes = listOf(SCOPE_GMAIL_MODIFY),
+ extraAuthParams = mapOf("access_type" to "offline", "prompt" to "consent")
+ )
+
+ /**
+ * Finish connecting after the OAuth code exchange: identify the account via
+ * users/me/profile and persist the credential blob.
+ */
+ suspend fun completeConnect(clientId: String, clientSecret: String, tokens: TokenSet) {
+ val refreshToken = checkNotNull(tokens.refreshToken) {
+ "Google did not return a refresh token — remove the app's access at " +
+ "myaccount.google.com/permissions and try connecting again."
+ }
+ val email = api.profileEmail(tokens.accessToken)
+ val creds = GoogleCredentials(
+ clientId = clientId,
+ clientSecret = clientSecret,
+ refreshToken = refreshToken,
+ accountEmail = email,
+ scopes = listOf(SCOPE_GMAIL_MODIFY)
+ )
+ persist(creds)
+ accessToken = tokens.accessToken
+ accessTokenExpiresAt = tokens.expiresAtMillis
+ }
+
+ /** Valid access token, refreshing proactively when missing/expiring. */
+ private suspend fun token(forceRefresh: Boolean = false): String {
+ val creds = checkNotNull(credentials) { "Google is not connected." }
+ check(!creds.needsReconnect) {
+ "The Google sign-in expired — ask the user to reconnect in Settings → Connectors."
+ }
+ val cached = accessToken
+ if (!forceRefresh && cached != null && clock() < accessTokenExpiresAt - EXPIRY_SKEW_MILLIS) {
+ return cached
+ }
+ try {
+ val tokens = oauth.refresh(oauthConfig(creds.clientId, creds.clientSecret), creds.refreshToken)
+ accessToken = tokens.accessToken
+ accessTokenExpiresAt = tokens.expiresAtMillis
+ tokens.refreshToken?.takeIf { it != creds.refreshToken }?.let { rotated ->
+ persist(creds.copy(refreshToken = rotated))
+ }
+ return tokens.accessToken
+ } catch (e: OAuthInvalidGrant) {
+ persist(creds.copy(needsReconnect = true))
+ accessToken = null
+ throw IllegalStateException(
+ "The Google sign-in expired (invalid_grant) — ask the user to reconnect in " +
+ "Settings → Connectors. Tip: publishing the consent screen to \"In production\" " +
+ "stops the weekly expiry.",
+ e
+ )
+ }
+ }
+
+ /** Runs [block] with a token, force-refreshing and retrying once on a 401. */
+ private suspend fun <T> withAuth(block: suspend (String) -> T): T {
+ return try {
+ block(token())
+ } catch (e: GmailApiException) {
+ if (e.code != 401) throw e
+ block(token(forceRefresh = true))
+ }
+ }
+
+ // ---- MailBackend (Gmail REST) ----
+
+ override suspend fun list(query: String?, unreadOnly: Boolean, max: Int): List<EmailSummary> =
+ withAuth { tok ->
+ api.listMessageIds(tok, query, unreadOnly, max).map { msgId ->
+ val meta = api.getMessageMetadata(tok, msgId)
+ val headers = GmailMessageParser.headerMap(meta)
+ EmailSummary(
+ id = "gmail:$msgId",
+ from = headers["from"].orEmpty(),
+ subject = headers["subject"] ?: "(no subject)",
+ date = headers["date"].orEmpty(),
+ unread = GmailMessageParser.labelIds(meta).contains("UNREAD"),
+ snippet = MailBodyExtractor.snippet(
+ meta["snippet"]?.jsonPrimitive?.contentOrNull.orEmpty()
+ )
+ )
+ }
+ }
+
+ override suspend fun read(id: String): EmailFull = withAuth { tok ->
+ val msgId = GmailMessageParser.stripPrefix(id)
+ val full = api.getMessageFull(tok, msgId)
+ val headers = GmailMessageParser.headerMap(full)
+ EmailFull(
+ id = id,
+ from = headers["from"].orEmpty(),
+ to = headers["to"].orEmpty(),
+ cc = headers["cc"].orEmpty(),
+ subject = headers["subject"] ?: "(no subject)",
+ date = headers["date"].orEmpty(),
+ body = GmailMessageParser.extractBody(full["payload"]?.jsonObject)
+ )
+ }
+
+ override suspend fun send(message: OutgoingEmail): String = withAuth { tok ->
+ val creds = checkNotNull(credentials) { "Google is not connected." }
+ val raw = MimeMessageBuilder.build(
+ from = creds.accountEmail,
+ to = message.to,
+ cc = message.cc,
+ bcc = message.bcc,
+ subject = message.subject,
+ body = message.body
+ )
+ val newId = api.sendRaw(tok, MimeMessageBuilder.toBase64Url(raw))
+ "Email sent to ${message.to.joinToString()} via Gmail (id gmail:$newId)."
+ }
+
+ override suspend fun markRead(id: String, read: Boolean) {
+ withAuth { tok -> api.setUnread(tok, GmailMessageParser.stripPrefix(id), unread = !read) }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/connectors/google/GoogleOAuthFlow.kt b/app/src/main/java/com/gotcha/connectors/google/GoogleOAuthFlow.kt
new file mode 100644
index 0000000..6339da3
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/google/GoogleOAuthFlow.kt
@@ -0,0 +1,119 @@
+package com.gotcha.connectors.google
+
+import android.content.ActivityNotFoundException
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import androidx.browser.customtabs.CustomTabsIntent
+import com.gotcha.connectors.oauth.LoopbackRedirectServer
+import com.gotcha.connectors.oauth.OAuth2Helper
+import com.gotcha.connectors.oauth.Pkce
+import java.util.UUID
+
+/**
+ * Drives the desktop-app loopback OAuth flow for [GoogleConnector] from the
+ * Settings UI: build the authorization URL with PKCE, open it in a Custom Tab,
+ * wait on a transient loopback listener for the redirect, then exchange the
+ * code. A Desktop-type OAuth client needs no redirect-URI registration, so any
+ * ephemeral 127.0.0.1 port works.
+ */
+class GoogleOAuthFlow(
+ private val context: Context,
+ private val connector: GoogleConnector,
+ private val oauth: OAuth2Helper = OAuth2Helper()
+) {
+
+ sealed class Outcome {
+ data class Connected(val email: String) : Outcome()
+ data class Failed(val message: String) : Outcome()
+ }
+
+ // Kept from the most recent connect() attempt so the paste-URL fallback can
+ // exchange a code the user copied out of a Custom Tab that died mid-flow.
+ private var lastRedirectUri: String? = null
+ private var lastVerifier: String? = null
+ private var lastState: String? = null
+
+ /**
+ * Launches the Custom Tab and suspends until the loopback server captures
+ * the redirect (or times out after 5 minutes). Call from a coroutine scope
+ * tied to the Settings screen.
+ */
+ suspend fun connect(clientId: String, clientSecret: String): Outcome {
+ val cfg = connector.oauthConfig(clientId.trim(), clientSecret.trim())
+ val server = LoopbackRedirectServer()
+ val verifier = Pkce.generateVerifier()
+ val challenge = Pkce.challengeS256(verifier)
+ val state = UUID.randomUUID().toString()
+ lastRedirectUri = server.redirectUri
+ lastVerifier = verifier
+ lastState = state
+
+ return try {
+ val authUrl = oauth.buildAuthorizationUrl(cfg, server.redirectUri, state, challenge)
+ openCustomTab(authUrl)
+
+ when (val result = server.awaitCode(state)) {
+ is LoopbackRedirectServer.Result.Error -> Outcome.Failed(result.message)
+ is LoopbackRedirectServer.Result.Code -> {
+ val tokens = oauth.exchangeCode(cfg, result.code, server.redirectUri, verifier)
+ connector.completeConnect(clientId.trim(), clientSecret.trim(), tokens)
+ relaunchApp()
+ Outcome.Connected(connector.credentials()?.accountEmail.orEmpty())
+ }
+ }
+ } catch (e: Exception) {
+ Outcome.Failed(e.message ?: "Connection failed.")
+ } finally {
+ server.close()
+ }
+ }
+
+ /**
+ * Fallback for a died Custom Tab listener: the user pastes the final
+ * `http://127.0.0.1:.../?code=...&state=...` URL manually. Reuses the
+ * redirect URI, PKCE verifier and state from the most recent [connect]
+ * attempt, so this only works right after calling it.
+ */
+ suspend fun connectWithPastedUrl(clientId: String, clientSecret: String, pastedUrl: String): Outcome {
+ val redirectUri = lastRedirectUri
+ val verifier = lastVerifier
+ val expectedState = lastState
+ if (redirectUri == null || verifier == null || expectedState == null) {
+ return Outcome.Failed("Start Connect first, then paste the redirect URL if the browser didn't return.")
+ }
+ val uri = Uri.parse(pastedUrl.trim())
+ val code = uri.getQueryParameter("code")
+ ?: return Outcome.Failed("That URL doesn't contain a 'code' parameter.")
+ if (uri.getQueryParameter("state") != expectedState) {
+ return Outcome.Failed("State mismatch — start Connect again and paste the new redirect URL.")
+ }
+ val cfg = connector.oauthConfig(clientId.trim(), clientSecret.trim())
+ return try {
+ val tokens = oauth.exchangeCode(cfg, code, redirectUri, verifier)
+ connector.completeConnect(clientId.trim(), clientSecret.trim(), tokens)
+ Outcome.Connected(connector.credentials()?.accountEmail.orEmpty())
+ } catch (e: Exception) {
+ Outcome.Failed(e.message ?: "Connection failed.")
+ }
+ }
+
+ private fun openCustomTab(url: String) {
+ val intent = CustomTabsIntent.Builder().build()
+ try {
+ intent.launchUrl(context, Uri.parse(url))
+ } catch (ignored: ActivityNotFoundException) {
+ // No Custom Tabs-capable browser — fall back to a plain view intent.
+ context.startActivity(
+ Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ )
+ }
+ }
+
+ private fun relaunchApp() {
+ val launchIntent = context.packageManager.getLaunchIntentForPackage(context.packageName)
+ ?: return
+ launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
+ context.startActivity(launchIntent)
+ }
+}
diff --git a/app/src/main/java/com/gotcha/connectors/imap/ImapConnector.kt b/app/src/main/java/com/gotcha/connectors/imap/ImapConnector.kt
new file mode 100644
index 0000000..a283d33
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/imap/ImapConnector.kt
@@ -0,0 +1,268 @@
+package com.gotcha.connectors.imap
+
+import com.gotcha.connectors.Connector
+import com.gotcha.connectors.CredentialStore
+import com.gotcha.connectors.mail.EmailFull
+import com.gotcha.connectors.mail.EmailSummary
+import com.gotcha.connectors.mail.MailBackend
+import com.gotcha.connectors.mail.MailBodyExtractor
+import com.gotcha.connectors.mail.OutgoingEmail
+import com.gotcha.tools.MimeMessageBuilder
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.decodeFromString
+import kotlinx.serialization.encodeToString
+import kotlinx.serialization.json.Json
+import java.io.ByteArrayInputStream
+import java.time.Instant
+import java.util.Properties
+import javax.mail.AuthenticationFailedException
+import javax.mail.Flags
+import javax.mail.Folder
+import javax.mail.Message
+import javax.mail.Part
+import javax.mail.Session
+import javax.mail.Store
+import javax.mail.Transport
+import javax.mail.UIDFolder
+import javax.mail.internet.MimeMessage
+import javax.mail.internet.MimeMultipart
+import javax.mail.search.BodyTerm
+import javax.mail.search.FlagTerm
+import javax.mail.search.FromStringTerm
+import javax.mail.search.OrTerm
+import javax.mail.search.SearchTerm
+import javax.mail.search.SubjectTerm
+
+@Serializable
+data class ImapCredentials(
+ val email: String,
+ val appPassword: String,
+ val imapHost: String,
+ val imapPort: Int = 993,
+ val smtpHost: String,
+ val smtpPort: Int = 465
+) {
+ companion object {
+ /** Gmail preset (requires a Google app password). */
+ fun gmail(email: String, appPassword: String) = ImapCredentials(
+ email = email,
+ appPassword = appPassword,
+ imapHost = "imap.gmail.com",
+ imapPort = 993,
+ smtpHost = "smtp.gmail.com",
+ smtpPort = 465
+ )
+ }
+}
+
+/** Thrown when the server rejects the stored app password. */
+class ImapAuthException(message: String, cause: Throwable? = null) : Exception(message, cause)
+
+/**
+ * Provider-agnostic IMAP/SMTP connector using app-password auth. Works with
+ * any provider that offers IMAP (Gmail preset in Settings). Caches the IMAP
+ * [Store] and reconnects when stale. All I/O runs on the caller's dispatcher
+ * (ToolExecutor already dispatches on IO).
+ */
+class ImapConnector(
+ private val store: CredentialStore
+) : Connector, MailBackend {
+
+ override val id = "imap"
+ override val displayName = "Email (IMAP)"
+ override val description =
+ "Read and send email on any provider via IMAP/SMTP with an app password."
+ override val toolNames =
+ setOf("list_emails", "read_email", "send_email", "mark_email_read")
+ override val idPrefix = "imap"
+
+ private val json = Json { ignoreUnknownKeys = true }
+ private var cachedStore: Store? = null
+
+ @Volatile
+ private var credentials: ImapCredentials? = store.loadRaw(id)?.let { blob ->
+ runCatching { json.decodeFromString<ImapCredentials>(blob) }.getOrNull()
+ }
+
+ fun credentials(): ImapCredentials? = credentials
+
+ fun connect(newCredentials: ImapCredentials) {
+ disconnect()
+ store.saveRaw(id, json.encodeToString(newCredentials))
+ credentials = newCredentials
+ }
+
+ override fun isConnected(): Boolean = credentials != null
+
+ override fun statusLine(): String =
+ credentials?.let { "Connected as ${it.email} (${it.imapHost})" } ?: "Not connected"
+
+ @Synchronized
+ override fun disconnect() {
+ runCatching { cachedStore?.close() }
+ cachedStore = null
+ store.clear(id)
+ credentials = null
+ }
+
+ /** Opens (or reuses) the IMAP store. Throws [ImapAuthException] on bad credentials. */
+ @Synchronized
+ private fun imapStore(): Store {
+ val creds = checkNotNull(credentials) { "IMAP is not connected." }
+ cachedStore?.let { if (it.isConnected) return it }
+ val props = Properties().apply {
+ put("mail.store.protocol", "imaps")
+ put("mail.imaps.host", creds.imapHost)
+ put("mail.imaps.port", creds.imapPort.toString())
+ put("mail.imaps.ssl.enable", "true")
+ put("mail.imaps.connectiontimeout", "20000")
+ put("mail.imaps.timeout", "30000")
+ }
+ val session = Session.getInstance(props)
+ val newStore = session.getStore("imaps")
+ try {
+ newStore.connect(creds.imapHost, creds.email, creds.appPassword)
+ } catch (e: AuthenticationFailedException) {
+ throw ImapAuthException(
+ "The mail server rejected the app password — open Settings and reconnect the IMAP connector.",
+ e
+ )
+ }
+ cachedStore = newStore
+ return newStore
+ }
+
+ private fun smtpSession(creds: ImapCredentials): Session {
+ val props = Properties().apply {
+ put("mail.transport.protocol", "smtp")
+ put("mail.smtp.host", creds.smtpHost)
+ put("mail.smtp.port", creds.smtpPort.toString())
+ put("mail.smtp.auth", "true")
+ if (creds.smtpPort == 587) {
+ put("mail.smtp.starttls.enable", "true")
+ } else {
+ put("mail.smtp.ssl.enable", "true")
+ }
+ put("mail.smtp.connectiontimeout", "20000")
+ put("mail.smtp.timeout", "30000")
+ }
+ return Session.getInstance(props)
+ }
+
+ // ---- MailBackend ----
+
+ override suspend fun list(query: String?, unreadOnly: Boolean, max: Int): List<EmailSummary> {
+ val inbox = imapStore().getFolder("INBOX")
+ inbox.open(Folder.READ_ONLY)
+ try {
+ val terms = mutableListOf<SearchTerm>()
+ if (unreadOnly) terms += FlagTerm(Flags(Flags.Flag.SEEN), false)
+ if (!query.isNullOrBlank()) {
+ terms += OrTerm(arrayOf(SubjectTerm(query), FromStringTerm(query), BodyTerm(query)))
+ }
+ val messages: Array<Message> = when (terms.size) {
+ 0 -> inbox.messages
+ 1 -> inbox.search(terms[0])
+ else -> inbox.search(terms.reduce { a, b -> javax.mail.search.AndTerm(a, b) })
+ }
+ val uidFolder = inbox as UIDFolder
+ // Newest first; message number order follows arrival order.
+ return messages.sortedByDescending { it.messageNumber }.take(max).map { msg ->
+ val body = runCatching { extractBody(msg) }.getOrDefault("")
+ EmailSummary(
+ id = "imap:INBOX:${uidFolder.getUID(msg)}",
+ from = msg.from?.joinToString { addr -> addr.toString() } ?: "",
+ subject = msg.subject ?: "(no subject)",
+ date = msg.sentDate?.toInstant()?.toString()
+ ?: msg.receivedDate?.toInstant()?.toString().orEmpty(),
+ unread = !msg.isSet(Flags.Flag.SEEN),
+ snippet = MailBodyExtractor.snippet(body)
+ )
+ }
+ } finally {
+ runCatching { inbox.close(false) }
+ }
+ }
+
+ override suspend fun read(id: String): EmailFull {
+ val (folderName, uid) = parseId(id)
+ val folder = imapStore().getFolder(folderName)
+ folder.open(Folder.READ_ONLY)
+ try {
+ val msg = (folder as UIDFolder).getMessageByUID(uid)
+ ?: throw IllegalArgumentException("No message with id $id — it may have been moved or deleted.")
+ return EmailFull(
+ id = id,
+ from = msg.from?.joinToString { it.toString() } ?: "",
+ to = msg.getRecipients(Message.RecipientType.TO)?.joinToString { it.toString() } ?: "",
+ cc = msg.getRecipients(Message.RecipientType.CC)?.joinToString { it.toString() } ?: "",
+ subject = msg.subject ?: "(no subject)",
+ date = msg.sentDate?.toInstant()?.toString() ?: Instant.EPOCH.toString(),
+ body = extractBody(msg)
+ )
+ } finally {
+ runCatching { folder.close(false) }
+ }
+ }
+
+ override suspend fun send(message: OutgoingEmail): String {
+ val creds = checkNotNull(credentials) { "IMAP is not connected." }
+ val raw = MimeMessageBuilder.build(
+ from = creds.email,
+ to = message.to,
+ cc = message.cc,
+ bcc = message.bcc,
+ subject = message.subject,
+ body = message.body
+ )
+ val session = smtpSession(creds)
+ val mime = MimeMessage(session, ByteArrayInputStream(raw.toByteArray(Charsets.UTF_8)))
+ try {
+ Transport.send(mime, creds.email, creds.appPassword)
+ } catch (e: AuthenticationFailedException) {
+ throw ImapAuthException(
+ "The SMTP server rejected the app password — open Settings and reconnect the IMAP connector.",
+ e
+ )
+ }
+ return "Email sent to ${message.to.joinToString()} via ${creds.smtpHost}."
+ }
+
+ override suspend fun markRead(id: String, read: Boolean) {
+ val (folderName, uid) = parseId(id)
+ val folder = imapStore().getFolder(folderName)
+ folder.open(Folder.READ_WRITE)
+ try {
+ val msg = (folder as UIDFolder).getMessageByUID(uid)
+ ?: throw IllegalArgumentException("No message with id $id — it may have been moved or deleted.")
+ msg.setFlag(Flags.Flag.SEEN, read)
+ } finally {
+ runCatching { folder.close(false) }
+ }
+ }
+
+ private fun parseId(id: String): Pair<String, Long> {
+ val parts = id.split(":", limit = 3)
+ require(parts.size == 3 && parts[0] == "imap") { "Not an IMAP message id: $id" }
+ return parts[1] to (
+ parts[2].toLongOrNull()
+ ?: throw IllegalArgumentException("Bad IMAP uid in id: $id")
+ )
+ }
+
+ /** Prefer text/plain; fall back to stripped HTML; recurse into multiparts. */
+ private fun extractBody(part: Part): String = when {
+ part.isMimeType("text/plain") -> part.content?.toString().orEmpty()
+ part.isMimeType("text/html") ->
+ MailBodyExtractor.htmlToText(part.content?.toString().orEmpty())
+ part.isMimeType("multipart/*") -> {
+ val multipart = part.content as MimeMultipart
+ val parts = (0 until multipart.count).map { multipart.getBodyPart(it) }
+ parts.firstOrNull { it.isMimeType("text/plain") }?.let { extractBody(it) }
+ ?.takeIf { it.isNotBlank() }
+ ?: parts.asSequence().map { extractBody(it) }.firstOrNull { it.isNotBlank() }
+ ?: ""
+ }
+ else -> ""
+ }
+}
diff --git a/app/src/main/java/com/gotcha/connectors/mail/EmailTools.kt b/app/src/main/java/com/gotcha/connectors/mail/EmailTools.kt
new file mode 100644
index 0000000..99bfab9
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/mail/EmailTools.kt
@@ -0,0 +1,228 @@
+package com.gotcha.connectors.mail
+
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import com.gotcha.connectors.google.GoogleConnector
+import com.gotcha.connectors.imap.ImapConnector
+import com.gotcha.tools.ToolResult
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.booleanOrNull
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.intOrNull
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonPrimitive
+
+/**
+ * Router owning the email tools. Backend precedence: Gmail API when the Google
+ * connector is connected, else IMAP/SMTP, else an error steering the model to
+ * Settings or `compose_email`. Message ids are uniform (`gmail:...` /
+ * `imap:...`) and read/mark route by prefix so ids stay valid even after the
+ * user connects a second backend.
+ */
+class EmailTools(
+ private val gmailBackend: () -> MailBackend?,
+ private val imapBackend: () -> MailBackend?,
+ private val composeLauncher: (to: String?, subject: String?, body: String?) -> ToolResult
+) {
+
+ constructor(context: Context, imap: ImapConnector, google: GoogleConnector) : this(
+ gmailBackend = { google.takeIf { it.isConnected() } },
+ imapBackend = { imap.takeIf { it.isConnected() } },
+ composeLauncher = { to, subject, body -> launchCompose(context, to, subject, body) }
+ )
+
+ companion object {
+ const val CONFIRM_SEND_PREFIX = "CONFIRM_SEND_EMAIL:"
+ private const val DEFAULT_LIST_MAX = 10
+ private const val MAX_LIST_MAX = 50
+
+ private fun launchCompose(
+ context: Context,
+ to: String?,
+ subject: String?,
+ body: String?
+ ): ToolResult {
+ val intent = Intent(Intent.ACTION_SENDTO).apply {
+ data = Uri.parse("mailto:" + Uri.encode(to.orEmpty()))
+ subject?.let { putExtra(Intent.EXTRA_SUBJECT, it) }
+ body?.let { putExtra(Intent.EXTRA_TEXT, it) }
+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ }
+ if (intent.resolveActivity(context.packageManager) == null) {
+ return ToolResult.error("No email app is installed that can handle compose.")
+ }
+ context.startActivity(intent)
+ return ToolResult.ok(
+ "Opened the email composer" + (to?.let { " addressed to $it" } ?: "") +
+ ". The user reviews and sends it themselves."
+ )
+ }
+ }
+
+ val toolNames: Set<String> =
+ setOf("list_emails", "read_email", "send_email", "mark_email_read", "compose_email")
+
+ private val json = Json { ignoreUnknownKeys = true }
+
+ suspend fun execute(name: String, args: JsonObject): ToolResult = try {
+ when (name) {
+ "list_emails" -> listEmails(args)
+ "read_email" -> readEmail(args)
+ "send_email" -> requestSendConfirmation(args)
+ "mark_email_read" -> markEmailRead(args)
+ "compose_email" -> composeLauncher(
+ args.optString("to"),
+ args.optString("subject"),
+ args.optString("body")
+ )
+ else -> ToolResult.error("Unknown email tool '$name'.")
+ }
+ } catch (e: Exception) {
+ ToolResult.error("$name failed: ${e.message}")
+ }
+
+ /** Preferred backend for new operations (listing, sending). */
+ private fun primaryBackend(): MailBackend? = gmailBackend() ?: imapBackend()
+
+ /** Backend that owns an existing message id, by prefix. */
+ private fun backendForId(id: String): MailBackend? = when {
+ id.startsWith("gmail:") -> gmailBackend()
+ id.startsWith("imap:") -> imapBackend()
+ else -> null
+ }
+
+ private fun notConnectedError(): ToolResult = ToolResult.error(
+ "No email account is connected. Ask the user to connect Gmail or IMAP in Settings → Connectors, " +
+ "or use compose_email to open their email app with a pre-filled draft instead."
+ )
+
+ private suspend fun listEmails(args: JsonObject): ToolResult {
+ val backend = primaryBackend() ?: return notConnectedError()
+ val max = (args.optInt("max") ?: DEFAULT_LIST_MAX).coerceIn(1, MAX_LIST_MAX)
+ val emails = backend.list(
+ query = args.optString("query"),
+ unreadOnly = args.optBoolean("unread_only") ?: false,
+ max = max
+ )
+ if (emails.isEmpty()) return ToolResult.ok("No matching emails found.")
+ val rows = emails.joinToString("\n") { e ->
+ val flag = if (e.unread) "UNREAD" else "read"
+ "[${e.id}] $flag | ${e.date} | from: ${e.from} | ${e.subject}\n ${e.snippet}"
+ }
+ return ToolResult.ok("${emails.size} email(s):\n$rows")
+ }
+
+ private suspend fun readEmail(args: JsonObject): ToolResult {
+ val id = args.optString("id") ?: return ToolResult.error("Missing required arg 'id'.")
+ val backend = backendForId(id)
+ ?: return ToolResult.error(
+ "Cannot read '$id' — its backend is not connected (ids look like gmail:... or imap:...)."
+ )
+ val email = backend.read(id)
+ return ToolResult.ok(
+ "From: ${email.from}\nTo: ${email.to}\n" +
+ (if (email.cc.isNotBlank()) "Cc: ${email.cc}\n" else "") +
+ "Date: ${email.date}\nSubject: ${email.subject}\n\n${email.body}"
+ )
+ }
+
+ private suspend fun markEmailRead(args: JsonObject): ToolResult {
+ val id = args.optString("id") ?: return ToolResult.error("Missing required arg 'id'.")
+ val read = args.optBoolean("read") ?: true
+ val backend = backendForId(id)
+ ?: return ToolResult.error("Cannot modify '$id' — its backend is not connected.")
+ backend.markRead(id, read)
+ return ToolResult.ok("Marked $id as ${if (read) "read" else "unread"}.")
+ }
+
+ /**
+ * send_email never sends directly: it validates, then returns a
+ * CONFIRM_SEND_EMAIL payload that AgentEngine turns into a user
+ * confirmation dialog; on approval ToolExecutor calls [executeSendConfirmed].
+ */
+ private fun requestSendConfirmation(args: JsonObject): ToolResult {
+ if (primaryBackend() == null) {
+ return ToolResult.error(
+ "No email account is connected, so send_email is unavailable. " +
+ "Use compose_email to open the user's email app with a pre-filled draft, " +
+ "or ask them to connect an account in Settings → Connectors."
+ )
+ }
+ parseOutgoing(args)
+ ?: return ToolResult.error("send_email needs 'to' (list or string), 'subject' and 'body'.")
+ val payload = java.util.Base64.getEncoder()
+ .encodeToString(args.toString().toByteArray(Charsets.UTF_8))
+ return ToolResult.ok(CONFIRM_SEND_PREFIX + payload)
+ }
+
+ /** Executes a send the user already approved. [argsBase64] is the CONFIRM payload body. */
+ suspend fun executeSendConfirmed(argsBase64: String): ToolResult {
+ return try {
+ val args = json.parseToJsonElement(
+ String(java.util.Base64.getDecoder().decode(argsBase64), Charsets.UTF_8)
+ ) as JsonObject
+ val message = parseOutgoing(args)
+ ?: return ToolResult.error("Send confirmation payload was malformed.")
+ val backend = primaryBackend()
+ ?: return ToolResult.error("No email account is connected anymore.")
+ ToolResult.ok(backend.send(message))
+ } catch (e: Exception) {
+ ToolResult.error("send_email failed: ${e.message}")
+ }
+ }
+
+ /** Human-readable summary of a pending send, for the confirmation dialog. */
+ fun describeSend(argsBase64: String): String = runCatching {
+ val args = json.parseToJsonElement(
+ String(java.util.Base64.getDecoder().decode(argsBase64), Charsets.UTF_8)
+ ) as JsonObject
+ val message = parseOutgoing(args)
+ ?: return@runCatching "Send an email (details unavailable)."
+ val bodyPreview = message.body.replace(Regex("\\s+"), " ").trim().take(200)
+ buildString {
+ append("Send email to ${message.to.joinToString()}")
+ if (message.cc.isNotEmpty()) append(" (cc: ${message.cc.joinToString()})")
+ append("\nSubject: ${message.subject}")
+ append("\n\n$bodyPreview")
+ if (message.body.length > 200) append("…")
+ }
+ }.getOrDefault("Send an email (details unavailable).")
+
+ private fun parseOutgoing(args: JsonObject): OutgoingEmail? {
+ val to = args.optStringList("to")
+ val subject = args.optString("subject")
+ val body = args.optString("body")
+ if (to.isEmpty() || subject == null || body == null) return null
+ return OutgoingEmail(
+ to = to,
+ cc = args.optStringList("cc"),
+ bcc = args.optStringList("bcc"),
+ subject = subject,
+ body = body
+ )
+ }
+
+ private fun JsonObject.optString(key: String): String? =
+ this[key]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() }
+
+ private fun JsonObject.optInt(key: String): Int? = this[key]?.jsonPrimitive?.intOrNull
+
+ private fun JsonObject.optBoolean(key: String): Boolean? =
+ this[key]?.jsonPrimitive?.booleanOrNull
+
+ /** Accepts either a JSON array of strings or a single/comma-separated string. */
+ private fun JsonObject.optStringList(key: String): List<String> {
+ val element = this[key] ?: return emptyList()
+ return runCatching {
+ element.jsonArray.mapNotNull { it.jsonPrimitive.contentOrNull }
+ }.getOrElse {
+ element.jsonPrimitive.contentOrNull
+ ?.split(',')
+ ?.map { it.trim() }
+ ?.filter { it.isNotEmpty() }
+ ?: emptyList()
+ }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/connectors/mail/MailBackend.kt b/app/src/main/java/com/gotcha/connectors/mail/MailBackend.kt
new file mode 100644
index 0000000..61c8c17
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/mail/MailBackend.kt
@@ -0,0 +1,52 @@
+package com.gotcha.connectors.mail
+
+/** One row in a mailbox listing. */
+data class EmailSummary(
+ /** Uniform id: `gmail:<messageId>` or `imap:<folder>:<uid>`. */
+ val id: String,
+ val from: String,
+ val subject: String,
+ /** ISO-8601 date string, empty when the message has no date header. */
+ val date: String,
+ val unread: Boolean,
+ /** Plain-text snippet, roughly 150 chars. */
+ val snippet: String
+)
+
+/** Full content of a single message. */
+data class EmailFull(
+ val id: String,
+ val from: String,
+ val to: String,
+ val cc: String,
+ val subject: String,
+ val date: String,
+ val body: String
+)
+
+/** An outgoing message (already confirmed by the user). */
+data class OutgoingEmail(
+ val to: List<String>,
+ val cc: List<String> = emptyList(),
+ val bcc: List<String> = emptyList(),
+ val subject: String,
+ val body: String
+)
+
+/**
+ * Common mail operations implemented by both the IMAP/SMTP and the Gmail REST
+ * backends. All functions may throw; EmailTools converts failures to ToolResults.
+ */
+interface MailBackend {
+ /** Uniform id prefix this backend owns ("gmail" or "imap"). */
+ val idPrefix: String
+
+ suspend fun list(query: String?, unreadOnly: Boolean, max: Int): List<EmailSummary>
+
+ suspend fun read(id: String): EmailFull
+
+ /** Sends the message; returns a short human-readable confirmation. */
+ suspend fun send(message: OutgoingEmail): String
+
+ suspend fun markRead(id: String, read: Boolean)
+}
diff --git a/app/src/main/java/com/gotcha/connectors/mail/MailBodyExtractor.kt b/app/src/main/java/com/gotcha/connectors/mail/MailBodyExtractor.kt
new file mode 100644
index 0000000..ab61986
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/mail/MailBodyExtractor.kt
@@ -0,0 +1,30 @@
+package com.gotcha.connectors.mail
+
+import org.jsoup.Jsoup
+
+/**
+ * Extracts a readable plain-text body from raw message content: prefers
+ * text/plain parts; strips markup from HTML parts with jsoup.
+ */
+object MailBodyExtractor {
+
+ /** Convert an HTML body to readable plain text. */
+ fun htmlToText(html: String): String {
+ val doc = Jsoup.parse(html)
+ // Preserve rough line structure: jsoup's text() collapses everything to one line.
+ doc.select("br").append("\\n")
+ doc.select("p, div, li, tr, h1, h2, h3, h4, h5, h6").append("\\n")
+ return doc.text()
+ .replace("\\n", "\n")
+ .lines()
+ .joinToString("\n") { it.trim() }
+ .replace(Regex("\n{3,}"), "\n\n")
+ .trim()
+ }
+
+ /** Collapse whitespace and truncate to a listing snippet. */
+ fun snippet(text: String, maxChars: Int = 150): String {
+ val collapsed = text.replace(Regex("\\s+"), " ").trim()
+ return if (collapsed.length <= maxChars) collapsed else collapsed.take(maxChars) + "…"
+ }
+}
diff --git a/app/src/main/java/com/gotcha/connectors/oauth/LoopbackRedirectServer.kt b/app/src/main/java/com/gotcha/connectors/oauth/LoopbackRedirectServer.kt
new file mode 100644
index 0000000..79da9c3
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/oauth/LoopbackRedirectServer.kt
@@ -0,0 +1,114 @@
+package com.gotcha.connectors.oauth
+
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import java.io.Closeable
+import java.net.InetAddress
+import java.net.ServerSocket
+import java.net.SocketTimeoutException
+import java.net.URLDecoder
+
+/**
+ * Transient loopback HTTP listener for the OAuth desktop-app redirect
+ * (`http://127.0.0.1:{port}/...`). Binds an ephemeral port, accepts a single
+ * connection, parses the query string, replies with a small success/error page,
+ * and closes. Pure java.net — JVM-testable.
+ */
+class LoopbackRedirectServer(
+ timeoutMillis: Int = DEFAULT_TIMEOUT_MILLIS
+) : Closeable {
+
+ companion object {
+ const val DEFAULT_TIMEOUT_MILLIS = 5 * 60 * 1000
+ private const val MAX_REQUEST_LINE_LENGTH = 8192
+ }
+
+ sealed class Result {
+ data class Code(val code: String) : Result()
+ data class Error(val message: String) : Result()
+ }
+
+ private val serverSocket = ServerSocket(0, 1, InetAddress.getLoopbackAddress()).apply {
+ soTimeout = timeoutMillis
+ }
+
+ val port: Int get() = serverSocket.localPort
+
+ val redirectUri: String get() = "http://127.0.0.1:$port"
+
+ /**
+ * Blocks until one request arrives (or the timeout elapses) and returns the
+ * outcome. [expectedState] is checked against the `state` query parameter to
+ * reject forged redirects.
+ */
+ suspend fun awaitCode(expectedState: String): Result = withContext(Dispatchers.IO) {
+ try {
+ serverSocket.accept().use { socket ->
+ val requestLine = socket.getInputStream().bufferedReader().readLine().orEmpty()
+ .take(MAX_REQUEST_LINE_LENGTH)
+ val params = parseQuery(requestLine)
+ val result = when {
+ params["error"] != null ->
+ Result.Error("Authorization failed: ${params["error"]}")
+ params["state"] != expectedState ->
+ Result.Error("State mismatch — possible forged redirect. Try connecting again.")
+ params["code"].isNullOrBlank() ->
+ Result.Error("Redirect did not contain an authorization code.")
+ else -> Result.Code(params.getValue("code"))
+ }
+ val page = if (result is Result.Code) successHtml else errorHtml(result)
+ socket.getOutputStream().apply {
+ write(httpResponse(page).toByteArray(Charsets.UTF_8))
+ flush()
+ }
+ result
+ }
+ } catch (ignored: SocketTimeoutException) {
+ Result.Error("Timed out waiting for the sign-in redirect (5 minutes). Try connecting again.")
+ } finally {
+ close()
+ }
+ }
+
+ override fun close() {
+ runCatching { serverSocket.close() }
+ }
+
+ /** Extracts query parameters from an HTTP request line like `GET /?code=x&state=y HTTP/1.1`. */
+ private fun parseQuery(requestLine: String): Map<String, String> {
+ val path = requestLine.split(" ").getOrNull(1) ?: return emptyMap()
+ val query = path.substringAfter('?', missingDelimiterValue = "")
+ if (query.isEmpty()) return emptyMap()
+ return query.split('&').mapNotNull { pair ->
+ val idx = pair.indexOf('=')
+ if (idx <= 0) return@mapNotNull null
+ val key = URLDecoder.decode(pair.substring(0, idx), "UTF-8")
+ val value = URLDecoder.decode(pair.substring(idx + 1), "UTF-8")
+ key to value
+ }.toMap()
+ }
+
+ private fun httpResponse(html: String): String {
+ val body = html.toByteArray(Charsets.UTF_8)
+ return "HTTP/1.1 200 OK\r\n" +
+ "Content-Type: text/html; charset=utf-8\r\n" +
+ "Content-Length: ${body.size}\r\n" +
+ "Connection: close\r\n" +
+ "\r\n" +
+ html
+ }
+
+ private fun errorHtml(result: Result): String {
+ val message = (result as? Result.Error)?.message ?: "Unknown error"
+ return "<html><body style=\"font-family:sans-serif;text-align:center;padding-top:4em\">" +
+ "<h2>Sign-in failed</h2><p>${escapeHtml(message)}</p>" +
+ "<p>Return to the app and try again.</p></body></html>"
+ }
+
+ private fun escapeHtml(s: String): String =
+ s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+
+ private val successHtml =
+ "<html><body style=\"font-family:sans-serif;text-align:center;padding-top:4em\">" +
+ "<h2>Signed in</h2><p>You can close this tab and return to the app.</p></body></html>"
+}
diff --git a/app/src/main/java/com/gotcha/connectors/oauth/OAuth2Helper.kt b/app/src/main/java/com/gotcha/connectors/oauth/OAuth2Helper.kt
new file mode 100644
index 0000000..31cebc8
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/oauth/OAuth2Helper.kt
@@ -0,0 +1,133 @@
+package com.gotcha.connectors.oauth
+
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.longOrNull
+import okhttp3.FormBody
+import okhttp3.HttpUrl.Companion.toHttpUrl
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import java.io.IOException
+import java.util.concurrent.TimeUnit
+
+/** Static config for one OAuth2 provider (n8n client-oauth2 analog). */
+data class OAuth2Config(
+ val authUrl: String,
+ val tokenUrl: String,
+ val clientId: String,
+ val clientSecret: String,
+ val scopes: List<String>,
+ val extraAuthParams: Map<String, String> = emptyMap()
+)
+
+/** Tokens returned by an exchange or refresh. */
+data class TokenSet(
+ val accessToken: String,
+ /** Null when the provider did not rotate the refresh token. */
+ val refreshToken: String?,
+ /** Absolute epoch-millis expiry (computed from expires_in). */
+ val expiresAtMillis: Long
+)
+
+/** The refresh token is invalid/expired/revoked — user must reconnect. */
+class OAuthInvalidGrant(message: String) : IOException(message)
+
+/** Any other non-2xx token endpoint response. */
+class OAuthTokenError(val code: Int, message: String) : IOException(message)
+
+/**
+ * Provider-generic OAuth2 authorization-code + PKCE engine. Pure OkHttp;
+ * JVM-testable against MockWebServer.
+ */
+class OAuth2Helper(
+ private val client: OkHttpClient = OkHttpClient.Builder()
+ .connectTimeout(20, TimeUnit.SECONDS)
+ .readTimeout(20, TimeUnit.SECONDS)
+ .build(),
+ private val clock: () -> Long = System::currentTimeMillis
+) {
+
+ private val json = Json { ignoreUnknownKeys = true }
+
+ fun buildAuthorizationUrl(
+ cfg: OAuth2Config,
+ redirectUri: String,
+ state: String,
+ codeChallenge: String
+ ): String {
+ val builder = cfg.authUrl.toHttpUrl().newBuilder()
+ .addQueryParameter("response_type", "code")
+ .addQueryParameter("client_id", cfg.clientId)
+ .addQueryParameter("redirect_uri", redirectUri)
+ .addQueryParameter("scope", cfg.scopes.joinToString(" "))
+ .addQueryParameter("state", state)
+ .addQueryParameter("code_challenge", codeChallenge)
+ .addQueryParameter("code_challenge_method", "S256")
+ cfg.extraAuthParams.forEach { (k, v) -> builder.addQueryParameter(k, v) }
+ return builder.build().toString()
+ }
+
+ suspend fun exchangeCode(
+ cfg: OAuth2Config,
+ code: String,
+ redirectUri: String,
+ codeVerifier: String
+ ): TokenSet {
+ val form = FormBody.Builder()
+ .add("grant_type", "authorization_code")
+ .add("code", code)
+ .add("redirect_uri", redirectUri)
+ .add("client_id", cfg.clientId)
+ .add("client_secret", cfg.clientSecret)
+ .add("code_verifier", codeVerifier)
+ .build()
+ return requestToken(cfg.tokenUrl, form, currentRefreshToken = null)
+ }
+
+ suspend fun refresh(cfg: OAuth2Config, refreshToken: String): TokenSet {
+ val form = FormBody.Builder()
+ .add("grant_type", "refresh_token")
+ .add("refresh_token", refreshToken)
+ .add("client_id", cfg.clientId)
+ .add("client_secret", cfg.clientSecret)
+ .build()
+ return requestToken(cfg.tokenUrl, form, currentRefreshToken = refreshToken)
+ }
+
+ private suspend fun requestToken(
+ tokenUrl: String,
+ form: FormBody,
+ currentRefreshToken: String?
+ ): TokenSet = withContext(Dispatchers.IO) {
+ val request = Request.Builder().url(tokenUrl).post(form).build()
+ client.newCall(request).execute().use { response ->
+ val body = response.body?.string().orEmpty()
+ if (!response.isSuccessful) {
+ val error = runCatching {
+ json.parseToJsonElement(body).jsonObject["error"]?.jsonPrimitive?.contentOrNull
+ }.getOrNull()
+ if (error == "invalid_grant") {
+ throw OAuthInvalidGrant("Token endpoint returned invalid_grant — reconnect required.")
+ }
+ throw OAuthTokenError(
+ response.code,
+ "Token endpoint HTTP ${response.code}: ${error ?: body.take(200)}"
+ )
+ }
+ val obj = json.parseToJsonElement(body).jsonObject
+ val accessToken = obj["access_token"]?.jsonPrimitive?.contentOrNull
+ ?: throw OAuthTokenError(response.code, "Token response missing access_token")
+ val expiresIn = obj["expires_in"]?.jsonPrimitive?.longOrNull ?: 3600L
+ TokenSet(
+ accessToken = accessToken,
+ refreshToken = obj["refresh_token"]?.jsonPrimitive?.contentOrNull
+ ?: currentRefreshToken,
+ expiresAtMillis = clock() + expiresIn * 1000
+ )
+ }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/connectors/oauth/Pkce.kt b/app/src/main/java/com/gotcha/connectors/oauth/Pkce.kt
new file mode 100644
index 0000000..9aed98a
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/oauth/Pkce.kt
@@ -0,0 +1,29 @@
+package com.gotcha.connectors.oauth
+
+import java.security.MessageDigest
+import java.security.SecureRandom
+
+/** PKCE (RFC 7636) code verifier + S256 challenge generation. */
+object Pkce {
+
+ private val verifierChars =
+ ('A'..'Z') + ('a'..'z') + ('0'..'9') + listOf('-', '.', '_', '~')
+
+ fun generateVerifier(length: Int = 64): String {
+ require(length in 43..128) { "RFC 7636 verifier length must be 43-128" }
+ val random = SecureRandom()
+ return buildString(length) {
+ repeat(length) { append(verifierChars[random.nextInt(verifierChars.size)]) }
+ }
+ }
+
+ /** S256: BASE64URL-ENCODE(SHA256(ASCII(verifier))) without padding. */
+ fun challengeS256(verifier: String): String {
+ val digest = MessageDigest.getInstance("SHA-256")
+ .digest(verifier.toByteArray(Charsets.US_ASCII))
+ return base64UrlNoPadding(digest)
+ }
+
+ fun base64UrlNoPadding(bytes: ByteArray): String =
+ java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
+}
diff --git a/app/src/main/java/com/gotcha/tools/AlarmTool.kt b/app/src/main/java/com/gotcha/tools/AlarmTool.kt
index 3458630..f5d7f21 100644
--- a/app/src/main/java/com/gotcha/tools/AlarmTool.kt
+++ b/app/src/main/java/com/gotcha/tools/AlarmTool.kt
@@ -44,6 +44,12 @@ import java.util.Locale
@Suppress("TooManyFunctions")
class AlarmTool(private val context: Context) {
+ companion object {
+ // Not a documented android.provider.AlarmClock constant; some clock apps
+ // (e.g. Google Clock) honor it best-effort to dismiss a ringing timer.
+ private const val ACTION_DISMISS_TIMER = "android.intent.action.DISMISS_TIMER"
+ }
+
private val prefs: SharedPreferences = context.getSharedPreferences("gotcha_alarms", Context.MODE_PRIVATE)
private var nextId: Long
get() = prefs.getLong("next_id", 1)
@@ -102,13 +108,38 @@ class AlarmTool(private val context: Context) {
)
}
- fun setTimer(seconds: Int, message: String? = null, hours: Int? = null, minutes: Int? = null): ToolResult {
+ fun setTimer(
+ seconds: Int,
+ message: String? = null,
+ hours: Int? = null,
+ minutes: Int? = null,
+ system: Boolean = false
+ ): ToolResult {
val totalSeconds = seconds + (hours ?: 0) * 3600 + (minutes ?: 0) * 60
if (totalSeconds < 1) return ToolResult.error("Timer length must be at least 1 second.")
- exactAlarmError()?.let { return it }
- val id = nextId++
val label = message?.takeIf { it.isNotBlank() }
+ if (system) {
+ val intent = Intent(AlarmClock.ACTION_SET_TIMER).apply {
+ putExtra(AlarmClock.EXTRA_LENGTH, totalSeconds)
+ if (label != null) putExtra(AlarmClock.EXTRA_MESSAGE, label)
+ putExtra(AlarmClock.EXTRA_SKIP_UI, true)
+ }
+ if (!dispatchClockIntent(intent)) {
+ return ToolResult.error(
+ "No clock app handled the system timer request. Omit system=true to use an in-app timer instead."
+ )
+ }
+ val id = nextId++
+ saveTimer(TimerRecord(id, totalSeconds, label, system = true))
+ return ToolResult.ok(
+ "Started ${label ?: "a timer"} for ${totalSeconds}s in the system clock app (id=$id). " +
+ "Use dismiss_timer while it's ringing; delete_timer only removes it from this assistant's list."
+ )
+ }
+
+ exactAlarmError()?.let { return it }
+ val id = nextId++
val record = TimerRecord(id, totalSeconds, label)
try {
scheduleTimer(record)
@@ -125,6 +156,51 @@ class AlarmTool(private val context: Context) {
return ToolResult.ok("Started ${label ?: "a timer"} for${extra.trimStart()} (id=$id).")
}
+ /** Opens the system clock app's alarms list (ACTION_SHOW_ALARMS). */
+ fun showAlarms(): ToolResult {
+ val intent = Intent(AlarmClock.ACTION_SHOW_ALARMS)
+ return if (dispatchClockIntent(intent)) {
+ ToolResult.ok("Opened the alarms list in the clock app.")
+ } else {
+ ToolResult.error("No clock app handled the show-alarms request.")
+ }
+ }
+
+ /** Snoozes the currently ringing alarm (ACTION_SNOOZE_ALARM). No effect if no alarm is ringing. */
+ fun snoozeAlarm(minutes: Int? = null): ToolResult {
+ val intent = Intent(AlarmClock.ACTION_SNOOZE_ALARM).apply {
+ if (minutes != null && minutes > 0) putExtra(AlarmClock.EXTRA_ALARM_SNOOZE_DURATION, minutes)
+ }
+ return if (dispatchClockIntent(intent)) {
+ ToolResult.ok(
+ "Sent a snooze request to the clock app" +
+ (minutes?.let { " for $it minute(s)" } ?: "") +
+ ". This only has an effect if an alarm is currently ringing."
+ )
+ } else {
+ ToolResult.error("No clock app handled the snooze request.")
+ }
+ }
+
+ /**
+ * Dismisses a currently ringing system-clock-app timer (best-effort; not
+ * all clock apps support this action). Distinct from [deleteTimer], which
+ * only removes an in-app timer's shadow record.
+ */
+ fun dismissTimer(): ToolResult {
+ val intent = Intent(ACTION_DISMISS_TIMER)
+ return if (dispatchClockIntent(intent)) {
+ ToolResult.ok(
+ "Sent a dismiss request to the clock app. This only has an effect if a timer is " +
+ "currently ringing there; support varies by clock app."
+ )
+ } else {
+ ToolResult.error(
+ "No clock app handled the dismiss-timer request (this action isn't supported by all clock apps)."
+ )
+ }
+ }
+
fun listAlarms(): ToolResult {
var alarms = loadAlarms()
@@ -273,9 +349,15 @@ class AlarmTool(private val context: Context) {
fun doDeleteTimer(id: Long): ToolResult {
val timers = loadTimersMutable()
- if (timers.none { it.id == id }) return ToolResult.error("Timer $id not found.")
- cancelPendingIntent(timerRequestCode(id))
+ val t = timers.firstOrNull { it.id == id } ?: return ToolResult.error("Timer $id not found.")
saveTimers(timers.filter { it.id != id })
+ if (t.system) {
+ return ToolResult.ok(
+ "Removed timer $id from this assistant's list, but it lives in the system clock app — " +
+ "use dismiss_timer while it's ringing, or ask the user to cancel it there."
+ )
+ }
+ cancelPendingIntent(timerRequestCode(id))
return ToolResult.ok("Deleted timer $id.")
}
@@ -439,7 +521,8 @@ class AlarmTool(private val context: Context) {
val id: Long,
val seconds: Int,
val label: String?,
- val triggerAt: Long = System.currentTimeMillis() + seconds * 1000L
+ val triggerAt: Long = System.currentTimeMillis() + seconds * 1000L,
+ val system: Boolean = false
)
private fun saveAlarm(r: AlarmRecord) {
@@ -507,6 +590,7 @@ class AlarmTool(private val context: Context) {
put("seconds", t.seconds)
if (t.label != null) put("label", t.label)
put("triggerAt", t.triggerAt)
+ put("system", t.system)
}
)
}
@@ -524,7 +608,8 @@ class AlarmTool(private val context: Context) {
id = id,
seconds = seconds,
label = o["label"]?.jsonPrimitive?.content,
- triggerAt = o["triggerAt"]?.jsonPrimitive?.content?.toLongOrNull() ?: (System.currentTimeMillis() + seconds * 1000L)
+ triggerAt = o["triggerAt"]?.jsonPrimitive?.content?.toLongOrNull() ?: (System.currentTimeMillis() + seconds * 1000L),
+ system = o["system"]?.jsonPrimitive?.booleanOrNull ?: false
)
}
} catch (_: Exception) { emptyList() }
diff --git a/app/src/main/java/com/gotcha/tools/CalendarRecurrence.kt b/app/src/main/java/com/gotcha/tools/CalendarRecurrence.kt
new file mode 100644
index 0000000..4f4041f
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/CalendarRecurrence.kt
@@ -0,0 +1,73 @@
+package com.gotcha.tools
+
+import java.text.SimpleDateFormat
+import java.util.Calendar
+import java.util.Date
+import java.util.Locale
+import java.util.TimeZone
+
+/** Pure date/recurrence helpers for [CalendarTool] — no ContentResolver access. */
+internal object CalendarRecurrence {
+
+ fun parseWhen(value: String): Long? {
+ val v = value.trim()
+ v.toLongOrNull()?.let { return it }
+ val formats = listOf(
+ "yyyy-MM-dd HH:mm",
+ "yyyy-MM-dd'T'HH:mm",
+ "yyyy-MM-dd HH:mm:ss",
+ "yyyy-MM-dd'T'HH:mm:ss"
+ )
+ for (f in formats) {
+ try {
+ return SimpleDateFormat(f, Locale.getDefault()).parse(v)?.time
+ } catch (_: Exception) { }
+ }
+ return null
+ }
+
+ /** Floors [epochMs] to the start of its UTC calendar day. */
+ fun utcMidnight(epochMs: Long): Long {
+ val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
+ cal.timeInMillis = epochMs
+ cal.set(Calendar.HOUR_OF_DAY, 0)
+ cal.set(Calendar.MINUTE, 0)
+ cal.set(Calendar.SECOND, 0)
+ cal.set(Calendar.MILLISECOND, 0)
+ return cal.timeInMillis
+ }
+
+ /** RFC 5545 RRULE for a simple daily/weekly/monthly/yearly recurrence. */
+ fun buildRRule(frequency: String, count: Int?, until: String?): String? {
+ val freq = when (frequency.trim().lowercase()) {
+ "daily" -> "DAILY"
+ "weekly" -> "WEEKLY"
+ "monthly" -> "MONTHLY"
+ "yearly", "annually" -> "YEARLY"
+ else -> return null
+ }
+ return buildString {
+ append("FREQ=$freq")
+ if (count != null && count > 0) {
+ append(";COUNT=$count")
+ } else if (!until.isNullOrBlank()) {
+ val untilMs = parseWhen(until)
+ if (untilMs != null) {
+ val utc = SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.US).apply {
+ timeZone = TimeZone.getTimeZone("UTC")
+ }
+ append(";UNTIL=${utc.format(Date(untilMs))}")
+ }
+ }
+ }
+ }
+
+ /** RFC 5545 duration string (e.g. "P0DT1H0M0S") for the events DURATION column. */
+ fun iso8601Duration(millis: Long): String {
+ val totalSeconds = (millis / 1000).coerceAtLeast(0)
+ val hours = totalSeconds / 3600
+ val minutes = (totalSeconds % 3600) / 60
+ val seconds = totalSeconds % 60
+ return "P0DT${hours}H${minutes}M${seconds}S"
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/CalendarTool.kt b/app/src/main/java/com/gotcha/tools/CalendarTool.kt
index 5eb88a7..5177277 100644
--- a/app/src/main/java/com/gotcha/tools/CalendarTool.kt
+++ b/app/src/main/java/com/gotcha/tools/CalendarTool.kt
@@ -32,32 +32,7 @@ class CalendarTool(private val context: Context) {
)
}
return try {
- val now = System.currentTimeMillis()
- val rangeStart: Long
- val rangeEnd: Long
- val rangeDesc: String
-
- if (fromDate != null || toDate != null) {
- val df = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
- rangeStart = if (fromDate != null) {
- try { df.parse(fromDate)?.time ?: now } catch (_: Exception) { now }
- } else {
- now
- }
- rangeEnd = if (toDate != null) {
- try { df.parse(toDate)?.time?.plus(86_400_000L - 1) ?: (now + 86400000L) } catch (
- _: Exception
- ) { now + 86400000L }
- } else {
- rangeStart + 86400000L
- }
- rangeDesc = "${fromDate ?: "today"} → ${toDate ?: "tomorrow"}"
- } else {
- val days = (daysAhead ?: 7).coerceIn(1, 365)
- rangeStart = now
- rangeEnd = now + days * 24L * 60 * 60 * 1000
- rangeDesc = "next $days day(s)"
- }
+ val (rangeStart, rangeEnd, rangeDesc) = resolveRange(daysAhead, fromDate, toDate)
val builder = CalendarContract.Instances.CONTENT_URI.buildUpon()
ContentUris.appendId(builder, rangeStart)
@@ -101,29 +76,9 @@ class CalendarTool(private val context: Context) {
val calIdx = cursor.getColumnIndexOrThrow(CalendarContract.Instances.CALENDAR_DISPLAY_NAME)
val out = StringBuilder()
var count = 0
+ val indices = EventCursorIndices(idIdx, titleIdx, beginIdx, endIdx, locIdx, descIdx, statusIdx, calIdx)
while (cursor.moveToNext() && count < 50) {
- val eventId = cursor.getLong(idIdx)
- val title = cursor.getString(titleIdx) ?: "(untitled)"
- val begin = readable.format(Date(cursor.getLong(beginIdx)))
- val end = readable.format(Date(cursor.getLong(endIdx)))
- val loc = cursor.getString(locIdx)
- val desc = cursor.getString(descIdx)
- val status = when (cursor.getInt(statusIdx)) {
- CalendarContract.Instances.STATUS_CONFIRMED -> "confirmed"
- CalendarContract.Instances.STATUS_TENTATIVE -> "tentative"
- CalendarContract.Instances.STATUS_CANCELED -> "cancelled"
- else -> null
- }
- val calName = cursor.getString(calIdx)
-
- out.append("[id=$eventId] $begin")
- if (status != null) out.append(" [$status]")
- out.append(" $title")
- if (calName != null) out.append(" 📅 $calName")
- out.append("\n ends $end")
- if (!loc.isNullOrBlank()) out.append("\n 📍 $loc")
- if (!desc.isNullOrBlank()) out.append("\n ${desc.take(200)}")
- out.append("\n")
+ out.append(formatEventRow(cursor, indices))
count++
}
if (count == 0) {
@@ -146,7 +101,11 @@ class CalendarTool(private val context: Context) {
description: String? = null,
allDay: Boolean? = null,
reminderMinutes: Int? = null,
- calendarName: String? = null
+ calendarName: String? = null,
+ attendees: List<String>? = null,
+ recurrence: String? = null,
+ recurrenceCount: Int? = null,
+ recurrenceUntil: String? = null
): ToolResult {
if (title.isBlank()) {
return ToolResult.error(
@@ -161,79 +120,123 @@ class CalendarTool(private val context: Context) {
"Adding a calendar event needs the Calendar permission. I have requested it — please grant it and ask again."
)
}
- val startMs = parseWhen(start)
+ var startMs = CalendarRecurrence.parseWhen(start)
?: return ToolResult.error(
"Could not understand the start time '$start'. Use 'yyyy-MM-dd HH:mm' (e.g. '2026-07-17 15:30') " +
"or epoch milliseconds."
)
- val endMs = if (end.isNullOrBlank()) {
+ var endMs = if (end.isNullOrBlank()) {
startMs + 60 * 60 * 1000
} else {
- parseWhen(end) ?: return ToolResult.error(
+ CalendarRecurrence.parseWhen(end) ?: return ToolResult.error(
"Could not understand the end time '$end'. Use 'yyyy-MM-dd HH:mm' (e.g. " +
"'2026-07-17 17:00') or epoch milliseconds."
)
}
if (allDay == true) {
- // all-day events: set to midnight of the start date
- val cal = java.util.Calendar.getInstance()
- cal.timeInMillis = startMs
- cal.set(java.util.Calendar.HOUR_OF_DAY, 0)
- cal.set(java.util.Calendar.MINUTE, 0)
- cal.set(java.util.Calendar.SECOND, 0)
- cal.set(java.util.Calendar.MILLISECOND, 0)
- // startMs is already set above from parseWhen
+ // All-day events must use UTC-midnight boundaries with EVENT_TIMEZONE="UTC"
+ // (Android calendar provider convention), else they render on the wrong day.
+ startMs = CalendarRecurrence.utcMidnight(startMs)
+ endMs = CalendarRecurrence.utcMidnight(endMs).let { if (it <= startMs) startMs + 86_400_000L else it }
+ }
+
+ val rrule = recurrence?.let {
+ CalendarRecurrence.buildRRule(it, recurrenceCount, recurrenceUntil)
+ ?: return ToolResult.error(
+ "Unknown recurrence '$it'. Use one of: daily, weekly, monthly, yearly."
+ )
}
return try {
- val calendarId = if (!calendarName.isNullOrBlank()) {
- findCalendarByName(calendarName)
- } else {
- null
- ?: defaultWritableCalendarId()
- ?: return ToolResult.error(
- "No writable calendar was found on this device. You may add a Google account or use the " +
- "device's calendar app to set one up."
- )
- }
+ val calendarId = resolveCalendarId(calendarName)
+ ?: return ToolResult.error(calendarIdErrorMessage(calendarName))
- val values = ContentValues().apply {
- put(CalendarContract.Events.CALENDAR_ID, calendarId)
- put(CalendarContract.Events.TITLE, title)
- put(CalendarContract.Events.DTSTART, startMs)
- put(CalendarContract.Events.DTEND, endMs)
- put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().id)
- if (allDay == true) put(CalendarContract.Events.ALL_DAY, 1)
- if (!location.isNullOrBlank()) put(CalendarContract.Events.EVENT_LOCATION, location)
- if (!description.isNullOrBlank()) put(CalendarContract.Events.DESCRIPTION, description)
- }
+ val values = buildEventValues(
+ NewEventSpec(calendarId, title, startMs, endMs, rrule, allDay, location, description)
+ )
val uri = context.contentResolver.insert(CalendarContract.Events.CONTENT_URI, values)
?: return ToolResult.error(
"The calendar rejected the new event. You may check that the calendar is writable and try " +
"again."
)
+ val eventId = uri.lastPathSegment!!.toLong()
- // Add reminder if requested
- if (reminderMinutes != null && reminderMinutes >= 0) {
- val reminderValues = ContentValues().apply {
- put(CalendarContract.Reminders.EVENT_ID, uri.lastPathSegment!!.toLong())
- put(CalendarContract.Reminders.MINUTES, reminderMinutes)
- put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT)
- }
- context.contentResolver.insert(CalendarContract.Reminders.CONTENT_URI, reminderValues)
- }
+ insertReminder(eventId, reminderMinutes)
+ // Add attendees if requested — synced Google calendars send real invites.
+ addAttendees(eventId, attendees)
- val extras = buildString {
- if (allDay == true) append(" all-day")
- if (reminderMinutes != null && reminderMinutes >= 0) append(", reminder $reminderMinutes min before")
- }
+ val extras = createEventExtrasSummary(allDay, rrule, recurrence, reminderMinutes, attendees)
ToolResult.ok("Added '$title' on ${readable.format(Date(startMs))}$extras.")
} catch (e: Exception) {
ToolResult.error("Could not create the event: ${e.message}")
}
}
+ private fun resolveCalendarId(calendarName: String?): Long? =
+ if (!calendarName.isNullOrBlank()) findCalendarByName(calendarName) else defaultWritableCalendarId()
+
+ private fun calendarIdErrorMessage(calendarName: String?): String =
+ if (!calendarName.isNullOrBlank()) {
+ "No calendar named '$calendarName' was found. Available calendars: " +
+ listCalendarNames().joinToString(", ").ifBlank { "(none)" } +
+ ". Omit calendarName to use the default writable calendar."
+ } else {
+ "No writable calendar was found on this device. You may add a Google account or use the " +
+ "device's calendar app to set one up."
+ }
+
+ private data class NewEventSpec(
+ val calendarId: Long,
+ val title: String,
+ val startMs: Long,
+ val endMs: Long,
+ val rrule: String?,
+ val allDay: Boolean?,
+ val location: String?,
+ val description: String?
+ )
+
+ private fun buildEventValues(spec: NewEventSpec): ContentValues = ContentValues().apply {
+ put(CalendarContract.Events.CALENDAR_ID, spec.calendarId)
+ put(CalendarContract.Events.TITLE, spec.title)
+ put(CalendarContract.Events.DTSTART, spec.startMs)
+ if (spec.rrule != null) {
+ // Recurring events use DURATION instead of DTEND (CalendarContract requirement).
+ put(CalendarContract.Events.DURATION, CalendarRecurrence.iso8601Duration(spec.endMs - spec.startMs))
+ put(CalendarContract.Events.RRULE, spec.rrule)
+ } else {
+ put(CalendarContract.Events.DTEND, spec.endMs)
+ }
+ put(CalendarContract.Events.EVENT_TIMEZONE, if (spec.allDay == true) "UTC" else TimeZone.getDefault().id)
+ if (spec.allDay == true) put(CalendarContract.Events.ALL_DAY, 1)
+ if (!spec.location.isNullOrBlank()) put(CalendarContract.Events.EVENT_LOCATION, spec.location)
+ if (!spec.description.isNullOrBlank()) put(CalendarContract.Events.DESCRIPTION, spec.description)
+ }
+
+ private fun insertReminder(eventId: Long, reminderMinutes: Int?) {
+ if (reminderMinutes == null || reminderMinutes < 0) return
+ val reminderValues = ContentValues().apply {
+ put(CalendarContract.Reminders.EVENT_ID, eventId)
+ put(CalendarContract.Reminders.MINUTES, reminderMinutes)
+ put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT)
+ }
+ context.contentResolver.insert(CalendarContract.Reminders.CONTENT_URI, reminderValues)
+ }
+
+ private fun createEventExtrasSummary(
+ allDay: Boolean?,
+ rrule: String?,
+ recurrence: String?,
+ reminderMinutes: Int?,
+ attendees: List<String>?
+ ): String = buildString {
+ if (allDay == true) append(" all-day")
+ if (rrule != null) append(", repeating $recurrence")
+ if (reminderMinutes != null && reminderMinutes >= 0) append(", reminder $reminderMinutes min before")
+ if (!attendees.isNullOrEmpty()) append(", ${attendees.size} attendee(s) invited")
+ }
+
fun editEvent(
eventId: Long,
title: String? = null,
@@ -242,7 +245,11 @@ class CalendarTool(private val context: Context) {
location: String? = null,
description: String? = null,
allDay: Boolean? = null,
- reminderMinutes: Int? = null
+ reminderMinutes: Int? = null,
+ attendees: List<String>? = null,
+ recurrence: String? = null,
+ recurrenceCount: Int? = null,
+ recurrenceUntil: String? = null
): ToolResult {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR)
!= PackageManager.PERMISSION_GRANTED
@@ -254,25 +261,44 @@ class CalendarTool(private val context: Context) {
}
return try {
val values = ContentValues()
+ var startMs: Long? = null
+ var endMs: Long? = null
if (title != null) values.put(CalendarContract.Events.TITLE, title)
if (start != null) {
- val ms = parseWhen(start) ?: return ToolResult.error(
+ startMs = CalendarRecurrence.parseWhen(start) ?: return ToolResult.error(
"Could not understand the start time '$start'. Use 'yyyy-MM-dd " +
"HH:mm' (e.g. '2026-07-17 15:30') or epoch milliseconds."
)
- values.put(CalendarContract.Events.DTSTART, ms)
+ values.put(CalendarContract.Events.DTSTART, startMs)
}
if (end != null) {
- val ms = parseWhen(end) ?: return ToolResult.error(
+ endMs = CalendarRecurrence.parseWhen(end) ?: return ToolResult.error(
"Could not understand the end time '$end'. Use 'yyyy-MM-dd HH:mm' " +
"(e.g. '2026-07-17 17:00') or epoch milliseconds."
)
- values.put(CalendarContract.Events.DTEND, ms)
}
if (location != null) values.put(CalendarContract.Events.EVENT_LOCATION, location)
if (description != null) values.put(CalendarContract.Events.DESCRIPTION, description)
if (allDay != null) values.put(CalendarContract.Events.ALL_DAY, if (allDay) 1 else 0)
+ if (recurrence != null) {
+ val rrule = CalendarRecurrence.buildRRule(recurrence, recurrenceCount, recurrenceUntil)
+ ?: return ToolResult.error(
+ "Unknown recurrence '$recurrence'. Use one of: daily, weekly, monthly, yearly."
+ )
+ values.put(CalendarContract.Events.RRULE, rrule)
+ if (startMs != null && endMs != null) {
+ values.put(CalendarContract.Events.DURATION, CalendarRecurrence.iso8601Duration(endMs - startMs))
+ } else if (endMs != null) {
+ // Recurring events use DURATION, not DTEND — caller must supply both to change length.
+ return ToolResult.error(
+ "To change the length of a recurring event, provide both 'start' and 'end'."
+ )
+ }
+ } else if (endMs != null) {
+ values.put(CalendarContract.Events.DTEND, endMs)
+ }
+
val uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId)
val rows = context.contentResolver.update(uri, values, null, null)
if (rows == 0) {
@@ -281,6 +307,8 @@ class CalendarTool(private val context: Context) {
)
}
+ if (attendees != null) replaceAttendees(eventId, attendees)
+
// Update reminders: clear existing, add new if requested
if (reminderMinutes != null) {
context.contentResolver.delete(
@@ -331,6 +359,145 @@ class CalendarTool(private val context: Context) {
}
}
+ private data class EventCursorIndices(
+ val id: Int,
+ val title: Int,
+ val begin: Int,
+ val end: Int,
+ val location: Int,
+ val description: Int,
+ val status: Int,
+ val calendarName: Int
+ )
+
+ private fun formatEventRow(cursor: android.database.Cursor, idx: EventCursorIndices): String {
+ val eventId = cursor.getLong(idx.id)
+ val title = cursor.getString(idx.title) ?: "(untitled)"
+ val begin = readable.format(Date(cursor.getLong(idx.begin)))
+ val end = readable.format(Date(cursor.getLong(idx.end)))
+ val loc = cursor.getString(idx.location)
+ val desc = cursor.getString(idx.description)
+ val status = when (cursor.getInt(idx.status)) {
+ CalendarContract.Instances.STATUS_CONFIRMED -> "confirmed"
+ CalendarContract.Instances.STATUS_TENTATIVE -> "tentative"
+ CalendarContract.Instances.STATUS_CANCELED -> "cancelled"
+ else -> null
+ }
+ val calName = cursor.getString(idx.calendarName)
+
+ return buildString {
+ append("[id=$eventId] $begin")
+ if (status != null) append(" [$status]")
+ append(" $title")
+ if (calName != null) append(" 📅 $calName")
+ append("\n ends $end")
+ if (!loc.isNullOrBlank()) append("\n 📍 $loc")
+ if (!desc.isNullOrBlank()) append("\n ${desc.take(200)}")
+ reminderMinutesFor(eventId).takeIf { it.isNotEmpty() }?.let {
+ append("\n ⏰ reminder(s): ${it.joinToString(", ") { m -> "${m}m before" }}")
+ }
+ attendeesFor(eventId).takeIf { it.isNotEmpty() }?.let {
+ append("\n 👤 attendees: ${it.joinToString(", ")}")
+ }
+ append("\n")
+ }
+ }
+
+ private fun resolveRange(daysAhead: Int?, fromDate: String?, toDate: String?): Triple<Long, Long, String> {
+ val now = System.currentTimeMillis()
+ if (fromDate == null && toDate == null) {
+ val days = (daysAhead ?: 7).coerceIn(1, 365)
+ return Triple(now, now + days * 24L * 60 * 60 * 1000, "next $days day(s)")
+ }
+ val df = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
+ val rangeStart = if (fromDate != null) {
+ try { df.parse(fromDate)?.time ?: now } catch (_: Exception) { now }
+ } else {
+ now
+ }
+ val rangeEnd = if (toDate != null) {
+ try {
+ df.parse(toDate)?.time?.plus(86_400_000L - 1) ?: (now + 86400000L)
+ } catch (_: Exception) {
+ now + 86400000L
+ }
+ } else {
+ rangeStart + 86400000L
+ }
+ return Triple(rangeStart, rangeEnd, "${fromDate ?: "today"} → ${toDate ?: "tomorrow"}")
+ }
+
+ private fun reminderMinutesFor(eventId: Long): List<Int> {
+ val minutes = mutableListOf<Int>()
+ context.contentResolver.query(
+ CalendarContract.Reminders.CONTENT_URI,
+ arrayOf(CalendarContract.Reminders.MINUTES),
+ "${CalendarContract.Reminders.EVENT_ID} = ?",
+ arrayOf(eventId.toString()),
+ null
+ )?.use { cursor ->
+ val idx = cursor.getColumnIndexOrThrow(CalendarContract.Reminders.MINUTES)
+ while (cursor.moveToNext()) minutes.add(cursor.getInt(idx))
+ }
+ return minutes
+ }
+
+ private fun attendeesFor(eventId: Long): List<String> {
+ val emails = mutableListOf<String>()
+ context.contentResolver.query(
+ CalendarContract.Attendees.CONTENT_URI,
+ arrayOf(CalendarContract.Attendees.ATTENDEE_EMAIL),
+ "${CalendarContract.Attendees.EVENT_ID} = ?",
+ arrayOf(eventId.toString()),
+ null
+ )?.use { cursor ->
+ val idx = cursor.getColumnIndexOrThrow(CalendarContract.Attendees.ATTENDEE_EMAIL)
+ while (cursor.moveToNext()) cursor.getString(idx)?.let { emails.add(it) }
+ }
+ return emails
+ }
+
+ private fun addAttendees(eventId: Long, attendees: List<String>?) {
+ if (attendees.isNullOrEmpty()) return
+ attendees.forEach { email ->
+ if (email.isBlank()) return@forEach
+ val values = ContentValues().apply {
+ put(CalendarContract.Attendees.EVENT_ID, eventId)
+ put(CalendarContract.Attendees.ATTENDEE_EMAIL, email.trim())
+ put(CalendarContract.Attendees.ATTENDEE_RELATIONSHIP, CalendarContract.Attendees.RELATIONSHIP_ATTENDEE)
+ put(CalendarContract.Attendees.ATTENDEE_TYPE, CalendarContract.Attendees.TYPE_REQUIRED)
+ put(CalendarContract.Attendees.ATTENDEE_STATUS, CalendarContract.Attendees.ATTENDEE_STATUS_NONE)
+ }
+ context.contentResolver.insert(CalendarContract.Attendees.CONTENT_URI, values)
+ }
+ }
+
+ private fun replaceAttendees(eventId: Long, attendees: List<String>) {
+ context.contentResolver.delete(
+ CalendarContract.Attendees.CONTENT_URI,
+ "${CalendarContract.Attendees.EVENT_ID} = ?",
+ arrayOf(eventId.toString())
+ )
+ addAttendees(eventId, attendees)
+ }
+
+ private fun listCalendarNames(): List<String> {
+ val names = mutableListOf<String>()
+ context.contentResolver.query(
+ CalendarContract.Calendars.CONTENT_URI,
+ arrayOf(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME),
+ null,
+ null,
+ null
+ )?.use { cursor ->
+ val nameIdx = cursor.getColumnIndexOrThrow(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME)
+ while (cursor.moveToNext()) {
+ cursor.getString(nameIdx)?.let { names.add(it) }
+ }
+ }
+ return names
+ }
+
private fun findCalendarByName(name: String): Long? {
val projection = arrayOf(
CalendarContract.Calendars._ID,
@@ -355,23 +522,6 @@ class CalendarTool(private val context: Context) {
return null
}
- private fun parseWhen(value: String): Long? {
- val v = value.trim()
- v.toLongOrNull()?.let { return it }
- val formats = listOf(
- "yyyy-MM-dd HH:mm",
- "yyyy-MM-dd'T'HH:mm",
- "yyyy-MM-dd HH:mm:ss",
- "yyyy-MM-dd'T'HH:mm:ss"
- )
- for (f in formats) {
- try {
- return SimpleDateFormat(f, Locale.getDefault()).parse(v)?.time
- } catch (_: Exception) { }
- }
- return null
- }
-
private fun defaultWritableCalendarId(): Long? {
val projection = arrayOf(CalendarContract.Calendars._ID)
val selection = "${CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL} >= ?"
diff --git a/app/src/main/java/com/gotcha/tools/MimeMessageBuilder.kt b/app/src/main/java/com/gotcha/tools/MimeMessageBuilder.kt
new file mode 100644
index 0000000..bbfae4f
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/MimeMessageBuilder.kt
@@ -0,0 +1,49 @@
+package com.gotcha.tools
+
+/**
+ * Builds a minimal RFC 2822 plain-text message. Pure string manipulation —
+ * no JavaMail dependency — so the exact same bytes can be handed to SMTP
+ * (via MimeMessage parsing) and to the Gmail API (`{"raw": base64url}`).
+ */
+object MimeMessageBuilder {
+
+ /**
+ * Build the RFC 2822 message text (CRLF line endings). Non-ASCII subjects
+ * are RFC 2047 UTF-8 base64 encoded; the body is sent as UTF-8 8bit.
+ */
+ fun build(
+ from: String,
+ to: List<String>,
+ cc: List<String> = emptyList(),
+ bcc: List<String> = emptyList(),
+ subject: String,
+ body: String
+ ): String {
+ require(to.isNotEmpty()) { "At least one recipient required" }
+ val headers = buildList {
+ add("From: ${from.trim()}")
+ add("To: ${to.joinToString(", ") { it.trim() }}")
+ if (cc.isNotEmpty()) add("Cc: ${cc.joinToString(", ") { it.trim() }}")
+ if (bcc.isNotEmpty()) add("Bcc: ${bcc.joinToString(", ") { it.trim() }}")
+ add("Subject: ${encodeHeader(subject)}")
+ add("MIME-Version: 1.0")
+ add("Content-Type: text/plain; charset=\"UTF-8\"")
+ add("Content-Transfer-Encoding: 8bit")
+ }
+ val normalizedBody = body.replace("\r\n", "\n").replace("\n", "\r\n")
+ return headers.joinToString("\r\n") + "\r\n\r\n" + normalizedBody
+ }
+
+ /** Gmail API `messages.send` payload value: base64url (no padding) of the raw message. */
+ fun toBase64Url(rawMessage: String): String =
+ java.util.Base64.getUrlEncoder().withoutPadding()
+ .encodeToString(rawMessage.toByteArray(Charsets.UTF_8))
+
+ /** RFC 2047 encoded-word for non-ASCII header values; plain values pass through. */
+ private fun encodeHeader(value: String): String {
+ if (value.all { it.code in 32..126 }) return value
+ val encoded = java.util.Base64.getEncoder()
+ .encodeToString(value.toByteArray(Charsets.UTF_8))
+ return "=?UTF-8?B?$encoded?="
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/NotificationTool.kt b/app/src/main/java/com/gotcha/tools/NotificationTool.kt
index 93f4291..6d8637e 100644
--- a/app/src/main/java/com/gotcha/tools/NotificationTool.kt
+++ b/app/src/main/java/com/gotcha/tools/NotificationTool.kt
@@ -18,11 +18,21 @@ import java.util.Locale
*/
class NotificationTool(private val context: Context) {
- fun readNotifications(limit: Int): ToolResult {
+ fun readNotifications(limit: Int, app: String? = null): ToolResult {
val service = requireService() ?: return notEnabled()
- val notifications = service.currentNotifications()
+ var notifications = service.currentNotifications().toList()
if (notifications.isEmpty()) return ToolResult.ok("There are no active notifications.")
val pm = context.packageManager
+
+ if (!app.isNullOrBlank()) {
+ val needle = app.trim()
+ notifications = notifications.filter { sbn ->
+ sbn.packageName.contains(needle, ignoreCase = true) ||
+ appLabel(pm, sbn.packageName).contains(needle, ignoreCase = true)
+ }
+ if (notifications.isEmpty()) return ToolResult.ok("No active notifications from '$app'.")
+ }
+
val fmt = SimpleDateFormat("HH:mm", Locale.getDefault())
val out = notifications
.sortedByDescending { it.postTime }
@@ -31,17 +41,31 @@ class NotificationTool(private val context: Context) {
val extras = sbn.notification.extras
val title = extras.getCharSequence("android.title")?.toString()?.trim().orEmpty()
val text = extras.getCharSequence("android.text")?.toString()?.trim().orEmpty()
- val app = try {
- pm.getApplicationLabel(pm.getApplicationInfo(sbn.packageName, 0)).toString()
- } catch (_: Exception) {
- sbn.packageName
- }
+ val bigText = extras.getCharSequence("android.bigText")?.toString()?.trim().orEmpty()
+ val textLines = extras.getCharSequenceArray("android.textLines")
+ ?.mapNotNull { it?.toString()?.trim() }
+ ?.filter { it.isNotEmpty() }
+ .orEmpty()
+ val appName = appLabel(pm, sbn.packageName)
val body = listOf(title, text).filter { it.isNotEmpty() }.joinToString(" — ")
- "- [${fmt.format(Date(sbn.postTime))}] $app: ${body.ifEmpty { "(no text)" }} {key=${sbn.key}}"
+ val extraDetail = listOfNotNull(
+ bigText.takeIf { it.isNotEmpty() && it != text },
+ textLines.takeIf { it.isNotEmpty() }?.joinToString(" / ")
+ ).joinToString(" | ")
+ val line = "- [${fmt.format(
+ Date(sbn.postTime)
+ )}] $appName: ${body.ifEmpty { "(no text)" }} {key=${sbn.key}}"
+ if (extraDetail.isNotEmpty()) "$line\n $extraDetail" else line
}
return ToolResult.ok("Active notifications (${notifications.size}):\n$out")
}
+ private fun appLabel(pm: android.content.pm.PackageManager, packageName: String): String = try {
+ pm.getApplicationLabel(pm.getApplicationInfo(packageName, 0)).toString()
+ } catch (_: Exception) {
+ packageName
+ }
+
/** Dismiss a specific notification by key, or all of them when [key] is blank/null. */
fun dismissNotifications(key: String?): ToolResult {
val service = requireService() ?: return notEnabled()
diff --git a/app/src/main/java/com/gotcha/tools/ToolCategories.kt b/app/src/main/java/com/gotcha/tools/ToolCategories.kt
index 3ddd0e5..c7aef77 100644
--- a/app/src/main/java/com/gotcha/tools/ToolCategories.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolCategories.kt
@@ -14,7 +14,7 @@ object ToolCategories {
"global_action", "open_app",
"read_screen", "read_screen_raw",
"navigate_app", "task",
- "dial_number"
+ "dial_number", "compose_email", "show_alarms"
)
private val backgroundTools = setOf(
@@ -26,7 +26,7 @@ object ToolCategories {
"set_wallpaper", "set_clipboard",
"call_number", "send_sms", "add_contact",
"create_calendar_event", "edit_calendar_event",
- "set_alarm", "set_timer",
+ "set_alarm", "set_timer", "snooze_alarm", "dismiss_timer",
"take_photo",
"start_audio_recording", "stop_audio_recording",
"pause_audio_recording", "resume_audio_recording",
@@ -34,7 +34,8 @@ object ToolCategories {
"show_overlay", "hide_overlay",
"lock_screen", "disable_camera", "set_password_policy",
"dismiss_notifications", "media_control",
- "vibrate", "write_secure_settings"
+ "vibrate", "write_secure_settings",
+ "send_email", "mark_email_read"
)
fun classify(toolName: String): Category = when {
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index 8a0d528..ea47fcf 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -507,6 +507,32 @@ object ToolDefinitions {
"Calendar account name to add the event to (e.g. 'Work', 'Personal'). Defaults to the primary writable calendar."
)
}
+ putJsonObject("attendees") {
+ put("type", "array")
+ putJsonObject("items") { put("type", "string") }
+ put(
+ "description",
+ "Optional attendee email addresses. On a synced Google calendar this sends real invites."
+ )
+ }
+ putJsonObject("recurrence") {
+ put("type", "string")
+ put("description", "Optional repeat frequency: daily, weekly, monthly, or yearly.")
+ }
+ putJsonObject("recurrence_count") {
+ put("type", "integer")
+ put(
+ "description",
+ "Number of occurrences (with recurrence). Omit for recurrence_until or indefinite."
+ )
+ }
+ putJsonObject("recurrence_until") {
+ put("type", "string")
+ put(
+ "description",
+ "Last occurrence date (with recurrence), same format as start. Omit for recurrence_count or indefinite."
+ )
+ }
}
putJsonArray("required") {
add("title")
@@ -556,6 +582,23 @@ object ToolDefinitions {
"New reminder before event in minutes. -1 to remove reminder. Omit to keep current."
)
}
+ putJsonObject("attendees") {
+ put("type", "array")
+ putJsonObject("items") { put("type", "string") }
+ put("description", "Replace the attendee list with these email addresses. Omit to keep current.")
+ }
+ putJsonObject("recurrence") {
+ put("type", "string")
+ put("description", "New repeat frequency: daily, weekly, monthly, or yearly. Omit to keep current.")
+ }
+ putJsonObject("recurrence_count") {
+ put("type", "integer")
+ put("description", "Number of occurrences (with recurrence).")
+ }
+ putJsonObject("recurrence_until") {
+ put("type", "string")
+ put("description", "Last occurrence date (with recurrence), same format as start.")
+ }
}
putJsonArray("required") { add("event_id") }
}
@@ -619,9 +662,10 @@ object ToolDefinitions {
val setTimer = tool(
"set_timer",
- "Start a countdown timer. Timers are managed in-app (a notification fires when done), not in " +
- "the system clock app. Returns a timer ID that can be used to delete it later. " +
- "List timers with list_timers. Delete with delete_timer.",
+ "Start a countdown timer. By default it's managed in-app (a notification fires when done), " +
+ "not in the system clock app. Returns a timer ID that can be used to delete it later. " +
+ "List timers with list_timers. Delete with delete_timer (dismiss a ringing system timer " +
+ "with dismiss_timer instead).",
schema {
putJsonObject("properties") {
putJsonObject("seconds") {
@@ -640,11 +684,48 @@ object ToolDefinitions {
put("type", "string")
put("description", "Optional timer label.")
}
+ putJsonObject("system") {
+ put("type", "boolean")
+ put(
+ "description",
+ "If true, start the timer in the system clock app instead of in-app. " +
+ "Default false."
+ )
+ }
}
putJsonArray("required") { add("seconds") }
}
)
+ val showAlarms = tool(
+ "show_alarms",
+ "Open the system clock app's alarms list so the user can see all alarms, including ones " +
+ "not created by this assistant.",
+ schema { putJsonObject("properties") {} }
+ )
+
+ val snoozeAlarm = tool(
+ "snooze_alarm",
+ "Snooze the currently ringing alarm. Only has an effect if an alarm is actively ringing " +
+ "in the clock app right now.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("minutes") {
+ put("type", "integer")
+ put("description", "Snooze duration in minutes. Omit to use the clock app's default.")
+ }
+ }
+ }
+ )
+
+ val dismissTimer = tool(
+ "dismiss_timer",
+ "Dismiss a currently ringing system-clock-app timer. Only has an effect if a timer is " +
+ "actively ringing there right now; support varies by clock app. Distinct from " +
+ "delete_timer, which only removes a timer this assistant is tracking.",
+ schema { putJsonObject("properties") {} }
+ )
+
val toggleTorch = tool(
"toggle_torch",
"Turn the camera flashlight (torch) on or off. If the flashlight is already in the " +
@@ -1547,14 +1628,22 @@ object ToolDefinitions {
val readNotifications = tool(
"read_notifications",
- "Read the currently active notifications from all apps (app, time, title/text, and a " +
- "dismiss key). Needs Notification access.",
+ "Read the currently active notifications from all apps (app, time, title/text/expanded " +
+ "text, and a dismiss key). Needs Notification access.",
schema {
putJsonObject("properties") {
putJsonObject("limit") {
put("type", "integer")
put("description", "How many recent notifications to return (1-50). Default 15.")
}
+ putJsonObject("app") {
+ put("type", "string")
+ put(
+ "description",
+ "Optional filter: only notifications from this app (matches package name " +
+ "or app label, e.g. 'gmail' or 'com.google.android.gm')."
+ )
+ }
}
}
)
@@ -1720,6 +1809,133 @@ object ToolDefinitions {
}
)
+ // ---- Email connector tools (Settings → Connectors: Gmail BYO-OAuth or IMAP) ----
+
+ val listEmails = tool(
+ "list_emails",
+ "List emails from the connected account's inbox (Gmail or IMAP connector). " +
+ "Returns one row per message: [id] read-state | date | from | subject + snippet. " +
+ "Use the returned id with read_email / mark_email_read. Requires an email " +
+ "connector in Settings; if none is connected, use compose_email or the Gmail app.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("query") {
+ put("type", "string")
+ put(
+ "description",
+ "Optional search text. With Gmail connected this is full Gmail query " +
+ "syntax (e.g. 'from:alice is:unread newer_than:7d'); with IMAP it " +
+ "matches subject/from/body."
+ )
+ }
+ putJsonObject("unread_only") {
+ put("type", "boolean")
+ put("description", "Only return unread messages. Default false.")
+ }
+ putJsonObject("max") {
+ put("type", "integer")
+ put("description", "Max messages to return (1-50). Default 10.")
+ }
+ }
+ }
+ )
+
+ val readEmail = tool(
+ "read_email",
+ "Read one email's full headers and plain-text body by the id returned from list_emails " +
+ "(e.g. 'gmail:18c...' or 'imap:INBOX:42'). Does not change the unread state.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("id") {
+ put("type", "string")
+ put("description", "Message id from list_emails.")
+ }
+ }
+ putJsonArray("required") { add("id") }
+ }
+ )
+
+ val sendEmail = tool(
+ "send_email",
+ "Send a plain-text email from the connected account (Gmail or IMAP connector). " +
+ "The user always sees a confirmation dialog with recipient, subject and a body " +
+ "preview before anything is sent. If no email connector is connected, use " +
+ "compose_email instead.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("to") {
+ put("type", "array")
+ putJsonObject("items") { put("type", "string") }
+ put("description", "Recipient email addresses.")
+ }
+ putJsonObject("cc") {
+ put("type", "array")
+ putJsonObject("items") { put("type", "string") }
+ put("description", "Optional CC addresses.")
+ }
+ putJsonObject("bcc") {
+ put("type", "array")
+ putJsonObject("items") { put("type", "string") }
+ put("description", "Optional BCC addresses.")
+ }
+ putJsonObject("subject") {
+ put("type", "string")
+ put("description", "Subject line.")
+ }
+ putJsonObject("body") {
+ put("type", "string")
+ put("description", "Plain-text message body.")
+ }
+ }
+ putJsonArray("required") {
+ add("to")
+ add("subject")
+ add("body")
+ }
+ }
+ )
+
+ val markEmailRead = tool(
+ "mark_email_read",
+ "Mark an email as read or unread by its id from list_emails.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("id") {
+ put("type", "string")
+ put("description", "Message id from list_emails.")
+ }
+ putJsonObject("read") {
+ put("type", "boolean")
+ put("description", "true = mark read (default), false = mark unread.")
+ }
+ }
+ putJsonArray("required") { add("id") }
+ }
+ )
+
+ val composeEmail = tool(
+ "compose_email",
+ "Open the user's email app with a pre-filled draft (recipient/subject/body) that they " +
+ "review and send themselves. Works without any connector — use this when no email " +
+ "account is connected, or when the user wants to review before sending.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("to") {
+ put("type", "string")
+ put("description", "Recipient address (optional).")
+ }
+ putJsonObject("subject") {
+ put("type", "string")
+ put("description", "Subject line (optional).")
+ }
+ putJsonObject("body") {
+ put("type", "string")
+ put("description", "Message body (optional).")
+ }
+ }
+ }
+ )
+
val all: List<ToolDefinition> = listOf(
dialNumber, getStorageInfo, getBatteryInfo, listFiles, readFile, writeFile,
openApp, setBrightness, toggleWifi,
@@ -1758,6 +1974,12 @@ object ToolDefinitions {
// Tier 4 additions: privileged / rooted execution
checkRoot, runRootCommand, writeSecureSettings,
- searchSkills
+ searchSkills,
+
+ // Email connector tools
+ listEmails, readEmail, sendEmail, markEmailRead, composeEmail,
+
+ // Clock enhancements
+ showAlarms, snoozeAlarm, dismissTimer
)
}
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index e2030da..f12051c 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -63,6 +63,10 @@ class ToolExecutor(
private val rootTool = RootTool()
private val actionLog = ActionLog(appContext)
+ init {
+ com.gotcha.connectors.ConnectorRegistry.init(appContext)
+ }
+
/**
* Execute [name] with [args] on behalf of the given [agent].
* Returns an error without running the tool if the agent mode disallows it.
@@ -127,10 +131,25 @@ class ToolExecutor(
return withContext(Dispatchers.IO) { calendarTool.doDeleteEvent(eventId) }
}
+ /** Execute an email send the user already confirmed (payload from CONFIRM_SEND_EMAIL:). */
+ suspend fun executeSendEmail(argsBase64: String): ToolResult {
+ val email = com.gotcha.connectors.ConnectorRegistry.email()
+ ?: return ToolResult.error("Email connectors are not initialized.")
+ val result = withContext(Dispatchers.IO) { email.executeSendConfirmed(argsBase64) }
+ actionLog.record("send_email", "(confirmed send)", result)
+ return result
+ }
+
+ /** Human-readable description of a pending send, for the confirmation dialog. */
+ fun describeSendEmail(argsBase64: String): String =
+ com.gotcha.connectors.ConnectorRegistry.email()?.describeSend(argsBase64)
+ ?: "Send an email (details unavailable)."
+
// Single when-dispatch over the entire fixed tool catalog; size and branch count are
// inherent to the design (see AGENTS.md).
@Suppress("CyclomaticComplexMethod", "LongMethod")
private suspend fun dispatch(name: String, args: JsonObject): ToolResult {
+ com.gotcha.connectors.ConnectorRegistry.toolHandler(name)?.let { return it.invoke(name, args) }
return when (name) {
"dial_number" -> phoneTool.dialNumber(args.requireString("number") ?: return missing("number"))
"get_storage_info" -> storageTool.getStorageInfo()
@@ -226,7 +245,11 @@ class ToolExecutor(
description = args.requireString("description"),
allDay = args["all_day"]?.jsonPrimitive?.booleanOrNull,
reminderMinutes = args.requireInt("reminder_minutes"),
- calendarName = args.requireString("calendar_name")
+ calendarName = args.requireString("calendar_name"),
+ attendees = args.requireStringList("attendees"),
+ recurrence = args.requireString("recurrence"),
+ recurrenceCount = args.requireInt("recurrence_count"),
+ recurrenceUntil = args.requireString("recurrence_until")
)
"edit_calendar_event" -> calendarTool.editEvent(
eventId = args.requireInt("event_id")?.toLong() ?: return missing("event_id"),
@@ -236,7 +259,11 @@ class ToolExecutor(
location = args.requireString("location"),
description = args.requireString("description"),
allDay = args["all_day"]?.jsonPrimitive?.booleanOrNull,
- reminderMinutes = args.requireInt("reminder_minutes")
+ reminderMinutes = args.requireInt("reminder_minutes"),
+ attendees = args.requireStringList("attendees"),
+ recurrence = args.requireString("recurrence"),
+ recurrenceCount = args.requireInt("recurrence_count"),
+ recurrenceUntil = args.requireString("recurrence_until")
)
"delete_calendar_event" -> calendarTool.deleteEvent(
eventId = args.requireInt("event_id")?.toLong() ?: return missing("event_id")
@@ -252,10 +279,14 @@ class ToolExecutor(
seconds = args.requireInt("seconds") ?: 0,
message = args.requireString("message"),
hours = args.requireInt("hours"),
- minutes = args.requireInt("minutes")
+ minutes = args.requireInt("minutes"),
+ system = args["system"]?.jsonPrimitive?.booleanOrNull ?: false
)
"list_alarms" -> alarmTool.listAlarms()
"list_timers" -> alarmTool.listTimers()
+ "show_alarms" -> alarmTool.showAlarms()
+ "snooze_alarm" -> alarmTool.snoozeAlarm(minutes = args.requireInt("minutes"))
+ "dismiss_timer" -> alarmTool.dismissTimer()
"edit_alarm" -> alarmTool.editAlarm(
id = args.requireInt("alarm_id")?.toLong() ?: return missing("alarm_id"),
hour = args.requireInt("hour"),
@@ -425,7 +456,10 @@ class ToolExecutor(
index = args.requireInt("index")
)
"global_action" -> accessibilityTool.globalAction(args.requireString("action") ?: return missing("action"))
- "read_notifications" -> notificationTool.readNotifications(args.requireInt("limit") ?: 15)
+ "read_notifications" -> notificationTool.readNotifications(
+ limit = args.requireInt("limit") ?: 15,
+ app = args.requireString("app")
+ )
"dismiss_notifications" -> notificationTool.dismissNotifications(args.requireString("key"))
"media_control" -> notificationTool.mediaControl(args.requireString("action") ?: return missing("action"))
"show_overlay" -> overlayTool.showOverlay(
@@ -473,6 +507,9 @@ class ToolExecutor(
private fun JsonObject.requireBoolean(key: String): Boolean? =
this[key]?.jsonPrimitive?.booleanOrNull
+ private fun JsonObject.requireStringList(key: String): List<String>? =
+ this[key]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content }
+
private fun missing(param: String) =
ToolResult.error("Missing or invalid required parameter '$param'.")
diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
index 8ad1b67..538f239 100644
--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
@@ -15,7 +15,7 @@ object ToolRegistry {
private val definitions: Map<String, ToolDefinition> =
ToolDefinitions.all.associateBy { it.function.name }
- val sensitiveTools: Set<String> = emptySet()
+ val sensitiveTools: Set<String> = setOf("send_email")
val destructiveTools: Set<String> = setOf(
"uninstall_app",
@@ -32,13 +32,14 @@ object ToolRegistry {
"get_app_usage", "get_data_usage",
"open_app", "list_installed_apps",
"list_files", "read_file", "grep", "glob",
- "todowrite", "list_alarms", "list_timers",
+ "todowrite", "list_alarms", "list_timers", "show_alarms",
"question",
"sleep",
"websearch", "webfetch",
"get_clipboard",
"read_screen", "read_notifications",
- "check_root", "search_skills"
+ "check_root", "search_skills",
+ "list_emails", "read_email"
)
/** Full Operator tool set minus task + navigate_app (sub-agents cannot delegate further). */
diff --git a/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt b/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt
new file mode 100644
index 0000000..9fbc1a1
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt
@@ -0,0 +1,267 @@
+package com.gotcha.ui
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.material3.Button
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedTextField
+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.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.text.input.PasswordVisualTransformation
+import androidx.compose.ui.unit.dp
+import com.gotcha.connectors.ConnectorRegistry
+import com.gotcha.connectors.google.GoogleOAuthFlow
+import com.gotcha.connectors.imap.ImapCredentials
+import kotlinx.coroutines.launch
+
+/**
+ * Settings → Connectors: one card per connector (IMAP app-password, Gmail
+ * BYO-OAuth). Talks to [ConnectorRegistry] directly since connectors own their
+ * own credential storage — there is nothing for the Settings/SettingsRepository
+ * layer to persist.
+ */
+@Composable
+fun ConnectorsSection() {
+ val context = LocalContext.current
+ remember { ConnectorRegistry.init(context) }
+ val imap = remember { ConnectorRegistry.byId("imap") as com.gotcha.connectors.imap.ImapConnector }
+ val google = remember { ConnectorRegistry.byId("google") as com.gotcha.connectors.google.GoogleConnector }
+
+ Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
+ ImapCard(imap)
+ HorizontalDivider(thickness = 1.dp)
+ GoogleCard(google, context)
+ }
+}
+
+@Composable
+private fun ImapCard(imap: com.gotcha.connectors.imap.ImapConnector) {
+ var refreshTick by remember { mutableStateOf(0) }
+ var email by remember { mutableStateOf(imap.credentials()?.email ?: "") }
+ var appPassword by remember { mutableStateOf("") }
+ var imapHost by remember { mutableStateOf(imap.credentials()?.imapHost ?: "imap.gmail.com") }
+ var imapPort by remember { mutableStateOf((imap.credentials()?.imapPort ?: 993).toString()) }
+ var smtpHost by remember { mutableStateOf(imap.credentials()?.smtpHost ?: "smtp.gmail.com") }
+ var smtpPort by remember { mutableStateOf((imap.credentials()?.smtpPort ?: 465).toString()) }
+ var status by remember { mutableStateOf("") }
+
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text("Email (IMAP)", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Medium)
+ Text(imap.statusLine(), style = MaterialTheme.typography.bodyMedium)
+
+ if (!imap.isConnected()) {
+ OutlinedTextField(
+ value = email,
+ onValueChange = { email = it },
+ label = { Text("Email address") },
+ singleLine = true,
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = appPassword,
+ onValueChange = { appPassword = it },
+ label = { Text("App password") },
+ singleLine = true,
+ visualTransformation = PasswordVisualTransformation(),
+ modifier = Modifier.fillMaxWidth()
+ )
+ Text(
+ "Generate one at Google Account ▸ Security ▸ 2-Step Verification ▸ App passwords " +
+ "(requires 2-Step Verification). Other providers: check their IMAP app-password docs.",
+ style = MaterialTheme.typography.bodySmall
+ )
+ TextButton(onClick = {
+ imapHost = "imap.gmail.com"
+ imapPort = "993"
+ smtpHost = "smtp.gmail.com"
+ smtpPort = "465"
+ }) { Text("Use Gmail preset") }
+ OutlinedTextField(
+ value = imapHost,
+ onValueChange = { imapHost = it },
+ label = { Text("IMAP host") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = imapPort,
+ onValueChange = { imapPort = it },
+ label = { Text("IMAP port") },
+ singleLine = true,
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = smtpHost,
+ onValueChange = { smtpHost = it },
+ label = { Text("SMTP host") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = smtpPort,
+ onValueChange = { smtpPort = it },
+ label = { Text("SMTP port") },
+ singleLine = true,
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
+ modifier = Modifier.fillMaxWidth()
+ )
+ Button(
+ onClick = {
+ val port = imapPort.toIntOrNull() ?: 993
+ val sPort = smtpPort.toIntOrNull() ?: 465
+ imap.connect(
+ ImapCredentials(
+ email = email.trim(),
+ appPassword = appPassword.trim(),
+ imapHost = imapHost.trim(),
+ imapPort = port,
+ smtpHost = smtpHost.trim(),
+ smtpPort = sPort
+ )
+ )
+ status = "Saved. Credentials are verified on first use."
+ refreshTick++
+ },
+ enabled = email.isNotBlank() && appPassword.isNotBlank() &&
+ imapHost.isNotBlank() && smtpHost.isNotBlank(),
+ modifier = Modifier.fillMaxWidth()
+ ) { Text("Connect") }
+ } else {
+ OutlinedButton(
+ onClick = {
+ imap.disconnect()
+ appPassword = ""
+ status = "Disconnected."
+ refreshTick++
+ },
+ modifier = Modifier.fillMaxWidth()
+ ) { Text("Disconnect") }
+ }
+ if (status.isNotBlank()) Text(status, style = MaterialTheme.typography.bodySmall)
+ // Force recomposition of statusLine() after connect/disconnect.
+ if (refreshTick >= 0) Unit
+ }
+}
+
+@Composable
+private fun GoogleCard(
+ google: com.gotcha.connectors.google.GoogleConnector,
+ context: android.content.Context
+) {
+ val scope = rememberCoroutineScope()
+ var refreshTick by remember { mutableStateOf(0) }
+ var clientId by remember { mutableStateOf(google.credentials()?.clientId ?: "") }
+ var clientSecret by remember { mutableStateOf(google.credentials()?.clientSecret ?: "") }
+ var pastedUrl by remember { mutableStateOf("") }
+ var showPasteFallback by remember { mutableStateOf(false) }
+ var busy by remember { mutableStateOf(false) }
+ var status by remember { mutableStateOf("") }
+ val flow = remember(google) { GoogleOAuthFlow(context, google) }
+
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text("Gmail (BYO OAuth)", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Medium)
+ Text(google.statusLine(), style = MaterialTheme.typography.bodyMedium)
+ Text(
+ "Full read/write Gmail access using your own Google Cloud OAuth client — no shared " +
+ "app, no verification wait. Steps: 1) create a Google Cloud project, 2) enable the " +
+ "Gmail API, 3) configure the OAuth consent screen (External, add yourself as a test " +
+ "user — or publish to skip weekly reconnects), 4) create a Desktop app OAuth client, " +
+ "5) paste its Client ID and secret below, 6) tap Connect.",
+ style = MaterialTheme.typography.bodySmall
+ )
+
+ if (!google.isConnected() || google.needsReconnect()) {
+ OutlinedTextField(
+ value = clientId,
+ onValueChange = { clientId = it },
+ label = { Text("Client ID") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = clientSecret,
+ onValueChange = { clientSecret = it },
+ label = { Text("Client secret") },
+ singleLine = true,
+ visualTransformation = PasswordVisualTransformation(),
+ modifier = Modifier.fillMaxWidth()
+ )
+ Button(
+ onClick = {
+ busy = true
+ status = "Opening sign-in…"
+ scope.launch {
+ when (val outcome = flow.connect(clientId, clientSecret)) {
+ is GoogleOAuthFlow.Outcome.Connected ->
+ status = "Connected as ${outcome.email}."
+ is GoogleOAuthFlow.Outcome.Failed ->
+ status = outcome.message
+ }
+ busy = false
+ refreshTick++
+ }
+ },
+ enabled = !busy && clientId.isNotBlank() && clientSecret.isNotBlank(),
+ modifier = Modifier.fillMaxWidth()
+ ) { Text(if (busy) "Waiting for sign-in…" else "Connect") }
+
+ TextButton(onClick = { showPasteFallback = !showPasteFallback }) {
+ Text(if (showPasteFallback) "Hide paste-URL fallback" else "Browser didn't return? Paste redirect URL")
+ }
+ if (showPasteFallback) {
+ OutlinedTextField(
+ value = pastedUrl,
+ onValueChange = { pastedUrl = it },
+ label = { Text("Pasted redirect URL") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth()
+ )
+ Button(
+ onClick = {
+ busy = true
+ scope.launch {
+ when (val outcome = flow.connectWithPastedUrl(clientId, clientSecret, pastedUrl)) {
+ is GoogleOAuthFlow.Outcome.Connected ->
+ status = "Connected as ${outcome.email}."
+ is GoogleOAuthFlow.Outcome.Failed ->
+ status = outcome.message
+ }
+ busy = false
+ refreshTick++
+ }
+ },
+ enabled = !busy && pastedUrl.isNotBlank(),
+ modifier = Modifier.fillMaxWidth()
+ ) { Text("Finish sign-in with pasted URL") }
+ }
+ } else {
+ OutlinedButton(
+ onClick = {
+ google.disconnect()
+ clientSecret = ""
+ status = "Disconnected."
+ refreshTick++
+ },
+ modifier = Modifier.fillMaxWidth()
+ ) { Text("Disconnect") }
+ }
+ if (status.isNotBlank()) Text(status, style = MaterialTheme.typography.bodySmall)
+ if (refreshTick >= 0) Unit
+ }
+}
diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
index 1de3957..cdb1ac8 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
@@ -118,6 +118,7 @@ fun SettingsScreen(
var refreshingChatModels by remember { mutableStateOf(false) }
// Collapsible sections
var aiConfigExpanded by remember { mutableStateOf(false) }
+ var connectorsExpanded by remember { mutableStateOf(false) }
var speechExpanded by remember { mutableStateOf(false) }
var skillsExpanded by remember { mutableStateOf(false) }
var proactiveExpanded by remember { mutableStateOf(false) }
@@ -575,6 +576,18 @@ fun SettingsScreen(
HorizontalDivider(thickness = 1.dp)
+ // ---- Connectors (collapsible, collapsed by default) ----
+ SectionHeader(
+ title = "Connectors",
+ expanded = connectorsExpanded,
+ onToggle = { connectorsExpanded = !connectorsExpanded }
+ )
+ AnimatedVisibility(visible = connectorsExpanded) {
+ ConnectorsSection()
+ }
+
+ HorizontalDivider(thickness = 1.dp)
+
// ---- Permissions (collapsible, expanded by default) ----
PermissionsSection(packageName = packageName)
diff --git a/app/src/test/java/com/gotcha/connectors/google/GmailApiTest.kt b/app/src/test/java/com/gotcha/connectors/google/GmailApiTest.kt
new file mode 100644
index 0000000..b497000
--- /dev/null
+++ b/app/src/test/java/com/gotcha/connectors/google/GmailApiTest.kt
@@ -0,0 +1,84 @@
+package com.gotcha.connectors.google
+
+import kotlinx.coroutines.test.runTest
+import okhttp3.mockwebserver.MockResponse
+import okhttp3.mockwebserver.MockWebServer
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+
+class GmailApiTest {
+
+ private lateinit var server: MockWebServer
+ private lateinit var api: GmailApi
+
+ @Before
+ fun setUp() {
+ server = MockWebServer()
+ server.start()
+ api = GmailApi(baseUrl = server.url("/gmail/v1/users/me").toString())
+ }
+
+ @After
+ fun tearDown() {
+ server.shutdown()
+ }
+
+ @Test
+ fun `listMessageIds sends bearer token and query`() = runTest {
+ server.enqueue(MockResponse().setBody("""{"messages":[{"id":"m1"},{"id":"m2"}]}"""))
+ val ids = api.listMessageIds("tok-1", "is:unread", unreadOnly = true, max = 10)
+ assertEquals(listOf("m1", "m2"), ids)
+
+ val request = server.takeRequest()
+ assertEquals("Bearer tok-1", request.getHeader("Authorization"))
+ assertTrue(request.path?.contains("q=is%3Aunread") == true || request.path?.contains("is:unread") == true)
+ }
+
+ @Test
+ fun `listMessageIds handles empty result`() = runTest {
+ server.enqueue(MockResponse().setBody("{}"))
+ val ids = api.listMessageIds("tok", null, unreadOnly = false, max = 10)
+ assertTrue(ids.isEmpty())
+ }
+
+ @Test
+ fun `retries once on 401 is caller responsibility - api surfaces GmailApiException`() = runTest {
+ server.enqueue(MockResponse().setResponseCode(401).setBody("""{"error":{"message":"invalid token"}}"""))
+ try {
+ api.profileEmail("bad-token")
+ throw AssertionError("expected GmailApiException")
+ } catch (e: GmailApiException) {
+ assertEquals(401, e.code)
+ }
+ }
+
+ @Test
+ fun `403 rate limit mapped to actionable message`() = runTest {
+ server.enqueue(MockResponse().setResponseCode(403).setBody("""{"error":{"message":"quota exceeded"}}"""))
+ try {
+ api.profileEmail("tok")
+ throw AssertionError("expected GmailApiException")
+ } catch (e: GmailApiException) {
+ assertEquals(403, e.code)
+ assertTrue(e.message!!.contains("try again later", ignoreCase = true))
+ }
+ }
+
+ @Test
+ fun `sendRaw posts raw payload and returns id`() = runTest {
+ server.enqueue(MockResponse().setBody("""{"id":"sent-1"}"""))
+ val id = api.sendRaw("tok", "base64url-content")
+ assertEquals("sent-1", id)
+ val request = server.takeRequest()
+ assertTrue(request.body.readUtf8().contains("base64url-content"))
+ }
+
+ @Test
+ fun `profileEmail parses emailAddress`() = runTest {
+ server.enqueue(MockResponse().setBody("""{"emailAddress":"[email protected]"}"""))
+ assertEquals("[email protected]", api.profileEmail("tok"))
+ }
+}
diff --git a/app/src/test/java/com/gotcha/connectors/google/GoogleConnectorTest.kt b/app/src/test/java/com/gotcha/connectors/google/GoogleConnectorTest.kt
new file mode 100644
index 0000000..b6722f3
--- /dev/null
+++ b/app/src/test/java/com/gotcha/connectors/google/GoogleConnectorTest.kt
@@ -0,0 +1,128 @@
+package com.gotcha.connectors.google
+
+import com.gotcha.connectors.CredentialStore
+import com.gotcha.connectors.oauth.OAuth2Helper
+import kotlinx.coroutines.test.runTest
+import okhttp3.mockwebserver.MockResponse
+import okhttp3.mockwebserver.MockWebServer
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+
+private class InMemoryCredentialStore : CredentialStore {
+ private val map = mutableMapOf<String, String>()
+ override fun loadRaw(connectorId: String): String? = map[connectorId]
+ override fun saveRaw(connectorId: String, blob: String) { map[connectorId] = blob }
+ override fun clear(connectorId: String) { map.remove(connectorId) }
+}
+
+class GoogleConnectorTest {
+
+ private lateinit var tokenServer: MockWebServer
+ private lateinit var gmailServer: MockWebServer
+ private lateinit var store: InMemoryCredentialStore
+ private lateinit var connector: GoogleConnector
+
+ @Before
+ fun setUp() {
+ tokenServer = MockWebServer()
+ tokenServer.start()
+ gmailServer = MockWebServer()
+ gmailServer.start()
+ store = InMemoryCredentialStore()
+ connector = GoogleConnector(
+ store = store,
+ api = GmailApi(baseUrl = gmailServer.url("/gmail/v1/users/me").toString()),
+ oauth = OAuth2Helper(),
+ tokenUrl = tokenServer.url("/token").toString()
+ )
+ }
+
+ @After
+ fun tearDown() {
+ tokenServer.shutdown()
+ gmailServer.shutdown()
+ }
+
+ @Test
+ fun `completeConnect identifies account and persists credentials`() = runTest {
+ gmailServer.enqueue(MockResponse().setBody("""{"emailAddress":"[email protected]"}"""))
+ connector.completeConnect(
+ "client-id",
+ "client-secret",
+ com.gotcha.connectors.oauth.TokenSet("at-1", "rt-1", System.currentTimeMillis() + 3600_000)
+ )
+ assertTrue(connector.isConnected())
+ assertEquals("[email protected]", connector.credentials()?.accountEmail)
+ assertTrue(store.loadRaw("google")?.contains("[email protected]") == true)
+ }
+
+ @Test
+ fun `completeConnect without refresh token throws`() = runTest {
+ try {
+ connector.completeConnect(
+ "client-id",
+ "client-secret",
+ com.gotcha.connectors.oauth.TokenSet("at-1", null, System.currentTimeMillis() + 3600_000)
+ )
+ throw AssertionError("expected IllegalStateException")
+ } catch (e: IllegalStateException) {
+ assertTrue(e.message!!.contains("refresh token"))
+ }
+ }
+
+ @Test
+ fun `expired access token triggers proactive refresh before gmail call`() = runTest {
+ gmailServer.enqueue(MockResponse().setBody("""{"emailAddress":"[email protected]"}"""))
+ connector.completeConnect(
+ "client-id",
+ "client-secret",
+ com.gotcha.connectors.oauth.TokenSet("stale-token", "rt-1", System.currentTimeMillis() - 1000)
+ )
+ tokenServer.enqueue(MockResponse().setBody("""{"access_token":"fresh-token","expires_in":3600}"""))
+ gmailServer.enqueue(MockResponse().setBody("""{"messages":[]}"""))
+
+ val emails = connector.list(null, false, 10)
+
+ assertTrue(emails.isEmpty())
+ gmailServer.takeRequest() // profile call from completeConnect
+ val listRequest = gmailServer.takeRequest()
+ assertEquals("Bearer fresh-token", listRequest.getHeader("Authorization"))
+ }
+
+ @Test
+ fun `invalid_grant on refresh flips needsReconnect`() = runTest {
+ gmailServer.enqueue(MockResponse().setBody("""{"emailAddress":"[email protected]"}"""))
+ connector.completeConnect(
+ "client-id",
+ "client-secret",
+ com.gotcha.connectors.oauth.TokenSet("stale-token", "rt-1", System.currentTimeMillis() - 1000)
+ )
+ tokenServer.enqueue(MockResponse().setResponseCode(400).setBody("""{"error":"invalid_grant"}"""))
+
+ try {
+ connector.list(null, false, 10)
+ throw AssertionError("expected IllegalStateException")
+ } catch (e: IllegalStateException) {
+ assertTrue(e.message!!.contains("reconnect"))
+ }
+ assertTrue(connector.needsReconnect())
+ assertTrue(!connector.isConnected())
+ }
+
+ @Test
+ fun `disconnect clears credentials`() = runTest {
+ gmailServer.enqueue(MockResponse().setBody("""{"emailAddress":"[email protected]"}"""))
+ connector.completeConnect(
+ "client-id",
+ "client-secret",
+ com.gotcha.connectors.oauth.TokenSet("at-1", "rt-1", System.currentTimeMillis() + 3600_000)
+ )
+ connector.disconnect()
+ assertTrue(!connector.isConnected())
+ assertEquals(null, connector.credentials())
+ assertEquals(null, store.loadRaw("google"))
+ }
+}
diff --git a/app/src/test/java/com/gotcha/connectors/mail/EmailToolsTest.kt b/app/src/test/java/com/gotcha/connectors/mail/EmailToolsTest.kt
new file mode 100644
index 0000000..6af0425
--- /dev/null
+++ b/app/src/test/java/com/gotcha/connectors/mail/EmailToolsTest.kt
@@ -0,0 +1,193 @@
+package com.gotcha.connectors.mail
+
+import com.gotcha.tools.ToolResult
+import kotlinx.coroutines.test.runTest
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.add
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+import kotlinx.serialization.json.putJsonArray
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+private class FakeBackend(override val idPrefix: String) : MailBackend {
+ var lastListQuery: String? = null
+ var lastUnreadOnly: Boolean = false
+ var lastMax: Int = -1
+ var sentMessage: OutgoingEmail? = null
+ val markedRead = mutableMapOf<String, Boolean>()
+ var listResult: List<EmailSummary> = emptyList()
+ var readResult: EmailFull? = null
+
+ override suspend fun list(query: String?, unreadOnly: Boolean, max: Int): List<EmailSummary> {
+ lastListQuery = query
+ lastUnreadOnly = unreadOnly
+ lastMax = max
+ return listResult
+ }
+
+ override suspend fun read(id: String): EmailFull = readResult ?: error("no read result set")
+
+ override suspend fun send(message: OutgoingEmail): String {
+ sentMessage = message
+ return "sent to ${message.to.joinToString()}"
+ }
+
+ override suspend fun markRead(id: String, read: Boolean) {
+ markedRead[id] = read
+ }
+}
+
+class EmailToolsTest {
+
+ private fun buildArgs(block: kotlinx.serialization.json.JsonObjectBuilder.() -> Unit): JsonObject =
+ buildJsonObject(block)
+
+ @Test
+ fun `list_emails prefers gmail backend over imap`() = runTest {
+ val gmail = FakeBackend("gmail").apply {
+ listResult = listOf(EmailSummary("gmail:1", "[email protected]", "Hi", "2024-01-01", true, "snip"))
+ }
+ val imap = FakeBackend("imap")
+ val tools = EmailTools(
+ gmailBackend = { gmail },
+ imapBackend = { imap },
+ composeLauncher = { _, _, _ -> ToolResult.ok("composed") }
+ )
+ val result = tools.execute("list_emails", buildArgs {})
+ assertTrue(result.success)
+ assertTrue(result.message.contains("gmail:1"))
+ assertEquals(-1, imap.lastMax) // imap never called
+ }
+
+ @Test
+ fun `list_emails falls back to imap when gmail not connected`() = runTest {
+ val imap = FakeBackend("imap").apply {
+ listResult = listOf(EmailSummary("imap:INBOX:5", "[email protected]", "Yo", "2024-01-02", false, "snip2"))
+ }
+ val tools = EmailTools(
+ gmailBackend = { null },
+ imapBackend = { imap },
+ composeLauncher = { _, _, _ -> ToolResult.ok("composed") }
+ )
+ val result = tools.execute("list_emails", buildArgs { put("max", 5) })
+ assertTrue(result.success)
+ assertTrue(result.message.contains("imap:INBOX:5"))
+ assertEquals(5, imap.lastMax)
+ }
+
+ @Test
+ fun `list_emails with no backend steers to settings`() = runTest {
+ val tools = EmailTools(
+ gmailBackend = { null },
+ imapBackend = { null },
+ composeLauncher = { _, _, _ -> ToolResult.ok("composed") }
+ )
+ val result = tools.execute("list_emails", buildArgs {})
+ assertTrue(!result.success)
+ assertTrue(result.message.contains("Settings"))
+ assertTrue(result.message.contains("compose_email"))
+ }
+
+ @Test
+ fun `read_email routes by id prefix`() = runTest {
+ val gmail = FakeBackend("gmail").apply {
+ readResult = EmailFull("gmail:1", "[email protected]", "[email protected]", "", "Subj", "2024-01-01", "Body text")
+ }
+ val imap = FakeBackend("imap")
+ val tools = EmailTools(
+ gmailBackend = { gmail },
+ imapBackend = { imap },
+ composeLauncher = { _, _, _ -> ToolResult.ok("composed") }
+ )
+ val result = tools.execute("read_email", buildArgs { put("id", "gmail:1") })
+ assertTrue(result.success)
+ assertTrue(result.message.contains("Body text"))
+ }
+
+ @Test
+ fun `read_email with disconnected backend for id prefix errors`() = runTest {
+ val tools = EmailTools(
+ gmailBackend = { null },
+ imapBackend = { null },
+ composeLauncher = { _, _, _ -> ToolResult.ok("composed") }
+ )
+ val result = tools.execute("read_email", buildArgs { put("id", "gmail:1") })
+ assertTrue(!result.success)
+ }
+
+ @Test
+ fun `send_email returns confirm payload without sending`() = runTest {
+ val gmail = FakeBackend("gmail")
+ val tools = EmailTools(
+ gmailBackend = { gmail },
+ imapBackend = { null },
+ composeLauncher = { _, _, _ -> ToolResult.ok("composed") }
+ )
+ val args = buildArgs {
+ putJsonArray("to") { add("[email protected]") }
+ put("subject", "Subj")
+ put("body", "Body")
+ }
+ val result = tools.execute("send_email", args)
+ assertTrue(result.success)
+ assertTrue(result.message.startsWith(EmailTools.CONFIRM_SEND_PREFIX))
+ assertEquals(null, gmail.sentMessage) // not sent yet
+ }
+
+ @Test
+ fun `executeSendConfirmed sends via primary backend`() = runTest {
+ val gmail = FakeBackend("gmail")
+ val tools = EmailTools(
+ gmailBackend = { gmail },
+ imapBackend = { null },
+ composeLauncher = { _, _, _ -> ToolResult.ok("composed") }
+ )
+ val args = buildArgs {
+ putJsonArray("to") { add("[email protected]") }
+ put("subject", "Subj")
+ put("body", "Body")
+ }
+ val confirm = tools.execute("send_email", args)
+ val payload = confirm.message.removePrefix(EmailTools.CONFIRM_SEND_PREFIX)
+ val result = tools.executeSendConfirmed(payload)
+ assertTrue(result.success)
+ assertEquals("[email protected]", gmail.sentMessage?.to?.first())
+ }
+
+ @Test
+ fun `mark_email_read routes to correct backend by prefix`() = runTest {
+ val imap = FakeBackend("imap")
+ val tools = EmailTools(
+ gmailBackend = { null },
+ imapBackend = { imap },
+ composeLauncher = { _, _, _ -> ToolResult.ok("composed") }
+ )
+ val result = tools.execute(
+ "mark_email_read",
+ buildArgs {
+ put("id", "imap:INBOX:9")
+ put("read", false)
+ }
+ )
+ assertTrue(result.success)
+ assertEquals(false, imap.markedRead["imap:INBOX:9"])
+ }
+
+ @Test
+ fun `compose_email delegates to compose launcher`() = runTest {
+ var capturedTo: String? = null
+ val tools = EmailTools(
+ gmailBackend = { null },
+ imapBackend = { null },
+ composeLauncher = { to, _, _ ->
+ capturedTo = to
+ ToolResult.ok("opened")
+ }
+ )
+ val result = tools.execute("compose_email", buildArgs { put("to", "[email protected]") })
+ assertTrue(result.success)
+ assertEquals("[email protected]", capturedTo)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/connectors/mail/MailBodyExtractorTest.kt b/app/src/test/java/com/gotcha/connectors/mail/MailBodyExtractorTest.kt
new file mode 100644
index 0000000..14e6017
--- /dev/null
+++ b/app/src/test/java/com/gotcha/connectors/mail/MailBodyExtractorTest.kt
@@ -0,0 +1,37 @@
+package com.gotcha.connectors.mail
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class MailBodyExtractorTest {
+
+ @Test
+ fun `strips html tags to readable text`() {
+ val html = "<html><body><p>Hello <b>world</b></p><p>Second paragraph</p></body></html>"
+ val text = MailBodyExtractor.htmlToText(html)
+ assertTrue(text.contains("Hello world"))
+ assertTrue(text.contains("Second paragraph"))
+ assertTrue(!text.contains("<"))
+ }
+
+ @Test
+ fun `snippet truncates long text with ellipsis`() {
+ val long = "a".repeat(200)
+ val snippet = MailBodyExtractor.snippet(long, maxChars = 150)
+ assertEquals(151, snippet.length) // 150 chars + ellipsis
+ assertTrue(snippet.endsWith("…"))
+ }
+
+ @Test
+ fun `snippet collapses whitespace`() {
+ val text = "line one\n\n line two\t\tline three"
+ val snippet = MailBodyExtractor.snippet(text)
+ assertEquals("line one line two line three", snippet)
+ }
+
+ @Test
+ fun `snippet passes short text through unchanged`() {
+ assertEquals("short text", MailBodyExtractor.snippet("short text"))
+ }
+}
diff --git a/app/src/test/java/com/gotcha/connectors/oauth/LoopbackRedirectServerTest.kt b/app/src/test/java/com/gotcha/connectors/oauth/LoopbackRedirectServerTest.kt
new file mode 100644
index 0000000..17f9ff3
--- /dev/null
+++ b/app/src/test/java/com/gotcha/connectors/oauth/LoopbackRedirectServerTest.kt
@@ -0,0 +1,65 @@
+package com.gotcha.connectors.oauth
+
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.async
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withContext
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.net.HttpURLConnection
+import java.net.URL
+
+class LoopbackRedirectServerTest {
+
+ private fun hit(url: String): Pair<Int, String> {
+ val conn = URL(url).openConnection() as HttpURLConnection
+ conn.connectTimeout = 5000
+ conn.readTimeout = 5000
+ val code = conn.responseCode
+ val body = conn.inputStream.bufferedReader().readText()
+ conn.disconnect()
+ return code to body
+ }
+
+ @Test
+ fun `round trip returns code and success page`() = runBlocking {
+ val server = LoopbackRedirectServer()
+ val result = async { server.awaitCode("expected-state") }
+ val (status, body) = withContext(Dispatchers.IO) {
+ hit("${server.redirectUri}/?code=auth-c0de&state=expected-state")
+ }
+ assertEquals(200, status)
+ assertTrue(body.contains("Signed in"))
+ assertEquals(LoopbackRedirectServer.Result.Code("auth-c0de"), result.await())
+ }
+
+ @Test
+ fun `state mismatch rejected`() = runBlocking {
+ val server = LoopbackRedirectServer()
+ val result = async { server.awaitCode("expected-state") }
+ withContext(Dispatchers.IO) {
+ hit("${server.redirectUri}/?code=auth-c0de&state=evil")
+ }
+ assertTrue(result.await() is LoopbackRedirectServer.Result.Error)
+ }
+
+ @Test
+ fun `provider error propagated`() = runBlocking {
+ val server = LoopbackRedirectServer()
+ val result = async { server.awaitCode("s") }
+ withContext(Dispatchers.IO) {
+ hit("${server.redirectUri}/?error=access_denied&state=s")
+ }
+ val error = result.await() as LoopbackRedirectServer.Result.Error
+ assertTrue(error.message.contains("access_denied"))
+ }
+
+ @Test
+ fun `timeout produces error`() = runBlocking {
+ val server = LoopbackRedirectServer(timeoutMillis = 200)
+ val result = server.awaitCode("s")
+ assertTrue(result is LoopbackRedirectServer.Result.Error)
+ assertTrue((result as LoopbackRedirectServer.Result.Error).message.contains("Timed out"))
+ }
+}
diff --git a/app/src/test/java/com/gotcha/connectors/oauth/OAuth2HelperTest.kt b/app/src/test/java/com/gotcha/connectors/oauth/OAuth2HelperTest.kt
new file mode 100644
index 0000000..b7e90a0
--- /dev/null
+++ b/app/src/test/java/com/gotcha/connectors/oauth/OAuth2HelperTest.kt
@@ -0,0 +1,104 @@
+package com.gotcha.connectors.oauth
+
+import kotlinx.coroutines.test.runTest
+import okhttp3.mockwebserver.MockResponse
+import okhttp3.mockwebserver.MockWebServer
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import java.net.URLDecoder
+
+class OAuth2HelperTest {
+
+ private lateinit var server: MockWebServer
+ private lateinit var helper: OAuth2Helper
+ private lateinit var cfg: OAuth2Config
+
+ private val fixedNow = 1_000_000L
+
+ @Before
+ fun setUp() {
+ server = MockWebServer()
+ server.start()
+ helper = OAuth2Helper(clock = { fixedNow })
+ cfg = OAuth2Config(
+ authUrl = server.url("/auth").toString(),
+ tokenUrl = server.url("/token").toString(),
+ clientId = "client-id",
+ clientSecret = "client-secret",
+ scopes = listOf("scope.a", "scope.b"),
+ extraAuthParams = mapOf("access_type" to "offline", "prompt" to "consent")
+ )
+ }
+
+ @After
+ fun tearDown() {
+ server.shutdown()
+ }
+
+ @Test
+ fun `authorization url carries all parameters`() {
+ val url = helper.buildAuthorizationUrl(cfg, "http://127.0.0.1:8080", "st4te", "chall3nge")
+ val decoded = URLDecoder.decode(url, "UTF-8")
+ assertTrue(decoded.contains("response_type=code"))
+ assertTrue(decoded.contains("client_id=client-id"))
+ assertTrue(decoded.contains("redirect_uri=http://127.0.0.1:8080"))
+ assertTrue(decoded.contains("scope=scope.a scope.b"))
+ assertTrue(decoded.contains("state=st4te"))
+ assertTrue(decoded.contains("code_challenge=chall3nge"))
+ assertTrue(decoded.contains("code_challenge_method=S256"))
+ assertTrue(decoded.contains("access_type=offline"))
+ assertTrue(decoded.contains("prompt=consent"))
+ }
+
+ @Test
+ fun `exchangeCode posts form and parses token set`() = runTest {
+ server.enqueue(
+ MockResponse().setBody(
+ """{"access_token":"at-1","refresh_token":"rt-1","expires_in":3599}"""
+ )
+ )
+ val tokens = helper.exchangeCode(cfg, "the-code", "http://127.0.0.1:8080", "verif13r")
+
+ assertEquals("at-1", tokens.accessToken)
+ assertEquals("rt-1", tokens.refreshToken)
+ assertEquals(fixedNow + 3599 * 1000, tokens.expiresAtMillis)
+
+ val body = URLDecoder.decode(server.takeRequest().body.readUtf8(), "UTF-8")
+ assertTrue(body.contains("grant_type=authorization_code"))
+ assertTrue(body.contains("code=the-code"))
+ assertTrue(body.contains("code_verifier=verif13r"))
+ assertTrue(body.contains("client_secret=client-secret"))
+ }
+
+ @Test
+ fun `refresh keeps old refresh token when provider omits it`() = runTest {
+ server.enqueue(MockResponse().setBody("""{"access_token":"at-2","expires_in":3600}"""))
+ val tokens = helper.refresh(cfg, "rt-old")
+
+ assertEquals("at-2", tokens.accessToken)
+ assertEquals("rt-old", tokens.refreshToken)
+ val body = URLDecoder.decode(server.takeRequest().body.readUtf8(), "UTF-8")
+ assertTrue(body.contains("grant_type=refresh_token"))
+ assertTrue(body.contains("refresh_token=rt-old"))
+ }
+
+ @Test(expected = OAuthInvalidGrant::class)
+ fun `invalid_grant throws typed exception`() = runTest {
+ server.enqueue(MockResponse().setResponseCode(400).setBody("""{"error":"invalid_grant"}"""))
+ helper.refresh(cfg, "rt-revoked")
+ }
+
+ @Test
+ fun `other token errors carry status code`() = runTest {
+ server.enqueue(MockResponse().setResponseCode(500).setBody("oops"))
+ try {
+ helper.refresh(cfg, "rt")
+ throw AssertionError("expected OAuthTokenError")
+ } catch (e: OAuthTokenError) {
+ assertEquals(500, e.code)
+ }
+ }
+}
diff --git a/app/src/test/java/com/gotcha/connectors/oauth/PkceTest.kt b/app/src/test/java/com/gotcha/connectors/oauth/PkceTest.kt
new file mode 100644
index 0000000..9aa0f12
--- /dev/null
+++ b/app/src/test/java/com/gotcha/connectors/oauth/PkceTest.kt
@@ -0,0 +1,33 @@
+package com.gotcha.connectors.oauth
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class PkceTest {
+
+ @Test
+ fun `challenge matches RFC 7636 appendix B vector`() {
+ // Verifier and expected S256 challenge from RFC 7636 Appendix B.
+ val verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
+ assertEquals("E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", Pkce.challengeS256(verifier))
+ }
+
+ @Test
+ fun `generated verifier has requested length and legal charset`() {
+ val verifier = Pkce.generateVerifier(64)
+ assertEquals(64, verifier.length)
+ assertTrue(verifier.all { it.isLetterOrDigit() || it in "-._~" })
+ }
+
+ @Test
+ fun `generated verifiers are unique`() {
+ assertNotEquals(Pkce.generateVerifier(), Pkce.generateVerifier())
+ }
+
+ @Test(expected = IllegalArgumentException::class)
+ fun `verifier length below 43 rejected`() {
+ Pkce.generateVerifier(42)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/tools/MimeMessageBuilderTest.kt b/app/src/test/java/com/gotcha/tools/MimeMessageBuilderTest.kt
new file mode 100644
index 0000000..3cc46cc
--- /dev/null
+++ b/app/src/test/java/com/gotcha/tools/MimeMessageBuilderTest.kt
@@ -0,0 +1,73 @@
+package com.gotcha.tools
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class MimeMessageBuilderTest {
+
+ @Test
+ fun `builds RFC 2822 message with CRLF line endings`() {
+ val raw = MimeMessageBuilder.build(
+ from = "[email protected]",
+ to = listOf("[email protected]"),
+ subject = "Hello",
+ body = "Line one\nLine two"
+ )
+ assertTrue(raw.contains("From: [email protected]\r\n"))
+ assertTrue(raw.contains("To: [email protected]\r\n"))
+ assertTrue(raw.contains("Subject: Hello\r\n"))
+ assertTrue(raw.contains("\r\n\r\nLine one\r\nLine two"))
+ }
+
+ @Test
+ fun `includes cc and bcc when present`() {
+ val raw = MimeMessageBuilder.build(
+ from = "[email protected]",
+ cc = listOf("[email protected]"),
+ bcc = listOf("[email protected]"),
+ subject = "Subj",
+ body = "Body"
+ )
+ assertTrue(raw.contains("To: [email protected], [email protected]\r\n"))
+ assertTrue(raw.contains("Cc: [email protected]\r\n"))
+ assertTrue(raw.contains("Bcc: [email protected]\r\n"))
+ }
+
+ @Test
+ fun `non-ascii subject is RFC 2047 encoded`() {
+ val raw = MimeMessageBuilder.build(
+ from = "[email protected]",
+ to = listOf("[email protected]"),
+ subject = "Café",
+ body = "Body"
+ )
+ assertTrue(raw.contains("Subject: =?UTF-8?B?"))
+ }
+
+ @Test
+ fun `ascii subject passes through unencoded`() {
+ val raw = MimeMessageBuilder.build(
+ from = "[email protected]",
+ to = listOf("[email protected]"),
+ subject = "Plain subject",
+ body = "Body"
+ )
+ assertTrue(raw.contains("Subject: Plain subject\r\n"))
+ }
+
+ @Test(expected = IllegalArgumentException::class)
+ fun `requires at least one recipient`() {
+ MimeMessageBuilder.build(from = "[email protected]", to = emptyList(), subject = "s", body = "b")
+ }
+
+ @Test
+ fun `base64url encoding has no padding`() {
+ val raw = "test message"
+ val encoded = MimeMessageBuilder.toBase64Url(raw)
+ assertEquals(false, encoded.contains("="))
+ assertEquals(false, encoded.contains("+"))
+ assertEquals(false, encoded.contains("/"))
+ }
+}
diff --git a/docs/gmail-byo-oauth-setup.md b/docs/gmail-byo-oauth-setup.md
new file mode 100644
index 0000000..5a66aca
--- /dev/null
+++ b/docs/gmail-byo-oauth-setup.md
@@ -0,0 +1,103 @@
+# Gmail (BYO OAuth) connector setup
+
+Gotcha doesn't ship a shared Google OAuth client — instead, every user connects
+Gmail with a client they create in their own free Google Cloud project. This
+"Bring Your Own OAuth" approach (same one n8n uses for self-hosted Gmail nodes)
+means restricted scopes like `gmail.modify` don't need Google's CASA security
+verification, at the cost of a few minutes of one-time setup.
+
+## Why this instead of a built-in "Sign in with Google" button
+
+- A shared OAuth client requesting `gmail.modify` for public distribution would
+ require Google's CASA assessment (an ongoing paid security review).
+- Android-type OAuth clients are bound to a package name + SHA-1 fingerprint,
+ so users can't each register their own `com.gotcha` client.
+- The fix: each user creates a **Desktop app** OAuth client. Desktop clients
+ support the "loopback" redirect (`http://127.0.0.1:<port>`), which needs no
+ redirect URI to be pre-registered — the app just picks an ephemeral port at
+ connect time.
+
+## Setup steps (Settings → Connectors → Gmail (BYO OAuth))
+
+1. **Create a Google Cloud project** at [console.cloud.google.com](https://console.cloud.google.com)
+ (any Google account, free tier is enough).
+2. **Enable the Gmail API**: APIs & Services → Library → search "Gmail API" → Enable.
+3. **Configure the OAuth consent screen**: APIs & Services → OAuth consent screen.
+ - User type: **External**.
+ - Add your own Google account as a **test user**.
+ - Leave the app in **"Testing"** status, or **publish to "In production"**
+ (see the note on 7-day expiry below). Either way you'll see an
+ "unverified app" warning during sign-in — that's expected and fine,
+ since you own the app.
+4. **Create a Desktop app OAuth client**: APIs & Services → Credentials →
+ Create Credentials → OAuth client ID → Application type: **Desktop app**.
+ No redirect URI needs to be entered.
+5. **Paste the Client ID and Client secret** into the Gmail card in
+ Settings → Connectors.
+6. Tap **Connect**. A browser tab opens for Google sign-in; after you approve,
+ it redirects to a local `127.0.0.1` address that the app is listening on,
+ and the tab shows "Signed in — you can close this tab."
+
+### If the browser tab doesn't return to the app
+
+Some devices kill the app process while the browser tab is open, or the
+listener dies before the redirect lands. Use the **"Browser didn't return?
+Paste redirect URL"** field: copy the full URL from the browser's address bar
+after it shows the "Signed in" page (or any redirect to `127.0.0.1`), paste it
+in, and tap "Finish sign-in with pasted URL." This only works immediately
+after tapping Connect, since it reuses that attempt's PKCE verifier.
+
+## The 7-day reconnect note
+
+While the consent screen is in **"Testing"** status, Google expires refresh
+tokens after 7 days, so you'll need to reconnect weekly. To avoid this,
+**publish the consent screen to "In production"** (OAuth consent screen →
+Publish app). You'll still see the "unverified app" warning on sign-in — since
+restricted scopes on an app only you use don't require CASA verification —
+but tokens will stop expiring weekly.
+
+If a refresh does expire, the connector shows "Reconnect needed" and email
+tools return an error steering the user back to Settings.
+
+## Revoking access
+
+Settings → Connectors → Gmail → Disconnect clears the locally stored
+credentials and best-effort revokes the grant. You can also revoke it directly
+at [myaccount.google.com/permissions](https://myaccount.google.com/permissions).
+
+## Manual end-to-end checklist
+
+- [ ] Connect completes and the card shows "Connected as <email>."
+- [ ] `list_emails` returns recent messages; `unread_only` and `query` filter correctly.
+- [ ] `read_email` shows the plain-text body (including for HTML-only messages).
+- [ ] `send_email` shows a confirmation with To/Subject/body preview before sending.
+- [ ] `mark_email_read` toggles the unread flag (verify in the Gmail app).
+- [ ] Revoke access at myaccount.google.com/permissions, then retry a tool call →
+ connector reports "Reconnect needed" instead of crashing.
+- [ ] Reconnect succeeds and clears the reconnect-needed state.
+- [ ] Kill the app while the Custom Tab is open mid-consent → use the paste-URL
+ fallback to complete the connection.
+
+## IMAP connector (no Google Cloud project needed)
+
+For any provider (Gmail included) that supports IMAP with an app password,
+Settings → Connectors → Email (IMAP) is the simpler default: enter your email
+address and an app password (Google Account → Security → 2-Step Verification →
+App passwords — requires 2-Step Verification to be enabled), use the "Use
+Gmail preset" button for Gmail's IMAP/SMTP hosts, or fill in another provider's
+host/port. This gets full read/write email access with no OAuth setup, at the
+cost of scoping to "everything IMAP/SMTP can do" rather than Gmail's more
+granular `gmail.modify` scope.
+
+## Manual clock intent checklist
+
+`set_timer(system=true)`, `show_alarms`, `snooze_alarm`, and `dismiss_timer`
+send intents to whatever clock app is installed; behavior (especially
+`EXTRA_SKIP_UI` and dismiss/snooze support) varies by OEM. Verify manually on
+Google Clock at minimum:
+
+- [ ] `set_alarm` / `set_timer` land in Google Clock's lists.
+- [ ] `show_alarms` opens the alarms tab.
+- [ ] While an alarm is ringing, `snooze_alarm` snoozes it.
+- [ ] While a system timer (`set_timer(system=true)`) is ringing, `dismiss_timer`
+ stops it.