From 0005d8f7ee13b28017e258d38750cb3782753fa4 Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Thu, 8 Oct 2026 01:56:22 +0000 Subject: [PATCH] bridges: resolve Nextcloud tasks to VTODO-capable lists Task operations used the same calendar resolver as events, so a request that named (or defaulted to) an event-only calendar like "personal" put a VTODO into a collection that rejects it. Read each collection's CalDAV supported-calendar-component-set, expose it as `components` on /calendars, and add GET /tasklists (VTODO-capable calendars, minus Nextcloud Deck boards). _resolve_calendar is now component-aware: task routes only target a VTODO-capable list and reject an event-only calendar with a clear 400; with no name they try default_task_calendar, then default_calendar when it also accepts VTODO, then the sole user task list. Add the default_task_calendar config (top-level nextcloud_default_task_calendar fallback) and document the routes in the bridge catalog. --- AGENTS.md | 8 +- config.example.json | 3 +- semif_agent/bridges/nextcloud.py | 133 +++++++++++++++++++++--- semif_agent/bridges/nextcloud_client.py | 20 ++++ semif_agent/bridges/registry.py | 1 + tests/test_nextcloud_bridge.py | 86 ++++++++++++++- 6 files changed, 231 insertions(+), 20 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ab62234..e2feebc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1314,9 +1314,11 @@ CLI, unit tests (24) + integration tests (2). `nextcloud_bridge_token`); the `BridgeInfo` declares only those two config vars. Routes (reads `GET`, mutations `POST`): files (`/files`, `/files/stat`, `/files/read` text-or-base64, `/files/search`, `/files/write|mkdir|delete|move|copy`), - calendars (`/calendars`, `/calendars/events` list, `POST /calendars/events` + - `/update` + `/delete`), tasks (`/tasks` list, `POST /tasks` + `/update` + - `/complete` + `/delete`), contacts (`/addressbooks`, `/contacts` list/search, + calendars (`/calendars` with each collection's `supported-calendar-component-set` + as `components`, `/tasklists` for VTODO-capable task lists, `/calendars/events` + list, `POST /calendars/events` + `/update` + `/delete`), tasks (`/tasks` list, + `POST /tasks` + `/update` + `/complete` + `/delete`; task routes only target a + VTODO-capable calendar and reject an event-only one), contacts (`/addressbooks`, `/contacts` list/search, `POST /contacts` + `/update` + `/delete`), notes (`/notes`, `/notes/get`, `POST /notes` + `/update` + `/delete`), and `/user` + `/capabilities` (OCS). A missing connection is `503`; a real failure (`NextcloudError` — transport, diff --git a/config.example.json b/config.example.json index f221871..5f37e74 100644 --- a/config.example.json +++ b/config.example.json @@ -149,7 +149,7 @@ "token": "" }, "nextcloud": { - "_comment": "Nextcloud bridge: files (WebDAV), calendar events and tasks (CalDAV), contacts (CardDAV), and Notes (the Notes app) over one uniform local JSON API, so skill bodies never speak the native DAV/OCS protocols. It has no service daemon (Nextcloud is plain HTTPS) and runs inside the same `semif-bridge` process as the other enabled bridges. The connection is configured HERE (url/username/app_password); when a value is blank the bridge falls back to the top-level nextcloud_url/nextcloud_username/nextcloud_app_password/nextcloud_default_calendar the calendar seeds already use, so the account is configured once. `app_password` is a Nextcloud app password (Settings > Security > Devices & sessions), not the account password. `default_calendar`/`default_addressbook` are used when a request names none and the account has several. `verify_tls` false skips certificate verification (self-signed hosts). Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.", + "_comment": "Nextcloud bridge: files (WebDAV), calendar events and tasks (CalDAV), contacts (CardDAV), and Notes (the Notes app) over one uniform local JSON API, so skill bodies never speak the native DAV/OCS protocols. It has no service daemon (Nextcloud is plain HTTPS) and runs inside the same `semif-bridge` process as the other enabled bridges. The connection is configured HERE (url/username/app_password); when a value is blank the bridge falls back to the top-level nextcloud_url/nextcloud_username/nextcloud_app_password/nextcloud_default_calendar the calendar seeds already use, so the account is configured once. `app_password` is a Nextcloud app password (Settings > Security > Devices & sessions), not the account password. `default_calendar`/`default_task_calendar`/`default_addressbook` are used when a request names none and the account has several; task operations only ever target a VTODO-capable task list (GET /tasklists), never an event-only calendar. `verify_tls` false skips certificate verification (self-signed hosts). Skills call it at http://host:port (derived from this block; no top-level duplicate). Binds localhost only; an optional `token` is required in the X-Semif-Token header when set.", "enabled": true, "host": "127.0.0.1", "port": 5230, @@ -158,6 +158,7 @@ "username": "", "app_password": "", "default_calendar": "", + "default_task_calendar": "", "default_addressbook": "", "verify_tls": true, "timeout": 30 diff --git a/semif_agent/bridges/nextcloud.py b/semif_agent/bridges/nextcloud.py index bbc6013..a65f5aa 100644 --- a/semif_agent/bridges/nextcloud.py +++ b/semif_agent/bridges/nextcloud.py @@ -26,6 +26,45 @@ import uuid from .base import BridgeInfo, BridgeService from .nextcloud_client import DEFAULT_TIMEOUT, NextcloudClient, NextcloudError +#: Nextcloud Deck backs each board with a VTODO-only calendar named like this. +_DECK_PREFIX = "app-generated--deck--" + +_COMPONENT_KINDS = { + "VTODO": "task list", + "VEVENT": "event calendar", + "VJOURNAL": "journal", +} + + +def _supports(calendar: dict, component: str) -> bool: + """Whether a calendar accepts `component`; unknown (empty) means allow.""" + components = calendar.get("components") or [] + return not components or component in components + + +def _is_deck_board(calendar: dict) -> bool: + return str(calendar.get("name") or "").startswith(_DECK_PREFIX) + + +def _component_kind(component: str) -> str: + return _COMPONENT_KINDS.get(component, "calendar of that kind") + + +def _join_components(calendar: dict) -> str: + components = calendar.get("components") or [] + return ", ".join(components) if components else "an unknown component set" + + +def _task_list_hint(calendars: list[dict]) -> str: + names = [ + c["name"] + for c in calendars + if _supports(c, "VTODO") and not _is_deck_board(c) + ] + if names: + return "task lists: " + ", ".join(names) + return "no VTODO-capable task lists are available" + class NextcloudBridge(BridgeService): name = "nextcloud" @@ -62,7 +101,12 @@ class NextcloudBridge(BridgeService): "POST /files/copy {\"path\", \"destination\", \"overwrite\"?: bool} " "-> 200 {\"ok\": true, \"path\", \"destination\"}", "GET /calendars -> 200 {\"calendars\": [{name, label, description, " - "color, ctag}]}", + "color, ctag, components}]} — components lists the CalDAV component " + "types each collection accepts (VEVENT, VTODO, VJOURNAL)", + "GET /tasklists -> 200 {\"tasklists\": [{name, label, description, " + "color, ctag, components}]} — the user's task lists (calendars that " + "accept VTODO), excluding Nextcloud Deck boards; use this to pick a " + "target for POST /tasks", "GET /calendars/events?calendar=&start=&end= -> 200 " "{\"calendar\", \"events\": [{uid, summary, start, end, all_day, " "location, description, rrule, status, href, etag}]} — start/end " @@ -79,10 +123,12 @@ class NextcloudBridge(BridgeService): "{\"ok\": true, \"uid\", \"calendar\"}", "GET /tasks?calendar= -> 200 {\"calendar\", \"tasks\": [{uid, " "summary, due, status, percent_complete, priority, description, href, " - "etag}]} — CalDAV VTODO", + "etag}]} — CalDAV VTODO; calendar must be a VTODO-capable task list " + "(see GET /tasklists), defaulting to the configured task calendar", "POST /tasks {\"calendar\"?, \"uid\"?, \"summary\", \"due\"?, " "\"priority\"?, \"description\"?} -> 200 {\"ok\": true, \"uid\", " - "\"calendar\", \"etag\"}", + "\"calendar\", \"etag\"} — calendar must be a VTODO-capable task list " + "(see GET /tasklists); an event-only calendar is rejected with 400", "POST /tasks/update {\"calendar\"?, \"uid\", \"summary\"?, \"due\"?, " "\"priority\"?, \"description\"?, \"status\"?, \"percent_complete\"?} " "-> 200 {ok, uid}", @@ -148,6 +194,7 @@ class NextcloudBridge(BridgeService): self.username = str(pick("username")).strip() self.app_password = str(pick("app_password")) self.default_calendar = str(pick("default_calendar")).strip() + self.default_task_calendar = str(pick("default_task_calendar")).strip() self.default_addressbook = str(pick("default_addressbook")).strip() self.verify_tls = bool(cfg.get("verify_tls", fb.get("verify_tls", True))) self.timeout = float(cfg.get("timeout", DEFAULT_TIMEOUT)) @@ -222,6 +269,8 @@ class NextcloudBridge(BridgeService): } if path == "/calendars": return 200, {"calendars": self.client.list_calendars()} + if path == "/tasklists": + return 200, {"tasklists": self._task_lists()} if path == "/calendars/events": calendar = self._resolve_calendar(self._q(query, "calendar")) return 200, { @@ -233,7 +282,7 @@ class NextcloudBridge(BridgeService): ), } if path == "/tasks": - calendar = self._resolve_calendar(self._q(query, "calendar")) + calendar = self._resolve_calendar(self._q(query, "calendar"), "VTODO") return 200, {"calendar": calendar, "tasks": self.client.list_tasks(calendar)} if path == "/addressbooks": return 200, {"addressbooks": self.client.list_addressbooks()} @@ -287,10 +336,10 @@ class NextcloudBridge(BridgeService): if path == "/tasks/update": return 200, self._update_task(payload) if path == "/tasks/complete": - calendar = self._resolve_calendar(self._optional_str(payload, "calendar")) + calendar = self._resolve_calendar(self._optional_str(payload, "calendar"), "VTODO") return 200, self.client.complete_task(calendar, self._required(payload, "uid")) if path == "/tasks/delete": - calendar = self._resolve_calendar(self._optional_str(payload, "calendar")) + calendar = self._resolve_calendar(self._optional_str(payload, "calendar"), "VTODO") return 200, self.client.delete_object(calendar, self._required(payload, "uid")) if path == "/contacts": return 200, self._create_contact(payload) @@ -348,7 +397,7 @@ class NextcloudBridge(BridgeService): return self.client.update_event(calendar, uid, **changes) def _create_task(self, payload: dict) -> dict: - calendar = self._resolve_calendar(self._optional_str(payload, "calendar")) + calendar = self._resolve_calendar(self._optional_str(payload, "calendar"), "VTODO") uid = self._optional_str(payload, "uid") or uuid.uuid4().hex return self.client.create_task( calendar, @@ -360,7 +409,7 @@ class NextcloudBridge(BridgeService): ) def _update_task(self, payload: dict) -> dict: - calendar = self._resolve_calendar(self._optional_str(payload, "calendar")) + calendar = self._resolve_calendar(self._optional_str(payload, "calendar"), "VTODO") uid = self._required(payload, "uid") changes = { key: payload[key] @@ -410,18 +459,72 @@ class NextcloudBridge(BridgeService): # ---- default resolution ---- - def _resolve_calendar(self, name) -> str: - name = str(name or self.default_calendar or "").strip() - if name: - return name - calendars = self.client.list_calendars() + def _resolve_calendar(self, name, component: str | None = None) -> str: + """Resolve a calendar name, honoring the CalDAV component it must accept. + + An explicit name is validated when the collection's component set is + known: asking a task operation to write to an event-only calendar is a + real error (a `VTODO` PUT there is rejected), not a silent redirect. With + no name, a task operation falls back to the configured task calendar, then + the event default when it also accepts VTODO, then the sole user task + list. `component=None` (events, files) keeps the historical behavior. + """ + requested = str(name or "").strip() + if requested: + if component: + calendars = self.client.list_calendars() + match = next((c for c in calendars if c.get("name") == requested), None) + if match is not None and not _supports(match, component): + raise ValueError( + f"{requested!r} is not a {_component_kind(component)} " + f"(it accepts {_join_components(match)}); " + f"{_task_list_hint(calendars)}" + ) + return requested + + # The configured defaults, most specific first. For a task operation the + # event default is still consulted when it also accepts VTODO. + defaults = [self.default_task_calendar] if component == "VTODO" else [] + defaults.append(self.default_calendar) + calendars = None + for default in defaults: + if not default: + continue + if not component: + return default + if calendars is None: + calendars = self.client.list_calendars() + match = next((c for c in calendars if c.get("name") == default), None) + if match is None or _supports(match, component): + return default + + if calendars is None: + calendars = self.client.list_calendars() + if component: + calendars = [c for c in calendars if _supports(c, component)] + if component == "VTODO": + calendars = [c for c in calendars if not _is_deck_board(c)] if len(calendars) == 1: return calendars[0]["name"] raise ValueError( - "calendar is required (name one in the request, or set " - "bridges.nextcloud.default_calendar)" + f"calendar is required (name one in the request, or set " + f"bridges.nextcloud.default_calendar" + + ( + " / default_task_calendar" + if component == "VTODO" + else "" + ) + + ")" ) + def _task_lists(self) -> list[dict]: + """The user's task lists: VTODO-capable calendars, minus Deck boards.""" + return [ + calendar + for calendar in self.client.list_calendars() + if _supports(calendar, "VTODO") and not _is_deck_board(calendar) + ] + def _resolve_addressbook(self, name) -> str: name = str(name or self.default_addressbook or "").strip() if name: diff --git a/semif_agent/bridges/nextcloud_client.py b/semif_agent/bridges/nextcloud_client.py index f148a7f..2ec4b02 100644 --- a/semif_agent/bridges/nextcloud_client.py +++ b/semif_agent/bridges/nextcloud_client.py @@ -57,6 +57,23 @@ def _int(value, default=None): return default +def _component_set(prop) -> list[str]: + """The component types a calendar accepts (`VEVENT`/`VTODO`/`VJOURNAL`). + + Parsed from the CalDAV `supported-calendar-component-set` property. An empty + list means the server did not advertise it (unknown), not "accepts nothing". + """ + node = prop.find(f"{{{CALDAV}}}supported-calendar-component-set") + if node is None: + return [] + names = [] + for comp in node.findall(f"{{{CALDAV}}}comp"): + name = (comp.get("name") or "").strip().upper() + if name: + names.append(name) + return names + + def _norm_path(path) -> str: """A user-facing DAV path: always leading `/`, no trailing slash (root `/`).""" text = "/" + str(path or "").strip("/") @@ -457,6 +474,7 @@ _CALENDAR_PROPFIND = ( '' "" + "" "" "" ).encode("utf-8") @@ -860,6 +878,7 @@ class NextcloudClient: ctag = _text(prop.find(f"{{{CALDAV}}}getctag")) or _text( prop.find(f"{{{OC}}}getctag") ) + components = _component_set(prop) calendars.append( { "name": name, @@ -867,6 +886,7 @@ class NextcloudClient: "description": _text(prop.find(f"{{{CALDAV}}}calendar-description")), "color": color, "ctag": ctag, + "components": components, } ) calendars.sort(key=lambda calendar: calendar["name"].lower()) diff --git a/semif_agent/bridges/registry.py b/semif_agent/bridges/registry.py index e25328e..b1e71bf 100644 --- a/semif_agent/bridges/registry.py +++ b/semif_agent/bridges/registry.py @@ -124,6 +124,7 @@ def build_bridge( "username": config.get("nextcloud_username"), "app_password": config.get("nextcloud_app_password"), "default_calendar": config.get("nextcloud_default_calendar"), + "default_task_calendar": config.get("nextcloud_default_task_calendar"), "default_addressbook": config.get("nextcloud_default_addressbook"), }, ) diff --git a/tests/test_nextcloud_bridge.py b/tests/test_nextcloud_bridge.py index 945535e..4ba57f8 100644 --- a/tests/test_nextcloud_bridge.py +++ b/tests/test_nextcloud_bridge.py @@ -48,7 +48,9 @@ class FakeNextcloud: "/Documents/readme.txt": {"type": "file", "content": b"hello world"}, "/image.png": {"type": "file", "content": b"\x89PNG\x00\xff"}, } - self.calendars = {"personal": {"label": "Personal", "objects": {}}} + self.calendars = { + "personal": {"label": "Personal", "components": ["VEVENT"], "objects": {}} + } self.addressbooks = {"contacts": {"label": "Contacts", "cards": {}}} self.notes = {} self._next_note_id = 1 @@ -257,12 +259,16 @@ class FakeNextcloud: ) ] for name, calendar in self.calendars.items(): + components = calendar.get("components") or ["VEVENT"] + comp_xml = "".join(f'' for c in components) responses.append( self._response( f"/remote.php/dav/calendars/{USER}/{name}/", "" f"{calendar['label']}" "desc" + f"{comp_xml}" + "" '#ff0000' "ctag-1", ) @@ -546,6 +552,7 @@ def test_list_calendars(nextcloud): "description": "desc", "color": "#ff0000", "ctag": "ctag-1", + "components": ["VEVENT"], } ] @@ -809,6 +816,83 @@ def test_bridge_uses_only_calendar_when_unset(nextcloud): assert status == 200 and payload["calendar"] == "personal" +# ---- bridge: task-list resolution ---- + + +def test_bridge_tasklists_exclude_event_calendars_and_deck(nextcloud): + fake, base = nextcloud + fake.calendars["tasks"] = {"label": "Tasks", "components": ["VTODO"], "objects": {}} + fake.calendars["app-generated--deck--board-1"] = { + "label": "Deck: Board", + "components": ["VTODO"], + "objects": {}, + } + status, payload = bridge_for(base).handle_get("/tasklists", {}) + assert status == 200 + assert [c["name"] for c in payload["tasklists"]] == ["tasks"] + + +def test_bridge_create_task_uses_default_task_calendar(nextcloud): + fake, base = nextcloud + fake.calendars["tasks"] = {"label": "Tasks", "components": ["VTODO"], "objects": {}} + status, payload = bridge_for(base, default_task_calendar="tasks").handle_post( + "/tasks", {"summary": "Buy milk"} + ) + assert status == 200 + assert payload["ok"] is True and payload["calendar"] == "tasks" + + +def test_bridge_create_task_resolves_sole_task_list(nextcloud): + fake, base = nextcloud + fake.calendars["tasks"] = {"label": "Tasks", "components": ["VTODO"], "objects": {}} + # default_calendar points at an event-only calendar; a task must skip it. + status, payload = bridge_for(base, default_calendar="personal").handle_post( + "/tasks", {"summary": "Buy milk"} + ) + assert status == 200 and payload["calendar"] == "tasks" + + +def test_bridge_task_default_must_accept_vtodo(nextcloud): + fake, base = nextcloud + fake.calendars["tasks"] = {"label": "Tasks", "components": ["VTODO"], "objects": {}} + status, payload = bridge_for(base, default_task_calendar="personal").handle_post( + "/tasks", {"summary": "Buy milk"} + ) + assert status == 200 and payload["calendar"] == "tasks" + + +def test_bridge_task_prefers_vtodo_capable_default_calendar(nextcloud): + fake, base = nextcloud + fake.calendars["morgan"] = { + "label": "Morgan", + "components": ["VEVENT", "VTODO"], + "objects": {}, + } + fake.calendars["other"] = {"label": "Other", "components": ["VTODO"], "objects": {}} + status, payload = bridge_for(base, default_calendar="morgan").handle_post( + "/tasks", {"summary": "Buy milk"} + ) + assert status == 200 and payload["calendar"] == "morgan" + + +def test_bridge_create_task_rejects_event_calendar(nextcloud): + _fake, base = nextcloud + status, payload = bridge_for(base).handle_post( + "/tasks", {"calendar": "personal", "summary": "Buy milk"} + ) + assert status == 400 + assert "not a task list" in payload["error"] + + +def test_bridge_task_requires_calendar_when_ambiguous(nextcloud): + fake, base = nextcloud + fake.calendars["tasks-a"] = {"label": "Tasks A", "components": ["VTODO"], "objects": {}} + fake.calendars["tasks-b"] = {"label": "Tasks B", "components": ["VTODO"], "objects": {}} + status, payload = bridge_for(base).handle_post("/tasks", {"summary": "Buy milk"}) + assert status == 400 + assert "calendar is required" in payload["error"] + + def test_bridge_maps_nextcloud_error_to_502(nextcloud): _fake, base = nextcloud status, payload = bridge_for(base).handle_get("/files/read", {"path": ["/missing.txt"]})