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: enable reading Notion databases and child database blocks with enhanced pagination and error handling
Rishabh Bajpai8e304b604d08
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f079273..cee1755 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -35,6 +35,26 @@ All notable changes to Gotcha are documented here.50 entries) in addition to logcat, so post-mortem analysis is possiblefrom a user report after the logcat buffer has rolled over.+### Fixed — Notion databases unreadable (#8)++- `notion_read_page` now reads **databases** as well as pages. A Notion todo+ list is a database, and previously passing its id returned a 404 that wrongly+ blamed page sharing — now it falls back to `GET /databases/{id}` ++ `POST /databases/{id}/query` and renders each row with its checkbox state.+- Inline `child_database` blocks inside a page are queried and embedded instead+ of rendering as `[unsupported block: child_database]`, so a todo list dropped+ onto a page is readable too.+- `notion_search` shows a database's real title instead of `(untitled)`.+- `notion_search` no longer crashes when a database appears in the results: a+ database's title column definition carries `"title": {}` (an empty object,+ not an array), and rendering now treats any non-array as empty text instead+ of throwing "is not a JsonArray".+- Reads paginate past 100 blocks via `start_cursor` and recurse into nested+ blocks (bounded by a shared budget); if a cap is hit, the output says+ `[truncated]` instead of silently dropping content.+- A 404 that names a database steers to re-running `notion_search` rather than+ to re-sharing the page.+### 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 29b49ae..b3c7d63 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 by title. Always start here — the other tools need a page id from it.\n2. notion_read_page returns the page's text as Markdown.\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 that have been explicitly shared with it (open the page in Notion → ⋯ → Connections → add the integration). If a search comes back empty or a read returns 'could not find page', 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.\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."}diff --git a/app/src/main/java/com/gotcha/connectors/notion/NotionApi.kt b/app/src/main/java/com/gotcha/connectors/notion/NotionApi.ktindex 50cc308..7bcae2e 100644--- a/app/src/main/java/com/gotcha/connectors/notion/NotionApi.kt+++ b/app/src/main/java/com/gotcha/connectors/notion/NotionApi.kt@@ -6,9 +6,9 @@ import kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonArrayimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.booleanOrNullimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.contentOrNull-import kotlinx.serialization.json.jsonArrayimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitiveimport kotlinx.serialization.json.put@@ -22,6 +22,13 @@ import java.util.concurrent.TimeUnit/** Non-2xx Notion API response, with a user-actionable message. */class NotionApiException(val code: Int, message: String) : IOException(message)+/** A paginated list response: `results` plus the cursor that continues it. */+data class ListResult(+ val results: JsonArray,+ val hasMore: Boolean,+ val nextCursor: String?+)+/*** Thin OkHttp wrapper over the Notion API. Authenticated with an internal* integration token (no OAuth, no refresh), so every call simply carries the@@ -62,10 +69,40 @@ class NotionApi(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()+ /**+ * `GET /databases/{id}` — database metadata. Todo lists and other table-style+ * content are stored as databases, which live under `/databases/{id}` rather+ * than `/pages/{id}`.+ */+ suspend fun database(token: String, databaseId: String): JsonObject =+ get("$baseUrl/databases/${databaseId.trim()}", token)++ /** `POST /databases/{id}/query` — a database's rows (each row is a page). */+ suspend fun databaseQuery(+ token: String,+ databaseId: String,+ pageSize: Int,+ startCursor: String? = null+ ): ListResult {+ val body = buildJsonObject {+ put("page_size", JsonPrimitive(pageSize))+ startCursor?.let { put("start_cursor", JsonPrimitive(it)) }+ }+ return post("$baseUrl/databases/${databaseId.trim()}/query", token, body).toListResult()+ }++ /** `GET /blocks/{id}/children` — a page's (or block's) content blocks. */+ suspend fun blockChildren(+ token: String,+ blockId: String,+ pageSize: Int,+ startCursor: String? = null+ ): ListResult {+ val url = buildString {+ append("$baseUrl/blocks/${blockId.trim()}/children?page_size=$pageSize")+ startCursor?.let { append("&start_cursor=").append(it) }+ }+ return get(url, token).toListResult()}/** `POST /pages` — creates a page. Returns the new page object. */@@ -79,7 +116,15 @@ class NotionApi(}private fun JsonObject.results(): JsonArray =- this["results"]?.jsonArray ?: JsonArray(emptyList())+ this["results"] as? JsonArray ?: JsonArray(emptyList())++ /** Single place that unpacks a paginated list response. */+ private fun JsonObject.toListResult(): ListResult = ListResult(+ results = results(),+ hasMore = this["has_more"]?.jsonPrimitive?.booleanOrNull ?: false,+ nextCursor = this["next_cursor"]?.jsonPrimitive?.contentOrNull+ ?.takeIf { it.isNotBlank() }+ )private fun Request.Builder.notionHeaders(token: String) = this.header("Authorization", "Bearer $token")@@ -123,9 +168,17 @@ class NotionApi("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"+ if (detail.contains("database", ignoreCase = true)) {+ "Notion could not find that database (404). A database id (e.g. a todo " ++ "list) can only be read through notion_read_page, which tries databases " ++ "as well as pages — re-run notion_search and pass the id it returns. " ++ "If it still fails, the database has not been shared with the " ++ "integration. $detail"+ } else {+ "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"diff --git a/app/src/main/java/com/gotcha/connectors/notion/NotionBlockRenderer.kt b/app/src/main/java/com/gotcha/connectors/notion/NotionBlockRenderer.ktindex 9cc8419..20190da 100644--- a/app/src/main/java/com/gotcha/connectors/notion/NotionBlockRenderer.kt+++ b/app/src/main/java/com/gotcha/connectors/notion/NotionBlockRenderer.kt@@ -1,6 +1,7 @@package com.gotcha.connectors.notionimport kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.booleanOrNull@@ -24,14 +25,31 @@ import kotlinx.serialization.json.putobject NotionBlockRenderer {private const val TITLE_MAX = 200+ private const val MAX_ROW_PROPERTIES = 3- /** 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- ?: ""+ /** Property types never rendered in a row's trailing extras. */+ private val EXCLUDED_FROM_EXTRAS = setOf(+ "title", "checkbox", "relation", "rollup", "formula", "people", "files",+ "unique_id", "created_by", "created_time", "last_edited_by", "last_edited_time"+ )++ /**+ * Concatenates a Notion `rich_text` array into plain text.+ *+ * Takes any [JsonElement] and only reads arrays: a database's title column+ * definition carries `"title": {}` (an empty object, not an array), so+ * rendering must never crash on a column definition.+ */+ fun richText(element: JsonElement?): String =+ if (element is JsonArray) {+ element.joinToString("") { node ->+ node.jsonObject["plain_text"]?.jsonPrimitive?.contentOrNull+ ?: node.jsonObject["text"]?.jsonObject+ ?.get("content")?.jsonPrimitive?.contentOrNull+ ?: ""+ }+ } else {+ ""}/** Renders one block as a Markdown line (no trailing newline). */@@ -39,7 +57,7 @@ object NotionBlockRenderer {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)+ val text = richText(payload?.get("rich_text"))return when (type) {"paragraph" -> text"heading_1" -> "# $text"@@ -59,6 +77,8 @@ object NotionBlockRenderer {"divider" -> "---""child_page" ->"- (sub-page) " + (payload?.get("title")?.jsonPrimitive?.contentOrNull).orEmpty()+ "child_database" ->+ "- (database) " + databaseBlockTitle(payload).ifBlank { "Untitled database" }else -> if (text.isNotBlank()) text else "[unsupported block: $type]"}}@@ -67,6 +87,86 @@ object NotionBlockRenderer {fun blocksToMarkdown(blocks: List<JsonObject>): String =blocks.joinToString("\n") { blockToMarkdown(it) }.trim()+ /**+ * Renders a database and its rows as a Markdown document: a heading with the+ * database title, then one compact line per row — title property plus checkbox+ * state (`- [x]`/`- [ ]`) and a few other scalar properties.+ */+ fun databaseToMarkdown(database: JsonObject, rows: List<JsonObject>): String {+ val title = pageTitle(database).takeIf { it != "(untitled)" } ?: "Untitled database"+ val body = rows.joinToString("\n") { rowToMarkdown(it) }+ return buildString {+ append("### Database: ").append(title)+ if (body.isNotBlank()) append("\n").append(body)+ }+ }++ /** One database row (a page object) as a compact Markdown line. */+ fun rowToMarkdown(row: JsonObject): String {+ val properties = row["properties"]?.jsonObject ?: return "- (empty row)"+ val titleText = firstTitleText(properties) ?: "(untitled)"+ val checked = firstCheckbox(properties)+ val extras = properties.entries+ .mapNotNull { (name, value) -> scalarProperty(name, value.jsonObject) }+ .take(MAX_ROW_PROPERTIES)+ .joinToString(" | ")+ return "- [${if (checked) "x" else " "}] $titleText" ++ if (extras.isNotBlank()) " ($extras)" else ""+ }++ private fun firstTitleText(properties: JsonObject): String? {+ properties.values.forEach { property ->+ val node = property.jsonObject+ if (node["type"]?.jsonPrimitive?.contentOrNull == "title") {+ val text = richText(node["title"])+ if (text.isNotBlank()) return text+ }+ }+ return null+ }++ private fun firstCheckbox(properties: JsonObject): Boolean {+ properties.values.forEach { property ->+ val node = property.jsonObject+ if (node["type"]?.jsonPrimitive?.contentOrNull == "checkbox") {+ return node["checkbox"]?.jsonPrimitive?.booleanOrNull ?: false+ }+ }+ return false+ }++ /** A scalar property as `Name: value`, or null for unsupported/empty types. */+ private fun scalarProperty(name: String, node: JsonObject): String? {+ val type = node["type"]?.jsonPrimitive?.contentOrNull ?: return null+ if (type in EXCLUDED_FROM_EXTRAS) return null+ val payload = node[type] ?: return null+ val text = when (type) {+ "select", "status" -> payload.jsonObject["name"]?.jsonPrimitive?.contentOrNull+ "multi_select" ->+ payload.jsonArray+ .mapNotNull { it.jsonObject["name"]?.jsonPrimitive?.contentOrNull }+ .filter { it.isNotBlank() }+ .joinToString(", ")+ .takeIf { it.isNotBlank() }+ "date" -> payload.jsonObject["start"]?.jsonPrimitive?.contentOrNull+ "number", "url", "email", "phone_number" -> payload.jsonPrimitive?.contentOrNull+ "rich_text", "text" ->+ if (payload is JsonArray) richText(payload) else payload.jsonPrimitive?.contentOrNull+ else -> null+ }+ return text?.trim()?.takeIf { it.isNotBlank() }?.let { "$name: $it" }+ }++ /** Title of an inline `child_database` block (rich-text array or plain string). */+ private fun databaseBlockTitle(payload: JsonObject?): String {+ val title = payload?.get("title") ?: return ""+ return if (title is JsonArray) {+ richText(title)+ } else {+ title.jsonPrimitive.contentOrNull.orEmpty()+ }+ }+/*** Converts Markdown-ish text to Notion blocks. Recognises the same subset* [blockToMarkdown] emits; anything unrecognised becomes a paragraph, so no@@ -107,16 +207,25 @@ object NotionBlockRenderer {)}- /** Best-effort page title from a page object's `properties`. */+ /**+ * Best-effort title for a page *or* database object. Pages store it in a+ * `properties.*.title` column; databases keep a top-level `title` array+ * instead, so search hits for a todo-list database show its real name+ * rather than "(untitled)".+ */fun pageTitle(page: JsonObject): String {- val properties = page["properties"]?.jsonObject ?: return "(untitled)"- properties.values.forEach { property ->+ page["properties"]?.jsonObject?.values?.forEach { property ->val node = property.jsonObjectif (node["type"]?.jsonPrimitive?.contentOrNull == "title") {- val text = richText(node["title"]?.jsonArray)+ val text = richText(node["title"])if (text.isNotBlank()) return text}}+ val title = page["title"]+ if (title is JsonArray) {+ val text = richText(title)+ if (text.isNotBlank()) return text+ }return "(untitled)"}diff --git a/app/src/main/java/com/gotcha/connectors/notion/NotionConnector.kt b/app/src/main/java/com/gotcha/connectors/notion/NotionConnector.ktindex 18cfd5a..7249a3d 100644--- a/app/src/main/java/com/gotcha/connectors/notion/NotionConnector.kt+++ b/app/src/main/java/com/gotcha/connectors/notion/NotionConnector.kt@@ -97,8 +97,13 @@ class NotionConnector(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 database(databaseId: String): JsonObject = api.database(token(), databaseId)++ suspend fun databaseQuery(databaseId: String, pageSize: Int, startCursor: String? = null): ListResult =+ api.databaseQuery(token(), databaseId, pageSize, startCursor)++ suspend fun blockChildren(blockId: String, pageSize: Int, startCursor: String? = null): ListResult =+ api.blockChildren(token(), blockId, pageSize, startCursor)suspend fun createPage(payload: JsonObject): JsonObject = api.createPage(token(), payload)diff --git a/app/src/main/java/com/gotcha/connectors/notion/NotionTools.kt b/app/src/main/java/com/gotcha/connectors/notion/NotionTools.ktindex 0e1a93d..01772c1 100644--- a/app/src/main/java/com/gotcha/connectors/notion/NotionTools.kt+++ b/app/src/main/java/com/gotcha/connectors/notion/NotionTools.kt@@ -4,6 +4,7 @@ import com.gotcha.connectors.ToolRouterimport com.gotcha.tools.ToolResultimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.booleanOrNullimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.contentOrNullimport kotlinx.serialization.json.intOrNull@@ -24,6 +25,12 @@ class NotionTools(private const val DEFAULT_PAGE_SIZE = 20private const val MAX_PAGE_SIZE = 100private const val BLOCK_PAGE_SIZE = 100+ private const val DB_PAGE_SIZE = 100++ /** Upper bound on blocks fetched for one read, across pagination and nesting. */+ private const val BLOCK_READ_BUDGET = 1000+ private const val DB_ROW_CAP = 200+ private const val MAX_NESTING_DEPTH = 3private const val SHARING_HINT ="If you expected results, the page is probably not shared with the integration yet: " +@@ -79,14 +86,145 @@ class NotionTools(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)" }- )+ return when (val target = pageOrDatabase(notion, pageId)) {+ is ReadTarget.Page -> {+ val url = target.json.str("url")?.let { "\nURL: $it" }.orEmpty()+ val body = pageMarkdown(notion, pageId)+ ToolResult.ok(+ "Title: ${NotionBlockRenderer.pageTitle(target.json)}$url\n\n" ++ body.ifBlank { "(this page has no text content)" }+ )+ }+ is ReadTarget.Database -> {+ val body = databaseMarkdown(notion, target.json, pageId, 0, ReadBudget(BLOCK_READ_BUDGET))+ ToolResult.ok(body.ifBlank { "(this database has no rows)" })+ }+ }+ }++ /**+ * A search id may point at a page *or* a database (Notion stores todo lists+ * and other table-style content as databases). Tries the page endpoint and+ * falls back to the database endpoint on a 404; any other error propagates.+ */+ private suspend fun pageOrDatabase(notion: NotionConnector, pageId: String): ReadTarget {+ val page = try {+ notion.page(pageId)+ } catch (e: NotionApiException) {+ if (e.code != 404) throw e+ return readDatabase(notion, pageId, e)+ }+ return ReadTarget.Page(page)+ }++ private suspend fun readDatabase(+ notion: NotionConnector,+ pageId: String,+ pageError: NotionApiException+ ): ReadTarget {+ return try {+ ReadTarget.Database(notion.database(pageId))+ } catch (dbE: NotionApiException) {+ throw if (dbE.code == 404) pageError else dbE+ }+ }++ /**+ * Walks a page's block tree into Markdown, paginating past 100 blocks and+ * recursing into nested blocks and inline databases (bounded by a shared+ * budget and nesting depth).+ */+ private suspend fun pageMarkdown(notion: NotionConnector, pageId: String): String {+ val budget = ReadBudget(BLOCK_READ_BUDGET)+ val blocks = fetchBlocks(notion, pageId, budget)+ val body = blocks.map { blockMarkdown(notion, it, 0, budget) }.joinToString("\n").trim()+ val note = if (budget.truncated) "\n\n[truncated — too many blocks to read]" else ""+ return body + note+ }++ private suspend fun blockMarkdown(+ notion: NotionConnector,+ block: JsonObject,+ depth: Int,+ budget: ReadBudget+ ): String {+ if (depth > MAX_NESTING_DEPTH) return ""+ val type = block["type"]?.jsonPrimitive?.contentOrNull ?: return ""+ if (type == "child_database") {+ val databaseId = block["id"]?.jsonPrimitive?.contentOrNull+ ?: return NotionBlockRenderer.blockToMarkdown(block)+ val database = try {+ notion.database(databaseId)+ } catch (e: NotionApiException) {+ // Graceful fallback, but tell the model why the rows are missing:+ // an unshared inline database is actionable, a transient error is not.+ val placeholder = NotionBlockRenderer.blockToMarkdown(block)+ return if (e.code == 404) "$placeholder — rows not readable (not shared)" else placeholder+ }+ return databaseMarkdown(notion, database, databaseId, depth, budget)+ }++ val line = NotionBlockRenderer.blockToMarkdown(block)+ val blockId = block["id"]?.jsonPrimitive?.contentOrNull+ val nested = if (block["has_children"]?.jsonPrimitive?.booleanOrNull == true && blockId != null) {+ val children = fetchBlocks(notion, blockId, budget)+ children.map { child -> blockMarkdown(notion, child, depth + 1, budget) }+ .joinToString("\n")+ } else {+ ""+ }+ val prefix = " ".repeat(depth)+ return if (nested.isBlank()) "$prefix$line" else "$prefix$line\n$nested"+ }++ /** A database plus its rows (paginated, capped) as Markdown. */+ private suspend fun databaseMarkdown(+ notion: NotionConnector,+ database: JsonObject,+ databaseId: String,+ depth: Int,+ budget: ReadBudget+ ): String {+ val rows = mutableListOf<JsonObject>()+ var cursor: String? = null+ var hasMore = true+ while (hasMore && rows.size < DB_ROW_CAP && rows.size < budget.remaining) {+ val result = notion.databaseQuery(databaseId, DB_PAGE_SIZE, cursor)+ rows += result.results.map { it.jsonObject }+ budget.remaining -= result.results.size+ hasMore = result.hasMore+ val next = result.nextCursor+ if (next == null) break+ cursor = next+ }+ val truncated = hasMore && (rows.size >= DB_ROW_CAP || rows.size >= budget.remaining)+ if (truncated) budget.truncated = true+ val rendered = NotionBlockRenderer.databaseToMarkdown(database, rows)+ val prefix = " ".repeat(depth)+ val note = if (truncated) "\n[truncated — too many rows to read]" else ""+ return rendered.lineSequence().joinToString("\n") { prefix + it } + note+ }++ /** One block-level list, following `start_cursor` until the budget is spent. */+ private suspend fun fetchBlocks(+ notion: NotionConnector,+ blockId: String,+ budget: ReadBudget+ ): List<JsonObject> {+ val blocks = mutableListOf<JsonObject>()+ var cursor: String? = null+ var hasMore = true+ while (hasMore && blocks.size < budget.remaining) {+ val result = notion.blockChildren(blockId, BLOCK_PAGE_SIZE, cursor)+ blocks += result.results.map { it.jsonObject }+ budget.remaining -= result.results.size+ hasMore = result.hasMore+ val next = result.nextCursor+ if (next == null) break+ cursor = next+ }+ if (hasMore && blocks.size >= budget.remaining) budget.truncated = true+ return blocks}private suspend fun createPage(args: JsonObject): ToolResult {@@ -136,3 +274,15 @@ class NotionTools(private fun JsonObject.optInt(key: String): Int? = this[key]?.jsonPrimitive?.intOrNull}++/** Mutable fetch allowance shared across pagination, nesting and inline databases. */+private class ReadBudget(var remaining: Int) {+ /** True when a fetch loop stopped because the budget ran out mid-list. */+ var truncated = false+}++/** What a [pageOrDatabase] lookup resolved to — a page or a database object. */+private sealed interface ReadTarget {+ data class Page(val json: JsonObject) : ReadTarget+ data class Database(val json: JsonObject) : ReadTarget+}diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex 6787712..08759d7 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -2092,13 +2092,13 @@ object ToolDefinitions {val notionReadPage = tool("notion_read_page",- "Read a Notion page's title and full text content as Markdown, using a page id from " +- "notion_search.",+ "Read a Notion page's or database's title and full text content as Markdown, using a " ++ "page or database id from notion_search.",schema {putJsonObject("properties") {putJsonObject("page_id") {put("type", "string")- put("description", "Page id from notion_search.")+ put("description", "Page or database id from notion_search.")}}putJsonArray("required") { add("page_id") }diff --git a/app/src/test/java/com/gotcha/connectors/notion/NotionBlockRendererTest.kt b/app/src/test/java/com/gotcha/connectors/notion/NotionBlockRendererTest.ktindex 0d8f61d..f1ca26f 100644--- a/app/src/test/java/com/gotcha/connectors/notion/NotionBlockRendererTest.kt+++ b/app/src/test/java/com/gotcha/connectors/notion/NotionBlockRendererTest.kt@@ -183,4 +183,83 @@ class NotionBlockRendererTest {assertTrue(property.contains("\"title\""))assertTrue(property.contains("New page"))}++ // ---- databases ----++ @Test+ fun `pageTitle reads a database top-level title when there is no properties title`() {+ val database = block(+ """{"object":"database",+ "title":[{"plain_text":"Todo list"}],+ "properties":{"Name":{"id":"title","type":"title","name":"Name"}}}"""+ )+ assertEquals("Todo list", NotionBlockRenderer.pageTitle(database))+ }++ @Test+ fun `pageTitle survives a title column definition with an empty object title`() {+ // A database's title column definition carries "title": {} (an object,+ // not an array) — rendering it must not crash.+ val database = block(+ """{"object":"database","title":[{"plain_text":"My Todos"}],+ "properties":{"Project name":{"id":"title","type":"title","name":"Project name","title":{}}}}"""+ )+ assertEquals("My Todos", NotionBlockRenderer.pageTitle(database))+ }++ @Test+ fun `richText of a non-array element is empty`() {+ assertEquals("", NotionBlockRenderer.richText(kotlinx.serialization.json.Json.parseToJsonElement("{}")))+ assertEquals("", NotionBlockRenderer.richText(null))+ }++ @Test+ fun `child_database block renders its title instead of an unsupported placeholder`() {+ assertEquals(+ "- (database) Todo list",+ markdownOf("""{"type":"child_database","child_database":{"title":[{"plain_text":"Todo list"}]}}""")+ )+ }++ @Test+ fun `databaseToMarkdown renders a heading and one line per row`() {+ val database = block(+ """{"object":"database","title":[{"plain_text":"Shopping"}],+ "properties":{"Item":{"type":"title","name":"Item"},+ "Done":{"type":"checkbox","name":"Done"},+ "Priority":{"type":"select","name":"Priority"}}}"""+ )+ val rows = listOf(+ block(+ """{"object":"page","properties":{+ "Item":{"type":"title","title":[{"plain_text":"Milk"}]},+ "Done":{"type":"checkbox","checkbox":false},+ "Priority":{"type":"select","select":{"name":"High"}}}}"""+ ),+ block(+ """{"object":"page","properties":{+ "Item":{"type":"title","title":[{"plain_text":"Bread"}]},+ "Done":{"type":"checkbox","checkbox":true}}}"""+ )+ )+ val markdown = NotionBlockRenderer.databaseToMarkdown(database, rows)++ assertTrue(markdown.startsWith("### Database: Shopping"))+ assertTrue(markdown.contains("- [ ] Milk (Priority: High)"))+ assertTrue(markdown.contains("- [x] Bread"))+ }++ @Test+ fun `rowToMarkdown drops non-scalar properties and untitled rows degrade`() {+ val row = block(+ """{"object":"page","properties":{+ "Title":{"type":"title","title":[{"plain_text":"Item"}]},+ "Relation":{"type":"relation","relation":[]},+ "Created":{"type":"created_time","created_time":"2026-01-01T00:00:00.000Z"}}}"""+ )+ assertEquals("- [ ] Item", NotionBlockRenderer.rowToMarkdown(row))++ val untitled = block("""{"object":"page","properties":{"Done":{"type":"checkbox","checkbox":true}}}""")+ assertEquals("- [x] (untitled)", NotionBlockRenderer.rowToMarkdown(untitled))+ }}diff --git a/app/src/test/java/com/gotcha/connectors/notion/NotionToolsTest.kt b/app/src/test/java/com/gotcha/connectors/notion/NotionToolsTest.ktindex 98fb402..4afb379 100644--- a/app/src/test/java/com/gotcha/connectors/notion/NotionToolsTest.kt+++ b/app/src/test/java/com/gotcha/connectors/notion/NotionToolsTest.kt@@ -113,6 +113,29 @@ class NotionToolsTest {assertTrue(server.takeRequest().body.readUtf8().contains("\"query\":\"road\""))}+ @Test+ fun `search renders a database result with a real title instead of crashing`() = runTest {+ connect()+ // A real database from /search: the title column definition has "title": {}.+ server.enqueue(+ MockResponse().setBody(+ """{"results":[+ {"id":"db1","object":"database","last_edited_time":"2026-08-01T10:00:00Z",+ "title":[{"plain_text":"My Todos"}],+ "properties":{+ "Task":{"id":"title","type":"title","name":"Task","title":{}},+ "Done":{"id":"cXh","type":"checkbox","name":"Done","checkbox":{}}}}]}"""+ )+ )+ val result = tools.execute("notion_search", args { put("query", "todo") })++ assertTrue(result.success)+ assertTrue(result.message.contains("[db1]"))+ assertTrue(result.message.contains("My Todos"))+ assertTrue(!result.message.contains("(untitled)"))+ assertTrue(!result.message.contains("failed"))+ }+@Testfun `an empty search explains the sharing requirement`() = runTest {connect()@@ -162,12 +185,225 @@ class NotionToolsTest {fun `a 404 is explained as an unshared page`() = runTest {connect()server.enqueue(MockResponse().setResponseCode(404).setBody("""{"message":"Could not find page"}"""))+ server.enqueue(MockResponse().setResponseCode(404).setBody("""{"message":"Could not find database"}"""))val result = tools.execute("notion_read_page", args { put("page_id", "missing") })assertTrue(!result.success)assertTrue(result.message.contains("shared with the integration"))}+ @Test+ fun `read_page falls back to a database read when the id is a database`() = runTest {+ connect()+ server.enqueue(MockResponse().setResponseCode(404).setBody("""{"message":"Could not find page"}"""))+ server.enqueue(+ MockResponse().setBody(+ """{"id":"db1","object":"database","title":[{"plain_text":"Todo list"}],+ "properties":{"Item":{"id":"title","type":"title","name":"Item"},+ "Done":{"id":"done","type":"checkbox","name":"Done"}}}"""+ )+ )+ server.enqueue(+ MockResponse().setBody(+ """{"results":[+ {"id":"r1","object":"page","properties":{+ "Item":{"type":"title","title":[{"plain_text":"Buy milk"}]},+ "Done":{"type":"checkbox","checkbox":false}}},+ {"id":"r2","object":"page","properties":{+ "Item":{"type":"title","title":[{"plain_text":"Call bank"}]},+ "Done":{"type":"checkbox","checkbox":true}}}]}"""+ )+ )+ val result = tools.execute("notion_read_page", args { put("page_id", "db1") })++ assertTrue(result.success)+ assertTrue(result.message.contains("### Database: Todo list"))+ assertTrue(result.message.contains("- [ ] Buy milk"))+ assertTrue(result.message.contains("- [x] Call bank"))++ assertEquals("/v1/pages/db1", server.takeRequest().path)+ assertEquals("/v1/databases/db1", server.takeRequest().path)+ val query = server.takeRequest()+ assertEquals("/v1/databases/db1/query", query.path)+ assertEquals("POST", query.method)+ assertTrue(query.body.readUtf8().contains("\"page_size\":100"))+ }++ @Test+ fun `read_page paginates block children past one page`() = 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":"paragraph","paragraph":{"rich_text":[{"plain_text":"First block"}]}}],+ "has_more":true,"next_cursor":"cur2"}"""+ )+ )+ server.enqueue(+ MockResponse().setBody(+ """{"results":[{"type":"paragraph","paragraph":{"rich_text":[{"plain_text":"Second block"}]}}],+ "has_more":false,"next_cursor":null}"""+ )+ )+ val result = tools.execute("notion_read_page", args { put("page_id", "p1") })++ assertTrue(result.success)+ assertTrue(result.message.contains("First block"))+ assertTrue(result.message.contains("Second block"))++ server.takeRequest() // the /pages call+ server.takeRequest() // first block page+ assertEquals("/v1/blocks/p1/children?page_size=100&start_cursor=cur2", server.takeRequest().path)+ }++ @Test+ fun `read_page recurses into nested blocks`() = runTest {+ connect()+ server.enqueue(+ MockResponse().setBody(+ """{"id":"p1","url":"https://notion.so/p1",+ "properties":{"Name":{"type":"title","title":[{"plain_text":"Nested"}]}}}"""+ )+ )+ server.enqueue(+ MockResponse().setBody(+ """{"results":[+ {"id":"b1","type":"bulleted_list_item","has_children":true,+ "bulleted_list_item":{"rich_text":[{"plain_text":"Parent"}]}}]}"""+ )+ )+ server.enqueue(+ MockResponse().setBody(+ """{"results":[+ {"id":"b2","type":"bulleted_list_item",+ "bulleted_list_item":{"rich_text":[{"plain_text":"Nested child"}]}}]}"""+ )+ )+ val result = tools.execute("notion_read_page", args { put("page_id", "p1") })++ assertTrue(result.success)+ assertTrue(result.message.contains("- Parent"))+ assertTrue(result.message.contains(" - Nested child"))++ server.takeRequest() // the /pages call+ server.takeRequest() // the top-level blocks+ assertEquals("/v1/blocks/b1/children?page_size=100", server.takeRequest().path)+ }++ @Test+ fun `read_page embeds an inline child_database instead of a placeholder`() = runTest {+ connect()+ server.enqueue(+ MockResponse().setBody(+ """{"id":"p1","url":"https://notion.so/p1",+ "properties":{"Name":{"type":"title","title":[{"plain_text":"Board"}]}}}"""+ )+ )+ server.enqueue(+ MockResponse().setBody(+ """{"results":[+ {"id":"cd1","type":"child_database",+ "child_database":{"title":[{"plain_text":"Todos"}]}}]}"""+ )+ )+ server.enqueue(+ MockResponse().setBody(+ """{"id":"cd1","object":"database","title":[{"plain_text":"Todos"}],+ "properties":{"Item":{"id":"title","type":"title","name":"Item"}}}"""+ )+ )+ server.enqueue(+ MockResponse().setBody(+ """{"results":[+ {"id":"r1","object":"page","properties":{+ "Item":{"type":"title","title":[{"plain_text":"Do the thing"}]}}}]}"""+ )+ )+ val result = tools.execute("notion_read_page", args { put("page_id", "p1") })++ assertTrue(result.success)+ assertTrue(result.message.contains("### Database: Todos"))+ assertTrue(result.message.contains("- [ ] Do the thing"))+ assertTrue(!result.message.contains("unsupported block"))+ }++ @Test+ fun `read_page marks the output truncated when a database exceeds the row cap`() = runTest {+ connect()+ server.enqueue(MockResponse().setResponseCode(404).setBody("""{"message":"Could not find page"}"""))+ server.enqueue(+ MockResponse().setBody(+ """{"id":"db1","object":"database","title":[{"plain_text":"Big list"}],+ "properties":{"Item":{"id":"title","type":"title","name":"Item"}}}"""+ )+ )+ fun queryPage(start: Int, cursor: String): String {+ val rows = (start until start + 100).joinToString(",") { i ->+ """{"id":"r$i","object":"page","properties":{+ "Item":{"type":"title","title":[{"plain_text":"Row $i"}]}}}"""+ }+ return """{"results":[$rows],"has_more":true,"next_cursor":"$cursor"}"""+ }+ server.enqueue(MockResponse().setBody(queryPage(0, "c2")))+ server.enqueue(MockResponse().setBody(queryPage(100, "c3")))+ server.enqueue(MockResponse().setBody(queryPage(200, "c4")))++ val result = tools.execute("notion_read_page", args { put("page_id", "db1") })++ assertTrue(result.success)+ assertTrue(result.message.contains("Row 0"))+ assertTrue(result.message.contains("Row 199"))+ assertTrue(!result.message.contains("Row 200"))+ assertTrue(result.message.contains("[truncated — too many rows to read]"))+ }++ @Test+ fun `read_page notes when an inline database is not shared`() = runTest {+ connect()+ server.enqueue(+ MockResponse().setBody(+ """{"id":"p1","url":"https://notion.so/p1",+ "properties":{"Name":{"type":"title","title":[{"plain_text":"Board"}]}}}"""+ )+ )+ server.enqueue(+ MockResponse().setBody(+ """{"results":[+ {"id":"cd1","type":"child_database",+ "child_database":{"title":[{"plain_text":"Todos"}]}}]}"""+ )+ )+ server.enqueue(+ MockResponse().setResponseCode(404).setBody("""{"message":"Could not find database"}""")+ )+ val result = tools.execute("notion_read_page", args { put("page_id", "p1") })++ assertTrue(result.success)+ assertTrue(result.message.contains("- (database) Todos"))+ assertTrue(result.message.contains("rows not readable (not shared)"))+ }++ @Test+ fun `a 404 naming a database steers to database ids rather than re-sharing`() = runTest {+ connect()+ server.enqueue(+ MockResponse().setResponseCode(404).setBody("""{"message":"Could not find database with ID"}""")+ )+ val error = runCatching { connector.page("missing") }.exceptionOrNull()++ assertTrue(error is NotionApiException)+ val message = error!!.message!!+ // A database 404 should name databases and steer to notion_search, not+ // fall back on the generic "re-share the page" guidance.+ assertTrue(message.contains("database", ignoreCase = true))+ assertTrue(message.contains("notion_search"))+ }+// ---- notion_create_page ----@Testdiff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.jsonindex f2c994b..5bb919f 100644--- a/app/src/test/resources/feature-test-coverage.json+++ b/app/src/test/resources/feature-test-coverage.json@@ -640,7 +640,7 @@"tests": ["com.gotcha.connectors.notion.NotionToolsTest"],- "notes": "query routing and result formatting"+ "notes": "query routing and result formatting, including database titles and title-column definitions with an object title"},{"tool": "notion_read_page",@@ -649,7 +649,7 @@"com.gotcha.connectors.notion.NotionToolsTest","com.gotcha.connectors.notion.NotionBlockRendererTest"],- "notes": "page fetch plus block-to-markdown rendering"+ "notes": "page and database reads, pagination, nested blocks, inline child_database, block-to-markdown rendering"},{"tool": "notion_create_page",diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.mdindex 9f5ec0f..47cb50c 100644--- a/docs/FEATURE_TEST_COVERAGE.md+++ b/docs/FEATURE_TEST_COVERAGE.md@@ -124,8 +124,8 @@ 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_read_page` | `UNIT` | `NotionToolsTest`, `NotionBlockRendererTest` — page fetch plus block-to-markdown rendering |-| `notion_search` | `UNIT` | `NotionToolsTest` — query routing and result formatting |+| `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 || `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 ace32c7..cc69450 100644--- a/docs/notion-setup.md+++ b/docs/notion-setup.md@@ -32,23 +32,28 @@ explicitly:Sharing a page also shares everything nested under it, so sharing one top-level page per areais usually enough.-If `notion_search` returns nothing, or `notion_read_page` reports "could not find page", this-is almost always why — not that the page is missing. Both tools say so in their output.+If `notion_search` returns nothing, this is almost always why — not that the page is missing.++**Todo lists are databases.** A Notion todo list is usually stored as a *database* rather than+a page of to-do blocks. `notion_search` returns databases too, and `notion_read_page` reads a+database id the same way as a page id: you get the title, each row, and the checkbox state+(`- [x]`/`- [ ]`). An inline database inside a page is read and embedded the same way.## What you get| Tool | Notes ||---|---|-| `notion_search` | Finds pages by title. Start here — the other tools need an id from it. |-| `notion_read_page` | Returns the page body as Markdown. |+| `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_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. |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-dividers. Anything else is read as a `[unsupported block: …]` placeholder rather than-silently vanishing, and unrecognised Markdown is written as a plain paragraph so no content-is lost.+dividers. Reads paginate past 100 blocks and recurse into nested blocks; inline databases+are queried for their rows. Anything else is read as a `[unsupported block: …]` placeholder+rather than silently vanishing, and unrecognised Markdown is written as a plain paragraph so+no content is lost.## Disconnecting@@ -63,5 +68,7 @@ delete the integration at [notion.so/my-integrations](https://www.notion.so/my-i3. `notion_search` **before** sharing any page → empty, with the sharing guidance.4. Share a page, then `notion_search` → the page appears with an id.5. `notion_read_page` on that id → title, URL and Markdown body.-6. `notion_create_page` with that id as `parent_page_id` → the new page appears in Notion.-7. `notion_append_to_page` → the content is added at the end, with earlier content intact.+6. `notion_read_page` on a database id (e.g. a shared todo list) → `### Database: <title>` and+ the 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.