AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(blocks): add "Update Notion page properties" and "Append to Notion page" blocks (#15861)
Reinier van der Leer48544c4ef720
diff --git a/autogpt_platform/backend/backend/blocks/notion/_api.py b/autogpt_platform/backend/backend/blocks/notion/_api.pyindex 5647f540db..7ab0e6c970 100644--- a/autogpt_platform/backend/backend/blocks/notion/_api.py+++ b/autogpt_platform/backend/backend/blocks/notion/_api.py@@ -177,22 +177,40 @@ class NotionClient:return response.json()- async def update_page(self, page_id: str, properties: dict) -> dict:+ async def update_page(+ self,+ page_id: str,+ properties: Optional[dict] = None,+ icon: Optional[dict] = None,+ cover: Optional[dict] = None,+ archived: Optional[bool] = None,+ ) -> dict:"""- Update a page's properties.+ Update a page's properties, icon, cover or trash state.Args:page_id: The ID of the page to update.- properties: Properties to update.+ properties: Optional properties to update.+ icon: Optional icon object.+ cover: Optional cover object.+ archived: True moves the page to the trash, False restores it.Returns:The updated page object."""url = f"https://api.notion.com/v1/pages/{page_id}"- response = await self.requests.patch(- url, headers=self.headers, json={"properties": properties}- )+ payload: Dict[str, Any] = {}+ if properties:+ payload["properties"] = properties+ if icon:+ payload["icon"] = icon+ if cover:+ payload["cover"] = cover+ if archived is not None:+ payload["archived"] = archived++ response = await self.requests.patch(url, headers=self.headers, json=payload)if not response.ok:raise NotionAPIException(diff --git a/autogpt_platform/backend/backend/blocks/notion/append_to_page.py b/autogpt_platform/backend/backend/blocks/notion/append_to_page.pynew file mode 100644index 0000000000..c6d0535c99--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/notion/append_to_page.py@@ -0,0 +1,158 @@+from __future__ import annotations++from backend.blocks._base import (+ Block,+ BlockCategory,+ BlockEffect,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+)+from backend.data.model import OAuth2Credentials, SchemaField++from ._api import NotionClient+from ._auth import (+ NOTION_OAUTH_IS_CONFIGURED,+ TEST_CREDENTIALS,+ TEST_CREDENTIALS_INPUT,+ NotionCredentialsField,+ NotionCredentialsInput,+)+from .create_page import NotionCreatePageBlock++# Notion refuses an append of more children than this in one request.+MAX_CHILDREN_PER_REQUEST = 100+# Notion refuses a rich-text segment longer than this, counted in UTF-16 units.+MAX_TEXT_LENGTH = 2000+++class NotionAppendToPageBlock(Block):+ """Add content to the end of an existing Notion page."""++ class Input(BlockSchemaInput):+ credentials: NotionCredentialsInput = NotionCredentialsField()+ page_id: str = SchemaField(+ description="ID of the page to add content to. Must be accessible by the connected integration.",+ )+ content: str = SchemaField(+ description="Content to add at the end of the page. Can be plain text or markdown - will be converted to Notion blocks.",+ )++ class Output(BlockSchemaOutput):+ block_ids: list[str] = SchemaField(+ description="IDs of the blocks added to the page, in page order."+ )++ def __init__(self):+ super().__init__(+ id="f33a076f-0eb1-46b2-97a3-04ab23ab06f4",+ description="Add content to the end of an existing Notion page. Supports markdown content.",+ categories={BlockCategory.PRODUCTIVITY},+ input_schema=NotionAppendToPageBlock.Input,+ output_schema=NotionAppendToPageBlock.Output,+ disabled=not NOTION_OAUTH_IS_CONFIGURED,+ test_input={+ "page_id": "12345678-1234-1234-1234-123456789012",+ "content": "## Update\n\nThis is appended content.",+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_output=[+ (+ "block_ids",+ [+ "aaaaaaaa-1234-1234-1234-123456789012",+ "bbbbbbbb-1234-1234-1234-123456789012",+ ],+ ),+ ],+ test_credentials=TEST_CREDENTIALS,+ test_mock={+ "append_content": lambda *args, **kwargs: [+ "aaaaaaaa-1234-1234-1234-123456789012",+ "bbbbbbbb-1234-1234-1234-123456789012",+ ]+ },+ effect=BlockEffect.EXTERNAL_JUDGED,+ )++ @staticmethod+ async def append_content(+ credentials: OAuth2Credentials, page_id: str, content: str+ ) -> list[str]:+ """+ Append markdown content to a Notion page.++ Returns:+ IDs of the appended blocks, in page order.+ """+ client = NotionClient(credentials)+ children = [+ _within_text_limit(block)+ for block in NotionCreatePageBlock._markdown_to_blocks(content)+ ]++ block_ids: list[str] = []+ for start in range(0, len(children), MAX_CHILDREN_PER_REQUEST):+ try:+ result = await client.append_blocks(+ page_id, children[start : start + MAX_CHILDREN_PER_REQUEST]+ )+ except Exception as e:+ if not block_ids:+ raise+ raise PartialAppendError(block_ids, len(children), e) from e+ block_ids.extend(block["id"] for block in result.get("results", []))+ return block_ids++ async def run(+ self,+ input_data: Input,+ *,+ credentials: OAuth2Credentials,+ **kwargs,+ ) -> BlockOutput:+ try:+ block_ids = await self.append_content(+ credentials, input_data.page_id, input_data.content+ )+ yield "block_ids", block_ids+ except Exception as e:+ yield "error", str(e) if str(e) else "Unknown error"+++class PartialAppendError(Exception):+ """Some blocks are on the page; the error names them instead of an output, which+ would run whatever is wired to `block_ids` on a partial append."""++ def __init__(self, block_ids: list[str], total: int, cause: Exception):+ super().__init__(+ f"Added {len(block_ids)} of {total} blocks, the last with ID "+ f"{block_ids[-1]}, then a request failed; check the page for the rest "+ f"before retrying: {cause}"+ )+++def _within_text_limit(block: dict) -> dict:+ """Split each rich-text segment over MAX_TEXT_LENGTH into several, in order."""+ body = block[block["type"]]+ if "rich_text" in body:+ body["rich_text"] = [+ {**segment, "text": {**segment["text"], "content": piece}}+ for segment in body["rich_text"]+ for piece in _split_text(segment["text"]["content"])+ ]+ return block+++def _split_text(text: str) -> list[str]:+ pieces: list[str] = []+ piece: list[str] = []+ size = 0+ for char in text:+ width = 2 if ord(char) > 0xFFFF else 1+ if size + width > MAX_TEXT_LENGTH:+ pieces.append("".join(piece))+ piece, size = [], 0+ piece.append(char)+ size += width+ return [*pieces, "".join(piece)]diff --git a/autogpt_platform/backend/backend/blocks/notion/append_to_page_test.py b/autogpt_platform/backend/backend/blocks/notion/append_to_page_test.pynew file mode 100644index 0000000000..b42fec9987--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/notion/append_to_page_test.py@@ -0,0 +1,109 @@+import pytest++from backend.blocks.notion._auth import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+from backend.blocks.notion.append_to_page import NotionAppendToPageBlock++PAGE_ID = "12345678-1234-1234-1234-123456789012"+CHILDREN_URL = f"https://api.notion.com/v1/blocks/{PAGE_ID}/children"+++def _paragraph(content: str) -> dict:+ return {+ "type": "paragraph",+ "paragraph": {"rich_text": [{"type": "text", "text": {"content": content}}]},+ }+++async def test_markdown_is_appended_as_children_of_the_page(notion_api):+ sent = notion_api({"results": [{"id": "h"}, {"id": "p"}]})++ block_ids = await NotionAppendToPageBlock.append_content(+ TEST_CREDENTIALS, PAGE_ID, "## Update\n\nShipped today."+ )++ assert block_ids == ["h", "p"]+ heading = {+ "type": "heading_2",+ "heading_2": {"rich_text": [{"type": "text", "text": {"content": "Update"}}]},+ }+ assert sent == [+ ("PATCH", CHILDREN_URL, {"children": [heading, _paragraph("Shipped today.")]})+ ]+++async def test_more_than_a_hundred_blocks_go_in_order_over_several_requests(+ notion_api,+):+ lines = [f"line {n}" for n in range(250)]+ sent = notion_api(+ *(+ {"results": [{"id": line} for line in chunk]}+ for chunk in (lines[:100], lines[100:200], lines[200:])+ )+ )++ block_ids = await NotionAppendToPageBlock.append_content(+ TEST_CREDENTIALS, PAGE_ID, "\n".join(lines)+ )++ assert block_ids == lines+ assert [(method, url) for method, url, _ in sent] == [("PATCH", CHILDREN_URL)] * 3+ assert [body["children"] for _, _, body in sent] == [+ [_paragraph(line) for line in chunk]+ for chunk in (lines[:100], lines[100:200], lines[200:])+ ]+++async def test_a_notion_error_is_the_blocks_only_output(notion_api):+ notion_api({"object": "error", "code": "object_not_found"}, statuses=[404])+ block = NotionAppendToPageBlock()+ input_data = block.Input(+ credentials=TEST_CREDENTIALS_INPUT, page_id=PAGE_ID, content="Shipped today."+ )++ outputs = [out async for out in block.run(input_data, credentials=TEST_CREDENTIALS)]++ assert [name for name, _ in outputs] == ["error"]+ assert "HTTP 404 Error: Not Found" in outputs[0][1]+ assert "object_not_found" in outputs[0][1]+++async def test_a_failure_after_the_first_request_names_the_blocks_added_in_the_error(+ notion_api,+):+ lines = [f"line {n}" for n in range(150)]+ notion_api(+ {"results": [{"id": line} for line in lines[:100]]},+ {"object": "error", "code": "rate_limited"},+ statuses=[200, 429],+ )+ block = NotionAppendToPageBlock()+ input_data = block.Input(+ credentials=TEST_CREDENTIALS_INPUT, page_id=PAGE_ID, content="\n".join(lines)+ )++ outputs = [out async for out in block.run(input_data, credentials=TEST_CREDENTIALS)]++ assert [name for name, _ in outputs] == ["error"]+ assert outputs[0][1].startswith(+ "Added 100 of 150 blocks, the last with ID line 99, then a request failed"+ )+ assert "rate_limited" in outputs[0][1]+++ "line, widths",+ [("a" * 4500, [2000, 2000, 500]), ("π" * 1500, [2000, 1000])],+ ids=["ascii", "emoji"],+)+async def test_a_line_over_the_text_limit_is_split_within_one_block(+ notion_api, line: str, widths: list[int]+):+ sent = notion_api({"results": [{"id": "p"}]})++ await NotionAppendToPageBlock.append_content(TEST_CREDENTIALS, PAGE_ID, line)++ [paragraph] = sent[0][2]["children"]+ pieces = [seg["text"]["content"] for seg in paragraph["paragraph"]["rich_text"]]+ assert [len(piece.encode("utf-16-le")) // 2 for piece in pieces] == widths+ assert "".join(pieces) == linediff --git a/autogpt_platform/backend/backend/blocks/notion/conftest.py b/autogpt_platform/backend/backend/blocks/notion/conftest.pynew file mode 100644index 0000000000..fa5299acab--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/notion/conftest.py@@ -0,0 +1,50 @@+import json+from collections.abc import Callable, Sequence+from http import HTTPStatus+from typing import Any++import pytest++from backend.util.request import Requests, http_status_error++Sent = list[tuple[str, str, Any]]+++def notion_api(monkeypatch: pytest.MonkeyPatch) -> Callable[..., Sent]:+ """Answer each Notion request with the next payload given; returns what was sent.++ `statuses` gives each answer's HTTP status (200 when absent); 400 or more fails+ that request the way `Requests` fails it.+ """++ def respond(*payloads: dict, statuses: Sequence[int] = ()) -> Sent:+ answers = iter(zip(payloads, [*statuses, *[200] * len(payloads)]))+ sent: Sent = []++ async def request(_self, method: str, url: str, **kwargs: Any) -> _Response:+ sent.append((method, url, kwargs.get("json")))+ payload, status = next(answers)+ if status >= 400:+ body = json.dumps(payload).encode()+ raise http_status_error(status, HTTPStatus(status).phrase, body)+ return _Response(payload)++ monkeypatch.setattr(Requests, "request", request)+ return sent++ return respond+++class _Response:+ ok = True+ status = 200++ def __init__(self, payload: dict):+ self._payload = payload++ def json(self) -> dict:+ return self._payload++ def text(self) -> str:+ return ""diff --git a/autogpt_platform/backend/backend/blocks/notion/update_page_properties.py b/autogpt_platform/backend/backend/blocks/notion/update_page_properties.pynew file mode 100644index 0000000000..0756e6f528--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/notion/update_page_properties.py@@ -0,0 +1,214 @@+from __future__ import annotations++from typing import Any++from pydantic import model_validator++from backend.blocks._base import (+ Block,+ BlockCategory,+ BlockEffect,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+)+from backend.data.model import OAuth2Credentials, SchemaField++from ._api import NotionClient+from ._auth import (+ NOTION_OAUTH_IS_CONFIGURED,+ TEST_CREDENTIALS,+ TEST_CREDENTIALS_INPUT,+ NotionCredentialsField,+ NotionCredentialsInput,+)+++class NotionUpdatePagePropertiesBlock(Block):+ """Set an existing Notion page's properties, icon, cover or trash state."""++ class Input(BlockSchemaInput):+ credentials: NotionCredentialsInput = NotionCredentialsField()+ page_id: str = SchemaField(+ description="ID of the page to update. Must be accessible by the connected integration.",+ )+ title: str | None = SchemaField(+ description="New title for the page", default=None+ )+ properties: dict[str, Any] | None = SchemaField(+ description="Properties to set by name (e.g., {'Status': 'Done', 'Tags': ['urgent']}). Each value is written as the type the property already has; null clears it, or resets a status to its default option.",+ default=None,+ )+ icon_emoji: str | None = SchemaField(+ description="Emoji to use as the page icon (e.g., 'π', 'π')", default=None+ )+ cover_url: str | None = SchemaField(+ description="URL of an image to use as the page cover", default=None+ )+ in_trash: bool | None = SchemaField(+ description="True moves the page to the trash, False restores it. Leave empty to keep it where it is.",+ default=None,+ )++ @model_validator(mode="after")+ def validate_change(self):+ """Ensure the update changes something."""+ if not (+ self.title+ or self.properties+ or self.icon_emoji+ or self.cover_url+ or self.in_trash is not None+ ):+ raise ValueError(+ "Provide at least one of title, properties, icon_emoji, cover_url or in_trash"+ )+ return self++ class Output(BlockSchemaOutput):+ page_id: str = SchemaField(description="ID of the updated page.")+ page_url: str = SchemaField(description="URL of the updated page.")++ def __init__(self):+ super().__init__(+ id="c80f7468-58e5-4638-a82e-bddf3bf2d383",+ description="Update an existing Notion page's properties, its title among them, its icon or cover, or whether it is in the trash. The page's content is left as it is.",+ categories={BlockCategory.PRODUCTIVITY},+ input_schema=NotionUpdatePagePropertiesBlock.Input,+ output_schema=NotionUpdatePagePropertiesBlock.Output,+ disabled=not NOTION_OAUTH_IS_CONFIGURED,+ test_input={+ "page_id": "12345678-1234-1234-1234-123456789012",+ "title": "Renamed Page",+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_output=[+ ("page_id", "12345678-1234-1234-1234-123456789012"),+ (+ "page_url",+ "https://notion.so/Renamed-Page-12345678123412341234123456789012",+ ),+ ],+ test_credentials=TEST_CREDENTIALS,+ test_mock={+ "update_page": lambda *args, **kwargs: (+ "12345678-1234-1234-1234-123456789012",+ "https://notion.so/Renamed-Page-12345678123412341234123456789012",+ )+ },+ effect=BlockEffect.EXTERNAL_JUDGED,+ )++ @staticmethod+ async def update_page(+ credentials: OAuth2Credentials,+ page_id: str,+ title: str | None = None,+ properties: dict[str, Any] | None = None,+ icon_emoji: str | None = None,+ cover_url: str | None = None,+ in_trash: bool | None = None,+ ) -> tuple[str, str]:+ """+ Update a Notion page.++ Returns:+ Tuple of (page_id, page_url)+ """+ client = NotionClient(credentials)++ page_properties: dict[str, Any] = {}+ if properties:+ page = await client.get_page(page_id)+ page_properties = _property_values(page.get("properties", {}), properties)+ if title:+ page_properties["title"] = {+ "title": [{"type": "text", "text": {"content": title}}]+ }++ result = await client.update_page(+ page_id,+ properties=page_properties,+ icon={"type": "emoji", "emoji": icon_emoji} if icon_emoji else None,+ cover=(+ {"type": "external", "external": {"url": cover_url}}+ if cover_url+ else None+ ),+ # `archived` is the trash flag's name in the pinned NOTION_VERSION.+ archived=in_trash,+ )+ return result["id"], result["url"]++ async def run(+ self,+ input_data: Input,+ *,+ credentials: OAuth2Credentials,+ **kwargs,+ ) -> BlockOutput:+ try:+ page_id, page_url = await self.update_page(+ credentials,+ input_data.page_id,+ input_data.title,+ input_data.properties,+ input_data.icon_emoji,+ input_data.cover_url,+ input_data.in_trash,+ )+ yield "page_id", page_id+ yield "page_url", page_url+ except Exception as e:+ yield "error", str(e) if str(e) else "Unknown error"+++# What clears each type this block writes; read-only types such as formula are absent.+_CLEARED_VALUES: dict[str, Any] = {+ "checkbox": False,+ "select": None,+ "status": None,+ "date": None,+ "number": None,+ "url": None,+ "email": None,+ "phone_number": None,+ "title": [],+ "rich_text": [],+ "multi_select": [],+ "people": [],+ "relation": [],+ "files": [],+}+_SCALAR_TYPES = {"number", "checkbox", "url", "email", "phone_number"}+++def _property_values(+ page_properties: dict[str, Any], values: dict[str, Any]+) -> dict[str, Any]:+ """Shape each value as the type the page's property of that name already has."""+ shaped: dict[str, Any] = {}+ for name, value in values.items():+ if name not in page_properties:+ raise ValueError(f"The page has no property named '{name}'")+ shaped[name] = _property_value(name, page_properties[name]["type"], value)+ return shaped+++def _property_value(name: str, prop_type: str, value: Any) -> dict:+ if prop_type not in _CLEARED_VALUES:+ raise ValueError(f"Writing a {prop_type} property ('{name}') is not supported")+ if value is None:+ return {prop_type: _CLEARED_VALUES[prop_type]}+ if prop_type in ("title", "rich_text"):+ return {prop_type: [{"type": "text", "text": {"content": str(value)}}]}+ if prop_type in ("select", "status"):+ return {prop_type: {"name": str(value)}}+ if prop_type == "multi_select":+ names = value if isinstance(value, list) else [value]+ return {"multi_select": [{"name": str(option)} for option in names]}+ if prop_type == "date":+ return {"date": {"start": str(value)}}+ if prop_type in _SCALAR_TYPES:+ return {prop_type: value}+ raise ValueError(f"Writing a {prop_type} property ('{name}') is not supported")diff --git a/autogpt_platform/backend/backend/blocks/notion/update_page_properties_test.py b/autogpt_platform/backend/backend/blocks/notion/update_page_properties_test.pynew file mode 100644index 0000000000..668110d37d--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/notion/update_page_properties_test.py@@ -0,0 +1,186 @@+import pytest+from pydantic import ValidationError++from backend.blocks.notion._auth import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+from backend.blocks.notion.update_page_properties import NotionUpdatePagePropertiesBlock++PAGE_ID = "12345678-1234-1234-1234-123456789012"+PAGE_URL = f"https://api.notion.com/v1/pages/{PAGE_ID}"+UPDATED = {"id": PAGE_ID, "url": "https://notion.so/Renamed-12345678"}+NOT_FOUND = {"object": "error", "status": 404, "code": "object_not_found"}+++def _text(content: str) -> list[dict]:+ return [{"type": "text", "text": {"content": content}}]+++async def test_properties_are_written_as_the_types_the_page_already_has(notion_api):+ schema = {+ "properties": {+ "Name": {"id": "title", "type": "title"},+ "Status": {"id": "a", "type": "status"},+ "Stage": {"id": "b", "type": "select"},+ "Tags": {"id": "c", "type": "multi_select"},+ "Notes": {"id": "d", "type": "rich_text"},+ "Due": {"id": "e", "type": "date"},+ "Done": {"id": "f", "type": "checkbox"},+ }+ }+ sent = notion_api(schema, UPDATED)++ result = await NotionUpdatePagePropertiesBlock.update_page(+ TEST_CREDENTIALS,+ PAGE_ID,+ title="Renamed",+ properties={+ "Status": "Done",+ "Stage": "Review",+ "Tags": ["urgent", "q4"],+ "Notes": "Shipped",+ "Due": "2026-10-31",+ "Done": True,+ },+ icon_emoji="π",+ cover_url="https://example.com/cover.png",+ )++ assert result == (PAGE_ID, UPDATED["url"])+ assert sent == [+ ("GET", PAGE_URL, None),+ (+ "PATCH",+ PAGE_URL,+ {+ "properties": {+ "Status": {"status": {"name": "Done"}},+ "Stage": {"select": {"name": "Review"}},+ "Tags": {"multi_select": [{"name": "urgent"}, {"name": "q4"}]},+ "Notes": {"rich_text": _text("Shipped")},+ "Due": {"date": {"start": "2026-10-31"}},+ "Done": {"checkbox": True},+ "title": {"title": _text("Renamed")},+ },+ "icon": {"type": "emoji", "emoji": "π"},+ "cover": {+ "type": "external",+ "external": {"url": "https://example.com/cover.png"},+ },+ },+ ),+ ]++[email protected]("in_trash", [True, False, None])+async def test_trash_state_is_sent_only_when_asked(notion_api, in_trash: bool | None):+ sent = notion_api(UPDATED)++ await NotionUpdatePagePropertiesBlock.update_page(+ TEST_CREDENTIALS, PAGE_ID, title="Renamed", in_trash=in_trash+ )++ expected: dict = {"properties": {"title": {"title": _text("Renamed")}}}+ if in_trash is not None:+ expected["archived"] = in_trash+ assert sent == [("PATCH", PAGE_URL, expected)]+++async def test_a_trash_only_update_sends_only_the_trash_flag(notion_api):+ sent = notion_api(UPDATED)++ await NotionUpdatePagePropertiesBlock.update_page(+ TEST_CREDENTIALS, PAGE_ID, in_trash=True+ )++ assert sent == [("PATCH", PAGE_URL, {"archived": True})]+++ "change, valid",+ [+ ({}, False),+ ({"in_trash": False}, True),+ ({"cover_url": "https://x.io/c.png"}, True),+ ],+)+def test_an_update_must_change_something(change: dict, valid: bool):+ def build():+ return NotionUpdatePagePropertiesBlock.Input(+ credentials=TEST_CREDENTIALS_INPUT,+ page_id=PAGE_ID,+ **change,+ )++ if valid:+ build()+ else:+ with pytest.raises(ValidationError, match="Provide at least one of"):+ build()+++async def test_a_notion_error_is_the_blocks_only_output(notion_api):+ notion_api(NOT_FOUND, statuses=[404])+ block = NotionUpdatePagePropertiesBlock()+ input_data = block.Input(+ credentials=TEST_CREDENTIALS_INPUT,+ page_id=PAGE_ID,+ title="Renamed",+ )++ outputs = [out async for out in block.run(input_data, credentials=TEST_CREDENTIALS)]++ assert [name for name, _ in outputs] == ["error"]+ assert "HTTP 404 Error: Not Found" in outputs[0][1]+ assert "object_not_found" in outputs[0][1]+++async def test_null_clears_each_property_the_way_its_type_allows(notion_api):+ schema = {+ "properties": {+ "Done": {"id": "a", "type": "checkbox"},+ "Stage": {"id": "b", "type": "select"},+ "Owner": {"id": "c", "type": "people"},+ }+ }+ sent = notion_api(schema, UPDATED)++ await NotionUpdatePagePropertiesBlock.update_page(+ TEST_CREDENTIALS,+ PAGE_ID,+ properties={"Done": None, "Stage": None, "Owner": None},+ )++ assert sent[-1][2] == {+ "properties": {+ "Done": {"checkbox": False},+ "Stage": {"select": None},+ "Owner": {"people": []},+ }+ }+++ "properties, error",+ [+ ({"Stauts": "Done"}, "no property named 'Stauts'"),+ ({"Total": None}, r"Writing a formula property \('Total'\) is not supported"),+ ({"Owner": ["Ada"]}, r"Writing a people property \('Owner'\) is not supported"),+ ],+)+async def test_a_property_it_cannot_write_is_refused_before_anything_is_written(+ notion_api, properties: dict, error: str+):+ schema = {+ "properties": {+ "Name": {"id": "title", "type": "title"},+ "Total": {"id": "a", "type": "formula"},+ "Owner": {"id": "b", "type": "people"},+ }+ }+ sent = notion_api(schema)++ with pytest.raises(ValueError, match=error):+ await NotionUpdatePagePropertiesBlock.update_page(+ TEST_CREDENTIALS, PAGE_ID, properties=properties+ )++ assert [method for method, _, _ in sent] == ["GET"]diff --git a/docs/integrations/README.md b/docs/integrations/README.mdindex e0b95ae79b..0fee91773f 100644--- a/docs/integrations/README.md+++ b/docs/integrations/README.md@@ -637,11 +637,13 @@ Below is a comprehensive list of all available blocks, categorized by their prim| Block Name | Description ||------------|-------------|| [Google Calendar Create Event](block-integrations/google/calendar.md#google-calendar-create-event) | This block creates a new event in Google Calendar with customizable parameters |+| [Notion Append To Page](block-integrations/notion/append_to_page.md#notion-append-to-page) | Add content to the end of an existing Notion page || [Notion Create Page](block-integrations/notion/create_page.md#notion-create-page) | Create a new page in Notion || [Notion Read Database](block-integrations/notion/read_database.md#notion-read-database) | Query a Notion database with optional filtering and sorting, returning structured entries || [Notion Read Page](block-integrations/notion/read_page.md#notion-read-page) | Read a Notion page by its ID and return its raw JSON || [Notion Read Page Markdown](block-integrations/notion/read_page_markdown.md#notion-read-page-markdown) | Read a Notion page and convert it to Markdown format with proper formatting for headings, lists, links, and rich text || [Notion Search](block-integrations/notion/search.md#notion-search) | Search your Notion workspace for pages and databases by text query |+| [Notion Update Page Properties](block-integrations/notion/update_page_properties.md#notion-update-page-properties) | Update an existing Notion page's properties, its title among them, its icon or cover, or whether it is in the trash || [Todoist Close Task](block-integrations/todoist/tasks.md#todoist-close-task) | Closes a task in Todoist || [Todoist Create Comment](block-integrations/todoist/comments.md#todoist-create-comment) | Creates a new comment on a Todoist task or project || [Todoist Create Label](block-integrations/todoist/labels.md#todoist-create-label) | Creates a new label in Todoist, It will not work if same name already exists |diff --git a/docs/integrations/SUMMARY.md b/docs/integrations/SUMMARY.mdindex 7054b95351..70f2816d69 100644--- a/docs/integrations/SUMMARY.md+++ b/docs/integrations/SUMMARY.md@@ -126,11 +126,13 @@* [Logic](block-integrations/logic.md)* [Mcp Block](block-integrations/mcp/block.md)* [Misc](block-integrations/misc.md)+* [Notion Append To Page](block-integrations/notion/append_to_page.md)* [Notion Create Page](block-integrations/notion/create_page.md)* [Notion Read Database](block-integrations/notion/read_database.md)* [Notion Read Page](block-integrations/notion/read_page.md)* [Notion Read Page Markdown](block-integrations/notion/read_page_markdown.md)* [Notion Search](block-integrations/notion/search.md)+* [Notion Update Page Properties](block-integrations/notion/update_page_properties.md)* [Nvidia Deepfake](block-integrations/nvidia/deepfake.md)* [Replicate Flux Advanced](block-integrations/replicate/flux_advanced.md)* [Replicate Replicate Block](block-integrations/replicate/replicate_block.md)diff --git a/docs/integrations/block-integrations/notion/append_to_page.md b/docs/integrations/block-integrations/notion/append_to_page.mdnew file mode 100644index 0000000000..073f1380ba--- /dev/null+++ b/docs/integrations/block-integrations/notion/append_to_page.md@@ -0,0 +1,41 @@+# Notion Append To Page+<!-- MANUAL: file_description -->+Blocks for adding content to pages that already exist in Notion.+<!-- END MANUAL -->++## Notion Append To Page++### What it is+Add content to the end of an existing Notion page. Supports markdown content.++### How it works+<!-- MANUAL: how_it_works -->+This block adds content to the end of an existing page through the Notion API. The content can be markdown, which is converted to Notion blocks the same way the Create Page block converts it: headings, bulleted and numbered lists, code blocks, quotes, dividers and paragraphs.++Notion takes at most 100 blocks per request, so longer content is sent in several requests, in order. The block outputs the IDs of the new blocks in page order. A line longer than Notion's 2,000-character limit for a run of text is split into several runs within the same block. If a later request fails, the block outputs only the error, which says how many blocks were added and gives the ID of the last one, so nothing wired to the block's IDs runs on a partial append. The failed request's blocks may or may not have reached the page, so check it before retrying.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| page_id | ID of the page to add content to. Must be accessible by the connected integration. | str | Yes |+| content | Content to add at the end of the page. Can be plain text or markdown - will be converted to Notion blocks. | str | Yes |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| block_ids | IDs of the blocks added to the page, in page order. | List[str] |++### Possible use case+<!-- MANUAL: use_case -->+**Running Logs**: Add each day's summary to the bottom of a shared log page.++**Meeting Notes**: Append action items to a meeting page once a transcript has been processed.++**Research Collection**: Add findings to a page as a workflow gathers them, without rewriting what is already there.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/notion/update_page_properties.md b/docs/integrations/block-integrations/notion/update_page_properties.mdnew file mode 100644index 0000000000..57e30861b6--- /dev/null+++ b/docs/integrations/block-integrations/notion/update_page_properties.md@@ -0,0 +1,46 @@+# Notion Update Page Properties+<!-- MANUAL: file_description -->+Blocks for changing pages that already exist in Notion workspaces and databases.+<!-- END MANUAL -->++## Notion Update Page Properties++### What it is+Update an existing Notion page's properties, its title among them, its icon or cover, or whether it is in the trash. The page's content is left as it is.++### How it works+<!-- MANUAL: how_it_works -->+This block updates an existing page through the Notion API. It can rename the page, set its properties, change its emoji icon or cover image, and move it to the trash or restore it, all in one request. The page must be shared with your integration. It leaves the page's content as it is; the Notion Append To Page block adds content to the end of a page.++Properties are named as they appear in the database, and each value is written as the type that property already has: a name for a select or status, a list of names for a multi-select, a date string for a date, and so on. The block reads the page first to learn those types. Before anything is written, it refuses a property the page does not have, a read-only one such as a formula, and a value for a people, relation or files property. A null value clears the property and unchecks a checkbox, but a status goes back to its default option if it has one.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| page_id | ID of the page to update. Must be accessible by the connected integration. | str | Yes |+| title | New title for the page | str | No |+| properties | Properties to set by name (e.g., {'Status': 'Done', 'Tags': ['urgent']}). Each value is written as the type the property already has; null clears it, or resets a status to its default option. | Dict[str, Any] | No |+| icon_emoji | Emoji to use as the page icon (e.g., 'π', 'π') | str | No |+| cover_url | URL of an image to use as the page cover | str | No |+| in_trash | True moves the page to the trash, False restores it. Leave empty to keep it where it is. | bool | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| page_id | ID of the updated page. | str |+| page_url | URL of the updated page. | str |++### Possible use case+<!-- MANUAL: use_case -->+**Task Status Sync**: Mark a task page as Done in a Notion database when the matching issue closes in another system.++**Content Workflow**: Move a draft through Review and Published by setting its Status property as each step finishes.++**Cleanup**: Move pages that a workflow no longer needs to the trash, where they can still be restored.+<!-- END MANUAL -->++---