Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
feat: add notion_update_page, notion_mark_todo, and notion_delete_item tools for Notion connector
Rishabh Bajpai7d64d95efe0d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cee1755..303288e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -55,6 +55,20 @@ All notable changes to Gotcha are documented here.- A 404 that names a database steers to re-running `notion_search` rather thanto re-sharing the page.+### Added — Notion update/delete tools++- `notion_update_page` updates a page's or database row's properties — pass+ column names mapped to simple values, e.g. `{"Done": true}` marks a todo row+ done, `{"Status": "In progress"}` changes a status. The column type is looked+ up from the page so the correct Notion payload is built.+- `notion_mark_todo` checks or unchecks a `to_do` block on a page+ (`checked: true`/`false`).+- `notion_delete_item` moves a page/row to the Notion trash (`item_type:+ "page"`, recoverable) or permanently deletes a block (`item_type: "block"`).+- `notion_read_page` output now marks every editable item with an id —+ `[row-<id>]` for database rows and `[block-<id>]` for to-do blocks — and lists+ each database's `Columns:` so the model knows which values it can update.+### Added — HumanReadableError (PR #77 utility)- New `com.gotcha.util.HumanReadableError` centralizes HTTP status, STT/TTSdiff --git a/app/src/main/assets/skills/notion_connector.json b/app/src/main/assets/skills/notion_connector.jsonindex b3c7d63..7747cc5 100644--- a/app/src/main/assets/skills/notion_connector.json+++ b/app/src/main/assets/skills/notion_connector.json@@ -4,5 +4,5 @@"name": "Notion Connector Skills","description": "Use the Notion connector tools instead of automating the Notion app UI.","requiresTools": ["notion_search"],- "instructions": "The Notion connector is set up, so never automate the Notion app's UI. Use these tools:\n1. notion_search finds pages and databases by title. Always start here — the other tools need an id from it.\n2. notion_read_page returns a page's or database's content as Markdown. A todo list is usually a database, so a database id from notion_search is read the same way — you get the rows with checkbox state.\n3. notion_create_page needs a parent_page_id: Notion gives integrations no workspace root to write into, so find a parent with notion_search first.\n4. notion_append_to_page adds to the end of a page and never overwrites existing content.\n\nThe one thing that trips users up: an integration can only see pages and databases that have been explicitly shared with it (open the page in Notion → ⋯ → Connections → add the integration). If a search comes back empty, that is almost always the cause — tell the user to share the page rather than concluding it does not exist.\n\nNotion is the right destination for notes, meeting summaries, research write-ups and reference material the user wants to keep. For short-lived items with a due date, prefer create_task (Microsoft To Do); for the agent's own working plan use todowrite."+ "instructions": "The Notion connector is set up, so never automate the Notion app's UI. Use these tools:\n1. notion_search finds pages and databases by title. Always start here — the other tools need an id from it.\n2. notion_read_page returns a page's or database's content as Markdown. A todo list is usually a database, so a database id from notion_search is read the same way — you get the rows with checkbox state. Read output marks every editable item with an id: [row-<id>] for database rows (pages) and [block-<id>] for to_do blocks, and lists a database's Columns: line.\n3. notion_create_page needs a parent_page_id: Notion gives integrations no workspace root to write into, so find a parent with notion_search first.\n4. notion_append_to_page adds to the end of a page and never overwrites existing content.\n5. notion_update_page updates a page or database row's properties — pass the column names from the Columns: line mapped to simple values, e.g. {\"Done\": true} to mark a todo done, {\"Status\": \"In progress\"}, or {\"Name\": \"New title\"}. Use it for todo items that live in a database.\n6. notion_mark_todo marks a to_do block (the [block-<id>] items on a page) done or not done with checked: true/false.\n7. notion_delete_item removes an item: item_type 'page' moves a row/page to the trash (recoverable), item_type 'block' permanently deletes a block.\n\nEditing needs the integration's 'Update content' capability, which the setup enables. The one thing that trips users up: an integration can only see pages and databases that have been explicitly shared with it (open the page in Notion → ⋯ → Connections → add the integration). If a search comes back empty, that is almost always the cause — tell the user to share the page rather than concluding it does not exist.\n\nNotion is the right destination for notes, meeting summaries, research write-ups and reference material the user wants to keep. For short-lived items with a due date, prefer create_task (Microsoft To Do); for the agent's own working plan use todowrite."}diff --git a/app/src/main/java/com/gotcha/connectors/ConnectorCatalog.kt b/app/src/main/java/com/gotcha/connectors/ConnectorCatalog.ktindex 7d695d7..54e6700 100644--- a/app/src/main/java/com/gotcha/connectors/ConnectorCatalog.kt+++ b/app/src/main/java/com/gotcha/connectors/ConnectorCatalog.kt@@ -76,7 +76,10 @@ object ConnectorCatalog {"notion_search","notion_read_page","notion_create_page",- "notion_append_to_page"+ "notion_append_to_page",+ "notion_update_page",+ "notion_mark_todo",+ "notion_delete_item"),readOnlyToolNames = setOf("notion_search", "notion_read_page"))diff --git a/app/src/main/java/com/gotcha/connectors/notion/NotionApi.kt b/app/src/main/java/com/gotcha/connectors/notion/NotionApi.ktindex 7bcae2e..b3c1270 100644--- a/app/src/main/java/com/gotcha/connectors/notion/NotionApi.kt+++ b/app/src/main/java/com/gotcha/connectors/notion/NotionApi.kt@@ -34,6 +34,7 @@ data class ListResult(* integration token (no OAuth, no refresh), so every call simply carries the* secret as a Bearer token. JVM-testable via a MockWebServer [baseUrl].*/+@Suppress("TooManyFunctions") // one function per Notion endpoint; splitting by service would not helpclass NotionApi(private val client: OkHttpClient = OkHttpClient.Builder().connectTimeout(20, TimeUnit.SECONDS)@@ -109,12 +110,24 @@ class NotionApi(suspend fun createPage(token: String, payload: JsonObject): JsonObject =post("$baseUrl/pages", token, payload)+ /** `PATCH /pages/{id}` — updates a page/row's properties, or trashes it (`in_trash`). */+ suspend fun updatePage(token: String, pageId: String, payload: JsonObject): JsonObject =+ patch("$baseUrl/pages/${pageId.trim()}", 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)}+ /** `PATCH /blocks/{id}` — updates a block (e.g. a to-do's checked state). */+ suspend fun updateBlock(token: String, blockId: String, payload: JsonObject): JsonObject =+ patch("$baseUrl/blocks/${blockId.trim()}", token, payload)++ /** `DELETE /blocks/{id}` — permanently deletes a block and its children. */+ suspend fun deleteBlock(token: String, blockId: String): JsonObject =+ delete("$baseUrl/blocks/${blockId.trim()}", token)+private fun JsonObject.results(): JsonArray =this["results"] as? JsonArray ?: JsonArray(emptyList())@@ -151,6 +164,15 @@ class NotionApi(.build())+ private suspend fun delete(url: String, token: String): JsonObject =+ execute(+ Request.Builder()+ .url(url)+ .notionHeaders(token)+ .delete()+ .build()+ )+private suspend fun execute(request: Request): JsonObject = withContext(Dispatchers.IO) {client.newCall(request).execute().use { response ->val body = response.body?.string().orEmpty()diff --git a/app/src/main/java/com/gotcha/connectors/notion/NotionBlockRenderer.kt b/app/src/main/java/com/gotcha/connectors/notion/NotionBlockRenderer.ktindex 20190da..2102c92 100644--- a/app/src/main/java/com/gotcha/connectors/notion/NotionBlockRenderer.kt+++ b/app/src/main/java/com/gotcha/connectors/notion/NotionBlockRenderer.kt@@ -67,7 +67,8 @@ object NotionBlockRenderer {"numbered_list_item" -> "1. $text""to_do" -> {val checked = payload?.get("checked")?.jsonPrimitive?.booleanOrNull ?: false- "- [${if (checked) "x" else " "}] $text"+ val marker = elementId(block)?.let { "[block-$it] " }.orEmpty()+ "- [${if (checked) "x" else " "}] $marker$text"}"quote" -> "> $text""code" -> {@@ -94,9 +95,13 @@ object NotionBlockRenderer {*/fun databaseToMarkdown(database: JsonObject, rows: List<JsonObject>): String {val title = pageTitle(database).takeIf { it != "(untitled)" } ?: "Untitled database"+ val columns = database["properties"]?.jsonObject?.keys+ ?.filter { it.isNotBlank() }+ ?.joinToString(", ")val body = rows.joinToString("\n") { rowToMarkdown(it) }return buildString {append("### Database: ").append(title)+ if (!columns.isNullOrBlank()) append("\nColumns: ").append(columns)if (body.isNotBlank()) append("\n").append(body)}}@@ -106,14 +111,19 @@ object NotionBlockRenderer {val properties = row["properties"]?.jsonObject ?: return "- (empty row)"val titleText = firstTitleText(properties) ?: "(untitled)"val checked = firstCheckbox(properties)+ val marker = elementId(row)?.let { "[row-$it] " }.orEmpty()val extras = properties.entries.mapNotNull { (name, value) -> scalarProperty(name, value.jsonObject) }.take(MAX_ROW_PROPERTIES).joinToString(" | ")- return "- [${if (checked) "x" else " "}] $titleText" ++ return "- [${if (checked) "x" else " "}] $marker$titleText" +if (extras.isNotBlank()) " ($extras)" else ""}+ /** The `id` of a block or page object, when present. */+ private fun elementId(element: JsonObject): String? =+ element["id"]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() }+private fun firstTitleText(properties: JsonObject): String? {properties.values.forEach { property ->val node = property.jsonObjectdiff --git a/app/src/main/java/com/gotcha/connectors/notion/NotionConnector.kt b/app/src/main/java/com/gotcha/connectors/notion/NotionConnector.ktindex 7249a3d..8b1da9f 100644--- a/app/src/main/java/com/gotcha/connectors/notion/NotionConnector.kt+++ b/app/src/main/java/com/gotcha/connectors/notion/NotionConnector.kt@@ -107,6 +107,14 @@ class NotionConnector(suspend fun createPage(payload: JsonObject): JsonObject = api.createPage(token(), payload)+ suspend fun updatePage(pageId: String, payload: JsonObject): JsonObject =+ api.updatePage(token(), pageId, payload)+suspend fun appendBlocks(blockId: String, children: JsonArray): JsonObject =api.appendBlocks(token(), blockId, children)++ suspend fun updateBlock(blockId: String, payload: JsonObject): JsonObject =+ api.updateBlock(token(), blockId, payload)++ suspend fun deleteBlock(blockId: String): JsonObject = api.deleteBlock(token(), blockId)}diff --git a/app/src/main/java/com/gotcha/connectors/notion/NotionTools.kt b/app/src/main/java/com/gotcha/connectors/notion/NotionTools.ktindex 01772c1..84fb899 100644--- a/app/src/main/java/com/gotcha/connectors/notion/NotionTools.kt+++ b/app/src/main/java/com/gotcha/connectors/notion/NotionTools.kt@@ -2,9 +2,12 @@ package com.gotcha.connectors.notionimport com.gotcha.connectors.ToolRouterimport com.gotcha.tools.ToolResult+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.booleanOrNull+import kotlinx.serialization.json.buildJsonArrayimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.contentOrNullimport kotlinx.serialization.json.intOrNull@@ -17,6 +20,7 @@ import kotlinx.serialization.json.put* with the integration first, so empty/404 outcomes say that explicitly rather* than letting the model conclude the content does not exist.*/+@Suppress("TooManyFunctions") // one function per tool, plus shared JSON/arg helpersclass NotionTools(private val backend: () -> NotionConnector?) : ToolRouter {@@ -35,13 +39,20 @@ class NotionTools(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."++ /** Column types notion_update_page can build a payload for. */+ private const val UPDATEABLE_TYPES =+ "checkbox, select, status, title, rich_text, number, url, email, phone_number, multi_select"}override val toolNames: Set<String> = setOf("notion_search","notion_read_page","notion_create_page",- "notion_append_to_page"+ "notion_append_to_page",+ "notion_update_page",+ "notion_mark_todo",+ "notion_delete_item")override suspend fun execute(name: String, args: JsonObject): ToolResult = try {@@ -50,6 +61,9 @@ class NotionTools("notion_read_page" -> readPage(args)"notion_create_page" -> createPage(args)"notion_append_to_page" -> appendToPage(args)+ "notion_update_page" -> updatePage(args)+ "notion_mark_todo" -> markTodo(args)+ "notion_delete_item" -> deleteItem(args)else -> ToolResult.error("Unknown Notion tool '$name'.")}} catch (e: Exception) {@@ -267,12 +281,179 @@ class NotionTools(return ToolResult.ok("Appended ${content.lines().size} line(s) to Notion page $pageId.")}+ /**+ * Updates a page's — or a database row's — properties. `properties` maps column+ * names to simple values (e.g. `{"Done": true}`, `{"Status": "Done"}`,+ * `{"Name": "New title"}`); the column type is looked up from the page so the+ * right Notion payload is built. `title` (as a reserved key) updates the+ * page's title column whatever it is called.+ */+ private suspend fun updatePage(args: JsonObject): ToolResult {+ val notion = connected() ?: return notConnected()+ val pageId = args.optString("page_id")?.let { stripItemPrefix(it) }+ ?: return ToolResult.error("notion_update_page needs a 'page_id' from notion_read_page.")+ val requested = args["properties"]?.jsonObject+ ?: return ToolResult.error(+ "notion_update_page needs 'properties' — a JSON object of column name to value, " ++ "e.g. {\"Done\": true}."+ )++ val current = notion.page(pageId)+ val schema = current["properties"]?.jsonObject+ ?: return ToolResult.error(+ "Cannot update $pageId — it has no properties. Pass a page or database-row id " ++ "from notion_read_page, not a database id."+ )+ val titleColumn = schema.entries+ .firstOrNull { (_, v) -> v.jsonObject["type"]?.jsonPrimitive?.contentOrNull == "title" }+ ?.key++ val updates = buildJsonObject {+ requested.forEach { (name, value) ->+ val column = if (name == "title") titleColumn ?: name else name+ val type = schema[column]?.jsonObject?.get("type")?.jsonPrimitive?.contentOrNull+ if (type == null) {+ return@updatePage ToolResult.error(+ "No column named '$column' on page $pageId. Columns: " ++ "${schema.keys.joinToString(", ")}."+ )+ }+ val built = propertyValue(type, value)+ if (built == null) {+ val reason = if (type == "number") {+ "'${value.asText()}' is not a number"+ } else {+ "updating a '$type' column is not supported"+ }+ return@updatePage ToolResult.error(+ "Cannot update column '$column': $reason. Updateable types: $UPDATEABLE_TYPES."+ )+ }+ put(column, built)+ }+ }+ notion.updatePage(pageId, buildJsonObject { put("properties", updates) })+ return ToolResult.ok("Updated Notion page $pageId.")+ }++ /** Marks a `to_do` block checked/unchecked. */+ private suspend fun markTodo(args: JsonObject): ToolResult {+ val notion = connected() ?: return notConnected()+ val blockId = args.optString("block_id")?.let { stripItemPrefix(it) }+ ?: return ToolResult.error("notion_mark_todo needs a 'block_id' from notion_read_page.")+ val checked = args.optBoolean("checked")+ ?: return ToolResult.error("notion_mark_todo needs 'checked' (true or false).")++ notion.updateBlock(+ blockId,+ buildJsonObject { put("to_do", buildJsonObject { put("checked", JsonPrimitive(checked)) }) }+ )+ return ToolResult.ok("Marked Notion block $blockId as ${if (checked) "done" else "not done"}.")+ }++ /**+ * Deletes an item. `item_type` is `page` — trashes a page or database row+ * (recoverable in Notion) — or `block` — permanently deletes a block.+ */+ private suspend fun deleteItem(args: JsonObject): ToolResult {+ val notion = connected() ?: return notConnected()+ val itemId = args.optString("item_id")?.let { stripItemPrefix(it) }+ ?: return ToolResult.error("notion_delete_item needs an 'item_id' from notion_read_page.")+ val type = args.optString("item_type")+ ?: return ToolResult.error(+ "notion_delete_item needs 'item_type': 'page' (trashes a page or row) or 'block' " ++ "(permanently deletes a block)."+ )+ return when (type) {+ "page" -> {+ notion.updatePage(itemId, buildJsonObject { put("in_trash", JsonPrimitive(true)) })+ ToolResult.ok("Moved Notion page $itemId to the trash.")+ }+ "block" -> {+ notion.deleteBlock(itemId)+ ToolResult.ok("Deleted Notion block $itemId.")+ }+ else -> ToolResult.error("notion_delete_item 'item_type' must be 'page' or 'block', got '$type'.")+ }+ }++ /**+ * Builds a Notion property value object for an update, given its column type.+ * Returns null when the value cannot be expressed for that type (unsupported+ * type, or a non-numeric string for a number column).+ */+ private fun propertyValue(type: String, value: JsonElement): JsonObject? = when (type) {+ "checkbox" -> buildJsonObject { put("checkbox", JsonPrimitive(value.asBoolean())) }+ "select", "status" ->+ buildJsonObject { put(type, buildJsonObject { put("name", JsonPrimitive(value.asText())) }) }+ "title", "rich_text" ->+ buildJsonObject { put(type, buildJsonArray { add(textContent(value.asText())) }) }+ "number" -> value.asDouble()?.let { number ->+ buildJsonObject { put("number", JsonPrimitive(number)) }+ }+ "url", "email", "phone_number" ->+ buildJsonObject { put(type, JsonPrimitive(value.asText())) }+ "multi_select" ->+ buildJsonObject {+ put(+ "multi_select",+ buildJsonArray {+ value.asStringList().forEach { option ->+ add(buildJsonObject { put("name", JsonPrimitive(option)) })+ }+ }+ )+ }+ else -> null+ }++ private fun textContent(content: String): JsonObject = buildJsonObject {+ put("type", JsonPrimitive("text"))+ put("text", buildJsonObject { put("content", JsonPrimitive(content)) })+ }++ /** The `row-`/`block-` prefix on ids in read output is cosmetic — strip it if present. */+ private fun stripItemPrefix(id: String): String =+ id.removePrefix("row-").removePrefix("block-")++ private fun JsonElement.asBoolean(): Boolean {+ jsonPrimitive.booleanOrNull?.let { return it }+ return jsonPrimitive.contentOrNull?.toBooleanStrictOrNull() ?: false+ }++ private fun JsonElement.asText(): String = jsonPrimitive.contentOrNull.orEmpty()++ private fun JsonElement.asDouble(): Double? = jsonPrimitive.contentOrNull?.toDoubleOrNull()++ /**+ * Multi-select values as a list of option names. Prefer a JSON array of+ * strings; a comma-separated string is accepted as a fallback, so option+ * names containing commas should be passed as an array.+ */+ private fun JsonElement.asStringList(): List<String> {+ val names = when (this) {+ is JsonArray -> mapNotNull { (it as? JsonPrimitive)?.contentOrNull }+ else -> listOf(jsonPrimitive.contentOrNull.orEmpty())+ }+ return if (this is JsonArray) {+ names.map { it.trim() }.filter { it.isNotBlank() }+ } else {+ names.flatMap { it.split(",") }.map { it.trim() }.filter { it.isNotBlank() }+ }+ }+private fun JsonObject.str(key: String): String? = this[key]?.jsonPrimitive?.contentOrNullprivate 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? {+ val primitive = this[key]?.jsonPrimitive ?: return null+ primitive.booleanOrNull?.let { return it }+ return primitive.contentOrNull?.toBooleanStrictOrNull()+ }}/** Mutable fetch allowance shared across pagination, nesting and inline databases. */diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex 08759d7..4bf153c 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -4,6 +4,7 @@ import com.gotcha.llm.FunctionDefinitionimport com.gotcha.llm.ToolDefinitionimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.add+import kotlinx.serialization.json.buildJsonArrayimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.putimport kotlinx.serialization.json.putJsonArray@@ -2153,6 +2154,85 @@ object ToolDefinitions {})+ val notionUpdatePage = tool(+ "notion_update_page",+ "Update a Notion page's — or a database row's — properties. Use for todo lists: mark a " ++ "row done, set its status, rename it, etc. Pass 'properties' as a JSON object of " ++ "column name to a simple value, e.g. {\"Done\": true}, {\"Status\": \"In progress\"}, " ++ "{\"Name\": \"New name\"}. Column names appear in the 'Columns:' line of " ++ "notion_read_page. Use notion_mark_todo for a to_do block on a page instead.",+ schema {+ putJsonObject("properties") {+ putJsonObject("page_id") {+ put("type", "string")+ put("description", "Page or database-row id from notion_read_page (the id after [row-]).")+ }+ putJsonObject("properties") {+ put("type", "object")+ put("description", "JSON object mapping column names to new values, e.g. {\"Done\": true}.")+ }+ }+ putJsonArray("required") {+ add("page_id")+ add("properties")+ }+ }+ )++ val notionMarkTodo = tool(+ "notion_mark_todo",+ "Mark a Notion to_do block as done or not done. Use the id shown after [block-] in " ++ "notion_read_page output. For a todo item stored as a database row, use " ++ "notion_update_page instead.",+ schema {+ putJsonObject("properties") {+ putJsonObject("block_id") {+ put("type", "string")+ put("description", "Block id from notion_read_page (the id after [block-]).")+ }+ putJsonObject("checked") {+ put("type", "boolean")+ put("description", "true to mark done, false to reopen.")+ }+ }+ putJsonArray("required") {+ add("block_id")+ add("checked")+ }+ }+ )++ val notionDeleteItem = tool(+ "notion_delete_item",+ "Delete a Notion item. item_type 'page' moves a page or database row to the trash " ++ "(recoverable; Notion auto-purges trash after ~30 days, permanent deletion is done " ++ "in the Notion app); item_type 'block' permanently deletes a block and its children. " ++ "Use the id after [row-] or [block-] in notion_read_page output.",+ schema {+ putJsonObject("properties") {+ putJsonObject("item_id") {+ put("type", "string")+ put("description", "Row or block id from notion_read_page (after [row-] or [block-]).")+ }+ putJsonObject("item_type") {+ put("type", "string")+ put(+ "enum",+ buildJsonArray {+ add("page")+ add("block")+ }+ )+ put("description", "'page' trashes a page/row; 'block' permanently deletes a block.")+ }+ }+ putJsonArray("required") {+ add("item_id")+ add("item_type")+ }+ }+ )+// ---- Health Connect tools (on-device, read-only) ----val getHealthSummary = tool(@@ -2246,6 +2326,7 @@ object ToolDefinitions {// Notion connector toolsnotionSearch, notionReadPage, notionCreatePage, notionAppendToPage,+ notionUpdatePage, notionMarkTodo, notionDeleteItem,// Health Connect (on-device, read-only)getHealthSummary, getHealthRecords,diff --git a/app/src/test/java/com/gotcha/connectors/notion/NotionBlockRendererTest.kt b/app/src/test/java/com/gotcha/connectors/notion/NotionBlockRendererTest.ktindex f1ca26f..7ff797d 100644--- a/app/src/test/java/com/gotcha/connectors/notion/NotionBlockRendererTest.kt+++ b/app/src/test/java/com/gotcha/connectors/notion/NotionBlockRendererTest.kt@@ -249,6 +249,38 @@ class NotionBlockRendererTest {assertTrue(markdown.contains("- [x] Bread"))}+ @Test+ fun `to_do block with an id renders a block marker for update tools`() {+ assertEquals(+ "- [ ] [block-b1] Buy milk",+ markdownOf(+ """{"id":"b1","type":"to_do","to_do":{"rich_text":[{"plain_text":"Buy milk"}],"checked":false}}"""+ )+ )+ }++ @Test+ fun `rowToMarkdown includes the row id marker`() {+ val row = block(+ """{"id":"r1","object":"page","properties":{+ "Item":{"type":"title","title":[{"plain_text":"Buy milk"}]}}}"""+ )+ assertEquals("- [ ] [row-r1] Buy milk", NotionBlockRenderer.rowToMarkdown(row))+ }++ @Test+ fun `databaseToMarkdown lists the columns for update tools`() {+ val database = block(+ """{"object":"database","title":[{"plain_text":"Shopping"}],+ "properties":{"Item":{"type":"title","name":"Item"},+ "Done":{"type":"checkbox","name":"Done"}}}"""+ )+ val markdown = NotionBlockRenderer.databaseToMarkdown(database, emptyList())++ assertTrue(markdown.contains("### Database: Shopping"))+ assertTrue(markdown.contains("Columns: Item, Done"))+ }+@Testfun `rowToMarkdown drops non-scalar properties and untitled rows degrade`() {val row = block(diff --git a/app/src/test/java/com/gotcha/connectors/notion/NotionToolsMutationTest.kt b/app/src/test/java/com/gotcha/connectors/notion/NotionToolsMutationTest.ktnew file mode 100644index 0000000..cfdeca6--- /dev/null+++ b/app/src/test/java/com/gotcha/connectors/notion/NotionToolsMutationTest.kt@@ -0,0 +1,392 @@+package com.gotcha.connectors.notion++import com.gotcha.connectors.CredentialStore+import kotlinx.coroutines.test.runTest+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.buildJsonArray+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 InMemoryStore : 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 NotionToolsMutationTest {++ private lateinit var server: MockWebServer+ private lateinit var store: InMemoryStore+ private lateinit var connector: NotionConnector+ private lateinit var tools: NotionTools++ @Before+ fun setUp() {+ server = MockWebServer()+ server.start()+ store = InMemoryStore()+ 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)++ // ---- notion_update_page ----++ private val pageWithSchema = """{+ "id":"r1",+ "properties":{+ "Task":{"id":"title","type":"title","title":[{"plain_text":"Buy milk"}]},+ "Done":{"id":"cXh","type":"checkbox","checkbox":false},+ "Status":{"id":"st","type":"status","status":{"name":"Not started"}},+ "Estimate":{"id":"est","type":"number","number":{"format":"number"}},+ "Tags":{"id":"tg","type":"multi_select","multi_select":{"options":[]}},+ "Created":{"id":"cr","type":"created_time","created_time":"2026-08-01T00:00:00.000Z"}}}"""++ @Test+ fun `update_page patches a checkbox property built from a simple value`() = runTest {+ connect()+ server.enqueue(MockResponse().setBody(pageWithSchema))+ server.enqueue(MockResponse().setBody("""{"id":"r1","object":"page"}"""))+ val result = tools.execute(+ "notion_update_page",+ args {+ put("page_id", "r1")+ put(+ "properties",+ buildJsonObject {+ put("Done", JsonPrimitive(true))+ }+ )+ }+ )++ assertTrue(result.success)+ assertTrue(result.message.contains("Updated Notion page r1"))+ assertEquals("/v1/pages/r1", server.takeRequest().path)+ val patch = server.takeRequest()+ assertEquals("PATCH", patch.method)+ assertEquals("/v1/pages/r1", patch.path)+ assertTrue(patch.body.readUtf8().contains("\"checkbox\":true"))+ }++ @Test+ fun `update_page resolves a select property by name`() = runTest {+ connect()+ server.enqueue(MockResponse().setBody(pageWithSchema))+ server.enqueue(MockResponse().setBody("""{"id":"r1","object":"page"}"""))+ val result = tools.execute(+ "notion_update_page",+ args {+ put("page_id", "r1")+ put(+ "properties",+ buildJsonObject {+ put("Status", JsonPrimitive("Done"))+ }+ )+ }+ )++ assertTrue(result.success)+ server.takeRequest() // the schema fetch+ val body = server.takeRequest().body.readUtf8()+ assertTrue(body.contains("\"status\""))+ assertTrue(body.contains("\"name\":\"Done\""))+ }++ @Test+ fun `update_page supports the reserved title key whatever the column is named`() = runTest {+ connect()+ server.enqueue(MockResponse().setBody(pageWithSchema))+ server.enqueue(MockResponse().setBody("""{"id":"r1","object":"page"}"""))+ val result = tools.execute(+ "notion_update_page",+ args {+ put("page_id", "r1")+ put(+ "properties",+ buildJsonObject {+ put("title", JsonPrimitive("New name"))+ }+ )+ }+ )++ assertTrue(result.success)+ server.takeRequest() // the schema fetch+ val body = server.takeRequest().body.readUtf8()+ assertTrue(body.contains("\"Task\""))+ assertTrue(body.contains("\"content\":\"New name\""))+ }++ @Test+ fun `update_page rejects an unknown column`() = runTest {+ connect()+ server.enqueue(MockResponse().setBody(pageWithSchema))+ val result = tools.execute(+ "notion_update_page",+ args {+ put("page_id", "r1")+ put(+ "properties",+ buildJsonObject {+ put("Nope", JsonPrimitive(true))+ }+ )+ }+ )++ assertTrue(!result.success)+ assertTrue(result.message.contains("No column named 'Nope'"))+ }++ @Test+ fun `update_page rejects a non-numeric value for a number column`() = runTest {+ connect()+ server.enqueue(MockResponse().setBody(pageWithSchema))+ val result = tools.execute(+ "notion_update_page",+ args {+ put("page_id", "r1")+ put(+ "properties",+ buildJsonObject {+ put("Estimate", JsonPrimitive("lots"))+ }+ )+ }+ )++ assertTrue(!result.success)+ assertTrue(result.message.contains("Estimate"))+ assertTrue(result.message.contains("not a number"))+ }++ @Test+ fun `update_page rejects an unsupported column type with the supported list`() = runTest {+ connect()+ server.enqueue(MockResponse().setBody(pageWithSchema))+ val result = tools.execute(+ "notion_update_page",+ args {+ put("page_id", "r1")+ put(+ "properties",+ buildJsonObject {+ put("Created", JsonPrimitive("2026-08-01"))+ }+ )+ }+ )++ assertTrue(!result.success)+ assertTrue(result.message.contains("not supported"))+ assertTrue(result.message.contains("checkbox"))+ }++ @Test+ fun `update_page accepts a multi_select value as an array of names`() = runTest {+ connect()+ server.enqueue(MockResponse().setBody(pageWithSchema))+ server.enqueue(MockResponse().setBody("""{"id":"r1","object":"page"}"""))+ val result = tools.execute(+ "notion_update_page",+ args {+ put("page_id", "r1")+ put(+ "properties",+ buildJsonObject {+ put(+ "Tags",+ buildJsonArray {+ add(JsonPrimitive("Home"))+ add(JsonPrimitive("Work"))+ }+ )+ }+ )+ }+ )++ assertTrue(result.success)+ server.takeRequest() // the schema fetch+ val body = server.takeRequest().body.readUtf8()+ assertTrue(body.contains("\"multi_select\""))+ assertTrue(body.contains("\"name\":\"Home\""))+ assertTrue(body.contains("\"name\":\"Work\""))+ }++ @Test+ fun `update_page accepts a comma-separated multi_select string as a fallback`() = runTest {+ connect()+ server.enqueue(MockResponse().setBody(pageWithSchema))+ server.enqueue(MockResponse().setBody("""{"id":"r1","object":"page"}"""))+ val result = tools.execute(+ "notion_update_page",+ args {+ put("page_id", "r1")+ put(+ "properties",+ buildJsonObject {+ put("Tags", JsonPrimitive("Home, Work"))+ }+ )+ }+ )++ assertTrue(result.success)+ server.takeRequest() // the schema fetch+ val body = server.takeRequest().body.readUtf8()+ assertTrue(body.contains("\"name\":\"Home\""))+ assertTrue(body.contains("\"name\":\"Work\""))+ }++ @Test+ fun `update_page strips a row prefix from the id`() = runTest {+ connect()+ server.enqueue(MockResponse().setBody(pageWithSchema))+ server.enqueue(MockResponse().setBody("""{"id":"r1","object":"page"}"""))+ val result = tools.execute(+ "notion_update_page",+ args {+ put("page_id", "row-r1")+ put(+ "properties",+ buildJsonObject {+ put("Done", JsonPrimitive(false))+ }+ )+ }+ )++ assertTrue(result.success)+ server.takeRequest() // the schema fetch+ assertEquals("/v1/pages/r1", server.takeRequest().path)+ }++ // ---- notion_mark_todo ----++ @Test+ fun `mark_todo patches the checked state`() = runTest {+ connect()+ server.enqueue(MockResponse().setBody("""{"id":"b1","object":"block"}"""))+ val result = tools.execute(+ "notion_mark_todo",+ args {+ put("block_id", "b1")+ put("checked", true)+ }+ )++ assertTrue(result.success)+ assertTrue(result.message.contains("done"))+ val request = server.takeRequest()+ assertEquals("PATCH", request.method)+ assertEquals("/v1/blocks/b1", request.path)+ assertTrue(request.body.readUtf8().contains("\"checked\":true"))+ }++ @Test+ fun `mark_todo strips a block prefix from the id`() = runTest {+ connect()+ server.enqueue(MockResponse().setBody("""{"id":"b1","object":"block"}"""))+ val result = tools.execute(+ "notion_mark_todo",+ args {+ put("block_id", "block-b1")+ put("checked", false)+ }+ )++ assertTrue(result.success)+ assertEquals("/v1/blocks/b1", server.takeRequest().path)+ }++ @Test+ fun `mark_todo needs checked`() = runTest {+ connect()+ val result = tools.execute("notion_mark_todo", args { put("block_id", "b1") })+ assertTrue(!result.success)+ assertTrue(result.message.contains("checked"))+ }++ // ---- notion_delete_item ----++ @Test+ fun `delete_item with type page trashes the page`() = runTest {+ connect()+ server.enqueue(MockResponse().setBody("""{"id":"r1","object":"page"}"""))+ val result = tools.execute(+ "notion_delete_item",+ args {+ put("item_id", "r1")+ put("item_type", "page")+ }+ )++ assertTrue(result.success)+ assertTrue(result.message.contains("trash"))+ val request = server.takeRequest()+ assertEquals("PATCH", request.method)+ assertEquals("/v1/pages/r1", request.path)+ assertTrue(request.body.readUtf8().contains("\"in_trash\":true"))+ }++ @Test+ fun `delete_item with type block sends a delete request`() = runTest {+ connect()+ server.enqueue(MockResponse().setBody("""{"id":"b1","object":"block"}"""))+ val result = tools.execute(+ "notion_delete_item",+ args {+ put("item_id", "b1")+ put("item_type", "block")+ }+ )++ assertTrue(result.success)+ assertTrue(result.message.contains("Deleted"))+ val request = server.takeRequest()+ assertEquals("DELETE", request.method)+ assertEquals("/v1/blocks/b1", request.path)+ }++ @Test+ fun `delete_item rejects an unknown item type`() = runTest {+ connect()+ val result = tools.execute(+ "notion_delete_item",+ args {+ put("item_id", "b1")+ put("item_type", "snippet")+ }+ )+ assertTrue(!result.success)+ assertTrue(result.message.contains("'page' or 'block'"))+ }+}diff --git a/app/src/test/java/com/gotcha/connectors/notion/NotionToolsTest.kt b/app/src/test/java/com/gotcha/connectors/notion/NotionToolsTest.ktindex 4afb379..883c6ae 100644--- a/app/src/test/java/com/gotcha/connectors/notion/NotionToolsTest.kt+++ b/app/src/test/java/com/gotcha/connectors/notion/NotionToolsTest.kt@@ -218,8 +218,8 @@ class NotionToolsTest {assertTrue(result.success)assertTrue(result.message.contains("### Database: Todo list"))- assertTrue(result.message.contains("- [ ] Buy milk"))- assertTrue(result.message.contains("- [x] Call bank"))+ assertTrue(result.message.contains("- [ ] [row-r1] Buy milk"))+ assertTrue(result.message.contains("- [x] [row-r2] Call bank"))assertEquals("/v1/pages/db1", server.takeRequest().path)assertEquals("/v1/databases/db1", server.takeRequest().path)@@ -328,7 +328,7 @@ class NotionToolsTest {assertTrue(result.success)assertTrue(result.message.contains("### Database: Todos"))- assertTrue(result.message.contains("- [ ] Do the thing"))+ assertTrue(result.message.contains("- [ ] [row-r1] Do the thing"))assertTrue(!result.message.contains("unsupported block"))}diff --git a/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.kt b/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.ktindex baf8410..a0d25ff 100644--- a/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.kt+++ b/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.kt@@ -136,6 +136,9 @@ class ToolArgValidationTest {"notion_read_page","notion_create_page","notion_append_to_page",+ "notion_update_page",+ "notion_mark_todo",+ "notion_delete_item","set_timer")}diff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.jsonindex 5bb919f..a9c3d5c 100644--- a/app/src/test/resources/feature-test-coverage.json+++ b/app/src/test/resources/feature-test-coverage.json@@ -667,6 +667,30 @@],"notes": "block append request shape"},+ {+ "tool": "notion_update_page",+ "tier": "UNIT",+ "tests": [+ "com.gotcha.connectors.notion.NotionToolsMutationTest"+ ],+ "notes": "property-value payloads built from simple values (checkbox/select/status/title/number/multi_select), non-numeric and unsupported-type rejection, unknown-column rejection, id-prefix stripping"+ },+ {+ "tool": "notion_mark_todo",+ "tier": "UNIT",+ "tests": [+ "com.gotcha.connectors.notion.NotionToolsMutationTest"+ ],+ "notes": "checked-state patch request shape and id-prefix stripping"+ },+ {+ "tool": "notion_delete_item",+ "tier": "UNIT",+ "tests": [+ "com.gotcha.connectors.notion.NotionToolsMutationTest"+ ],+ "notes": "page trash patch vs block delete request shapes"+ },{"tool": "get_health_summary","tier": "UNIT",diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.mdindex 47cb50c..11ed8b7 100644--- a/docs/FEATURE_TEST_COVERAGE.md+++ b/docs/FEATURE_TEST_COVERAGE.md@@ -13,13 +13,13 @@ Every tool the assistant can call is listed below, together with how it is verif| Tier | Tools | What it means ||---|---:|---|-| `UNIT` | 20 | Plain JVM unit test — no Android framework needed. |+| `UNIT` | 23 | Plain JVM unit test — no Android framework needed. || `ROBOLECTRIC` | 18 | JVM test against Robolectric's Android framework, often across several API levels. || `INSTRUMENTED` | 0 | Runs on a real device or emulator (`app/src/androidTest`). || `MANUAL_ONLY` | 64 | No automated test — verified by hand, see the checklist below. |-| **Total** | **102** | |+| **Total** | **105** | |-**38 of 102** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.+**41 of 105** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.## Foreground tools (act on the screen)@@ -124,8 +124,11 @@ Every tool the assistant can call is listed below, together with how it is verif| `list_installed_apps` | `ROBOLECTRIC` | `AppsToolTest` — listing, system-app marking, counts, search filtering || `list_tasks` | `MANUAL_ONLY` | Routed to a live Microsoft Graph account; only the underlying GraphApi has JVM coverage today. || `list_timers` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |+| `notion_delete_item` | `UNIT` | `NotionToolsMutationTest` — page trash patch vs block delete request shapes |+| `notion_mark_todo` | `UNIT` | `NotionToolsMutationTest` — checked-state patch request shape and id-prefix stripping || `notion_read_page` | `UNIT` | `NotionToolsTest`, `NotionBlockRendererTest` — page and database reads, pagination, nested blocks, inline child_database, block-to-markdown rendering || `notion_search` | `UNIT` | `NotionToolsTest` — query routing and result formatting, including database titles and title-column definitions with an object title |+| `notion_update_page` | `UNIT` | `NotionToolsMutationTest` — property-value payloads built from simple values (checkbox/select/status/title/number/multi_select), non-numeric and unsupported-type rejection, unknown-column rejection, id-prefix stripping || `question` | `MANUAL_ONLY` | Pure UI round-trip: the tool blocks until the user answers a prompt rendered in the chat surface. || `read_call_log` | `MANUAL_ONLY` | Needs a populated CallLog ContentProvider; the emulator has no real call history and Robolectric's provider fakes are not wired for this table. || `read_email` | `UNIT` | `EmailToolsTest`, `MailBodyExtractorTest` — id routing plus multipart/HTML body extraction |diff --git a/docs/notion-setup.md b/docs/notion-setup.mdindex cc69450..c9199db 100644--- a/docs/notion-setup.md+++ b/docs/notion-setup.md@@ -44,9 +44,12 @@ database id the same way as a page id: you get the title, each row, and the chec| Tool | Notes ||---|---|| `notion_search` | Finds pages and databases by title. Start here — the other tools need an id from it. |-| `notion_read_page` | Returns the page — or database, e.g. a todo list — body as Markdown. |+| `notion_read_page` | Returns the page — or database, e.g. a todo list — body as Markdown. Every editable item is marked with an id (`[row-…]` for database rows, `[block-…]` for to-do blocks) and each database lists its `Columns:`. || `notion_create_page` | Requires a `parent_page_id`: Notion gives integrations no workspace root to write into. || `notion_append_to_page` | Adds to the end of a page; never overwrites. |+| `notion_update_page` | Updates a page or database row's properties, e.g. `{"Done": true}` marks a todo done. Needs the integration's **Update content** capability. |+| `notion_mark_todo` | Checks/unchecks a `to_do` block on a page (`checked: true`/`false`). |+| `notion_delete_item` | `item_type: "page"` moves a page/row to the trash (recoverable); `item_type: "block"` permanently deletes a block. |Supported block types round-trip between Notion and Markdown: paragraphs, headings 1–3,bulleted and numbered lists, to-dos (including checked state), quotes, code blocks and@@ -72,3 +75,6 @@ delete the integration at [notion.so/my-integrations](https://www.notion.so/my-ithe rows with `- [x]`/`- [ ]` checkbox state.7. `notion_create_page` with that id as `parent_page_id` → the new page appears in Notion.8. `notion_append_to_page` → the content is added at the end, with earlier content intact.+9. On a database row, `notion_update_page` with `{"<checkbox column>": true}` (e.g. `{"Done": true}`)+ → the row is checked in Notion.+10. `notion_delete_item` with `item_type: "page"` → the row moves to the Notion trash.