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(connectors): add Google Calendar and a multi-backend calendar router

Durganshu Mishra3dfc62bac387
diff --git a/app/src/main/java/com/gotcha/connectors/calendar/CalendarTools.kt b/app/src/main/java/com/gotcha/connectors/calendar/CalendarTools.kt
new file mode 100644
index 0000000..12ded1e
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/calendar/CalendarTools.kt
@@ -0,0 +1,408 @@
+package com.gotcha.connectors.calendar
+
+import com.gotcha.connectors.ToolRouter
+import com.gotcha.connectors.google.GoogleConnector
+import com.gotcha.connectors.microsoft.MicrosoftConnector
+import com.gotcha.tools.CalendarRecurrence
+import com.gotcha.tools.ToolResult
+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.intOrNull
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.put
+
+/**
+ * Router owning the calendar tools across three backends.
+ *
+ * The on-device calendar (CalendarContract, via [DeviceCalendar]) stays the default and is used
+ * verbatim — connector calendars are opt-in via the `source` argument, so every
+ * existing prompt and behaviour is unchanged when nothing is connected. There is
+ * deliberately one tool per operation rather than parallel `gcal_*`/`ms_*` tools.
+ *
+ * Event ids: device events keep their bare numeric ids (so `edit_calendar_event`
+ * and `delete_calendar_event`, which stay device-only, keep working), while
+ * connector events are prefixed `gcal:` / `ms:`.
+ */
+@Suppress("TooManyFunctions") // three tools x three backends, plus shared JSON/arg helpers
+class CalendarTools(
+ private val device: DeviceCalendar,
+ private val google: () -> GoogleConnector?,
+ private val microsoft: () -> MicrosoftConnector?,
+ private val clock: () -> Long = System::currentTimeMillis
+) : ToolRouter {
+
+ companion object {
+ private const val DEFAULT_MAX = 50
+ private const val DEFAULT_SLOT_MINUTES = 30
+ private const val MINUTE_MILLIS = 60_000L
+ private const val MAX_FREE_SLOTS = 12
+ const val SOURCE_DEVICE = "device"
+ const val SOURCE_GOOGLE = "google"
+ const val SOURCE_MICROSOFT = "microsoft"
+ }
+
+ override val toolNames: Set<String> =
+ setOf("list_calendar_events", "create_calendar_event", "check_availability")
+
+ override suspend fun execute(name: String, args: JsonObject): ToolResult = try {
+ when (name) {
+ "list_calendar_events" -> listEvents(args)
+ "create_calendar_event" -> createEvent(args)
+ "check_availability" -> checkAvailability(args)
+ else -> ToolResult.error("Unknown calendar tool '$name'.")
+ }
+ } catch (e: Exception) {
+ ToolResult.error("$name failed: ${e.message}")
+ }
+
+ // ---- list_calendar_events ----
+
+ private suspend fun listEvents(args: JsonObject): ToolResult {
+ val window = window(args)
+ return when (val source = args.optString("source")?.lowercase() ?: SOURCE_DEVICE) {
+ SOURCE_DEVICE -> device.listEvents(
+ daysAhead = args.optInt("days_ahead"),
+ fromDate = args.optString("from_date"),
+ toDate = args.optString("to_date"),
+ search = args.optString("search")
+ )
+ SOURCE_GOOGLE -> listGoogleEvents(args, window)
+ SOURCE_MICROSOFT -> listMicrosoftEvents(args, window)
+ else -> unknownSource(source)
+ }
+ }
+
+ private suspend fun listGoogleEvents(args: JsonObject, window: Window): ToolResult {
+ val connector = readyGoogle() ?: return googleUnavailable()
+ val rows = connector.listCalendarEvents(
+ calendarId = args.optString("calendar_name") ?: "primary",
+ timeMin = CalendarWindow.toRfc3339(window.startMs),
+ timeMax = CalendarWindow.toRfc3339(window.endMs),
+ query = args.optString("search"),
+ max = DEFAULT_MAX
+ ).map { it.jsonObject }
+
+ if (rows.isEmpty()) return ToolResult.ok("No Google Calendar events ${window.description}.")
+ val text = rows.joinToString("\n") { event ->
+ val start = event["start"]?.jsonObject?.let {
+ it.str("dateTime") ?: it.str("date")
+ }.orEmpty()
+ val end = event["end"]?.jsonObject?.let { it.str("dateTime") ?: it.str("date") }.orEmpty()
+ val location = event.str("location")?.let { " @ $it" }.orEmpty()
+ "[gcal:${event.str("id").orEmpty()}] ${event.str("summary") ?: "(no title)"}\n" +
+ " $start → $end$location"
+ }
+ return ToolResult.ok("Google Calendar events ${window.description} (${rows.size}):\n$text")
+ }
+
+ private suspend fun listMicrosoftEvents(args: JsonObject, window: Window): ToolResult {
+ val connector = readyMicrosoft() ?: return microsoftUnavailable()
+ val search = args.optString("search")
+ val rows = connector.calendarView(
+ CalendarWindow.toRfc3339(window.startMs),
+ CalendarWindow.toRfc3339(window.endMs),
+ DEFAULT_MAX
+ ).map { it.jsonObject }.filter { event ->
+ search == null || event.str("subject")?.contains(search, ignoreCase = true) == true
+ }
+
+ if (rows.isEmpty()) return ToolResult.ok("No Outlook calendar events ${window.description}.")
+ val text = rows.joinToString("\n") { event ->
+ val start = event["start"]?.jsonObject?.str("dateTime").orEmpty()
+ val end = event["end"]?.jsonObject?.str("dateTime").orEmpty()
+ val location = event["location"]?.jsonObject?.str("displayName")
+ ?.takeIf { it.isNotBlank() }?.let { " @ $it" }.orEmpty()
+ "[ms:${event.str("id").orEmpty()}] ${event.str("subject") ?: "(no title)"}\n" +
+ " $start → $end$location"
+ }
+ return ToolResult.ok("Outlook calendar events ${window.description} (${rows.size}):\n$text")
+ }
+
+ // ---- create_calendar_event ----
+
+ private suspend fun createEvent(args: JsonObject): ToolResult =
+ when (val source = args.optString("source")?.lowercase() ?: SOURCE_DEVICE) {
+ SOURCE_DEVICE -> createDeviceEvent(args)
+ SOURCE_GOOGLE -> createGoogleEvent(args)
+ SOURCE_MICROSOFT -> createMicrosoftEvent(args)
+ else -> unknownSource(source)
+ }
+
+ private fun createDeviceEvent(args: JsonObject): ToolResult {
+ val title = args.optString("title")
+ ?: return ToolResult.error("create_calendar_event needs a 'title'.")
+ val start = args.optString("start")
+ ?: return ToolResult.error("create_calendar_event needs a 'start'.")
+ return device.createEvent(
+ title = title,
+ start = start,
+ end = args.optString("end"),
+ location = args.optString("location"),
+ description = args.optString("description"),
+ allDay = args.optBoolean("all_day"),
+ reminderMinutes = args.optInt("reminder_minutes"),
+ calendarName = args.optString("calendar_name"),
+ attendees = args.optStringList("attendees"),
+ recurrence = args.optString("recurrence"),
+ recurrenceCount = args.optInt("recurrence_count"),
+ recurrenceUntil = args.optString("recurrence_until")
+ )
+ }
+
+ private suspend fun createGoogleEvent(args: JsonObject): ToolResult {
+ val connector = readyGoogle() ?: return googleUnavailable()
+ val spec = parseNewEvent(args) ?: return missingTimes()
+ val payload = buildJsonObject {
+ put("summary", JsonPrimitive(spec.title))
+ spec.location?.let { put("location", JsonPrimitive(it)) }
+ spec.description?.let { put("description", JsonPrimitive(it)) }
+ put("start", googleTime(spec.startMs))
+ put("end", googleTime(spec.endMs))
+ if (spec.attendees.isNotEmpty()) {
+ put(
+ "attendees",
+ buildJsonArray {
+ spec.attendees.forEach {
+ add(buildJsonObject { put("email", JsonPrimitive(it)) })
+ }
+ }
+ )
+ }
+ }
+ val id = connector.insertCalendarEvent(args.optString("calendar_name") ?: "primary", payload)
+ return ToolResult.ok(
+ "Added '${spec.title}' to Google Calendar on ${CalendarWindow.readable(spec.startMs)} " +
+ "(id gcal:$id)."
+ )
+ }
+
+ private suspend fun createMicrosoftEvent(args: JsonObject): ToolResult {
+ val connector = readyMicrosoft() ?: return microsoftUnavailable()
+ val spec = parseNewEvent(args) ?: return missingTimes()
+ val payload = buildJsonObject {
+ put("subject", JsonPrimitive(spec.title))
+ spec.description?.let {
+ put(
+ "body",
+ buildJsonObject {
+ put("contentType", JsonPrimitive("text"))
+ put("content", JsonPrimitive(it))
+ }
+ )
+ }
+ spec.location?.let {
+ put("location", buildJsonObject { put("displayName", JsonPrimitive(it)) })
+ }
+ put("start", graphTime(spec.startMs))
+ put("end", graphTime(spec.endMs))
+ if (spec.attendees.isNotEmpty()) {
+ put(
+ "attendees",
+ buildJsonArray {
+ spec.attendees.forEach { addr ->
+ add(
+ buildJsonObject {
+ put(
+ "emailAddress",
+ buildJsonObject { put("address", JsonPrimitive(addr)) }
+ )
+ put("type", JsonPrimitive("required"))
+ }
+ )
+ }
+ }
+ )
+ }
+ }
+ val id = connector.createEvent(payload)
+ return ToolResult.ok(
+ "Added '${spec.title}' to the Outlook calendar on " +
+ "${CalendarWindow.readable(spec.startMs)} (id ms:$id)."
+ )
+ }
+
+ // ---- check_availability ----
+
+ private suspend fun checkAvailability(args: JsonObject): ToolResult {
+ val window = window(args)
+ val slotMinutes = (args.optInt("duration_minutes") ?: DEFAULT_SLOT_MINUTES).coerceAtLeast(1)
+ val busy = mutableListOf<BusyBlock>()
+ val sources = mutableListOf<String>()
+
+ google()?.takeIf { it.isConnected() && it.hasCalendar() }?.let { connector ->
+ val calendars = connector.freeBusy(
+ listOf("primary"),
+ CalendarWindow.toRfc3339(window.startMs),
+ CalendarWindow.toRfc3339(window.endMs)
+ )
+ calendars.values.forEach { calendar ->
+ calendar.jsonObject["busy"]?.jsonArray?.forEach { entry ->
+ val block = entry.jsonObject
+ val start = CalendarWindow.parseRfc3339(block.str("start"))
+ val end = CalendarWindow.parseRfc3339(block.str("end"))
+ if (start != null && end != null) busy.add(BusyBlock(start, end))
+ }
+ }
+ sources.add("Google Calendar")
+ }
+
+ microsoft()?.takeIf { it.isConnected() }?.let { connector ->
+ connector.busyBlocks(
+ CalendarWindow.toRfc3339(window.startMs),
+ CalendarWindow.toRfc3339(window.endMs),
+ slotMinutes
+ ).forEach { schedule ->
+ schedule.jsonObject["scheduleItems"]?.jsonArray?.forEach { entry ->
+ val item = entry.jsonObject
+ val start = CalendarWindow.parseRfc3339(item["start"]?.jsonObject?.str("dateTime"))
+ val end = CalendarWindow.parseRfc3339(item["end"]?.jsonObject?.str("dateTime"))
+ if (start != null && end != null) busy.add(BusyBlock(start, end))
+ }
+ }
+ sources.add("Outlook")
+ }
+
+ if (sources.isEmpty()) {
+ return ToolResult.error(
+ "check_availability needs a connected calendar account (Google with the Calendar " +
+ "scope, or Microsoft) — connect one in Settings → Connectors. For on-device " +
+ "calendars use list_calendar_events and read the gaps."
+ )
+ }
+
+ val merged = CalendarWindow.merge(busy)
+ val free = CalendarWindow.freeSlots(
+ busy,
+ window.startMs,
+ window.endMs,
+ slotMinutes * MINUTE_MILLIS
+ )
+ val busyText = if (merged.isEmpty()) {
+ "Busy: nothing."
+ } else {
+ "Busy (${merged.size}):\n" + merged.joinToString("\n") {
+ " ${CalendarWindow.readable(it.startMs)} → ${CalendarWindow.readable(it.endMs)}"
+ }
+ }
+ val freeText = if (free.isEmpty()) {
+ "No free slot of at least $slotMinutes minutes."
+ } else {
+ "Free slots of ≥$slotMinutes min (showing ${minOf(free.size, MAX_FREE_SLOTS)} " +
+ "of ${free.size}):\n" +
+ free.take(MAX_FREE_SLOTS).joinToString("\n") {
+ " ${CalendarWindow.readable(it.startMs)} → ${CalendarWindow.readable(it.endMs)}"
+ }
+ }
+ return ToolResult.ok(
+ "Availability ${window.description} from ${sources.joinToString(" + ")}:\n" +
+ "$busyText\n$freeText"
+ )
+ }
+
+ // ---- shared helpers ----
+
+ private data class NewEvent(
+ val title: String,
+ val startMs: Long,
+ val endMs: Long,
+ val location: String?,
+ val description: String?,
+ val attendees: List<String>
+ )
+
+ private fun parseNewEvent(args: JsonObject): NewEvent? {
+ val title = args.optString("title") ?: return null
+ val start = args.optString("start")?.let { CalendarRecurrence.parseWhen(it) } ?: return null
+ val end = args.optString("end")?.let { CalendarRecurrence.parseWhen(it) }
+ ?: (start + 60 * MINUTE_MILLIS)
+ return NewEvent(
+ title = title,
+ startMs = start,
+ endMs = end,
+ location = args.optString("location"),
+ description = args.optString("description"),
+ attendees = args.optStringList("attendees").orEmpty()
+ )
+ }
+
+ private fun missingTimes(): ToolResult = ToolResult.error(
+ "create_calendar_event needs 'title' and a parseable 'start' " +
+ "(e.g. '2026-07-17 15:30')."
+ )
+
+ private fun window(args: JsonObject): Window = CalendarWindow.resolve(
+ daysAhead = args.optInt("days_ahead"),
+ fromDate = args.optString("from_date"),
+ toDate = args.optString("to_date"),
+ now = clock()
+ )
+
+ private fun googleTime(epochMs: Long): JsonObject = buildJsonObject {
+ put("dateTime", JsonPrimitive(CalendarWindow.toRfc3339(epochMs)))
+ put("timeZone", JsonPrimitive("UTC"))
+ }
+
+ private fun graphTime(epochMs: Long): JsonObject = buildJsonObject {
+ put("dateTime", JsonPrimitive(CalendarWindow.toRfc3339(epochMs).removeSuffix("Z")))
+ put("timeZone", JsonPrimitive("UTC"))
+ }
+
+ /** The Google connector when it can actually serve calendar calls, else null. */
+ private fun readyGoogle(): GoogleConnector? =
+ google()?.takeIf { it.isConnected() && it.hasCalendar() }
+
+ /** Explains which of the two preconditions readyGoogle() failed on. */
+ private fun googleUnavailable(): ToolResult {
+ val connector = google()
+ return if (connector != null && connector.isConnected()) {
+ ToolResult.error(
+ "The Google connector is signed in for Gmail only. Reconnect it in Settings → " +
+ "Connectors with \"Calendar\" ticked to grant calendar access."
+ )
+ } else {
+ ToolResult.error(
+ "Google is not connected. Connect it in Settings → Connectors, or use " +
+ "source=\"device\" for the phone's own calendar."
+ )
+ }
+ }
+
+ private fun readyMicrosoft(): MicrosoftConnector? = microsoft()?.takeIf { it.isConnected() }
+
+ private fun microsoftUnavailable(): ToolResult = ToolResult.error(
+ "Microsoft is not connected. Connect it in Settings → Connectors, or use " +
+ "source=\"device\" for the phone's own calendar."
+ )
+
+ private fun unknownSource(source: String): ToolResult = ToolResult.error(
+ "Unknown source '$source'. Use \"device\" (default), \"google\" or \"microsoft\"."
+ )
+
+ 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
+
+ private fun JsonObject.optStringList(key: String): List<String>? {
+ val element = this[key] ?: return null
+ return runCatching {
+ element.jsonArray.mapNotNull { it.jsonPrimitive.contentOrNull }
+ }.getOrElse {
+ element.jsonPrimitive.contentOrNull
+ ?.split(',')
+ ?.map { it.trim() }
+ ?.filter { it.isNotEmpty() }
+ }?.takeIf { it.isNotEmpty() }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/connectors/calendar/CalendarWindow.kt b/app/src/main/java/com/gotcha/connectors/calendar/CalendarWindow.kt
new file mode 100644
index 0000000..ec263fe
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/calendar/CalendarWindow.kt
@@ -0,0 +1,115 @@
+package com.gotcha.connectors.calendar
+
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+import java.util.TimeZone
+
+/** A resolved query window plus a human description of it for tool output. */
+data class Window(val startMs: Long, val endMs: Long, val description: String)
+
+/** A busy interval. Half-open: `[startMs, endMs)`. */
+data class BusyBlock(val startMs: Long, val endMs: Long)
+
+/**
+ * Pure date-window and free/busy arithmetic shared by every calendar backend.
+ * No ContentResolver, no network — unit-testable on the JVM.
+ */
+object CalendarWindow {
+
+ private const val DAY_MILLIS = 24L * 60 * 60 * 1000
+ private const val MAX_DAYS_AHEAD = 365
+
+ private fun rfc3339Format() = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply {
+ timeZone = TimeZone.getTimeZone("UTC")
+ }
+
+ private fun dayFormat() = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
+
+ private fun readableFormat() = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
+
+ /** RFC 3339 UTC (`2026-01-01T09:00:00Z`), the format both Graph and Calendar v3 take. */
+ fun toRfc3339(epochMs: Long): String = rfc3339Format().format(Date(epochMs))
+
+ /** Parses RFC 3339 / ISO-8601 timestamps returned by Graph and Calendar v3. */
+ fun parseRfc3339(value: String?): Long? {
+ if (value.isNullOrBlank()) return null
+ val trimmed = value.trim()
+ // Graph omits the zone when Prefer: outlook.timezone is set; Calendar v3 includes it.
+ val patterns = listOf(
+ "yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
+ "yyyy-MM-dd'T'HH:mm:ssXXX",
+ "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS",
+ "yyyy-MM-dd'T'HH:mm:ss.SSS",
+ "yyyy-MM-dd'T'HH:mm:ss",
+ "yyyy-MM-dd"
+ )
+ for (pattern in patterns) {
+ runCatching {
+ val format = SimpleDateFormat(pattern, Locale.US)
+ // Patterns without an offset are UTC by convention for both APIs.
+ if (!pattern.contains("XXX")) format.timeZone = TimeZone.getTimeZone("UTC")
+ return format.parse(trimmed)?.time
+ }
+ }
+ return null
+ }
+
+ fun readable(epochMs: Long): String = readableFormat().format(Date(epochMs))
+
+ /**
+ * Same semantics as the device calendar tool: `from_date`/`to_date` win when
+ * present, else `days_ahead` (default 7) counting from [now].
+ */
+ fun resolve(daysAhead: Int?, fromDate: String?, toDate: String?, now: Long): Window {
+ if (fromDate == null && toDate == null) {
+ val days = (daysAhead ?: 7).coerceIn(1, MAX_DAYS_AHEAD)
+ return Window(now, now + days * DAY_MILLIS, "next $days day(s)")
+ }
+ val format = dayFormat()
+ val start = fromDate?.let { runCatching { format.parse(it)?.time }.getOrNull() } ?: now
+ val end = toDate?.let { runCatching { format.parse(it)?.time }.getOrNull()?.plus(DAY_MILLIS - 1) }
+ ?: (start + DAY_MILLIS)
+ return Window(start, end, "${fromDate ?: "today"} → ${toDate ?: "tomorrow"}")
+ }
+
+ /** Sorts and coalesces overlapping/adjacent busy blocks. */
+ fun merge(blocks: List<BusyBlock>): List<BusyBlock> {
+ if (blocks.isEmpty()) return emptyList()
+ val sorted = blocks.filter { it.endMs > it.startMs }.sortedBy { it.startMs }
+ val merged = mutableListOf<BusyBlock>()
+ sorted.forEach { block ->
+ val last = merged.lastOrNull()
+ if (last != null && block.startMs <= last.endMs) {
+ if (block.endMs > last.endMs) merged[merged.size - 1] = last.copy(endMs = block.endMs)
+ } else {
+ merged.add(block)
+ }
+ }
+ return merged
+ }
+
+ /**
+ * Gaps between [busy] blocks inside `[windowStart, windowEnd)` that are at
+ * least [minMillis] long. [busy] need not be sorted or merged.
+ */
+ fun freeSlots(
+ busy: List<BusyBlock>,
+ windowStart: Long,
+ windowEnd: Long,
+ minMillis: Long
+ ): List<BusyBlock> {
+ val slots = mutableListOf<BusyBlock>()
+ var cursor = windowStart
+ merge(busy).forEach { block ->
+ if (block.startMs > cursor && block.startMs - cursor >= minMillis) {
+ slots.add(BusyBlock(cursor, block.startMs))
+ }
+ if (block.endMs > cursor) cursor = block.endMs
+ }
+ if (windowEnd > cursor && windowEnd - cursor >= minMillis) {
+ slots.add(BusyBlock(cursor, windowEnd))
+ }
+ return slots
+ }
+}
diff --git a/app/src/main/java/com/gotcha/connectors/calendar/DeviceCalendar.kt b/app/src/main/java/com/gotcha/connectors/calendar/DeviceCalendar.kt
new file mode 100644
index 0000000..f90fb3c
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/calendar/DeviceCalendar.kt
@@ -0,0 +1,71 @@
+package com.gotcha.connectors.calendar
+
+import com.gotcha.tools.CalendarTool
+import com.gotcha.tools.ToolResult
+
+/**
+ * The device-calendar operations [CalendarTools] delegates `source="device"` to.
+ *
+ * Exists purely so the router is unit-testable: [CalendarTool] needs a Context
+ * and a ContentResolver, which are unavailable on the JVM. Production wiring goes
+ * through [CalendarToolDevice], which forwards to the untouched [CalendarTool].
+ */
+@Suppress("LongParameterList")
+interface DeviceCalendar {
+ fun listEvents(daysAhead: Int?, fromDate: String?, toDate: String?, search: String?): ToolResult
+
+ fun createEvent(
+ title: String,
+ start: String,
+ end: String?,
+ location: String?,
+ description: String?,
+ allDay: Boolean?,
+ reminderMinutes: Int?,
+ calendarName: String?,
+ attendees: List<String>?,
+ recurrence: String?,
+ recurrenceCount: Int?,
+ recurrenceUntil: String?
+ ): ToolResult
+}
+
+/** Production [DeviceCalendar] — a straight pass-through to the existing CalendarContract tool. */
+class CalendarToolDevice(private val tool: CalendarTool) : DeviceCalendar {
+
+ override fun listEvents(
+ daysAhead: Int?,
+ fromDate: String?,
+ toDate: String?,
+ search: String?
+ ): ToolResult = tool.listEvents(daysAhead, fromDate, toDate, search)
+
+ @Suppress("LongParameterList")
+ override fun createEvent(
+ title: String,
+ start: String,
+ end: String?,
+ location: String?,
+ description: String?,
+ allDay: Boolean?,
+ reminderMinutes: Int?,
+ calendarName: String?,
+ attendees: List<String>?,
+ recurrence: String?,
+ recurrenceCount: Int?,
+ recurrenceUntil: String?
+ ): ToolResult = tool.createEvent(
+ title = title,
+ start = start,
+ end = end,
+ location = location,
+ description = description,
+ allDay = allDay,
+ reminderMinutes = reminderMinutes,
+ calendarName = calendarName,
+ attendees = attendees,
+ recurrence = recurrence,
+ recurrenceCount = recurrenceCount,
+ recurrenceUntil = recurrenceUntil
+ )
+}
diff --git a/app/src/main/java/com/gotcha/connectors/google/GoogleCalendarApi.kt b/app/src/main/java/com/gotcha/connectors/google/GoogleCalendarApi.kt
new file mode 100644
index 0000000..14a9479
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/google/GoogleCalendarApi.kt
@@ -0,0 +1,137 @@
+package com.gotcha.connectors.google
+
+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.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
+import okhttp3.HttpUrl.Companion.toHttpUrl
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+import java.util.concurrent.TimeUnit
+
+/**
+ * Thin OkHttp wrapper over the Google Calendar v3 REST API. Stateless: every
+ * call takes the Bearer token so [GoogleConnector] owns refresh/retry. Reuses
+ * [GmailApiException] so the connector's shared 401-retry path applies to both
+ * Google services. JVM-testable via a MockWebServer [baseUrl].
+ */
+class GoogleCalendarApi(
+ private val client: OkHttpClient = OkHttpClient.Builder()
+ .connectTimeout(20, TimeUnit.SECONDS)
+ .readTimeout(30, TimeUnit.SECONDS)
+ .build(),
+ private val baseUrl: String = "https://www.googleapis.com/calendar/v3"
+) {
+
+ private val json = Json { ignoreUnknownKeys = true }
+ private val jsonMediaType = "application/json; charset=utf-8".toMediaType()
+
+ /**
+ * `events.list` with `singleEvents=true` so recurring events are expanded into
+ * individual instances within the window. [timeMin]/[timeMax] are RFC 3339.
+ */
+ suspend fun listEvents(
+ accessToken: String,
+ calendarId: String,
+ timeMin: String,
+ timeMax: String,
+ query: String?,
+ max: Int
+ ): JsonArray {
+ val url = "$baseUrl/calendars/$calendarId/events".toHttpUrl().newBuilder()
+ .addQueryParameter("timeMin", timeMin)
+ .addQueryParameter("timeMax", timeMax)
+ .addQueryParameter("singleEvents", "true")
+ .addQueryParameter("orderBy", "startTime")
+ .addQueryParameter("maxResults", max.toString())
+ .apply { if (!query.isNullOrBlank()) addQueryParameter("q", query) }
+ .build()
+ return get(url.toString(), accessToken).values()
+ }
+
+ /** `events.insert` — returns the new event id. */
+ suspend fun insertEvent(accessToken: String, calendarId: String, event: JsonObject): String =
+ post("$baseUrl/calendars/$calendarId/events", accessToken, event)["id"]
+ ?.jsonPrimitive?.contentOrNull ?: "(unknown id)"
+
+ /**
+ * `freeBusy.query` — busy blocks per calendar. Returns the `calendars` object,
+ * whose values each hold a `busy` array of `{start,end}` RFC 3339 pairs.
+ */
+ suspend fun freeBusy(
+ accessToken: String,
+ calendarIds: List<String>,
+ timeMin: String,
+ timeMax: String
+ ): JsonObject {
+ val body = buildJsonObject {
+ put("timeMin", JsonPrimitive(timeMin))
+ put("timeMax", JsonPrimitive(timeMax))
+ put(
+ "items",
+ buildJsonArray {
+ calendarIds.forEach { id ->
+ add(buildJsonObject { put("id", JsonPrimitive(id)) })
+ }
+ }
+ )
+ }
+ return post("$baseUrl/freeBusy", accessToken, body)["calendars"]?.jsonObject
+ ?: buildJsonObject {}
+ }
+
+ /** `calendarList.list` — every calendar the account can see, including unsynced ones. */
+ suspend fun calendarList(accessToken: String): JsonArray =
+ get("$baseUrl/users/me/calendarList", accessToken).values()
+
+ private fun JsonObject.values(): JsonArray = this["items"]?.jsonArray ?: JsonArray(emptyList())
+
+ 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 -> "Google auth expired (401): $detail"
+ 403 ->
+ "Google Calendar denied this request (403) — the Calendar scope was probably " +
+ "not granted. Reconnect Google in Settings → Connectors with Calendar " +
+ "ticked. $detail"
+ 429 -> "Google Calendar rate limit (429) — try again later. $detail"
+ 400 -> "Google Calendar rejected the request (400): $detail"
+ else -> "Google Calendar error (HTTP $code): $detail"
+ }
+ return GmailApiException(code, message)
+ }
+}
diff --git a/app/src/main/java/com/gotcha/connectors/google/GoogleConnector.kt b/app/src/main/java/com/gotcha/connectors/google/GoogleConnector.kt
index 8487655..9007917 100644
--- a/app/src/main/java/com/gotcha/connectors/google/GoogleConnector.kt
+++ b/app/src/main/java/com/gotcha/connectors/google/GoogleConnector.kt
@@ -16,6 +16,8 @@ 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
@@ -35,11 +37,15 @@ data class GoogleCredentials(
* 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.
+ * Google services: the scopes actually granted are stored alongside it, so
+ * [hasScope]/[hasCalendar] can steer per-service tools when the user connected
+ * for Gmail only.
*/
+@Suppress("TooManyFunctions") // one credential fronts two Google services (Gmail, Calendar)
class GoogleConnector(
private val store: CredentialStore,
private val api: GmailApi = GmailApi(),
+ private val calendarApi: GoogleCalendarApi = GoogleCalendarApi(),
private val oauth: OAuth2Helper = OAuth2Helper(),
private val tokenUrl: String = TOKEN_URL,
private val clock: () -> Long = System::currentTimeMillis
@@ -51,15 +57,23 @@ class GoogleConnector(
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"
+ const val SCOPE_CALENDAR = "https://www.googleapis.com/auth/calendar"
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")
+ "Gmail and Google Calendar via your own Google Cloud OAuth client (no app passwords)."
+ override val toolNames = setOf(
+ "list_emails",
+ "read_email",
+ "send_email",
+ "mark_email_read",
+ "list_calendar_events",
+ "create_calendar_event",
+ "check_availability"
+ )
override val idPrefix = "gmail"
@Volatile
@@ -119,20 +133,30 @@ class GoogleConnector(
}.start()
}
- fun oauthConfig(clientId: String, clientSecret: String) = OAuth2Config(
+ fun oauthConfig(
+ clientId: String,
+ clientSecret: String,
+ scopes: List<String> = listOf(SCOPE_GMAIL_MODIFY)
+ ) = OAuth2Config(
authUrl = AUTH_URL,
tokenUrl = tokenUrl,
clientId = clientId,
clientSecret = clientSecret,
- scopes = listOf(SCOPE_GMAIL_MODIFY),
+ scopes = scopes,
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.
+ * users/me/profile and persist the credential blob. [scopes] must be the
+ * scopes actually requested, so [hasScope] can steer per-service tools.
*/
- suspend fun completeConnect(clientId: String, clientSecret: String, tokens: TokenSet) {
+ suspend fun completeConnect(
+ clientId: String,
+ clientSecret: String,
+ tokens: TokenSet,
+ scopes: List<String> = listOf(SCOPE_GMAIL_MODIFY)
+ ) {
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."
@@ -143,7 +167,7 @@ class GoogleConnector(
clientSecret = clientSecret,
refreshToken = refreshToken,
accountEmail = email,
- scopes = listOf(SCOPE_GMAIL_MODIFY)
+ scopes = scopes
)
persist(creds)
accessToken = tokens.accessToken
@@ -161,7 +185,10 @@ class GoogleConnector(
return cached
}
try {
- val tokens = oauth.refresh(oauthConfig(creds.clientId, creds.clientSecret), creds.refreshToken)
+ val tokens = oauth.refresh(
+ oauthConfig(creds.clientId, creds.clientSecret, creds.scopes),
+ creds.refreshToken
+ )
accessToken = tokens.accessToken
accessTokenExpiresAt = tokens.expiresAtMillis
tokens.refreshToken?.takeIf { it != creds.refreshToken }?.let { rotated ->
@@ -242,4 +269,27 @@ class GoogleConnector(
override suspend fun markRead(id: String, read: Boolean) {
withAuth { tok -> api.setUnread(tok, GmailMessageParser.stripPrefix(id), unread = !read) }
}
+
+ // ---- Google Calendar (used by the shared calendar router) ----
+
+ /** True when the stored grant includes the Calendar scope. */
+ fun hasCalendar(): Boolean = hasScope(SCOPE_CALENDAR)
+
+ suspend fun listCalendarEvents(
+ calendarId: String,
+ timeMin: String,
+ timeMax: String,
+ query: String?,
+ max: Int
+ ): JsonArray = withAuth { tok ->
+ calendarApi.listEvents(tok, calendarId, timeMin, timeMax, query, max)
+ }
+
+ suspend fun insertCalendarEvent(calendarId: String, event: JsonObject): String =
+ withAuth { tok -> calendarApi.insertEvent(tok, calendarId, event) }
+
+ suspend fun freeBusy(calendarIds: List<String>, timeMin: String, timeMax: String): JsonObject =
+ withAuth { tok -> calendarApi.freeBusy(tok, calendarIds, timeMin, timeMax) }
+
+ suspend fun calendarList(): JsonArray = withAuth { tok -> calendarApi.calendarList(tok) }
}
diff --git a/app/src/test/java/com/gotcha/connectors/calendar/CalendarToolsTest.kt b/app/src/test/java/com/gotcha/connectors/calendar/CalendarToolsTest.kt
new file mode 100644
index 0000000..45ea434
--- /dev/null
+++ b/app/src/test/java/com/gotcha/connectors/calendar/CalendarToolsTest.kt
@@ -0,0 +1,319 @@
+package com.gotcha.connectors.calendar
+
+import com.gotcha.connectors.CredentialStore
+import com.gotcha.connectors.google.GmailApi
+import com.gotcha.connectors.google.GoogleCalendarApi
+import com.gotcha.connectors.google.GoogleConnector
+import com.gotcha.connectors.microsoft.GraphApi
+import com.gotcha.connectors.microsoft.MicrosoftConnector
+import com.gotcha.connectors.oauth.TokenSet
+import com.gotcha.tools.ToolResult
+import kotlinx.coroutines.test.runTest
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.buildJsonObject
+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
+
+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) }
+}
+
+private class FakeDeviceCalendar : DeviceCalendar {
+ var listCalls = 0
+ var createCalls = 0
+ var lastSearch: String? = null
+ var lastTitle: String? = null
+
+ override fun listEvents(
+ daysAhead: Int?,
+ fromDate: String?,
+ toDate: String?,
+ search: String?
+ ): ToolResult {
+ listCalls++
+ lastSearch = search
+ return ToolResult.ok("device events")
+ }
+
+ @Suppress("LongParameterList")
+ override fun createEvent(
+ title: String,
+ start: String,
+ end: String?,
+ location: String?,
+ description: String?,
+ allDay: Boolean?,
+ reminderMinutes: Int?,
+ calendarName: String?,
+ attendees: List<String>?,
+ recurrence: String?,
+ recurrenceCount: Int?,
+ recurrenceUntil: String?
+ ): ToolResult {
+ createCalls++
+ lastTitle = title
+ return ToolResult.ok("device event created")
+ }
+}
+
+class CalendarToolsTest {
+
+ private lateinit var googleServer: MockWebServer
+ private lateinit var graphServer: MockWebServer
+ private lateinit var device: FakeDeviceCalendar
+ private lateinit var google: GoogleConnector
+ private lateinit var microsoft: MicrosoftConnector
+
+ /** Fixed "now" so window arithmetic in assertions is deterministic. */
+ private val now = 1_767_225_600_000L
+
+ @Before
+ fun setUp() {
+ googleServer = MockWebServer()
+ googleServer.start()
+ graphServer = MockWebServer()
+ graphServer.start()
+ device = FakeDeviceCalendar()
+ google = GoogleConnector(
+ store = InMemoryCredentialStore(),
+ api = GmailApi(baseUrl = googleServer.url("/gmail").toString()),
+ calendarApi = GoogleCalendarApi(
+ baseUrl = googleServer.url("/calendar/v3").toString().trimEnd('/')
+ ),
+ tokenUrl = googleServer.url("/token").toString()
+ )
+ microsoft = MicrosoftConnector(
+ store = InMemoryCredentialStore(),
+ api = GraphApi(baseUrl = graphServer.url("/v1.0").toString().trimEnd('/'))
+ )
+ }
+
+ @After
+ fun tearDown() {
+ googleServer.shutdown()
+ graphServer.shutdown()
+ }
+
+ private fun tools(
+ withGoogle: Boolean = false,
+ withMicrosoft: Boolean = false
+ ) = CalendarTools(
+ device = device,
+ google = { google.takeIf { withGoogle } },
+ microsoft = { microsoft.takeIf { withMicrosoft } },
+ clock = { now }
+ )
+
+ /**
+ * Token expiry uses the real clock — the connectors validate it against
+ * System.currentTimeMillis(), so [now] (which only fixes the router's date
+ * window) must not be used here or every call would trigger a refresh.
+ */
+ private fun liveExpiry() = System.currentTimeMillis() + 3_600_000
+
+ private suspend fun connectGoogle(scopes: List<String>) {
+ googleServer.enqueue(MockResponse().setBody("""{"emailAddress":"[email protected]"}"""))
+ google.completeConnect("cid", "secret", TokenSet("at", "rt", liveExpiry()), scopes)
+ googleServer.takeRequest() // the profile call
+ }
+
+ private suspend fun connectMicrosoft() {
+ graphServer.enqueue(MockResponse().setBody("""{"mail":"[email protected]"}"""))
+ microsoft.completeConnect("cid", "common", TokenSet("at", "rt", liveExpiry()))
+ graphServer.takeRequest() // the /me call
+ }
+
+ private fun args(block: kotlinx.serialization.json.JsonObjectBuilder.() -> Unit = {}): JsonObject =
+ buildJsonObject(block)
+
+ // ---- routing ----
+
+ @Test
+ fun `list_calendar_events defaults to the device calendar`() = runTest {
+ val result = tools().execute("list_calendar_events", args())
+ assertTrue(result.success)
+ assertEquals(1, device.listCalls)
+ assertEquals("device events", result.message)
+ }
+
+ @Test
+ fun `explicit device source also routes to the device calendar`() = runTest {
+ tools().execute("list_calendar_events", args { put("source", "device") })
+ assertEquals(1, device.listCalls)
+ }
+
+ @Test
+ fun `create_calendar_event defaults to the device calendar`() = runTest {
+ val result = tools().execute(
+ "create_calendar_event",
+ args {
+ put("title", "Dentist")
+ put("start", "2026-07-17 15:30")
+ }
+ )
+ assertTrue(result.success)
+ assertEquals(1, device.createCalls)
+ assertEquals("Dentist", device.lastTitle)
+ }
+
+ @Test
+ fun `an unknown source is rejected without touching any backend`() = runTest {
+ val result = tools().execute("list_calendar_events", args { put("source", "yahoo") })
+ assertTrue(!result.success)
+ assertTrue(result.message.contains("device"))
+ assertEquals(0, device.listCalls)
+ }
+
+ // ---- google ----
+
+ @Test
+ fun `google source lists events with gcal-prefixed ids`() = runTest {
+ connectGoogle(listOf(GoogleConnector.SCOPE_GMAIL_MODIFY, GoogleConnector.SCOPE_CALENDAR))
+ googleServer.enqueue(
+ MockResponse().setBody(
+ """{"items":[{"id":"e1","summary":"Standup",
+ "start":{"dateTime":"2026-01-01T09:00:00Z"},
+ "end":{"dateTime":"2026-01-01T09:15:00Z"}}]}"""
+ )
+ )
+ val result = tools(withGoogle = true)
+ .execute("list_calendar_events", args { put("source", "google") })
+
+ assertTrue(result.success)
+ assertTrue(result.message.contains("[gcal:e1]"))
+ assertTrue(result.message.contains("Standup"))
+ assertEquals("the device backend must not be touched", 0, device.listCalls)
+ }
+
+ @Test
+ fun `google source without the calendar scope steers to reconnect`() = runTest {
+ connectGoogle(listOf(GoogleConnector.SCOPE_GMAIL_MODIFY))
+ val result = tools(withGoogle = true)
+ .execute("list_calendar_events", args { put("source", "google") })
+
+ assertTrue(!result.success)
+ assertTrue(result.message.contains("Gmail only"))
+ assertTrue(result.message.contains("Calendar"))
+ }
+
+ @Test
+ fun `google source when not connected steers to Settings`() = runTest {
+ val result = tools(withGoogle = true)
+ .execute("list_calendar_events", args { put("source", "google") })
+ assertTrue(!result.success)
+ assertTrue(result.message.contains("not connected"))
+ }
+
+ @Test
+ fun `creating a google event posts summary and times and returns a gcal id`() = runTest {
+ connectGoogle(listOf(GoogleConnector.SCOPE_CALENDAR))
+ googleServer.enqueue(MockResponse().setBody("""{"id":"new-1"}"""))
+ val result = tools(withGoogle = true).execute(
+ "create_calendar_event",
+ args {
+ put("source", "google")
+ put("title", "Lunch")
+ put("start", "2026-07-17 12:00")
+ }
+ )
+
+ assertTrue(result.success)
+ assertTrue(result.message.contains("gcal:new-1"))
+ val body = googleServer.takeRequest().body.readUtf8()
+ assertTrue(body.contains("\"summary\":\"Lunch\""))
+ assertTrue(body.contains("\"timeZone\":\"UTC\""))
+ assertEquals(0, device.createCalls)
+ }
+
+ // ---- microsoft ----
+
+ @Test
+ fun `microsoft source lists events with ms-prefixed ids`() = runTest {
+ connectMicrosoft()
+ graphServer.enqueue(
+ MockResponse().setBody(
+ """{"value":[{"id":"m1","subject":"Review",
+ "start":{"dateTime":"2026-01-01T09:00:00.0000000"},
+ "end":{"dateTime":"2026-01-01T10:00:00.0000000"}}]}"""
+ )
+ )
+ val result = tools(withMicrosoft = true)
+ .execute("list_calendar_events", args { put("source", "microsoft") })
+
+ assertTrue(result.success)
+ assertTrue(result.message.contains("[ms:m1]"))
+ assertTrue(result.message.contains("Review"))
+ }
+
+ @Test
+ fun `microsoft source filters by search client-side`() = runTest {
+ connectMicrosoft()
+ graphServer.enqueue(
+ MockResponse().setBody(
+ """{"value":[{"id":"m1","subject":"Review"},{"id":"m2","subject":"Lunch"}]}"""
+ )
+ )
+ val result = tools(withMicrosoft = true).execute(
+ "list_calendar_events",
+ args {
+ put("source", "microsoft")
+ put("search", "lunch")
+ }
+ )
+
+ assertTrue(result.message.contains("[ms:m2]"))
+ assertTrue(!result.message.contains("[ms:m1]"))
+ }
+
+ // ---- check_availability ----
+
+ @Test
+ fun `check_availability without any connector explains what is needed`() = runTest {
+ val result = tools().execute("check_availability", args())
+ assertTrue(!result.success)
+ assertTrue(result.message.contains("connected calendar"))
+ assertTrue(result.message.contains("list_calendar_events"))
+ }
+
+ @Test
+ fun `check_availability reports google busy blocks and the gaps between them`() = runTest {
+ connectGoogle(listOf(GoogleConnector.SCOPE_CALENDAR))
+ googleServer.enqueue(
+ MockResponse().setBody(
+ """{"calendars":{"primary":{"busy":[
+ {"start":"2026-01-01T09:00:00Z","end":"2026-01-01T10:00:00Z"},
+ {"start":"2026-01-01T09:30:00Z","end":"2026-01-01T11:00:00Z"}]}}}"""
+ )
+ )
+ val result = tools(withGoogle = true).execute(
+ "check_availability",
+ args {
+ put("days_ahead", 1)
+ put("duration_minutes", 60)
+ }
+ )
+
+ assertTrue(result.success)
+ assertTrue(result.message.contains("Google Calendar"))
+ // The two overlapping blocks must be merged into one.
+ assertTrue(result.message.contains("Busy (1)"))
+ assertTrue(result.message.contains("Free slots"))
+ }
+
+ @Test
+ fun `check_availability ignores a google connector without the calendar scope`() = runTest {
+ connectGoogle(listOf(GoogleConnector.SCOPE_GMAIL_MODIFY))
+ val result = tools(withGoogle = true).execute("check_availability", args())
+ assertTrue(!result.success)
+ assertTrue(result.message.contains("connected calendar"))
+ }
+}
diff --git a/app/src/test/java/com/gotcha/connectors/calendar/CalendarWindowTest.kt b/app/src/test/java/com/gotcha/connectors/calendar/CalendarWindowTest.kt
new file mode 100644
index 0000000..7e025cd
--- /dev/null
+++ b/app/src/test/java/com/gotcha/connectors/calendar/CalendarWindowTest.kt
@@ -0,0 +1,121 @@
+package com.gotcha.connectors.calendar
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class CalendarWindowTest {
+
+ private val hour = 3_600_000L
+ private val day = 24 * hour
+
+ @Test
+ fun `days_ahead builds a forward window from now`() {
+ val window = CalendarWindow.resolve(daysAhead = 3, fromDate = null, toDate = null, now = 1_000L)
+ assertEquals(1_000L, window.startMs)
+ assertEquals(1_000L + 3 * day, window.endMs)
+ assertTrue(window.description.contains("3 day"))
+ }
+
+ @Test
+ fun `days_ahead defaults to seven and is clamped`() {
+ val default = CalendarWindow.resolve(null, null, null, now = 0)
+ assertEquals(7 * day, default.endMs)
+
+ val clamped = CalendarWindow.resolve(daysAhead = 9999, fromDate = null, toDate = null, now = 0)
+ assertEquals(365 * day, clamped.endMs)
+ }
+
+ @Test
+ fun `explicit dates override days_ahead`() {
+ val window = CalendarWindow.resolve(daysAhead = 3, fromDate = "2026-01-01", toDate = "2026-01-02", now = 0)
+ assertTrue(window.endMs > window.startMs)
+ assertEquals("2026-01-01 → 2026-01-02", window.description)
+ }
+
+ @Test
+ fun `rfc3339 round-trips through the parser`() {
+ val epoch = 1_767_225_600_000L
+ assertEquals(epoch, CalendarWindow.parseRfc3339(CalendarWindow.toRfc3339(epoch)))
+ }
+
+ @Test
+ fun `parses graph timestamps that omit the zone`() {
+ // Graph returns this shape when Prefer: outlook.timezone="UTC" is set.
+ val parsed = CalendarWindow.parseRfc3339("2026-01-01T09:00:00.0000000")
+ assertEquals(CalendarWindow.parseRfc3339("2026-01-01T09:00:00Z"), parsed)
+ }
+
+ @Test
+ fun `parses calendar v3 timestamps with an offset`() {
+ val withOffset = CalendarWindow.parseRfc3339("2026-01-01T10:00:00+01:00")
+ assertEquals(CalendarWindow.parseRfc3339("2026-01-01T09:00:00Z"), withOffset)
+ }
+
+ @Test
+ fun `unparseable input yields null rather than throwing`() {
+ assertEquals(null, CalendarWindow.parseRfc3339("not a date"))
+ assertEquals(null, CalendarWindow.parseRfc3339(null))
+ }
+
+ @Test
+ fun `merge coalesces overlapping and adjacent blocks`() {
+ val merged = CalendarWindow.merge(
+ listOf(
+ BusyBlock(30, 40),
+ BusyBlock(0, 10),
+ BusyBlock(10, 20), // adjacent to the previous one
+ BusyBlock(5, 8) // fully contained
+ )
+ )
+ assertEquals(listOf(BusyBlock(0, 20), BusyBlock(30, 40)), merged)
+ }
+
+ @Test
+ fun `merge drops zero-length blocks`() {
+ assertEquals(emptyList<BusyBlock>(), CalendarWindow.merge(listOf(BusyBlock(5, 5))))
+ }
+
+ @Test
+ fun `freeSlots returns gaps at least as long as the minimum`() {
+ val busy = listOf(BusyBlock(2 * hour, 3 * hour), BusyBlock(5 * hour, 6 * hour))
+ val free = CalendarWindow.freeSlots(busy, 0, 8 * hour, hour)
+
+ assertEquals(
+ listOf(
+ BusyBlock(0, 2 * hour),
+ BusyBlock(3 * hour, 5 * hour),
+ BusyBlock(6 * hour, 8 * hour)
+ ),
+ free
+ )
+ }
+
+ @Test
+ fun `freeSlots skips gaps shorter than the minimum`() {
+ val busy = listOf(BusyBlock(0, hour), BusyBlock(hour + 60_000, 3 * hour))
+ val free = CalendarWindow.freeSlots(busy, 0, 3 * hour, hour)
+ assertTrue("the one-minute gap must not be offered", free.isEmpty())
+ }
+
+ @Test
+ fun `a fully free window is one slot`() {
+ assertEquals(
+ listOf(BusyBlock(0, 4 * hour)),
+ CalendarWindow.freeSlots(emptyList(), 0, 4 * hour, hour)
+ )
+ }
+
+ @Test
+ fun `a fully busy window has no slots`() {
+ val busy = listOf(BusyBlock(0, 4 * hour))
+ assertTrue(CalendarWindow.freeSlots(busy, 0, 4 * hour, hour).isEmpty())
+ }
+
+ @Test
+ fun `busy blocks overhanging the window do not produce negative slots`() {
+ val busy = listOf(BusyBlock(-2 * hour, 2 * hour), BusyBlock(3 * hour, 10 * hour))
+ val free = CalendarWindow.freeSlots(busy, 0, 4 * hour, 30 * 60_000L)
+ assertEquals(listOf(BusyBlock(2 * hour, 3 * hour)), free)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/connectors/google/GoogleCalendarApiTest.kt b/app/src/test/java/com/gotcha/connectors/google/GoogleCalendarApiTest.kt
new file mode 100644
index 0000000..1eb0b2d
--- /dev/null
+++ b/app/src/test/java/com/gotcha/connectors/google/GoogleCalendarApiTest.kt
@@ -0,0 +1,137 @@
+package com.gotcha.connectors.google
+
+import kotlinx.coroutines.test.runTest
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.put
+import 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 GoogleCalendarApiTest {
+
+ private lateinit var server: MockWebServer
+ private lateinit var api: GoogleCalendarApi
+
+ @Before
+ fun setUp() {
+ server = MockWebServer()
+ server.start()
+ api = GoogleCalendarApi(baseUrl = server.url("/calendar/v3").toString().trimEnd('/'))
+ }
+
+ @After
+ fun tearDown() {
+ server.shutdown()
+ }
+
+ @Test
+ fun `listEvents expands recurring events and orders by start`() = runTest {
+ server.enqueue(MockResponse().setBody("""{"items":[{"id":"e1","summary":"Standup"}]}"""))
+ val events = api.listEvents(
+ "tok",
+ "primary",
+ "2026-01-01T00:00:00Z",
+ "2026-01-08T00:00:00Z",
+ query = null,
+ max = 50
+ )
+
+ assertEquals(1, events.size)
+ assertEquals("Standup", events[0].jsonObject["summary"]!!.jsonPrimitive.content)
+
+ val request = server.takeRequest()
+ assertEquals("Bearer tok", request.getHeader("Authorization"))
+ val path = URLDecoder.decode(request.path.orEmpty(), "UTF-8")
+ assertTrue(path.contains("/calendars/primary/events"))
+ assertTrue("recurrences must be expanded", path.contains("singleEvents=true"))
+ assertTrue(path.contains("orderBy=startTime"))
+ assertTrue(path.contains("timeMin=2026-01-01T00:00:00Z"))
+ assertTrue(!path.contains("&q="))
+ }
+
+ @Test
+ fun `listEvents forwards a text query`() = runTest {
+ server.enqueue(MockResponse().setBody("""{"items":[]}"""))
+ api.listEvents("tok", "primary", "a", "b", query = "dentist", max = 10)
+ assertTrue(URLDecoder.decode(server.takeRequest().path.orEmpty(), "UTF-8").contains("q=dentist"))
+ }
+
+ @Test
+ fun `missing items yields an empty list rather than throwing`() = runTest {
+ server.enqueue(MockResponse().setBody("{}"))
+ assertTrue(api.listEvents("tok", "primary", "a", "b", null, 10).isEmpty())
+ }
+
+ @Test
+ fun `insertEvent posts the payload and returns the new id`() = runTest {
+ server.enqueue(MockResponse().setBody("""{"id":"new-1"}"""))
+ val id = api.insertEvent(
+ "tok",
+ "primary",
+ buildJsonObject { put("summary", JsonPrimitive("Lunch")) }
+ )
+
+ assertEquals("new-1", id)
+ val request = server.takeRequest()
+ assertEquals("POST", request.method)
+ assertTrue(request.body.readUtf8().contains("\"summary\":\"Lunch\""))
+ }
+
+ @Test
+ fun `freeBusy posts the window and returns the calendars map`() = runTest {
+ server.enqueue(
+ MockResponse().setBody(
+ """{"calendars":{"primary":{"busy":[
+ {"start":"2026-01-01T09:00:00Z","end":"2026-01-01T10:00:00Z"}]}}}"""
+ )
+ )
+ val calendars = api.freeBusy(
+ "tok",
+ listOf("primary"),
+ "2026-01-01T00:00:00Z",
+ "2026-01-02T00:00:00Z"
+ )
+
+ val busy = calendars["primary"]!!.jsonObject["busy"]!!.jsonArray
+ assertEquals(1, busy.size)
+
+ val body = server.takeRequest().body.readUtf8()
+ assertTrue(body.contains("\"timeMin\":\"2026-01-01T00:00:00Z\""))
+ assertTrue(body.contains("\"id\":\"primary\""))
+ }
+
+ @Test
+ fun `403 steers the user to reconnect with the calendar scope`() = runTest {
+ server.enqueue(
+ MockResponse().setResponseCode(403).setBody("""{"error":{"message":"insufficient scope"}}""")
+ )
+ try {
+ api.calendarList("tok")
+ throw AssertionError("expected GmailApiException")
+ } catch (e: GmailApiException) {
+ assertEquals(403, e.code)
+ assertTrue(e.message!!.contains("Calendar"))
+ assertTrue(e.message!!.contains("Reconnect"))
+ }
+ }
+
+ @Test
+ fun `401 is surfaced with its code so the connector can refresh and retry`() = runTest {
+ server.enqueue(MockResponse().setResponseCode(401).setBody("{}"))
+ try {
+ api.calendarList("tok")
+ throw AssertionError("expected GmailApiException")
+ } catch (e: GmailApiException) {
+ assertEquals(401, e.code)
+ }
+ }
+}