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(connectors): add Microsoft Graph connector
Durganshu Mishra7eb3e3458328
diff --git a/app/src/main/java/com/gotcha/connectors/mail/EmailTools.kt b/app/src/main/java/com/gotcha/connectors/mail/EmailTools.ktindex 99bfab9..5b5460b 100644--- a/app/src/main/java/com/gotcha/connectors/mail/EmailTools.kt+++ b/app/src/main/java/com/gotcha/connectors/mail/EmailTools.kt@@ -3,8 +3,10 @@ package com.gotcha.connectors.mailimport android.content.Contextimport android.content.Intentimport android.net.Uri+import com.gotcha.connectors.ToolRouterimport com.gotcha.connectors.google.GoogleConnectorimport com.gotcha.connectors.imap.ImapConnector+import com.gotcha.connectors.microsoft.MicrosoftConnectorimport com.gotcha.tools.ToolResultimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonObject@@ -15,20 +17,27 @@ import kotlinx.serialization.json.jsonArrayimport 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.+ * Router owning the email tools. Backend precedence for new operations: Gmail API,+ * else Microsoft Graph, else IMAP/SMTP, else an error steering the model to Settings+ * or `compose_email`. Message ids are uniform (`gmail:...` / `ms:...` / `imap:...`)+ * and read/mark route by prefix, so ids stay valid even after the user connects or+ * disconnects another backend.*/class EmailTools(private val gmailBackend: () -> MailBackend?,+ private val microsoftBackend: () -> MailBackend?,private val imapBackend: () -> MailBackend?,private val composeLauncher: (to: String?, subject: String?, body: String?) -> ToolResult-) {-- constructor(context: Context, imap: ImapConnector, google: GoogleConnector) : this(+) : ToolRouter {++ constructor(+ context: Context,+ imap: ImapConnector,+ google: GoogleConnector,+ microsoft: MicrosoftConnector+ ) : this(gmailBackend = { google.takeIf { it.isConnected() } },+ microsoftBackend = { microsoft.takeIf { it.isConnected() } },imapBackend = { imap.takeIf { it.isConnected() } },composeLauncher = { to, subject, body -> launchCompose(context, to, subject, body) })@@ -61,12 +70,12 @@ class EmailTools(}}- val toolNames: Set<String> =+ override 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 {+ override suspend fun execute(name: String, args: JsonObject): ToolResult = try {when (name) {"list_emails" -> listEmails(args)"read_email" -> readEmail(args)@@ -84,18 +93,21 @@ class EmailTools(}/** Preferred backend for new operations (listing, sending). */- private fun primaryBackend(): MailBackend? = gmailBackend() ?: imapBackend()+ private fun primaryBackend(): MailBackend? =+ gmailBackend() ?: microsoftBackend() ?: imapBackend()/** Backend that owns an existing message id, by prefix. */private fun backendForId(id: String): MailBackend? = when {id.startsWith("gmail:") -> gmailBackend()+ id.startsWith("ms:") -> microsoftBackend()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."+ "No email account is connected. Ask the user to connect Gmail, Microsoft 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 {diff --git a/app/src/main/java/com/gotcha/connectors/microsoft/GraphApi.kt b/app/src/main/java/com/gotcha/connectors/microsoft/GraphApi.ktnew file mode 100644index 0000000..90cd15e--- /dev/null+++ b/app/src/main/java/com/gotcha/connectors/microsoft/GraphApi.kt@@ -0,0 +1,253 @@+package com.gotcha.connectors.microsoft++import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+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 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 Microsoft Graph response, with a user-actionable message. */+class GraphApiException(val code: Int, message: String) : IOException(message)++/**+ * Thin OkHttp wrapper over Microsoft Graph v1.0 (mail, calendar, To Do).+ * Stateless: every call takes the Bearer token so [MicrosoftConnector] owns+ * refresh/retry. JVM-testable via a MockWebServer [baseUrl].+ */+@Suppress("TooManyFunctions") // one function per Graph endpoint; splitting by service would not help+class GraphApi(+ private val client: OkHttpClient = OkHttpClient.Builder()+ .connectTimeout(20, TimeUnit.SECONDS)+ .readTimeout(30, TimeUnit.SECONDS)+ .build(),+ private val baseUrl: String = "https://graph.microsoft.com/v1.0"+) {++ companion object {+ private const val MAIL_LIST_SELECT = "id,subject,from,receivedDateTime,isRead,bodyPreview"+ private const val MAIL_READ_SELECT =+ "id,subject,from,toRecipients,ccRecipients,receivedDateTime,body"+ private const val TODO_TASK_SELECT = "id,title,status,dueDateTime,body"+ }++ private val json = Json { ignoreUnknownKeys = true }+ private val jsonMediaType = "application/json; charset=utf-8".toMediaType()++ // ---- Identity ----++ /** `GET /me` — the connected account's address. */+ suspend fun me(accessToken: String): String {+ val obj = get("$baseUrl/me?\$select=mail,userPrincipalName,displayName", accessToken)+ return obj.str("mail") ?: obj.str("userPrincipalName") ?: "(unknown)"+ }++ // ---- Mail ----++ /**+ * `GET /me/messages`. Graph rejects `$search` combined with `$filter`/`$orderby`,+ * so a text query switches to search mode and unread filtering is applied by the+ * caller instead.+ */+ suspend fun listMessages(+ accessToken: String,+ query: String?,+ unreadOnly: Boolean,+ max: Int+ ): JsonArray {+ val searching = !query.isNullOrBlank()+ val url = "$baseUrl/me/messages".toHttpUrl().newBuilder()+ .addQueryParameter("\$select", MAIL_LIST_SELECT)+ .addQueryParameter("\$top", max.toString())+ .apply {+ if (searching) {+ addQueryParameter("\$search", "\"${query!!.trim()}\"")+ } else {+ addQueryParameter("\$orderby", "receivedDateTime desc")+ if (unreadOnly) addQueryParameter("\$filter", "isRead eq false")+ }+ }+ .build()+ return get(url.toString(), accessToken).values()+ }++ /** `GET /me/messages/{id}` — headers plus the full body. */+ suspend fun getMessage(accessToken: String, id: String): JsonObject =+ get("$baseUrl/me/messages/$id?\$select=$MAIL_READ_SELECT", accessToken)++ /** `POST /me/sendMail` — sends immediately and files a copy in Sent Items. */+ suspend fun sendMail(accessToken: String, message: JsonObject) {+ val body = buildJsonObject {+ put("message", message)+ put("saveToSentItems", JsonPrimitive(true))+ }+ post("$baseUrl/me/sendMail", accessToken, body)+ }++ /** `PATCH /me/messages/{id}` — flips the read flag. */+ suspend fun setRead(accessToken: String, id: String, read: Boolean) {+ val body = buildJsonObject { put("isRead", JsonPrimitive(read)) }+ patch("$baseUrl/me/messages/$id", accessToken, body)+ }++ // ---- Calendar ----++ /** `GET /me/calendarView` — expands recurrences within the window. ISO-8601 UTC bounds. */+ suspend fun calendarView(+ accessToken: String,+ startIso: String,+ endIso: String,+ max: Int+ ): JsonArray {+ val url = "$baseUrl/me/calendarView".toHttpUrl().newBuilder()+ .addQueryParameter("startDateTime", startIso)+ .addQueryParameter("endDateTime", endIso)+ .addQueryParameter("\$select", "id,subject,start,end,location,isAllDay,organizer,attendees")+ .addQueryParameter("\$orderby", "start/dateTime")+ .addQueryParameter("\$top", max.toString())+ .build()+ return get(url.toString(), accessToken, preferUtc = true).values()+ }++ /** `POST /me/events` — returns the new event id. */+ suspend fun createEvent(accessToken: String, event: JsonObject): String =+ post("$baseUrl/me/events", accessToken, event).str("id") ?: "(unknown id)"++ /** `POST /me/calendar/getSchedule` — busy blocks for the given addresses. */+ suspend fun getSchedule(+ accessToken: String,+ schedules: List<String>,+ startIso: String,+ endIso: String,+ intervalMinutes: Int+ ): JsonArray {+ val body = buildJsonObject {+ put("schedules", JsonArray(schedules.map { JsonPrimitive(it) }))+ put("startTime", dateTimeZone(startIso))+ put("endTime", dateTimeZone(endIso))+ put("availabilityViewInterval", JsonPrimitive(intervalMinutes))+ }+ return post("$baseUrl/me/calendar/getSchedule", accessToken, body).values()+ }++ // ---- To Do ----++ /** `GET /me/todo/lists` — the account's task lists. */+ suspend fun todoLists(accessToken: String): JsonArray =+ get("$baseUrl/me/todo/lists", accessToken).values()++ /** `GET /me/todo/lists/{listId}/tasks`, optionally hiding completed items. */+ suspend fun todoTasks(+ accessToken: String,+ listId: String,+ includeCompleted: Boolean,+ max: Int+ ): JsonArray {+ val url = "$baseUrl/me/todo/lists/$listId/tasks".toHttpUrl().newBuilder()+ .addQueryParameter("\$select", TODO_TASK_SELECT)+ .addQueryParameter("\$top", max.toString())+ .apply { if (!includeCompleted) addQueryParameter("\$filter", "status ne 'completed'") }+ .build()+ return get(url.toString(), accessToken).values()+ }++ /** `POST /me/todo/lists/{listId}/tasks` — returns the new task id. */+ suspend fun createTodoTask(accessToken: String, listId: String, task: JsonObject): String =+ post("$baseUrl/me/todo/lists/$listId/tasks", accessToken, task).str("id") ?: "(unknown id)"++ /** `PATCH /me/todo/lists/{listId}/tasks/{taskId}` — marks completed or reopens. */+ suspend fun setTodoTaskCompleted(+ accessToken: String,+ listId: String,+ taskId: String,+ completed: Boolean+ ) {+ val body = buildJsonObject {+ put(+ "status",+ JsonPrimitive(if (completed) "completed" else "notStarted")+ )+ }+ patch("$baseUrl/me/todo/lists/$listId/tasks/$taskId", accessToken, body)+ }++ // ---- Plumbing ----++ private fun dateTimeZone(iso: String): JsonObject = buildJsonObject {+ put("dateTime", JsonPrimitive(iso.removeSuffix("Z")))+ put("timeZone", JsonPrimitive("UTC"))+ }++ /** Graph collection responses wrap their rows in `value`. */+ private fun JsonObject.values(): JsonArray = this["value"]?.jsonArray ?: JsonArray(emptyList())++ private fun JsonObject.str(key: String): String? = this[key]?.jsonPrimitive?.contentOrNull++ private suspend fun get(+ url: String,+ accessToken: String,+ preferUtc: Boolean = false+ ): JsonObject = execute(+ Request.Builder()+ .url(url)+ .header("Authorization", "Bearer $accessToken")+ .apply { if (preferUtc) header("Prefer", "outlook.timezone=\"UTC\"") }+ .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 patch(url: String, accessToken: String, body: JsonObject): JsonObject =+ execute(+ Request.Builder()+ .url(url)+ .header("Authorization", "Bearer $accessToken")+ .patch(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): GraphApiException {+ val detail = runCatching {+ json.parseToJsonElement(body).jsonObject["error"]+ ?.jsonObject?.get("message")?.jsonPrimitive?.contentOrNull+ }.getOrNull() ?: body.take(200)+ val message = when (code) {+ 401 -> "Microsoft auth expired (401): $detail"+ 403 ->+ "Microsoft Graph denied this request (403) — the permission was probably not " ++ "granted. Reconnect in Settings → Connectors. $detail"+ 429, 503 -> "Microsoft Graph is throttling requests (HTTP $code) — try again later. $detail"+ 400 -> "Microsoft Graph rejected the request (400): $detail"+ else -> "Microsoft Graph error (HTTP $code): $detail"+ }+ return GraphApiException(code, message)+ }+}diff --git a/app/src/main/java/com/gotcha/connectors/microsoft/GraphMailParser.kt b/app/src/main/java/com/gotcha/connectors/microsoft/GraphMailParser.ktnew file mode 100644index 0000000..69a569b--- /dev/null+++ b/app/src/main/java/com/gotcha/connectors/microsoft/GraphMailParser.kt@@ -0,0 +1,98 @@+package com.gotcha.connectors.microsoft++import com.gotcha.connectors.mail.EmailFull+import com.gotcha.connectors.mail.EmailSummary+import com.gotcha.connectors.mail.MailBodyExtractor+import com.gotcha.connectors.mail.OutgoingEmail+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.booleanOrNull+import kotlinx.serialization.json.buildJsonArray+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++/**+ * Maps Microsoft Graph message JSON to the shared mail model and back. Pure+ * Kotlin so it is unit-testable without a device — the Graph counterpart of+ * [com.gotcha.connectors.google.GmailMessageParser].+ */+object GraphMailParser {++ /** Graph nests addresses as `{"emailAddress":{"name":..,"address":..}}`. */+ fun address(node: JsonObject?): String {+ val emailAddress = node?.get("emailAddress")?.jsonObject ?: return ""+ val name = emailAddress.str("name")+ val addr = emailAddress.str("address").orEmpty()+ return if (name.isNullOrBlank() || name == addr) addr else "$name <$addr>"+ }++ fun addresses(nodes: JsonArray?): String =+ nodes.orEmpty().joinToString(", ") { address(it.jsonObject) }.trim()++ fun summary(message: JsonObject): EmailSummary = EmailSummary(+ id = "ms:${message.str("id").orEmpty()}",+ from = address(message["from"]?.jsonObject),+ subject = message.str("subject")?.takeIf { it.isNotBlank() } ?: "(no subject)",+ date = message.str("receivedDateTime").orEmpty(),+ unread = message["isRead"]?.jsonPrimitive?.booleanOrNull?.not() ?: false,+ snippet = MailBodyExtractor.snippet(message.str("bodyPreview").orEmpty())+ )++ fun full(id: String, message: JsonObject): EmailFull = EmailFull(+ id = id,+ from = address(message["from"]?.jsonObject),+ to = addresses(message["toRecipients"]?.jsonArray),+ cc = addresses(message["ccRecipients"]?.jsonArray),+ subject = message.str("subject")?.takeIf { it.isNotBlank() } ?: "(no subject)",+ date = message.str("receivedDateTime").orEmpty(),+ body = body(message["body"]?.jsonObject)+ )++ /** Graph bodies carry their own contentType; HTML is stripped to readable text. */+ fun body(bodyNode: JsonObject?): String {+ val content = bodyNode?.str("content").orEmpty()+ return if (bodyNode?.str("contentType")?.equals("html", ignoreCase = true) == true) {+ MailBodyExtractor.htmlToText(content)+ } else {+ content.trim()+ }+ }++ /** Builds the `message` payload for `POST /me/sendMail`. */+ fun outgoing(message: OutgoingEmail): JsonObject = buildJsonObject {+ put("subject", JsonPrimitive(message.subject))+ put(+ "body",+ buildJsonObject {+ put("contentType", JsonPrimitive("Text"))+ put("content", JsonPrimitive(message.body))+ }+ )+ put("toRecipients", recipients(message.to))+ if (message.cc.isNotEmpty()) put("ccRecipients", recipients(message.cc))+ if (message.bcc.isNotEmpty()) put("bccRecipients", recipients(message.bcc))+ }++ private fun recipients(addresses: List<String>): JsonArray = buildJsonArray {+ addresses.forEach { addr ->+ add(+ buildJsonObject {+ put(+ "emailAddress",+ buildJsonObject { put("address", JsonPrimitive(addr.trim())) }+ )+ }+ )+ }+ }++ /** Strips the uniform `ms:` prefix from a message id. */+ fun stripPrefix(id: String): String = id.removePrefix("ms:")++ private fun JsonObject.str(key: String): String? = this[key]?.jsonPrimitive?.contentOrNull+}diff --git a/app/src/main/java/com/gotcha/connectors/microsoft/MicrosoftConnector.kt b/app/src/main/java/com/gotcha/connectors/microsoft/MicrosoftConnector.ktnew file mode 100644index 0000000..4769109--- /dev/null+++ b/app/src/main/java/com/gotcha/connectors/microsoft/MicrosoftConnector.kt@@ -0,0 +1,277 @@+package com.gotcha.connectors.microsoft++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.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 kotlinx.serialization.Serializable+import kotlinx.serialization.decodeFromString+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive++@Serializable+data class MicrosoftCredentials(+ val clientId: String,+ /** "common" for personal + work accounts; a tenant id/domain locks it to one org. */+ val tenant: String,+ val refreshToken: String,+ val accountEmail: String,+ val scopes: List<String>,+ /** Set when refresh hit invalid_grant (password change, admin revoke, MFA reset). */+ val needsReconnect: Boolean = false+)++/**+ * Bring-Your-Own-OAuth Microsoft Graph connector. The user registers a public+ * client ("Mobile and desktop applications") in their own Entra tenant, so no+ * client secret exists and no publisher verification is involved. Entra accepts+ * any loopback port for public clients, so the shared+ * [com.gotcha.connectors.oauth.LoopbackRedirectServer] flow works unchanged.+ *+ * One credential backs three services: Outlook mail (via [MailBackend], so it+ * reuses the existing email tools), calendar, and To Do.+ */+@Suppress("TooManyFunctions") // one credential fronts three Graph services (mail, calendar, To Do)+class MicrosoftConnector(+ private val store: CredentialStore,+ private val api: GraphApi = GraphApi(),+ private val oauth: OAuth2Helper = OAuth2Helper(),+ private val authorityOverride: String? = null,+ private val clock: () -> Long = System::currentTimeMillis+) : Connector, MailBackend {++ private val json = Json { ignoreUnknownKeys = true }++ companion object {+ const val DEFAULT_TENANT = "common"+ const val SCOPE_MAIL = "Mail.ReadWrite"+ const val SCOPE_MAIL_SEND = "Mail.Send"+ const val SCOPE_CALENDAR = "Calendars.ReadWrite"+ const val SCOPE_TASKS = "Tasks.ReadWrite"++ /** offline_access is what makes Entra return a refresh token at all. */+ val DEFAULT_SCOPES = listOf(+ "offline_access",+ "User.Read",+ SCOPE_MAIL,+ SCOPE_MAIL_SEND,+ SCOPE_CALENDAR,+ SCOPE_TASKS+ )++ private const val EXPIRY_SKEW_MILLIS = 60_000L+ }++ override val id = "microsoft"+ override val displayName = "Microsoft (Outlook, Calendar, To Do)"+ override val description =+ "Outlook mail, calendar and To Do via your own Entra app registration."+ override val toolNames = setOf(+ "list_emails",+ "read_email",+ "send_email",+ "mark_email_read",+ "list_tasks",+ "create_task",+ "complete_task"+ )+ override val idPrefix = "ms"++ @Volatile+ private var credentials: MicrosoftCredentials? = store.loadRaw(id)?.let { blob ->+ runCatching { json.decodeFromString<MicrosoftCredentials>(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: MicrosoftCredentials) {+ store.saveRaw(id, json.encodeToString(creds))+ credentials = creds+ }++ fun credentials(): MicrosoftCredentials? = 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 or was revoked."+ else -> "Connected as ${credentials?.accountEmail}"+ }++ override fun disconnect() {+ store.clear(id)+ credentials = null+ accessToken = null+ accessTokenExpiresAt = 0+ }++ private fun authority(tenant: String): String =+ authorityOverride ?: "https://login.microsoftonline.com/$tenant/oauth2/v2.0"++ fun oauthConfig(+ clientId: String,+ tenant: String = DEFAULT_TENANT,+ scopes: List<String> = DEFAULT_SCOPES+ ) = OAuth2Config(+ authUrl = "${authority(tenant)}/authorize",+ tokenUrl = "${authority(tenant)}/token",+ clientId = clientId,+ // Public client: PKCE only. Sending a secret makes Entra reject the request.+ clientSecret = null,+ scopes = scopes,+ extraAuthParams = mapOf("response_mode" to "query", "prompt" to "select_account")+ )++ /**+ * Finish connecting after the OAuth code exchange: identify the account via+ * `GET /me` and persist the credential blob.+ */+ suspend fun completeConnect(+ clientId: String,+ tenant: String,+ tokens: TokenSet,+ scopes: List<String> = DEFAULT_SCOPES+ ) {+ val refreshToken = checkNotNull(tokens.refreshToken) {+ "Microsoft did not return a refresh token — make sure the 'offline_access' " ++ "permission is included and try connecting again."+ }+ val email = api.me(tokens.accessToken)+ persist(+ MicrosoftCredentials(+ clientId = clientId,+ tenant = tenant.ifBlank { DEFAULT_TENANT },+ refreshToken = refreshToken,+ accountEmail = email,+ scopes = scopes+ )+ )+ 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) { "Microsoft is not connected." }+ check(!creds.needsReconnect) {+ "The Microsoft 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.tenant, creds.scopes),+ 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 Microsoft sign-in expired (invalid_grant) — ask the user to reconnect in " ++ "Settings → Connectors.",+ 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: GraphApiException) {+ if (e.code != 401) throw e+ block(token(forceRefresh = true))+ }+ }++ // ---- MailBackend (Outlook via Graph) ----++ override suspend fun list(query: String?, unreadOnly: Boolean, max: Int): List<EmailSummary> =+ withAuth { tok ->+ // Graph cannot combine $search with $filter, so unread filtering for a text+ // query happens here instead of server-side.+ val rows = api.listMessages(tok, query, unreadOnly, max)+ .map { GraphMailParser.summary(it.jsonObject) }+ if (unreadOnly && !query.isNullOrBlank()) rows.filter { it.unread } else rows+ }++ override suspend fun read(id: String): EmailFull = withAuth { tok ->+ GraphMailParser.full(id, api.getMessage(tok, GraphMailParser.stripPrefix(id)))+ }++ override suspend fun send(message: OutgoingEmail): String = withAuth { tok ->+ api.sendMail(tok, GraphMailParser.outgoing(message))+ "Email sent to ${message.to.joinToString()} via Outlook."+ }++ override suspend fun markRead(id: String, read: Boolean) {+ withAuth { tok -> api.setRead(tok, GraphMailParser.stripPrefix(id), read) }+ }++ // ---- Calendar (used by the shared calendar router) ----++ suspend fun calendarView(startIso: String, endIso: String, max: Int): JsonArray =+ withAuth { tok -> api.calendarView(tok, startIso, endIso, max) }++ suspend fun createEvent(event: JsonObject): String =+ withAuth { tok -> api.createEvent(tok, event) }++ suspend fun busyBlocks(startIso: String, endIso: String, intervalMinutes: Int): JsonArray =+ withAuth { tok ->+ val me = credentials?.accountEmail ?: return@withAuth JsonArray(emptyList())+ api.getSchedule(tok, listOf(me), startIso, endIso, intervalMinutes)+ }++ // ---- To Do ----++ suspend fun todoLists(): JsonArray = withAuth { tok -> api.todoLists(tok) }++ suspend fun todoTasks(listId: String, includeCompleted: Boolean, max: Int): JsonArray =+ withAuth { tok -> api.todoTasks(tok, listId, includeCompleted, max) }++ suspend fun createTodoTask(listId: String, task: JsonObject): String =+ withAuth { tok -> api.createTodoTask(tok, listId, task) }++ suspend fun completeTodoTask(listId: String, taskId: String, completed: Boolean) {+ withAuth { tok -> api.setTodoTaskCompleted(tok, listId, taskId, completed) }+ }++ /** Default list id (the built-in "Tasks" list) used when the caller names no list. */+ suspend fun defaultTodoListId(): String? {+ val lists = todoLists().map { it.jsonObject }+ val wellKnown = lists.firstOrNull {+ it["wellknownListName"]?.jsonPrimitive?.contentOrNull == "defaultList"+ }+ return (wellKnown ?: lists.firstOrNull())?.get("id")?.jsonPrimitive?.contentOrNull+ }+}diff --git a/app/src/main/java/com/gotcha/connectors/microsoft/TaskTools.kt b/app/src/main/java/com/gotcha/connectors/microsoft/TaskTools.ktnew file mode 100644index 0000000..20fa22d--- /dev/null+++ b/app/src/main/java/com/gotcha/connectors/microsoft/TaskTools.kt@@ -0,0 +1,143 @@+package com.gotcha.connectors.microsoft++import com.gotcha.connectors.ToolRouter+import com.gotcha.tools.ToolResult+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.booleanOrNull+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.intOrNull+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.put++/**+ * Router owning the persistent to-do tools, backed by Microsoft To Do.+ *+ * These are deliberately distinct from `todowrite`: `todowrite` is the agent's+ * in-session scratch plan and disappears when the conversation ends, whereas+ * these tools read and write the user's real task list, which syncs to their+ * other devices.+ *+ * Task ids are uniform: `ms:<listId>:<taskId>`.+ */+class TaskTools(+ private val backend: () -> MicrosoftConnector?+) : ToolRouter {++ companion object {+ private const val DEFAULT_MAX = 25+ private const val MAX_MAX = 100+ private const val ID_PARTS = 3+ }++ override val toolNames: Set<String> = setOf("list_tasks", "create_task", "complete_task")++ override suspend fun execute(name: String, args: JsonObject): ToolResult = try {+ when (name) {+ "list_tasks" -> listTasks(args)+ "create_task" -> createTask(args)+ "complete_task" -> completeTask(args)+ else -> ToolResult.error("Unknown task tool '$name'.")+ }+ } catch (e: Exception) {+ ToolResult.error("$name failed: ${e.message}")+ }++ private fun connectedOrNull(): MicrosoftConnector? = backend()?.takeIf { it.isConnected() }++ private fun notConnected(): ToolResult = ToolResult.error(+ "No task list is connected. These tools need the Microsoft connector (Settings → " ++ "Connectors). For a throwaway plan inside this conversation, use todowrite instead."+ )++ private suspend fun listTasks(args: JsonObject): ToolResult {+ val ms = connectedOrNull() ?: return notConnected()+ val max = (args.optInt("max") ?: DEFAULT_MAX).coerceIn(1, MAX_MAX)+ val includeCompleted = args.optBoolean("include_completed") ?: false+ val listId = resolveListId(ms, args.optString("list"))+ ?: return ToolResult.error("No Microsoft To Do lists were found on this account.")++ val tasks = ms.todoTasks(listId, includeCompleted, max).map { it.jsonObject }+ if (tasks.isEmpty()) {+ return ToolResult.ok(+ if (includeCompleted) "That list has no tasks." else "No open tasks in that list."+ )+ }+ val rows = tasks.joinToString("\n") { task ->+ val id = task.str("id").orEmpty()+ val status = task.str("status").orEmpty()+ val flag = if (status == "completed") "done" else "open"+ val due = task["dueDateTime"]?.jsonObject?.str("dateTime")+ ?.substringBefore('T')?.let { " | due $it" } ?: ""+ "[ms:$listId:$id] $flag | ${task.str("title").orEmpty()}$due"+ }+ return ToolResult.ok("${tasks.size} task(s):\n$rows")+ }++ private suspend fun createTask(args: JsonObject): ToolResult {+ val ms = connectedOrNull() ?: return notConnected()+ val title = args.optString("title")+ ?: return ToolResult.error("create_task needs a 'title'.")+ val listId = resolveListId(ms, args.optString("list"))+ ?: return ToolResult.error("No Microsoft To Do lists were found on this account.")++ val payload = buildJsonObject {+ put("title", JsonPrimitive(title))+ args.optString("notes")?.let { notes ->+ put(+ "body",+ buildJsonObject {+ put("contentType", JsonPrimitive("text"))+ put("content", JsonPrimitive(notes))+ }+ )+ }+ args.optString("due_date")?.let { due ->+ put(+ "dueDateTime",+ buildJsonObject {+ put("dateTime", JsonPrimitive("${due}T00:00:00"))+ put("timeZone", JsonPrimitive("UTC"))+ }+ )+ }+ }+ val newId = ms.createTodoTask(listId, payload)+ return ToolResult.ok("Created task \"$title\" (id ms:$listId:$newId).")+ }++ private suspend fun completeTask(args: JsonObject): ToolResult {+ val ms = connectedOrNull() ?: return notConnected()+ val id = args.optString("id") ?: return ToolResult.error("complete_task needs an 'id'.")+ val parts = id.split(":")+ if (parts.size != ID_PARTS || parts[0] != "ms") {+ return ToolResult.error("Task ids look like 'ms:<listId>:<taskId>' — got '$id'.")+ }+ val completed = args.optBoolean("completed") ?: true+ ms.completeTodoTask(parts[1], parts[2], completed)+ return ToolResult.ok(+ if (completed) "Marked $id complete." else "Reopened $id."+ )+ }++ /** Resolves a list name to its id; null [name] picks the account's default list. */+ private suspend fun resolveListId(ms: MicrosoftConnector, name: String?): String? {+ if (name.isNullOrBlank()) return ms.defaultTodoListId()+ val match = ms.todoLists().map { it.jsonObject }.firstOrNull { list ->+ list.str("displayName")?.equals(name, ignoreCase = true) == true+ }+ return match?.str("id") ?: ms.defaultTodoListId()+ }++ private fun JsonObject.str(key: String): String? = this[key]?.jsonPrimitive?.contentOrNull++ 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+}diff --git a/app/src/test/java/com/gotcha/connectors/mail/EmailToolsTest.kt b/app/src/test/java/com/gotcha/connectors/mail/EmailToolsTest.ktindex 6af0425..5822e1d 100644--- a/app/src/test/java/com/gotcha/connectors/mail/EmailToolsTest.kt+++ b/app/src/test/java/com/gotcha/connectors/mail/EmailToolsTest.kt@@ -52,6 +52,7 @@ class EmailToolsTest {val imap = FakeBackend("imap")val tools = EmailTools(gmailBackend = { gmail },+ microsoftBackend = { null },imapBackend = { imap },composeLauncher = { _, _, _ -> ToolResult.ok("composed") })@@ -68,6 +69,7 @@ class EmailToolsTest {}val tools = EmailTools(gmailBackend = { null },+ microsoftBackend = { null },imapBackend = { imap },composeLauncher = { _, _, _ -> ToolResult.ok("composed") })@@ -81,6 +83,7 @@ class EmailToolsTest {fun `list_emails with no backend steers to settings`() = runTest {val tools = EmailTools(gmailBackend = { null },+ microsoftBackend = { null },imapBackend = { null },composeLauncher = { _, _, _ -> ToolResult.ok("composed") })@@ -90,6 +93,72 @@ class EmailToolsTest {assertTrue(result.message.contains("compose_email"))}+ @Test+ fun `list_emails prefers microsoft over imap when gmail absent`() = runTest {+ val microsoft = FakeBackend("ms").apply {+ listResult = listOf(EmailSummary("ms:AAA", "[email protected]", "Hey", "2024-02-01", true, "snip3"))+ }+ val imap = FakeBackend("imap")+ val tools = EmailTools(+ gmailBackend = { null },+ microsoftBackend = { microsoft },+ imapBackend = { imap },+ composeLauncher = { _, _, _ -> ToolResult.ok("composed") }+ )+ val result = tools.execute("list_emails", buildArgs {})+ assertTrue(result.success)+ assertTrue(result.message.contains("ms:AAA"))+ assertEquals(-1, imap.lastMax) // imap never called+ }++ @Test+ fun `gmail still outranks microsoft`() = runTest {+ val gmail = FakeBackend("gmail").apply {+ listResult = listOf(EmailSummary("gmail:9", "[email protected]", "G", "2024-01-01", false, "s"))+ }+ val microsoft = FakeBackend("ms")+ val tools = EmailTools(+ gmailBackend = { gmail },+ microsoftBackend = { microsoft },+ imapBackend = { null },+ composeLauncher = { _, _, _ -> ToolResult.ok("composed") }+ )+ val result = tools.execute("list_emails", buildArgs {})+ assertTrue(result.message.contains("gmail:9"))+ assertEquals(-1, microsoft.lastMax)+ }++ @Test+ fun `read_email routes ms ids to the microsoft backend`() = runTest {+ val microsoft = FakeBackend("ms").apply {+ readResult = EmailFull("ms:AAA", "[email protected]", "[email protected]", "", "S", "2024-02-01", "Graph body")+ }+ val gmail = FakeBackend("gmail")+ val tools = EmailTools(+ gmailBackend = { gmail },+ microsoftBackend = { microsoft },+ imapBackend = { null },+ composeLauncher = { _, _, _ -> ToolResult.ok("composed") }+ )+ val result = tools.execute("read_email", buildArgs { put("id", "ms:AAA") })+ assertTrue(result.success)+ assertTrue(result.message.contains("Graph body"))+ }++ @Test+ fun `mark_email_read routes ms ids to the microsoft backend`() = runTest {+ val microsoft = FakeBackend("ms")+ val tools = EmailTools(+ gmailBackend = { FakeBackend("gmail") },+ microsoftBackend = { microsoft },+ imapBackend = { null },+ composeLauncher = { _, _, _ -> ToolResult.ok("composed") }+ )+ val result = tools.execute("mark_email_read", buildArgs { put("id", "ms:AAA") })+ assertTrue(result.success)+ assertEquals(true, microsoft.markedRead["ms:AAA"])+ }+@Testfun `read_email routes by id prefix`() = runTest {val gmail = FakeBackend("gmail").apply {@@ -98,6 +167,7 @@ class EmailToolsTest {val imap = FakeBackend("imap")val tools = EmailTools(gmailBackend = { gmail },+ microsoftBackend = { null },imapBackend = { imap },composeLauncher = { _, _, _ -> ToolResult.ok("composed") })@@ -110,6 +180,7 @@ class EmailToolsTest {fun `read_email with disconnected backend for id prefix errors`() = runTest {val tools = EmailTools(gmailBackend = { null },+ microsoftBackend = { null },imapBackend = { null },composeLauncher = { _, _, _ -> ToolResult.ok("composed") })@@ -122,6 +193,7 @@ class EmailToolsTest {val gmail = FakeBackend("gmail")val tools = EmailTools(gmailBackend = { gmail },+ microsoftBackend = { null },imapBackend = { null },composeLauncher = { _, _, _ -> ToolResult.ok("composed") })@@ -141,6 +213,7 @@ class EmailToolsTest {val gmail = FakeBackend("gmail")val tools = EmailTools(gmailBackend = { gmail },+ microsoftBackend = { null },imapBackend = { null },composeLauncher = { _, _, _ -> ToolResult.ok("composed") })@@ -161,6 +234,7 @@ class EmailToolsTest {val imap = FakeBackend("imap")val tools = EmailTools(gmailBackend = { null },+ microsoftBackend = { null },imapBackend = { imap },composeLauncher = { _, _, _ -> ToolResult.ok("composed") })@@ -180,6 +254,7 @@ class EmailToolsTest {var capturedTo: String? = nullval tools = EmailTools(gmailBackend = { null },+ microsoftBackend = { null },imapBackend = { null },composeLauncher = { to, _, _ ->capturedTo = todiff --git a/app/src/test/java/com/gotcha/connectors/microsoft/GraphApiTest.kt b/app/src/test/java/com/gotcha/connectors/microsoft/GraphApiTest.ktnew file mode 100644index 0000000..acb5599--- /dev/null+++ b/app/src/test/java/com/gotcha/connectors/microsoft/GraphApiTest.kt@@ -0,0 +1,185 @@+package com.gotcha.connectors.microsoft++import kotlinx.coroutines.test.runTest+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.put+import 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 GraphApiTest {++ private lateinit var server: MockWebServer+ private lateinit var api: GraphApi++ @Before+ fun setUp() {+ server = MockWebServer()+ server.start()+ api = GraphApi(baseUrl = server.url("/v1.0").toString().trimEnd('/'))+ }++ @After+ fun tearDown() {+ server.shutdown()+ }++ /** Takes the next request, asserts it carried the Bearer token, returns its decoded path. */+ private fun decodedPath(): String {+ val request = server.takeRequest()+ assertEquals("Bearer tok", request.getHeader("Authorization"))+ return URLDecoder.decode(request.path.orEmpty(), "UTF-8")+ }++ @Test+ fun `me prefers mail over userPrincipalName`() = runTest {+ server.enqueue(+ MockResponse().setBody("""{"mail":"[email protected]","userPrincipalName":"a_b.com#EXT#@x"}""")+ )+ assertEquals("[email protected]", api.me("tok"))+ assertTrue(decodedPath().contains("\$select=mail,userPrincipalName,displayName"))+ }++ @Test+ fun `me falls back to userPrincipalName`() = runTest {+ server.enqueue(MockResponse().setBody("""{"userPrincipalName":"[email protected]"}"""))+ assertEquals("[email protected]", api.me("tok"))+ }++ @Test+ fun `listMessages without query orders by date and can filter unread`() = runTest {+ server.enqueue(MockResponse().setBody("""{"value":[{"id":"1"}]}"""))+ val rows = api.listMessages("tok", query = null, unreadOnly = true, max = 5)++ assertEquals(1, rows.size)+ val path = decodedPath()+ assertTrue(path.contains("\$orderby=receivedDateTime desc"))+ assertTrue(path.contains("\$filter=isRead eq false"))+ assertTrue(path.contains("\$top=5"))+ assertTrue("search must not be combined with filter", !path.contains("\$search"))+ }++ @Test+ fun `listMessages with query switches to search and drops orderby and filter`() = runTest {+ server.enqueue(MockResponse().setBody("""{"value":[]}"""))+ api.listMessages("tok", query = "invoice", unreadOnly = true, max = 5)++ val path = decodedPath()+ assertTrue(path.contains("\$search=\"invoice\""))+ assertTrue("Graph rejects \$search with \$orderby", !path.contains("\$orderby"))+ assertTrue("Graph rejects \$search with \$filter", !path.contains("\$filter"))+ }++ @Test+ fun `sendMail wraps the message and saves to sent items`() = runTest {+ server.enqueue(MockResponse().setResponseCode(202))+ api.sendMail("tok", buildJsonObject { put("subject", JsonPrimitive("Hi")) })++ val request = server.takeRequest()+ assertEquals("POST", request.method)+ val body = kotlinx.serialization.json.Json.parseToJsonElement(request.body.readUtf8()).jsonObject+ assertEquals("Hi", body["message"]!!.jsonObject["subject"]!!.jsonPrimitive.content)+ assertEquals("true", body["saveToSentItems"]!!.jsonPrimitive.content)+ }++ @Test+ fun `setRead patches the isRead flag`() = runTest {+ server.enqueue(MockResponse().setBody("{}"))+ api.setRead("tok", "msg-1", read = true)++ val request = server.takeRequest()+ assertEquals("PATCH", request.method)+ assertTrue(request.path!!.endsWith("/me/messages/msg-1"))+ assertTrue(request.body.readUtf8().contains("\"isRead\":true"))+ }++ @Test+ fun `calendarView requests UTC and orders by start`() = runTest {+ server.enqueue(MockResponse().setBody("""{"value":[]}"""))+ api.calendarView("tok", "2026-01-01T00:00:00Z", "2026-01-08T00:00:00Z", 20)++ val request = server.takeRequest()+ assertEquals("outlook.timezone=\"UTC\"", request.getHeader("Prefer"))+ val path = URLDecoder.decode(request.path.orEmpty(), "UTF-8")+ assertTrue(path.contains("startDateTime=2026-01-01T00:00:00Z"))+ assertTrue(path.contains("\$orderby=start/dateTime"))+ }++ @Test+ fun `getSchedule posts the account and window`() = runTest {+ server.enqueue(MockResponse().setBody("""{"value":[{"scheduleId":"[email protected]"}]}"""))+ val rows = api.getSchedule(+ "tok",+ listOf("[email protected]"),+ "2026-01-01T09:00:00Z",+ "2026-01-01T17:00:00Z",+ 30+ )++ assertEquals(1, rows.size)+ val body = server.takeRequest().body.readUtf8()+ assertTrue(body.contains("\"[email protected]\""))+ assertTrue("Z suffix must be dropped when timeZone is explicit", body.contains("2026-01-01T09:00:00\""))+ assertTrue(body.contains("\"availabilityViewInterval\":30"))+ }++ @Test+ fun `todoTasks hides completed items by default`() = runTest {+ server.enqueue(MockResponse().setBody("""{"value":[]}"""))+ api.todoTasks("tok", "list-1", includeCompleted = false, max = 25)++ val path = decodedPath()+ assertTrue(path.contains("/me/todo/lists/list-1/tasks"))+ assertTrue(path.contains("\$filter=status ne 'completed'"))+ }++ @Test+ fun `todoTasks includes completed items when asked`() = runTest {+ server.enqueue(MockResponse().setBody("""{"value":[]}"""))+ api.todoTasks("tok", "list-1", includeCompleted = true, max = 25)+ assertTrue(!decodedPath().contains("\$filter"))+ }++ @Test+ fun `401 maps to an auth-expired exception so the connector can retry`() = runTest {+ server.enqueue(MockResponse().setResponseCode(401).setBody("""{"error":{"message":"expired"}}"""))+ try {+ api.me("tok")+ throw AssertionError("expected GraphApiException")+ } catch (e: GraphApiException) {+ assertEquals(401, e.code)+ assertTrue(e.message!!.contains("401"))+ }+ }++ @Test+ fun `429 maps to a throttling message`() = runTest {+ server.enqueue(MockResponse().setResponseCode(429).setBody("""{"error":{"message":"slow down"}}"""))+ try {+ api.me("tok")+ throw AssertionError("expected GraphApiException")+ } catch (e: GraphApiException) {+ assertEquals(429, e.code)+ assertTrue(e.message!!.contains("throttling"))+ }+ }++ @Test+ fun `403 steers the user to reconnect`() = runTest {+ server.enqueue(MockResponse().setResponseCode(403).setBody("""{"error":{"message":"no scope"}}"""))+ try {+ api.me("tok")+ throw AssertionError("expected GraphApiException")+ } catch (e: GraphApiException) {+ assertTrue(e.message!!.contains("Reconnect"))+ }+ }+}diff --git a/app/src/test/java/com/gotcha/connectors/microsoft/MicrosoftConnectorTest.kt b/app/src/test/java/com/gotcha/connectors/microsoft/MicrosoftConnectorTest.ktnew file mode 100644index 0000000..f516d65--- /dev/null+++ b/app/src/test/java/com/gotcha/connectors/microsoft/MicrosoftConnectorTest.kt@@ -0,0 +1,192 @@+package com.gotcha.connectors.microsoft++import com.gotcha.connectors.CredentialStore+import com.gotcha.connectors.mail.OutgoingEmail+import com.gotcha.connectors.oauth.OAuth2Helper+import com.gotcha.connectors.oauth.TokenSet+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++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 MicrosoftConnectorTest {++ private lateinit var authServer: MockWebServer+ private lateinit var graphServer: MockWebServer+ private lateinit var store: InMemoryCredentialStore+ private lateinit var connector: MicrosoftConnector++ @Before+ fun setUp() {+ authServer = MockWebServer()+ authServer.start()+ graphServer = MockWebServer()+ graphServer.start()+ store = InMemoryCredentialStore()+ connector = MicrosoftConnector(+ store = store,+ api = GraphApi(baseUrl = graphServer.url("/v1.0").toString().trimEnd('/')),+ oauth = OAuth2Helper(),+ authorityOverride = authServer.url("/oauth2/v2.0").toString().trimEnd('/')+ )+ }++ @After+ fun tearDown() {+ authServer.shutdown()+ graphServer.shutdown()+ }++ private suspend fun connect(accessToken: String = "at-1", expiresAt: Long = future()) {+ graphServer.enqueue(MockResponse().setBody("""{"mail":"[email protected]"}"""))+ connector.completeConnect(+ "client-id",+ MicrosoftConnector.DEFAULT_TENANT,+ TokenSet(accessToken, "rt-1", expiresAt)+ )+ }++ private fun future() = System.currentTimeMillis() + 3_600_000++ private fun past() = System.currentTimeMillis() - 1_000++ @Test+ fun `oauth config is a public client with no secret`() {+ val cfg = connector.oauthConfig("client-id")+ assertEquals(null, cfg.clientSecret)+ assertTrue(cfg.scopes.contains("offline_access"))+ assertTrue(cfg.scopes.contains(MicrosoftConnector.SCOPE_MAIL))+ assertTrue(cfg.scopes.contains(MicrosoftConnector.SCOPE_CALENDAR))+ assertTrue(cfg.scopes.contains(MicrosoftConnector.SCOPE_TASKS))+ }++ @Test+ fun `completeConnect identifies account and persists credentials`() = runTest {+ connect()+ assertTrue(connector.isConnected())+ assertEquals("[email protected]", connector.credentials()?.accountEmail)+ assertTrue(store.loadRaw("microsoft")?.contains("[email protected]") == true)+ }++ @Test+ fun `completeConnect without refresh token throws a steering error`() = runTest {+ try {+ connector.completeConnect("client-id", "common", TokenSet("at-1", null, future()))+ throw AssertionError("expected IllegalStateException")+ } catch (e: IllegalStateException) {+ assertTrue(e.message!!.contains("offline_access"))+ }+ }++ @Test+ fun `expired access token triggers proactive refresh before the graph call`() = runTest {+ connect(accessToken = "stale", expiresAt = past())+ authServer.enqueue(MockResponse().setBody("""{"access_token":"fresh","expires_in":3600}"""))+ graphServer.enqueue(MockResponse().setBody("""{"value":[]}"""))++ assertTrue(connector.list(null, false, 10).isEmpty())++ graphServer.takeRequest() // the /me call from completeConnect+ assertEquals("Bearer fresh", graphServer.takeRequest().getHeader("Authorization"))+ }++ @Test+ fun `refresh posts no client_secret for the public client`() = runTest {+ connect(accessToken = "stale", expiresAt = past())+ authServer.enqueue(MockResponse().setBody("""{"access_token":"fresh","expires_in":3600}"""))+ graphServer.enqueue(MockResponse().setBody("""{"value":[]}"""))+ connector.list(null, false, 10)++ val body = URLDecoder.decode(authServer.takeRequest().body.readUtf8(), "UTF-8")+ assertTrue(body.contains("grant_type=refresh_token"))+ assertTrue("public clients must not send a secret", !body.contains("client_secret"))+ }++ @Test+ fun `invalid_grant on refresh flips needsReconnect`() = runTest {+ connect(accessToken = "stale", expiresAt = past())+ authServer.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 `list maps graph messages to the shared summary model`() = runTest {+ connect()+ graphServer.enqueue(+ MockResponse().setBody(+ """{"value":[{"id":"AAA","subject":"Hello","isRead":false,+ "receivedDateTime":"2026-02-01T10:00:00Z",+ "from":{"emailAddress":{"name":"Ann","address":"[email protected]"}},+ "bodyPreview":"first line"}]}"""+ )+ )+ val rows = connector.list(null, false, 10)++ assertEquals(1, rows.size)+ assertEquals("ms:AAA", rows[0].id)+ assertEquals("Ann <[email protected]>", rows[0].from)+ assertTrue(rows[0].unread)+ }++ @Test+ fun `unread filtering happens client-side when a text query is used`() = runTest {+ connect()+ graphServer.enqueue(+ MockResponse().setBody(+ """{"value":[+ {"id":"A","subject":"a","isRead":true,"bodyPreview":""},+ {"id":"B","subject":"b","isRead":false,"bodyPreview":""}]}"""+ )+ )+ val rows = connector.list("report", unreadOnly = true, max = 10)++ assertEquals(1, rows.size)+ assertEquals("ms:B", rows[0].id)+ }++ @Test+ fun `send builds a graph message payload`() = runTest {+ connect()+ graphServer.enqueue(MockResponse().setResponseCode(202))+ val result = connector.send(+ OutgoingEmail(to = listOf("[email protected]"), subject = "Subj", body = "Body")+ )++ assertTrue(result.contains("[email protected]"))+ graphServer.takeRequest() // /me+ val body = graphServer.takeRequest().body.readUtf8()+ assertTrue(body.contains("\"address\":\"[email protected]\""))+ assertTrue(body.contains("\"subject\":\"Subj\""))+ }++ @Test+ fun `disconnect clears credentials`() = runTest {+ connect()+ connector.disconnect()+ assertTrue(!connector.isConnected())+ assertEquals(null, connector.credentials())+ assertEquals(null, store.loadRaw("microsoft"))+ }+}