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 Notion connector
Durganshu Mishra034df43d29bd
diff --git a/app/src/main/java/com/gotcha/connectors/notion/NotionApi.kt b/app/src/main/java/com/gotcha/connectors/notion/NotionApi.ktnew file mode 100644index 0000000..50cc308--- /dev/null+++ b/app/src/main/java/com/gotcha/connectors/notion/NotionApi.kt@@ -0,0 +1,135 @@+package com.gotcha.connectors.notion++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.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 Notion API response, with a user-actionable message. */+class NotionApiException(val code: Int, message: String) : IOException(message)++/**+ * Thin OkHttp wrapper over the Notion API. Authenticated with an internal+ * integration token (no OAuth, no refresh), so every call simply carries the+ * secret as a Bearer token. JVM-testable via a MockWebServer [baseUrl].+ */+class NotionApi(+ private val client: OkHttpClient = OkHttpClient.Builder()+ .connectTimeout(20, TimeUnit.SECONDS)+ .readTimeout(30, TimeUnit.SECONDS)+ .build(),+ private val baseUrl: String = "https://api.notion.com/v1"+) {++ companion object {+ /** Pinned API version — Notion requires this header on every request. */+ const val NOTION_VERSION = "2022-06-28"+ }++ private val json = Json { ignoreUnknownKeys = true }+ private val jsonMediaType = "application/json; charset=utf-8".toMediaType()++ /** `GET /users/me` — validates the token and names the integration/workspace. */+ suspend fun me(token: String): JsonObject = get("$baseUrl/users/me", token)++ /**+ * `POST /search` — only ever returns pages explicitly shared with the+ * integration, which is the single most common source of "why is it empty?".+ */+ suspend fun search(token: String, query: String?, pageSize: Int): JsonArray {+ val body = buildJsonObject {+ if (!query.isNullOrBlank()) put("query", JsonPrimitive(query))+ put("page_size", JsonPrimitive(pageSize))+ }+ return post("$baseUrl/search", token, body).results()+ }++ /** `GET /pages/{id}` — page metadata (properties, title, url). */+ suspend fun page(token: String, pageId: String): JsonObject =+ get("$baseUrl/pages/${pageId.trim()}", token)++ /** `GET /blocks/{id}/children` — the page's content blocks. */+ suspend fun blockChildren(token: String, blockId: String, pageSize: Int): JsonArray {+ val url = "$baseUrl/blocks/${blockId.trim()}/children?page_size=$pageSize"+ return get(url, token).results()+ }++ /** `POST /pages` — creates a page. Returns the new page object. */+ suspend fun createPage(token: String, payload: JsonObject): JsonObject =+ post("$baseUrl/pages", token, payload)++ /** `PATCH /blocks/{id}/children` — appends blocks to an existing page. */+ suspend fun appendBlocks(token: String, blockId: String, children: JsonArray): JsonObject {+ val body = buildJsonObject { put("children", children) }+ return patch("$baseUrl/blocks/${blockId.trim()}/children", token, body)+ }++ private fun JsonObject.results(): JsonArray =+ this["results"]?.jsonArray ?: JsonArray(emptyList())++ private fun Request.Builder.notionHeaders(token: String) = this+ .header("Authorization", "Bearer $token")+ .header("Notion-Version", NOTION_VERSION)++ private suspend fun get(url: String, token: String): JsonObject =+ execute(Request.Builder().url(url).notionHeaders(token).build())++ private suspend fun post(url: String, token: String, body: JsonObject): JsonObject =+ execute(+ Request.Builder()+ .url(url)+ .notionHeaders(token)+ .post(body.toString().toRequestBody(jsonMediaType))+ .build()+ )++ private suspend fun patch(url: String, token: String, body: JsonObject): JsonObject =+ execute(+ Request.Builder()+ .url(url)+ .notionHeaders(token)+ .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): NotionApiException {+ val detail = runCatching {+ json.parseToJsonElement(body).jsonObject["message"]?.jsonPrimitive?.contentOrNull+ }.getOrNull() ?: body.take(200)+ val message = when (code) {+ 401 ->+ "Notion rejected the integration token (401). Re-copy it from " ++ "notion.so/my-integrations and reconnect in Settings → Connectors. $detail"+ 404 ->+ "Notion could not find that page (404) — most often it simply has not been " ++ "shared with the integration. Open the page in Notion, use ⋯ → Connections, " ++ "and add the integration. $detail"+ 429 -> "Notion is rate limiting requests (429) — try again shortly. $detail"+ 400 -> "Notion rejected the request (400): $detail"+ else -> "Notion API error (HTTP $code): $detail"+ }+ return NotionApiException(code, message)+ }+}diff --git a/app/src/main/java/com/gotcha/connectors/notion/NotionBlockRenderer.kt b/app/src/main/java/com/gotcha/connectors/notion/NotionBlockRenderer.ktnew file mode 100644index 0000000..9cc8419--- /dev/null+++ b/app/src/main/java/com/gotcha/connectors/notion/NotionBlockRenderer.kt@@ -0,0 +1,153 @@+package com.gotcha.connectors.notion++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++/**+ * Converts Notion block JSON to Markdown and Markdown back to block JSON.+ *+ * Pure Kotlin, no Android dependencies — the Notion counterpart of+ * [com.gotcha.connectors.mail.MailBodyExtractor], and unit-testable on the JVM.+ * Supports the block types that carry the text a language model actually needs;+ * anything else renders as a `[unsupported: type]` placeholder rather than+ * silently disappearing.+ */+object NotionBlockRenderer {++ private const val TITLE_MAX = 200++ /** Concatenates a Notion `rich_text` array into plain text. */+ fun richText(array: JsonArray?): String =+ array.orEmpty().joinToString("") { node ->+ node.jsonObject["plain_text"]?.jsonPrimitive?.contentOrNull+ ?: node.jsonObject["text"]?.jsonObject+ ?.get("content")?.jsonPrimitive?.contentOrNull+ ?: ""+ }++ /** Renders one block as a Markdown line (no trailing newline). */+ @Suppress("CyclomaticComplexMethod")+ fun blockToMarkdown(block: JsonObject): String {+ val type = block["type"]?.jsonPrimitive?.contentOrNull ?: return ""+ val payload = block[type]?.jsonObject+ val text = richText(payload?.get("rich_text")?.jsonArray)+ return when (type) {+ "paragraph" -> text+ "heading_1" -> "# $text"+ "heading_2" -> "## $text"+ "heading_3" -> "### $text"+ "bulleted_list_item" -> "- $text"+ "numbered_list_item" -> "1. $text"+ "to_do" -> {+ val checked = payload?.get("checked")?.jsonPrimitive?.booleanOrNull ?: false+ "- [${if (checked) "x" else " "}] $text"+ }+ "quote" -> "> $text"+ "code" -> {+ val language = payload?.get("language")?.jsonPrimitive?.contentOrNull.orEmpty()+ "```$language\n$text\n```"+ }+ "divider" -> "---"+ "child_page" ->+ "- (sub-page) " + (payload?.get("title")?.jsonPrimitive?.contentOrNull).orEmpty()+ else -> if (text.isNotBlank()) text else "[unsupported block: $type]"+ }+ }++ /** Renders a list of blocks as a Markdown document. */+ fun blocksToMarkdown(blocks: List<JsonObject>): String =+ blocks.joinToString("\n") { blockToMarkdown(it) }.trim()++ /**+ * Converts Markdown-ish text to Notion blocks. Recognises the same subset+ * [blockToMarkdown] emits; anything unrecognised becomes a paragraph, so no+ * user content is ever dropped.+ */+ fun markdownToBlocks(markdown: String): JsonArray = buildJsonArray {+ markdown.lines().forEach { rawLine ->+ val line = rawLine.trimEnd()+ // Blank lines become empty paragraphs so spacing survives the round trip.+ if (line.isBlank()) {+ add(textBlock("paragraph", ""))+ return@forEach+ }+ val block = when {+ line.startsWith("### ") -> textBlock("heading_3", line.removePrefix("### "))+ line.startsWith("## ") -> textBlock("heading_2", line.removePrefix("## "))+ line.startsWith("# ") -> textBlock("heading_1", line.removePrefix("# "))+ line.startsWith("> ") -> textBlock("quote", line.removePrefix("> "))+ line.startsWith("- [ ] ") -> todoBlock(line.removePrefix("- [ ] "), false)+ line.startsWith("- [x] ") -> todoBlock(line.removePrefix("- [x] "), true)+ line.startsWith("- ") -> textBlock("bulleted_list_item", line.removePrefix("- "))+ line.startsWith("* ") -> textBlock("bulleted_list_item", line.removePrefix("* "))+ NUMBERED.matches(line) ->+ textBlock("numbered_list_item", line.replaceFirst(NUMBERED_PREFIX, ""))+ else -> textBlock("paragraph", line)+ }+ add(block)+ }+ }++ /** The `properties` payload for creating a page with [title] under a parent page. */+ fun titleProperty(title: String): JsonObject = buildJsonObject {+ put(+ "title",+ buildJsonObject {+ put("title", buildJsonArray { add(richTextNode(title.take(TITLE_MAX))) })+ }+ )+ }++ /** Best-effort page title from a page object's `properties`. */+ fun pageTitle(page: JsonObject): String {+ val properties = page["properties"]?.jsonObject ?: return "(untitled)"+ properties.values.forEach { property ->+ val node = property.jsonObject+ if (node["type"]?.jsonPrimitive?.contentOrNull == "title") {+ val text = richText(node["title"]?.jsonArray)+ if (text.isNotBlank()) return text+ }+ }+ return "(untitled)"+ }++ private val NUMBERED = Regex("^\\d+[.)] .*")+ private val NUMBERED_PREFIX = Regex("^\\d+[.)] ")++ private fun richTextNode(content: String): JsonObject = buildJsonObject {+ put("type", JsonPrimitive("text"))+ put("text", buildJsonObject { put("content", JsonPrimitive(content)) })+ }++ private fun textBlock(type: String, content: String): JsonObject = buildJsonObject {+ put("object", JsonPrimitive("block"))+ put("type", JsonPrimitive(type))+ put(+ type,+ buildJsonObject {+ put("rich_text", buildJsonArray { add(richTextNode(content)) })+ }+ )+ }++ private fun todoBlock(content: String, checked: Boolean): JsonObject = buildJsonObject {+ put("object", JsonPrimitive("block"))+ put("type", JsonPrimitive("to_do"))+ put(+ "to_do",+ buildJsonObject {+ put("rich_text", buildJsonArray { add(richTextNode(content)) })+ put("checked", JsonPrimitive(checked))+ }+ )+ }+}diff --git a/app/src/main/java/com/gotcha/connectors/notion/NotionConnector.kt b/app/src/main/java/com/gotcha/connectors/notion/NotionConnector.ktnew file mode 100644index 0000000..dd28d5c--- /dev/null+++ b/app/src/main/java/com/gotcha/connectors/notion/NotionConnector.kt@@ -0,0 +1,106 @@+package com.gotcha.connectors.notion++import com.gotcha.connectors.Connector+import com.gotcha.connectors.CredentialStore+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 NotionCredentials(+ val token: String,+ /** Bot/workspace name from `GET /users/me`, shown on the Settings card. */+ val workspaceName: String+)++/**+ * Notion connector authenticated by an **internal integration token**: the user+ * creates an integration in their own workspace at notion.so/my-integrations and+ * pastes the secret. There is no OAuth, no redirect URI and no refresh cycle —+ * the same shape as the IMAP app-password connector.+ *+ * The one non-obvious rule: an integration can only see pages that have been+ * explicitly shared with it (page ⋯ → Connections). Every empty result says so.+ */+class NotionConnector(+ private val store: CredentialStore,+ private val api: NotionApi = NotionApi()+) : Connector {++ private val json = Json { ignoreUnknownKeys = true }++ override val id = "notion"+ override val displayName = "Notion"+ override val description =+ "Search, read, create and append to Notion pages shared with your integration."+ override val toolNames = setOf(+ "notion_search",+ "notion_read_page",+ "notion_create_page",+ "notion_append_to_page"+ )++ @Volatile+ private var credentials: NotionCredentials? = store.loadRaw(id)?.let { blob ->+ runCatching { json.decodeFromString<NotionCredentials>(blob) }.getOrNull()+ }++ fun credentials(): NotionCredentials? = credentials++ override fun isConnected(): Boolean = credentials != null++ override fun statusLine(): String = credentials+ ?.let { "Connected to ${it.workspaceName}" }+ ?: "Not connected"++ override fun disconnect() {+ store.clear(id)+ credentials = null+ }++ /**+ * Validates [token] against `GET /users/me` before storing it, so a typo is+ * caught on the Settings screen instead of on the first tool call. Returns a+ * status message for the card.+ */+ suspend fun connect(token: String): String {+ val trimmed = token.trim()+ if (trimmed.isBlank()) return "Paste the integration token first."+ return try {+ val me = api.me(trimmed)+ val name = me["name"]?.jsonPrimitive?.contentOrNull+ ?: me["bot"]?.jsonObject?.get("workspace_name")?.jsonPrimitive?.contentOrNull+ ?: "your workspace"+ val creds = NotionCredentials(trimmed, name)+ store.saveRaw(id, json.encodeToString(creds))+ credentials = creds+ "Connected to $name. Remember to share the pages you want reachable with the " ++ "integration (page ⋯ → Connections)."+ } catch (e: Exception) {+ "Could not connect: ${e.message}"+ }+ }++ private fun token(): String = checkNotNull(credentials?.token) {+ "Notion is not connected — add an integration token in Settings → Connectors."+ }++ suspend fun search(query: String?, pageSize: Int): JsonArray =+ api.search(token(), query, pageSize)++ suspend fun page(pageId: String): JsonObject = api.page(token(), pageId)++ suspend fun blockChildren(blockId: String, pageSize: Int): JsonArray =+ api.blockChildren(token(), blockId, pageSize)++ suspend fun createPage(payload: JsonObject): JsonObject = api.createPage(token(), payload)++ suspend fun appendBlocks(blockId: String, children: JsonArray): JsonObject =+ api.appendBlocks(token(), blockId, children)+}diff --git a/app/src/main/java/com/gotcha/connectors/notion/NotionTools.kt b/app/src/main/java/com/gotcha/connectors/notion/NotionTools.ktnew file mode 100644index 0000000..0e1a93d--- /dev/null+++ b/app/src/main/java/com/gotcha/connectors/notion/NotionTools.kt@@ -0,0 +1,138 @@+package com.gotcha.connectors.notion++import com.gotcha.connectors.ToolRouter+import com.gotcha.tools.ToolResult+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+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 Notion tools. Every tool needs a page to have been shared+ * with the integration first, so empty/404 outcomes say that explicitly rather+ * than letting the model conclude the content does not exist.+ */+class NotionTools(+ private val backend: () -> NotionConnector?+) : ToolRouter {++ companion object {+ private const val DEFAULT_PAGE_SIZE = 20+ private const val MAX_PAGE_SIZE = 100+ private const val BLOCK_PAGE_SIZE = 100++ private const val SHARING_HINT =+ "If you expected results, the page is probably not shared with the integration yet: " ++ "open it in Notion, use ⋯ → Connections, and add the integration."+ }++ override val toolNames: Set<String> = setOf(+ "notion_search",+ "notion_read_page",+ "notion_create_page",+ "notion_append_to_page"+ )++ override suspend fun execute(name: String, args: JsonObject): ToolResult = try {+ when (name) {+ "notion_search" -> search(args)+ "notion_read_page" -> readPage(args)+ "notion_create_page" -> createPage(args)+ "notion_append_to_page" -> appendToPage(args)+ else -> ToolResult.error("Unknown Notion tool '$name'.")+ }+ } catch (e: Exception) {+ ToolResult.error("$name failed: ${e.message}")+ }++ private fun connected(): NotionConnector? = backend()?.takeIf { it.isConnected() }++ private fun notConnected(): ToolResult = ToolResult.error(+ "Notion is not connected. Ask the user to create an internal integration at " ++ "notion.so/my-integrations and paste its token in Settings → Connectors."+ )++ private suspend fun search(args: JsonObject): ToolResult {+ val notion = connected() ?: return notConnected()+ val pageSize = (args.optInt("max") ?: DEFAULT_PAGE_SIZE).coerceIn(1, MAX_PAGE_SIZE)+ val results = notion.search(args.optString("query"), pageSize).map { it.jsonObject }++ if (results.isEmpty()) return ToolResult.ok("No Notion pages matched. $SHARING_HINT")+ val rows = results.joinToString("\n") { item ->+ val kind = item.str("object") ?: "page"+ val title = NotionBlockRenderer.pageTitle(item)+ val edited = item.str("last_edited_time")?.substringBefore('T').orEmpty()+ "[${item.str("id").orEmpty()}] $kind | $title" ++ (if (edited.isNotBlank()) " | edited $edited" else "")+ }+ return ToolResult.ok(+ "${results.size} Notion result(s) — use the id with notion_read_page:\n$rows"+ )+ }++ private suspend fun readPage(args: JsonObject): ToolResult {+ val notion = connected() ?: return notConnected()+ val pageId = args.optString("page_id")+ ?: return ToolResult.error("notion_read_page needs a 'page_id' from notion_search.")++ val page = notion.page(pageId)+ val blocks = notion.blockChildren(pageId, BLOCK_PAGE_SIZE).map { it.jsonObject }+ val body = NotionBlockRenderer.blocksToMarkdown(blocks)+ val url = page.str("url")?.let { "\nURL: $it" }.orEmpty()+ return ToolResult.ok(+ "Title: ${NotionBlockRenderer.pageTitle(page)}$url\n\n" ++ body.ifBlank { "(this page has no text content)" }+ )+ }++ private suspend fun createPage(args: JsonObject): ToolResult {+ val notion = connected() ?: return notConnected()+ val title = args.optString("title")+ ?: return ToolResult.error("notion_create_page needs a 'title'.")+ val parentId = args.optString("parent_page_id")+ ?: return ToolResult.error(+ "notion_create_page needs a 'parent_page_id' — Notion has no root to create " ++ "into. Use notion_search to find a page that is shared with the integration " ++ "and create the new page underneath it."+ )++ val payload = buildJsonObject {+ put(+ "parent",+ buildJsonObject {+ put("type", JsonPrimitive("page_id"))+ put("page_id", JsonPrimitive(parentId))+ }+ )+ put("properties", NotionBlockRenderer.titleProperty(title))+ args.optString("content")?.let {+ put("children", NotionBlockRenderer.markdownToBlocks(it))+ }+ }+ val page = notion.createPage(payload)+ val url = page.str("url")?.let { " ($it)" }.orEmpty()+ return ToolResult.ok("Created Notion page \"$title\"$url, id ${page.str("id").orEmpty()}.")+ }++ private suspend fun appendToPage(args: JsonObject): ToolResult {+ val notion = connected() ?: return notConnected()+ val pageId = args.optString("page_id")+ ?: return ToolResult.error("notion_append_to_page needs a 'page_id'.")+ val content = args.optString("content")+ ?: return ToolResult.error("notion_append_to_page needs 'content' to append.")++ notion.appendBlocks(pageId, NotionBlockRenderer.markdownToBlocks(content))+ return ToolResult.ok("Appended ${content.lines().size} line(s) to Notion page $pageId.")+ }++ 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+}diff --git a/app/src/test/java/com/gotcha/connectors/notion/NotionBlockRendererTest.kt b/app/src/test/java/com/gotcha/connectors/notion/NotionBlockRendererTest.ktnew file mode 100644index 0000000..0d8f61d--- /dev/null+++ b/app/src/test/java/com/gotcha/connectors/notion/NotionBlockRendererTest.kt@@ -0,0 +1,186 @@+package com.gotcha.connectors.notion++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonObject+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class NotionBlockRendererTest {++ private val json = Json { ignoreUnknownKeys = true }++ private fun block(raw: String) = json.parseToJsonElement(raw).jsonObject++ private fun markdownOf(raw: String) = NotionBlockRenderer.blockToMarkdown(block(raw))++ // ---- blocks → markdown ----++ @Test+ fun `paragraph renders as plain text`() {+ assertEquals(+ "Hello there",+ markdownOf("""{"type":"paragraph","paragraph":{"rich_text":[{"plain_text":"Hello there"}]}}""")+ )+ }++ @Test+ fun `headings render at the right level`() {+ assertEquals("# One", markdownOf("""{"type":"heading_1","heading_1":{"rich_text":[{"plain_text":"One"}]}}"""))+ assertEquals("## Two", markdownOf("""{"type":"heading_2","heading_2":{"rich_text":[{"plain_text":"Two"}]}}"""))+ assertEquals(+ "### Three",+ markdownOf("""{"type":"heading_3","heading_3":{"rich_text":[{"plain_text":"Three"}]}}""")+ )+ }++ @Test+ fun `list items render as bullets and numbers`() {+ assertEquals(+ "- Milk",+ markdownOf("""{"type":"bulleted_list_item","bulleted_list_item":{"rich_text":[{"plain_text":"Milk"}]}}""")+ )+ assertEquals(+ "1. First",+ markdownOf("""{"type":"numbered_list_item","numbered_list_item":{"rich_text":[{"plain_text":"First"}]}}""")+ )+ }++ @Test+ fun `to_do renders its checked state`() {+ assertEquals(+ "- [ ] Buy milk",+ markdownOf("""{"type":"to_do","to_do":{"rich_text":[{"plain_text":"Buy milk"}],"checked":false}}""")+ )+ assertEquals(+ "- [x] Buy milk",+ markdownOf("""{"type":"to_do","to_do":{"rich_text":[{"plain_text":"Buy milk"}],"checked":true}}""")+ )+ }++ @Test+ fun `quote and divider render`() {+ assertEquals("> Said so", markdownOf("""{"type":"quote","quote":{"rich_text":[{"plain_text":"Said so"}]}}"""))+ assertEquals("---", markdownOf("""{"type":"divider","divider":{}}"""))+ }++ @Test+ fun `code block keeps its language fence`() {+ assertEquals(+ "```kotlin\nval x = 1\n```",+ markdownOf("""{"type":"code","code":{"rich_text":[{"plain_text":"val x = 1"}],"language":"kotlin"}}""")+ )+ }++ @Test+ fun `unsupported blocks are flagged rather than dropped silently`() {+ assertEquals("[unsupported block: table]", markdownOf("""{"type":"table","table":{}}"""))+ }++ @Test+ fun `rich_text falls back to nested text content when plain_text is absent`() {+ assertEquals(+ "Nested",+ markdownOf("""{"type":"paragraph","paragraph":{"rich_text":[{"text":{"content":"Nested"}}]}}""")+ )+ }++ @Test+ fun `blocksToMarkdown joins blocks with newlines`() {+ val blocks = listOf(+ block("""{"type":"heading_1","heading_1":{"rich_text":[{"plain_text":"Title"}]}}"""),+ block("""{"type":"paragraph","paragraph":{"rich_text":[{"plain_text":"Body"}]}}""")+ )+ assertEquals("# Title\nBody", NotionBlockRenderer.blocksToMarkdown(blocks))+ }++ // ---- markdown → blocks ----++ @Test+ fun `every supported markdown line maps back to its own block type`() {+ val markdown = """+ # Heading one+ ## Heading two+ ### Heading three+ - A bullet+ 1. A number+ - [ ] Open task+ - [x] Done task+ > A quote+ Just a paragraph+ """.trimIndent()++ val types = NotionBlockRenderer.markdownToBlocks(markdown).map {+ it.jsonObject["type"]!!.toString().trim('"')+ }+ assertEquals(+ listOf(+ "heading_1", "heading_2", "heading_3",+ "bulleted_list_item", "numbered_list_item",+ "to_do", "to_do", "quote", "paragraph"+ ),+ types+ )+ }++ @Test+ fun `checked state survives the markdown round trip`() {+ val blocks = NotionBlockRenderer.markdownToBlocks("- [x] Done task")+ val rendered = NotionBlockRenderer.blocksToMarkdown(blocks.map { it.jsonObject })+ assertEquals("- [x] Done task", rendered)+ }++ @Test+ fun `every supported type survives the markdown round trip`() {+ val markdown = "# Title\n- Bullet\n> Quote\n- [ ] Task\nParagraph"+ val blocks = NotionBlockRenderer.markdownToBlocks(markdown)+ assertEquals(markdown, NotionBlockRenderer.blocksToMarkdown(blocks.map { it.jsonObject }))+ }++ @Test+ fun `unrecognised markdown becomes a paragraph so nothing is lost`() {+ val blocks = NotionBlockRenderer.markdownToBlocks("| a | table | row |")+ assertEquals(1, blocks.size)+ assertTrue(blocks[0].toString().contains("paragraph"))+ assertTrue(blocks[0].toString().contains("table"))+ }++ @Test+ fun `blank lines are preserved as empty paragraphs`() {+ val blocks = NotionBlockRenderer.markdownToBlocks("One\n\nTwo")+ assertEquals(3, blocks.size)+ }++ // ---- page metadata ----++ @Test+ fun `pageTitle reads the title property whatever it is named`() {+ val page = block(+ """{"properties":{"Name":{"type":"title","title":[{"plain_text":"Project plan"}]}}}"""+ )+ assertEquals("Project plan", NotionBlockRenderer.pageTitle(page))+ }++ @Test+ fun `pageTitle ignores non-title properties`() {+ val page = block(+ """{"properties":{+ "Tags":{"type":"multi_select","multi_select":[]},+ "Name":{"type":"title","title":[{"plain_text":"Real title"}]}}}"""+ )+ assertEquals("Real title", NotionBlockRenderer.pageTitle(page))+ }++ @Test+ fun `pageTitle degrades gracefully when there is none`() {+ assertEquals("(untitled)", NotionBlockRenderer.pageTitle(block("""{"properties":{}}""")))+ assertEquals("(untitled)", NotionBlockRenderer.pageTitle(block("{}")))+ }++ @Test+ fun `titleProperty builds the shape the create-page endpoint expects`() {+ val property = NotionBlockRenderer.titleProperty("New page").toString()+ assertTrue(property.contains("\"title\""))+ assertTrue(property.contains("New page"))+ }+}diff --git a/app/src/test/java/com/gotcha/connectors/notion/NotionToolsTest.kt b/app/src/test/java/com/gotcha/connectors/notion/NotionToolsTest.ktnew file mode 100644index 0000000..98fb402--- /dev/null+++ b/app/src/test/java/com/gotcha/connectors/notion/NotionToolsTest.kt@@ -0,0 +1,234 @@+package com.gotcha.connectors.notion++import com.gotcha.connectors.CredentialStore+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) }+}++class NotionToolsTest {++ private lateinit var server: MockWebServer+ private lateinit var store: InMemoryCredentialStore+ private lateinit var connector: NotionConnector+ private lateinit var tools: NotionTools++ @Before+ fun setUp() {+ server = MockWebServer()+ server.start()+ store = InMemoryCredentialStore()+ connector = NotionConnector(+ store = store,+ api = NotionApi(baseUrl = server.url("/v1").toString().trimEnd('/'))+ )+ tools = NotionTools { connector }+ }++ @After+ fun tearDown() {+ server.shutdown()+ }++ private suspend fun connect() {+ server.enqueue(MockResponse().setBody("""{"name":"Gotcha bot"}"""))+ connector.connect("secret_token")+ server.takeRequest() // the /users/me validation call+ }++ private fun args(block: kotlinx.serialization.json.JsonObjectBuilder.() -> Unit = {}): JsonObject =+ buildJsonObject(block)++ // ---- connection ----++ @Test+ fun `connect validates the token and stores the workspace name`() = runTest {+ server.enqueue(MockResponse().setBody("""{"name":"My workspace"}"""))+ val status = connector.connect("secret_token")++ assertTrue(connector.isConnected())+ assertEquals("My workspace", connector.credentials()?.workspaceName)+ assertTrue("must remind about page sharing", status.contains("Connections"))++ val request = server.takeRequest()+ assertEquals("Bearer secret_token", request.getHeader("Authorization"))+ assertEquals(NotionApi.NOTION_VERSION, request.getHeader("Notion-Version"))+ }++ @Test+ fun `a rejected token is not stored`() = runTest {+ server.enqueue(MockResponse().setResponseCode(401).setBody("""{"message":"API token is invalid"}"""))+ val status = connector.connect("wrong")++ assertTrue(!connector.isConnected())+ assertEquals(null, store.loadRaw("notion"))+ assertTrue(status.contains("Could not connect"))+ }++ @Test+ fun `disconnect clears the token`() = runTest {+ connect()+ connector.disconnect()+ assertTrue(!connector.isConnected())+ assertEquals(null, store.loadRaw("notion"))+ }++ @Test+ fun `tools steer to Settings when not connected`() = runTest {+ val result = tools.execute("notion_search", args())+ assertTrue(!result.success)+ assertTrue(result.message.contains("my-integrations"))+ }++ // ---- notion_search ----++ @Test+ fun `search lists results with ids`() = runTest {+ connect()+ server.enqueue(+ MockResponse().setBody(+ """{"results":[{"id":"p1","object":"page","last_edited_time":"2026-02-01T10:00:00Z",+ "properties":{"Name":{"type":"title","title":[{"plain_text":"Roadmap"}]}}}]}"""+ )+ )+ val result = tools.execute("notion_search", args { put("query", "road") })++ assertTrue(result.success)+ assertTrue(result.message.contains("[p1]"))+ assertTrue(result.message.contains("Roadmap"))+ assertTrue(server.takeRequest().body.readUtf8().contains("\"query\":\"road\""))+ }++ @Test+ fun `an empty search explains the sharing requirement`() = runTest {+ connect()+ server.enqueue(MockResponse().setBody("""{"results":[]}"""))+ val result = tools.execute("notion_search", args { put("query", "nothing") })++ assertTrue(result.success)+ assertTrue("must not imply the page does not exist", result.message.contains("Connections"))+ }++ // ---- notion_read_page ----++ @Test+ fun `read_page returns the title and markdown body`() = runTest {+ connect()+ server.enqueue(+ MockResponse().setBody(+ """{"id":"p1","url":"https://notion.so/p1",+ "properties":{"Name":{"type":"title","title":[{"plain_text":"Roadmap"}]}}}"""+ )+ )+ server.enqueue(+ MockResponse().setBody(+ """{"results":[+ {"type":"heading_1","heading_1":{"rich_text":[{"plain_text":"Q1"}]}},+ {"type":"bulleted_list_item","bulleted_list_item":{"rich_text":[{"plain_text":"Ship it"}]}}]}"""+ )+ )+ val result = tools.execute("notion_read_page", args { put("page_id", "p1") })++ assertTrue(result.success)+ assertTrue(result.message.contains("Title: Roadmap"))+ assertTrue(result.message.contains("https://notion.so/p1"))+ assertTrue(result.message.contains("# Q1"))+ assertTrue(result.message.contains("- Ship it"))+ }++ @Test+ fun `read_page needs a page id`() = runTest {+ connect()+ val result = tools.execute("notion_read_page", args())+ assertTrue(!result.success)+ assertTrue(result.message.contains("page_id"))+ }++ @Test+ fun `a 404 is explained as an unshared page`() = runTest {+ connect()+ server.enqueue(MockResponse().setResponseCode(404).setBody("""{"message":"Could not find page"}"""))+ val result = tools.execute("notion_read_page", args { put("page_id", "missing") })++ assertTrue(!result.success)+ assertTrue(result.message.contains("shared with the integration"))+ }++ // ---- notion_create_page ----++ @Test+ fun `create_page posts parent title and markdown children`() = runTest {+ connect()+ server.enqueue(MockResponse().setBody("""{"id":"new1","url":"https://notion.so/new1"}"""))+ val result = tools.execute(+ "notion_create_page",+ args {+ put("title", "Meeting notes")+ put("parent_page_id", "parent1")+ put("content", "# Agenda\n- Item one")+ }+ )++ assertTrue(result.success)+ assertTrue(result.message.contains("new1"))++ val body = server.takeRequest().body.readUtf8()+ assertTrue(body.contains("\"page_id\":\"parent1\""))+ assertTrue(body.contains("Meeting notes"))+ assertTrue(body.contains("heading_1"))+ assertTrue(body.contains("bulleted_list_item"))+ }++ @Test+ fun `create_page without a parent explains why one is required`() = runTest {+ connect()+ val result = tools.execute("notion_create_page", args { put("title", "Orphan") })++ assertTrue(!result.success)+ assertTrue(result.message.contains("parent_page_id"))+ assertTrue(result.message.contains("notion_search"))+ }++ // ---- notion_append_to_page ----++ @Test+ fun `append_to_page patches block children`() = runTest {+ connect()+ server.enqueue(MockResponse().setBody("""{"results":[]}"""))+ val result = tools.execute(+ "notion_append_to_page",+ args {+ put("page_id", "p1")+ put("content", "- New idea")+ }+ )++ assertTrue(result.success)+ val request = server.takeRequest()+ assertEquals("PATCH", request.method)+ assertTrue(request.path!!.contains("/blocks/p1/children"))+ assertTrue(request.body.readUtf8().contains("bulleted_list_item"))+ }++ @Test+ fun `append_to_page needs content`() = runTest {+ connect()+ val result = tools.execute("notion_append_to_page", args { put("page_id", "p1") })+ assertTrue(!result.success)+ assertTrue(result.message.contains("content"))+ }+}