From f9048dc514be82d1c5364d976ad658de7118b3d2 Mon Sep 17 00:00:00 2001 From: chengyongru Date: Wed, 23 Sep 2026 17:22:17 +0800 Subject: [PATCH] fix(linear): retain issue context and clarify OAuth diagnostics --- docs/guides/linear-agent.md | 50 +++++++++++++---- nanobot/agent/tools/mcp_oauth.py | 22 ++++++++ nanobot/channels/linear/runtime.py | 27 +++++++++- nanobot/channels/linear/tests/test_linear.py | 51 ++++++++++++++++++ tests/tools/test_mcp_oauth.py | 56 ++++++++++++++++++++ 5 files changed, 193 insertions(+), 13 deletions(-) diff --git a/docs/guides/linear-agent.md b/docs/guides/linear-agent.md index 4a675d8a6..884067b50 100644 --- a/docs/guides/linear-agent.md +++ b/docs/guides/linear-agent.md @@ -2,8 +2,8 @@ This guide takes you from an empty Linear channel configuration to a working @mention or delegated issue. The recommended path uses the nanobot WebUI and a -pre-filled Linear app manifest, so you do not need to enter callback URLs or -webhook subscriptions by hand. +pre-filled Linear app manifest. Review the generated URLs and subscriptions, +and confirm that webhook delivery is enabled before testing a task. > [!NOTE] > Linear's Agent APIs are currently a Developer Preview. Their schema may @@ -113,6 +113,18 @@ are intended for testing and generate a new hostname on restart. Update the nanobot public URL and the Linear app's Redirect URI and Webhook URL before continuing with a new hostname. +These settings must be updated together: + +| Setting | Value with the new tunnel hostname | +|---|---| +| nanobot **Public HTTPS URL** | `https://.trycloudflare.com` | +| Linear **Redirect URIs** | `https://.trycloudflare.com/linear/oauth/callback` | +| Linear **Webhooks → URL** | `https://.trycloudflare.com/linear/webhook` | + +Updating only the Redirect URI allows OAuth to succeed but leaves task events +pointing at the old tunnel. After updating the Webhook URL, also check its +**Delivery status**; a correct URL does not enable delivery by itself. + ## Recommended setup in the WebUI Keep `nanobot webui` running throughout the setup. @@ -123,15 +135,15 @@ Keep `nanobot webui` running throughout the setup. 2. Enter your public origin in **Public HTTPS URL**, for example `https://nanobot.example.com`. 3. Leave the three credential fields empty for now. -4. Wait for **Settings saved.** The **Create prefilled Linear app** button - becomes available after the partial configuration is saved automatically. +4. Wait for **Settings saved.**, then select **Create Linear app**. Selecting it + before entering an address shows a prompt and returns focus to the URL field. Saving a partial configuration at this point is expected. You will create the credentials in the next step. ### 2. Create the Linear app -1. Select **Create prefilled Linear app**. Sign in to the Linear workspace in +1. Select **Create Linear app**. Sign in to the Linear workspace in which you want to create the app. 2. Review the pre-filled form. It should describe a **private** app and contain: @@ -144,6 +156,16 @@ credentials in the next step. 3. Choose a short, recognizable app name and icon if you want to customize how nanobot appears in Linear. 4. Create the app. +5. In the app's **Webhooks** section, check **Delivery status**. If it is + **Disabled**, use the adjacent **…** menu to enable delivery. Confirm the URL + points to the current public origin and that **Events** includes + **Agent session events** (`AgentSessionEvent`). + +> [!IMPORTANT] +> OAuth authorization and webhook delivery are separate. Authorization can +> succeed while webhook delivery is disabled. In that state, Linear can create +> an Agent Session, but nanobot receives no task and Linear may report +> **Agent didn't start** or **nanobot failed to start**. Do not add a `Comment` webhook subscription. Linear delivers new @mentions and Agent Session follow-ups through `AgentSessionEvent`; subscribing to comments @@ -217,14 +239,17 @@ workspace should be able to invoke the agent. By default, reasoning is posted as Linear thought activities. Turn off **Show reasoning** under **Advanced** for a quieter session. Use **Configure Linear -tools** to open the Apps page and connect Linear MCP when prompts need to search, -edit, or transition issues. +MCP**, to the left of **Create Linear app**, to open Linear MCP's connection +settings when prompts need to search, edit, or transition issues. Pairing and +access guidance is available in the dialog's **Help** menu. ## Verify the setup The setup is complete when all of these checks pass: - **Settings → Channels → Linear** shows the channel as on with no runtime error. +- The Linear app's **Webhooks → Delivery status** is enabled, its URL uses the + current public origin, and **Events** includes **Agent session events**. - While the channel is running, opening `http://127.0.0.1:3979/linear/health` on the nanobot machine returns `{"ok":true}`. Use your configured host and port if you changed them. @@ -274,7 +299,8 @@ Webhook: https://nanobot.example.com/linear/webhook ``` Subscribe the webhook to exactly `AgentSessionEvent`, `PermissionChange`, and -`OAuthAuthorization`. Do not subscribe to `Comment`. The OAuth connection step +`OAuthAuthorization` and enable webhook delivery in the Linear app's settings. +Do not subscribe to `Comment`. The OAuth connection step in the WebUI is still required: it installs the app and stores the workspace-scoped access and refresh tokens. @@ -302,18 +328,20 @@ secret. | Symptom | What to check | |---|---| -| **Create prefilled Linear app** is disabled | Enter only the public HTTPS origin in **Public HTTPS URL** and wait for automatic saving to finish. If saving fails, correct the address or select **Retry**. | +| **Create Linear app** asks for a public address or waits for saving | Enter only the public HTTPS origin in **Public HTTPS URL** and wait for automatic saving to finish. If saving fails, correct the address or select **Retry**. | | Linear rejects the callback or webhook URL | Use a public `https://` hostname. Do not use HTTP, localhost, a private IP, or a path in **Public HTTPS URL**. | +| `Invalid redirect_uri parameter for the application` | In the Linear app matching nanobot's Client ID, set **Redirect URIs** to the current public origin plus `/linear/oauth/callback` (or your configured OAuth path). It must match the authorization request's `redirect_uri`. Save, cancel the pending authorization in nanobot, and start **Connect Linear** again. | | The tunnel URL changed | Update **Public HTTPS URL** in nanobot and the Redirect URI and Webhook URL in the Linear app, then start **Connect Linear** again. | | Public health returns 502 | Start **Connect Linear** or enable the connected channel. Check local health first, then confirm the tunnel or proxy targets the same listener port. | | OAuth opens but cannot finish | Keep `nanobot webui` running. Confirm the proxy forwards `/linear/oauth/callback` to the configured listen host and port. Then start **Connect Linear** again. | | OAuth finishes in Linear but nanobot keeps waiting | Keep the nanobot connection dialog open. Confirm the Redirect URI reaches the same nanobot process, and inspect gateway logs for callback or token exchange errors. | | The local health URL does not load | Start **Connect Linear** or enable the connected channel, then check the configured listen host and port. | -| An @mention gets no response | Confirm `AgentSessionEvent` is subscribed, the Client ID and signing secret match the same app, and the workspace authorization has not been revoked. Run `nanobot gateway logs` for the exact error. | +| **Agent didn't start**, **nanobot failed to start**, or a session stays on **Thinking…** without a response | First check **Webhooks → Delivery status** in the Linear app. If **Disabled**, enable it from **…**. Confirm the current Webhook URL and `AgentSessionEvent` subscription, then select **Retry** in the Linear session. OAuth success and a working `/linear/health` endpoint do not prove that Linear is sending events. | +| An @mention still gets no response with delivery enabled | Inspect **Webhook delivery failures** in the Linear app and run `nanobot gateway logs`. A 404 points to the webhook path; a 502 points to the listener or tunnel; a 401 can indicate a signing-secret mismatch or stale event timestamp. Confirm the Client ID and signing secret belong to the same app and the workspace authorization has not been revoked. | | The first @mention returns a pairing code | Approve it in the WebUI pairing dialog, then repeat the prompt in the same Agent Session. Alternatively, configure a narrow **Allowed Linear users** list. | | Normal comments do nothing | This is intentional. Start a task by @mentioning the app, or continue inside an existing Agent Session. | | Delegating an issue does not start a session | Reconnect the workspace so the installation grants `app:assignable`, then confirm the app can be selected as the issue delegate. | -| The agent can discuss an issue but cannot search or change it | Connect the Linear MCP app from **Configure Linear tools**. The native channel transports the conversation but does not add issue-management tools. | +| The agent can discuss an issue but cannot search or change it | Connect the Linear MCP app from **Configure Linear MCP**. The native channel transports the conversation but does not add issue-management tools. | | Authorization reports missing scopes | Reconnect from nanobot. Do not reuse an authorization URL that omits `read`, `write`, `app:mentionable`, or `app:assignable`. | For Linear's platform-side behavior, see the official diff --git a/nanobot/agent/tools/mcp_oauth.py b/nanobot/agent/tools/mcp_oauth.py index 2340e97ca..bcb21f413 100644 --- a/nanobot/agent/tools/mcp_oauth.py +++ b/nanobot/agent/tools/mcp_oauth.py @@ -10,6 +10,7 @@ from __future__ import annotations import asyncio import hashlib import json +import logging import math import os import secrets @@ -70,6 +71,24 @@ class MCPAuthorizationRequiredError(RuntimeError): """Raised when a background MCP connection needs interactive authorization.""" +class _OAuthAuthorizationLogFilter(logging.Filter): + """Keep the SDK's expected authorization interruption out of error tracebacks.""" + + def filter(self, record: logging.LogRecord) -> bool: + if ( + record.getMessage() == "OAuth flow error" + and record.exc_info + and isinstance(record.exc_info[1], MCPAuthorizationRequiredError) + ): + record.levelno = logging.INFO + record.levelname = "INFO" + record.msg = "MCP OAuth request paused at browser authorization" + record.args = () + record.exc_info = None + record.exc_text = None + return True + + @dataclass(frozen=True) class MCPOAuthHandlers: """Browser callbacks supplied only for a user-initiated OAuth attempt.""" @@ -815,6 +834,9 @@ async def create_mcp_oauth_auth( handlers: MCPOAuthHandlers | None = None, ) -> OAuthClientProvider: """Build the official MCP SDK OAuth provider for one configured server.""" + sdk_logger = logging.getLogger("mcp.client.auth.oauth2") + if not any(isinstance(f, _OAuthAuthorizationLogFilter) for f in sdk_logger.filters): + sdk_logger.addFilter(_OAuthAuthorizationLogFilter()) storage = MCPOAuthStorage(server_name, server_url) if handlers is not None: await storage.prepare_redirect_uri( diff --git a/nanobot/channels/linear/runtime.py b/nanobot/channels/linear/runtime.py index 30cde9279..ba4b727b5 100644 --- a/nanobot/channels/linear/runtime.py +++ b/nanobot/channels/linear/runtime.py @@ -375,7 +375,9 @@ class LinearChannel(BaseChannel): "linear": { "organization_id": organization_id, "agent_session_id": agent_session_id, - "issue_id": str(session.get("issueId") or ""), + "issue_id": str( + session.get("issueId") or _optional_object(session.get("issue")).get("id") or "" + ), "comment_id": str(session.get("commentId") or ""), "app_user_id": installation.app_user_id, "oauth_client_id": str(payload.get("oauthClientId") or ""), @@ -515,9 +517,30 @@ def _prompt_text( value: object if action == "created": value = payload.get("promptContext") + if context := _text_from_value(value): + return context + text = _text_from_value(session.get("comment")) else: value = activity.get("body") or activity.get("content") - return _text_from_value(value) or _text_from_value(session.get("comment")) + text = _text_from_value(value) or _text_from_value(session.get("comment")) + if not text or text.startswith("/"): + return text + context = _issue_context(session) + return "\n\n".join(part for part in (context, text) if part) + + +def _issue_context(session: dict[str, Any]) -> str: + """Include issue identity even when pairing prevented the initial turn.""" + issue = _optional_object(session.get("issue")) + fields: dict[str, str] = {} + for key, limit in (("id", 200), ("identifier", 200), ("title", 500), + ("url", 2048), ("description", 12000)): + value = issue.get(key) or (session.get("issueId") if key == "id" else None) + if isinstance(value, str) and value.strip(): + fields[key] = value.strip()[:limit] + if not fields: + return "" + return "Current Linear issue:\n" + json.dumps(fields, ensure_ascii=False) def _text_from_value(value: object) -> str: diff --git a/nanobot/channels/linear/tests/test_linear.py b/nanobot/channels/linear/tests/test_linear.py index 3806773f5..2aab69394 100644 --- a/nanobot/channels/linear/tests/test_linear.py +++ b/nanobot/channels/linear/tests/test_linear.py @@ -723,6 +723,57 @@ async def test_created_agent_session_publishes_only_the_mention_prompt(tmp_path: assert client.activities[0]["content"] == {"type": "thought", "body": "Starting…"} +@pytest.mark.asyncio +async def test_followup_after_pairing_includes_current_issue( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + channel, _ = _runtime(tmp_path) + monkeypatch.setattr(channel, "is_allowed", lambda _sender: False) + await channel._process_webhook("unpaired", _agent_webhook()) # pyright: ignore[reportPrivateUsage] + assert channel.bus.inbound.empty() + + monkeypatch.setattr(channel, "is_allowed", lambda _sender: True) + payload = _agent_webhook(action="prompted") + payload.pop("promptContext") + payload["agentSession"].pop("issueId") + payload["agentSession"]["issue"] = { + "id": "issue-1", "identifier": "CHE-6", "title": "Update documentation", + "description": "Document webhook delivery setup.", + "url": "https://linear.app/example/issue/CHE-6", + } + payload["agentActivity"]["body"] = "What is the current task?" + await channel._process_webhook("paired-followup", payload) # pyright: ignore[reportPrivateUsage] + + inbound = await channel.bus.consume_inbound() + assert "CHE-6" in inbound.content + assert "Update documentation" in inbound.content + assert "Document webhook delivery setup." in inbound.content + assert inbound.content.endswith("What is the current task?") + assert inbound.metadata["linear"]["issue_id"] == "issue-1" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("action", ["created", "prompted"]) +async def test_issue_id_remains_visible_without_structured_details( + tmp_path: Path, action: str, +) -> None: + channel, _ = _runtime(tmp_path) + payload = _agent_webhook(action=action) + payload.pop("promptContext") + await channel._process_webhook("issue-id-only", payload) # pyright: ignore[reportPrivateUsage] + inbound = await channel.bus.consume_inbound() + assert '"id": "issue-1"' in inbound.content + + +@pytest.mark.asyncio +async def test_followup_slash_command_is_not_wrapped_in_issue_context(tmp_path: Path) -> None: + channel, _ = _runtime(tmp_path) + payload = _agent_webhook(action="prompted") + payload["agentActivity"]["body"] = "/help" + await channel._process_webhook("command", payload) # pyright: ignore[reportPrivateUsage] + assert (await channel.bus.consume_inbound()).content == "/help" + + @pytest.mark.asyncio async def test_created_session_downloads_private_linear_attachments( tmp_path: Path, diff --git a/tests/tools/test_mcp_oauth.py b/tests/tools/test_mcp_oauth.py index ad43de521..8bc921fd6 100644 --- a/tests/tools/test_mcp_oauth.py +++ b/tests/tools/test_mcp_oauth.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio import inspect import json +import logging from urllib.parse import parse_qs, urlsplit import httpx @@ -262,6 +263,51 @@ async def test_background_authorization_request_clears_rejected_token( assert await storage.get_client_info() == client_info +@pytest.mark.asyncio +async def test_stale_authorization_preserves_new_credentials_without_error_log( + tmp_path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + _use_data_dir(tmp_path, monkeypatch) + server_url = "https://mcp.example.com/mcp" + storage = MCPOAuthStorage("linear", server_url) + await storage.set_tokens(OAuthToken(access_token="old-access")) + auth = await create_mcp_oauth_auth("linear", server_url) + + replacement = MCPOAuthStorage("linear", server_url) + await replacement.prepare_redirect_uri("http://127.0.0.1/auth/mcp/callback") + await replacement.set_tokens(OAuthToken(access_token="new-access")) + + sdk_logger = logging.getLogger("mcp.client.auth.oauth2") + with caplog.at_level(logging.INFO, logger=sdk_logger.name): + # The SDK logs and rethrows exceptions from the authorization callback. + with pytest.raises(MCPAuthorizationRequiredError): + try: + await auth.context.redirect_handler("https://auth.example.com/authorize") + except MCPAuthorizationRequiredError: + sdk_logger.exception("OAuth flow error") + raise + + tokens = await MCPOAuthStorage("linear", server_url).get_tokens() + assert tokens is not None and tokens.access_token == "new-access" + records = [record for record in caplog.records if record.name == sdk_logger.name] + assert len(records) == 1 + assert records[0].levelno == logging.INFO + assert records[0].exc_info is None + assert "OAuth flow error" not in caplog.text + + caplog.clear() + with pytest.raises(ValueError): + try: + raise ValueError("invalid OAuth response") + except ValueError: + sdk_logger.exception("OAuth flow error") + raise + assert caplog.records[0].levelno == logging.ERROR + assert caplog.records[0].exc_info is not None + + @pytest.mark.asyncio async def test_expired_token_refreshes_from_persisted_metadata_after_restart( tmp_path, @@ -584,10 +630,12 @@ async def test_stale_token_endpoint_is_rediscovered_once( async def test_unrecoverable_refresh_error_requires_authorization( tmp_path, monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, error: str, clears_client: bool, ) -> None: _use_data_dir(tmp_path, monkeypatch) + caplog.set_level(logging.INFO, logger="mcp.client.auth.oauth2") server_url = "https://mcp.example.com/mcp" storage = MCPOAuthStorage("linear", server_url) await storage.set_oauth_metadata(_oauth_metadata()) @@ -635,6 +683,14 @@ async def test_unrecoverable_refresh_error_requires_authorization( await client.get(server_url) reloaded = MCPOAuthStorage("linear", server_url) + interruptions = [ + record for record in caplog.records + if record.getMessage() == "MCP OAuth request paused at browser authorization" + ] + assert interruptions + assert all(record.levelno == logging.INFO and record.exc_info is None + for record in interruptions) + assert "OAuth flow error" not in caplog.text assert await reloaded.get_tokens() is None client_info = await reloaded.get_client_info() assert client_info is not None