diff --git a/docs/guides/linear-agent.md b/docs/guides/linear-agent.md
index 3121b0492..4a675d8a6 100644
--- a/docs/guides/linear-agent.md
+++ b/docs/guides/linear-agent.md
@@ -1,7 +1,7 @@
# Connect nanobot as a Native Linear Agent
This guide takes you from an empty Linear channel configuration to a working
-@mention in an issue. The recommended path uses the nanobot WebUI and a
+@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.
@@ -11,21 +11,31 @@ webhook subscriptions by hand.
## What this channel does
-- A new task starts only when someone explicitly @mentions the installed app.
+- A new task starts when someone explicitly @mentions the installed app or
+ delegates an issue to it.
- An ordinary issue comment does not invoke nanobot.
- A follow-up inside the existing Agent Session continues the same nanobot
session without another @mention.
-- Linear's stop control cancels the active nanobot turn.
+- Linear's stop control asks nanobot to cancel the active turn without requiring
+ the sender to complete pairing first. An activity already delivered to Linear
+ cannot be recalled.
- nanobot reports its acknowledgement, tool activity, reasoning, and final
answer as native Linear Agent Activities.
+- Button choices are sent as Linear selection activities, and local outbound
+ files are uploaded to Linear before they are linked in the response.
+- Private `uploads.linear.app` links in the session prompt are downloaded with
+ the workspace OAuth token and passed to nanobot as inbound media after access
+ checks. A prompt can import up to 10 attachments and 40 MB in total; skipped
+ or unavailable files are called out in the prompt instead of failing silently.
-The OAuth request includes `app:mentionable` and deliberately excludes
-`app:assignable`. Do not add `app:assignable` if every new task must start with
-an @mention.
+The OAuth request includes `app:mentionable` and `app:assignable`, in addition
+to `read` and `write`. Existing workspace installations must be reconnected to
+grant `app:assignable`.
-Linear MCP is optional. Add it when the agent also needs tools for searching or
-changing Linear issues. MCP does not replace this channel's OAuth installation,
-webhook, or Agent Session transport.
+The native channel owns Agent Session transport. Connect the Linear MCP app when
+the agent also needs tools for searching or changing Linear issues; OAuth scopes
+on the channel do not expose those actions as nanobot tools. MCP does not replace
+the channel's OAuth installation, webhook, or Agent Session transport.
## Before you start
@@ -169,11 +179,14 @@ only in the nanobot configuration and the Linear application settings.
1. Select **Connect Linear**.
2. Open the displayed authorization link, or scan the QR code.
3. Choose the workspace and approve the installation as a workspace admin.
-4. Return to nanobot and wait for the **Connected** badge.
+4. Return to nanobot and wait for the **Channel running** badge. The
+ **Authorized workspaces** section lists the workspace separately.
nanobot enables the channel automatically after authorization. The gateway must
remain running so Linear can deliver webhooks. Reopening the panel shows the
-running connection immediately, without another authorization attempt.
+running channel and its authorized workspaces without another authorization
+attempt. Use **Disconnect** on a workspace to revoke its Linear OAuth tokens and
+remove the local installation; removing the last workspace also disables the channel.
To replace an authorization, select
**Connect another workspace** and authorize the same workspace again.
@@ -190,6 +203,7 @@ refreshes each workspace installation separately.
@nanobot summarize the likely cause and suggest the next diagnostic step
```
+ You can instead delegate the issue to the app to start the Agent Session.
3. Open the Agent Session. You should first see a starting acknowledgement,
followed by agent activity and a final response.
4. Send a follow-up inside that Agent Session. You do not need to @mention the
@@ -201,6 +215,11 @@ prompt in the same Agent Session. For a static allowlist, enter Linear user IDs
in **Allowed Linear users**. Enter `*` only if every member of every connected
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.
+
## Verify the setup
The setup is complete when all of these checks pass:
@@ -214,6 +233,7 @@ The setup is complete when all of these checks pass:
tunnel or proxy reachability; the task checks below verify the Linear connection.
- A new comment with an explicit @mention creates an Agent Session and receives
a response.
+- Delegating an issue to the app creates an Agent Session and receives a response.
- A normal issue comment without an @mention does nothing.
- A follow-up inside the Agent Session receives a response without another
@mention.
@@ -239,7 +259,8 @@ Merge this section into `~/.nanobot/config.json`:
"port": 3979,
"webhookPath": "/linear/webhook",
"oauthCallbackPath": "/linear/oauth/callback",
- "allowFrom": ["YOUR_LINEAR_USER_ID"]
+ "allowFrom": ["YOUR_LINEAR_USER_ID"],
+ "showReasoning": true
}
}
}
@@ -291,8 +312,9 @@ secret.
| 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. |
| 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. |
-| Issues can be delegated to the app without an @mention | Remove `app:assignable`, reconnect the workspace, and use nanobot's built-in OAuth flow, which requests only `read`, `write`, and `app:mentionable`. |
-| Authorization reports missing scopes | Reconnect from nanobot. Do not reuse an authorization URL that omits `read`, `write`, or `app:mentionable`. |
+| 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. |
+| 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
[Agents guide](https://linear.app/developers/agents),
diff --git a/nanobot/channels/linear/client.py b/nanobot/channels/linear/client.py
index 543ac4498..03498c3e7 100644
--- a/nanobot/channels/linear/client.py
+++ b/nanobot/channels/linear/client.py
@@ -3,7 +3,9 @@
from __future__ import annotations
import asyncio
+import mimetypes
import time
+from pathlib import Path
from typing import Any, cast
import httpx
@@ -11,9 +13,13 @@ import httpx
from nanobot.channels.linear.config import LinearConfig
from nanobot.channels.linear.oauth import LINEAR_SCOPES
from nanobot.channels.linear.state import LinearInstallation, LinearStateStore
+from nanobot.security.network import validate_url_target
LINEAR_GRAPHQL_URL = "https://api.linear.app/graphql"
LINEAR_TOKEN_URL = "https://api.linear.app/oauth/token"
+LINEAR_REVOKE_URL = "https://api.linear.app/oauth/revoke"
+MAX_UPLOAD_BYTES = 40 * 1024 * 1024
+MAX_DOWNLOAD_BYTES = 40 * 1024 * 1024
class LinearApiError(RuntimeError):
@@ -110,7 +116,19 @@ class LinearClient:
*,
activity_id: str,
ephemeral: bool = False,
+ signal: str | None = None,
+ signal_metadata: dict[str, Any] | None = None,
) -> None:
+ activity_input: dict[str, Any] = {
+ "id": activity_id,
+ "agentSessionId": agent_session_id,
+ "content": content,
+ "ephemeral": ephemeral,
+ }
+ if signal:
+ activity_input["signal"] = signal
+ if signal_metadata:
+ activity_input["signalMetadata"] = signal_metadata
data = await self.graphql(
organization_id,
"""
@@ -118,19 +136,174 @@ class LinearClient:
agentActivityCreate(input: $input) { success agentActivity { id } }
}
""",
- {
- "input": {
- "id": activity_id,
- "agentSessionId": agent_session_id,
- "content": content,
- "ephemeral": ephemeral,
- }
- },
+ {"input": activity_input},
)
result = _required_mapping(data, "agentActivityCreate")
if result.get("success") is not True:
raise LinearApiError("Linear did not accept the agent activity")
+ async def revoke_installation(self, installation: LinearInstallation) -> None:
+ """Revoke both tokens for an installation before removing local state."""
+ tokens = (
+ (installation.access_token, "access_token"),
+ (installation.refresh_token, "refresh_token"),
+ )
+ revoked: set[str] = set()
+ for token, token_type in tokens:
+ if not token or token in revoked:
+ continue
+ revoked.add(token)
+ try:
+ response = await self._http.post(
+ LINEAR_REVOKE_URL,
+ data={"token": token, "token_type_hint": token_type},
+ )
+ except httpx.HTTPError as exc:
+ raise LinearApiError(
+ f"Linear authorization revocation failed: {exc}", retryable=True
+ ) from exc
+ # Linear returns 400/401 for tokens that are already unusable. In
+ # either case there is no remaining credential for nanobot to keep.
+ if response.status_code not in {200, 400, 401}:
+ raise LinearApiError(
+ f"Linear authorization revocation failed with HTTP {response.status_code}",
+ retryable=response.status_code == 429 or response.status_code >= 500,
+ retry_after=_retry_after_seconds(response),
+ )
+
+ async def upload_file(self, organization_id: str, file_path: Path) -> str:
+ """Upload a local outbound attachment and return its Linear asset URL."""
+ try:
+ size = file_path.stat().st_size
+ except OSError as exc:
+ raise LinearApiError(f"Unable to read attachment {file_path.name}: {exc}") from exc
+ if not file_path.is_file():
+ raise LinearApiError(f"Attachment is not a file: {file_path.name}")
+ if size > MAX_UPLOAD_BYTES:
+ raise LinearApiError(
+ f"Attachment {file_path.name} is larger than the 40 MB Linear upload limit"
+ )
+ content_type = mimetypes.guess_type(file_path.name)[0] or "application/octet-stream"
+ data = await self.graphql(
+ organization_id,
+ """
+ mutation NanobotFileUpload($filename: String!, $contentType: String!, $size: Int!) {
+ fileUpload(filename: $filename, contentType: $contentType, size: $size) {
+ success
+ uploadFile { uploadUrl assetUrl headers { key value } }
+ }
+ }
+ """,
+ {"filename": file_path.name, "contentType": content_type, "size": size},
+ )
+ result = _required_mapping(data, "fileUpload")
+ if result.get("success") is not True:
+ raise LinearApiError("Linear did not create an attachment upload")
+ upload = _required_mapping(result, "uploadFile")
+ upload_url = _required_string(upload, "uploadUrl")
+ asset_url = _required_string(upload, "assetUrl")
+ safe, error = await asyncio.to_thread(validate_url_target, upload_url)
+ if not safe:
+ raise LinearApiError(f"Linear returned an unsafe upload URL: {error}")
+ raw_headers = upload.get("headers")
+ headers: dict[str, str] = {}
+ if isinstance(raw_headers, list):
+ for item in cast(list[object], raw_headers):
+ if not isinstance(item, dict):
+ continue
+ header = cast(dict[str, object], item)
+ key = header.get("key")
+ value = header.get("value")
+ if isinstance(key, str) and isinstance(value, str):
+ headers[key] = value
+ if not any(key.lower() == "content-type" for key in headers):
+ headers["Content-Type"] = content_type
+ if not any(key.lower() == "cache-control" for key in headers):
+ headers["Cache-Control"] = "public, max-age=31536000"
+ try:
+ content = await asyncio.to_thread(file_path.read_bytes)
+ response = await self._http.put(upload_url, headers=headers, content=content)
+ except (OSError, httpx.HTTPError) as exc:
+ raise LinearApiError(
+ f"Linear attachment upload failed: {exc}",
+ retryable=isinstance(exc, httpx.HTTPError),
+ ) from exc
+ if response.is_error:
+ raise LinearApiError(
+ f"Linear attachment upload failed with HTTP {response.status_code}",
+ retryable=response.status_code == 429 or response.status_code >= 500,
+ retry_after=_retry_after_seconds(response),
+ )
+ return asset_url
+
+ async def download_file(
+ self,
+ organization_id: str,
+ url: str,
+ *,
+ max_bytes: int = MAX_DOWNLOAD_BYTES,
+ ) -> tuple[bytes, str]:
+ """Download one authenticated Linear storage object with a bounded size."""
+ if max_bytes <= 0 or max_bytes > MAX_DOWNLOAD_BYTES:
+ raise LinearApiError("Invalid Linear attachment download limit")
+ parsed = httpx.URL(url)
+ if parsed.scheme != "https" or parsed.host != "uploads.linear.app":
+ raise LinearApiError("Linear attachment URL must use https://uploads.linear.app")
+ installation = await self._fresh_installation(organization_id)
+ try:
+ return await self._download_file_with_token(
+ url, installation.access_token, max_bytes=max_bytes
+ )
+ except LinearApiError as exc:
+ if "authentication" not in str(exc).lower():
+ raise
+ installation = await self._refresh(organization_id, force=True)
+ return await self._download_file_with_token(
+ url, installation.access_token, max_bytes=max_bytes
+ )
+
+ async def _download_file_with_token(
+ self,
+ url: str,
+ access_token: str,
+ *,
+ max_bytes: int,
+ ) -> tuple[bytes, str]:
+ try:
+ async with self._http.stream(
+ "GET",
+ url,
+ headers={"Authorization": f"Bearer {access_token}"},
+ ) as response:
+ if response.status_code in {401, 403}:
+ raise LinearApiError("Linear attachment authentication failed")
+ if response.is_error:
+ raise LinearApiError(
+ f"Linear attachment download failed with HTTP {response.status_code}",
+ retryable=response.status_code == 429 or response.status_code >= 500,
+ retry_after=_retry_after_seconds(response),
+ )
+ raw_length = response.headers.get("Content-Length", "")
+ try:
+ content_length = int(raw_length)
+ except ValueError:
+ content_length = -1
+ if content_length > max_bytes:
+ raise LinearApiError("Linear attachment exceeds the download budget")
+ chunks: list[bytes] = []
+ size = 0
+ async for chunk in response.aiter_bytes():
+ size += len(chunk)
+ if size > max_bytes:
+ raise LinearApiError("Linear attachment exceeds the download budget")
+ chunks.append(chunk)
+ content_type = response.headers.get("Content-Type", "application/octet-stream")
+ return b"".join(chunks), content_type.split(";", 1)[0].strip()
+ except httpx.HTTPError as exc:
+ raise LinearApiError(
+ f"Linear attachment download failed: {exc}", retryable=True
+ ) from exc
+
async def _fresh_installation(self, organization_id: str) -> LinearInstallation:
installation = self.state.installation(organization_id)
if installation is None:
diff --git a/nanobot/channels/linear/config.py b/nanobot/channels/linear/config.py
index 9ab43a402..6b34a6e09 100644
--- a/nanobot/channels/linear/config.py
+++ b/nanobot/channels/linear/config.py
@@ -27,6 +27,7 @@ class LinearConfig(Base):
webhook_path: str = DEFAULT_WEBHOOK_PATH
oauth_callback_path: str = DEFAULT_OAUTH_CALLBACK_PATH
allow_from: list[str] = Field(default_factory=list)
+ show_reasoning: bool = True
@field_validator("webhook_path", "oauth_callback_path")
@classmethod
diff --git a/nanobot/channels/linear/connect.py b/nanobot/channels/linear/connect.py
index e13ebf2a8..72ac6ccde 100644
--- a/nanobot/channels/linear/connect.py
+++ b/nanobot/channels/linear/connect.py
@@ -12,6 +12,7 @@ from nanobot.channels.linear.client import LinearApiError, LinearClient
from nanobot.channels.linear.config import LinearConfig
from nanobot.channels.linear.oauth import (
FLOW_TTL_SECONDS,
+ LINEAR_SCOPES,
OAUTH_FLOWS,
LinearOAuthFlow,
authorization_url,
@@ -28,7 +29,7 @@ class LinearConnectSession:
state: LinearStateStore
server: LinearServerLease
completion_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
- result: dict[str, str] | None = None
+ result: dict[str, Any] | None = None
class LinearConnectStore:
@@ -40,6 +41,16 @@ class LinearConnectStore:
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
await self._cleanup()
if action == "start":
+ operation = (query_first(query, "operation") or "connect").strip().lower()
+ if operation == "inspect":
+ return self.inspect()
+ if operation == "disconnect":
+ organization_id = (query_first(query, "organization_id") or "").strip()
+ if not organization_id:
+ raise ChannelConnectError("missing Linear workspace")
+ return await self.disconnect(organization_id)
+ if operation != "connect":
+ raise ChannelConnectError(f"unsupported Linear connect operation: {operation}")
return await self.start(force=_query_bool(query, "force"))
session_id = (query_first(query, "session_id") or "").strip()
if not session_id:
@@ -62,6 +73,7 @@ class LinearConnectStore:
"session_id": "",
"status": "succeeded",
"message": "Linear is already connected. Use reconnect to add or replace a workspace.",
+ "installations": _installation_payloads(state, config.client_id),
}
flow = OAUTH_FLOWS.create()
try:
@@ -134,6 +146,7 @@ class LinearConnectStore:
"message": "Linear is connected.",
"organization_id": installation.organization_id,
"organization_name": installation.organization_name,
+ "installations": _installation_payloads(session.state, session.config.client_id),
}
# A browser may miss the first successful poll while switching tabs.
# Retain its result until the session expires, but release the callback listener.
@@ -148,6 +161,51 @@ class LinearConnectStore:
await self._close_session(session_id)
return _terminal(session_id, "cancelled", "Linear authorization cancelled.")
+ def inspect(self) -> dict[str, Any]:
+ config = _load_linear_config()
+ state = LinearStateStore()
+ installations = (
+ _installation_payloads(state, config.client_id) if config.client_id else []
+ )
+ return {
+ "session_id": "",
+ "status": "inspected",
+ "message": (
+ f"{len(installations)} Linear workspace(s) authorized."
+ if installations
+ else "No Linear workspaces are authorized."
+ ),
+ "installations": installations,
+ "webhook_url": config.webhook_url if config.public_base_url else "",
+ "redirect_uri": config.redirect_uri if config.public_base_url else "",
+ }
+
+ async def disconnect(self, organization_id: str) -> dict[str, Any]:
+ config = _load_linear_config()
+ state = LinearStateStore()
+ installation = state.installation(organization_id)
+ if installation is None or installation.oauth_client_id != config.client_id:
+ raise ChannelConnectError("Linear workspace is not connected", status=404)
+ client = LinearClient(config, state)
+ try:
+ await client.revoke_installation(installation)
+ except LinearApiError as exc:
+ raise ChannelConnectError(
+ f"Unable to revoke the Linear workspace authorization: {exc}",
+ status=502,
+ ) from exc
+ finally:
+ await client.close()
+ state.delete_installation(organization_id)
+ installations = _installation_payloads(state, config.client_id)
+ return {
+ "session_id": "",
+ "status": "disconnected",
+ "message": f"Disconnected {installation.organization_name or organization_id}.",
+ "organization_id": organization_id,
+ "installations": installations,
+ }
+
async def _cleanup(self) -> None:
expired = [
session_id
@@ -180,3 +238,27 @@ def _query_bool(query: QueryParams, key: str) -> bool:
def _terminal(session_id: str, status: str, message: str) -> dict[str, Any]:
return {"session_id": session_id, "status": status, "message": message}
+
+
+def _installation_payloads(
+ state: LinearStateStore,
+ oauth_client_id: str | None,
+) -> list[dict[str, Any]]:
+ now = time.time()
+ payloads: list[dict[str, Any]] = []
+ for installation in state.list_installations(oauth_client_id):
+ missing_scopes = sorted(set(LINEAR_SCOPES) - set(installation.scope))
+ payloads.append({
+ "organization_id": installation.organization_id,
+ "organization_name": installation.organization_name,
+ "scopes": list(installation.scope),
+ "authorization_status": (
+ "missing_scopes"
+ if missing_scopes
+ else "refresh_required"
+ if installation.expires_at <= now + 60
+ else "authorized"
+ ),
+ "missing_scopes": missing_scopes,
+ })
+ return payloads
diff --git a/nanobot/channels/linear/manifest.py b/nanobot/channels/linear/manifest.py
index dafd71a48..b26649493 100644
--- a/nanobot/channels/linear/manifest.py
+++ b/nanobot/channels/linear/manifest.py
@@ -18,6 +18,7 @@ SETUP_SPEC = ChannelSetupSpec(
"webhookPath": field(default="/linear/webhook"),
"oauthCallbackPath": field(default="/linear/oauth/callback"),
"allowFrom": field("list"),
+ "showReasoning": field("bool", default=True),
},
required=required_fields(
"clientId",
diff --git a/nanobot/channels/linear/oauth.py b/nanobot/channels/linear/oauth.py
index d54e3e33b..0c9b0601d 100644
--- a/nanobot/channels/linear/oauth.py
+++ b/nanobot/channels/linear/oauth.py
@@ -13,7 +13,7 @@ from urllib.parse import urlencode
from nanobot.channels.linear.config import LinearConfig
LINEAR_AUTHORIZE_URL = "https://linear.app/oauth/authorize"
-LINEAR_SCOPES = ("read", "write", "app:mentionable")
+LINEAR_SCOPES = ("read", "write", "app:mentionable", "app:assignable")
FLOW_TTL_SECONDS = 600
diff --git a/nanobot/channels/linear/runtime.py b/nanobot/channels/linear/runtime.py
index 74e56a7a5..30cde9279 100644
--- a/nanobot/channels/linear/runtime.py
+++ b/nanobot/channels/linear/runtime.py
@@ -4,18 +4,27 @@ from __future__ import annotations
import asyncio
import json
+import mimetypes
+import re
import uuid
from contextlib import suppress
+from pathlib import Path
from typing import Any, cast
+from urllib.parse import urlparse
-from nanobot.bus.events import OutboundMessage
+from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent, RetryWaitEvent
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
-from nanobot.channels.linear.client import LinearApiError, LinearClient
+from nanobot.channels.linear.client import MAX_DOWNLOAD_BYTES, LinearApiError, LinearClient
from nanobot.channels.linear.config import LinearConfig
from nanobot.channels.linear.server import LinearServerLease, acquire_http_server
from nanobot.channels.linear.state import LinearStateStore, QueuedWebhook
+from nanobot.config.paths import get_media_dir
+from nanobot.security.network import validate_url_target
+from nanobot.utils.helpers import safe_filename
+
+MAX_PROMPT_ATTACHMENTS = 10
class LinearPayloadError(ValueError):
@@ -127,15 +136,64 @@ class LinearChannel(BaseChannel):
ephemeral=True,
)
return
- if not msg.content:
+ body = msg.content
+ if msg.media:
+ attachments = await self._attachment_markdown(msg)
+ body = "\n\n".join(part for part in (body, *attachments) if part)
+ if msg.buttons:
+ options = [label.strip() for row in msg.buttons for label in row if label.strip()]
+ if options:
+ await self._create_activity(
+ msg.chat_id,
+ msg.metadata,
+ {"type": "elicitation", "body": body or "Choose an option."},
+ key="response:select",
+ signal="select",
+ signal_metadata={
+ "options": [{"label": label, "value": label} for label in options]
+ },
+ )
+ return
+ if not body:
return
await self._create_activity(
msg.chat_id,
msg.metadata,
- {"type": "response", "body": msg.content},
+ {"type": "response", "body": body},
key="response",
)
+ async def _attachment_markdown(self, msg: OutboundMessage) -> list[str]:
+ client = self._client
+ if client is None:
+ raise RuntimeError("Linear HTTP client is not initialized")
+ route = _linear_route(msg.metadata) or self._routes.get(msg.chat_id)
+ if route is None:
+ raise RuntimeError("Linear outbound message is missing route metadata")
+ organization_id = _required_text(route, "organization_id")
+ rendered: list[str] = []
+ for media_ref in msg.media:
+ parsed = urlparse(media_ref)
+ try:
+ if parsed.scheme in {"http", "https"}:
+ safe, error = await asyncio.to_thread(validate_url_target, media_ref)
+ if not safe:
+ raise LinearApiError(f"Unsafe attachment URL: {error}")
+ asset_url = media_ref
+ name = Path(parsed.path).name or "attachment"
+ else:
+ path = Path(media_ref).expanduser()
+ asset_url = await client.upload_file(organization_id, path)
+ name = path.name or "attachment"
+ label = _markdown_label(name)
+ content_type = mimetypes.guess_type(name)[0] or ""
+ prefix = "!" if content_type.startswith("image/") else ""
+ rendered.append(f"{prefix}[{label}]({_markdown_target(asset_url)})")
+ except (LinearApiError, OSError, ValueError):
+ self.logger.exception("Failed to attach {} to Linear response", media_ref)
+ rendered.append(f"[Unable to attach {_markdown_label(Path(media_ref).name)}]")
+ return rendered
+
async def send_reasoning_delta(
self,
chat_id: str,
@@ -144,6 +202,8 @@ class LinearChannel(BaseChannel):
*,
stream_id: str | None = None,
) -> None:
+ if not self.config.show_reasoning:
+ return
key = (chat_id, stream_id or "default")
self._reasoning.setdefault(key, []).append(delta)
@@ -156,7 +216,7 @@ class LinearChannel(BaseChannel):
) -> None:
key = (chat_id, stream_id or "default")
body = "".join(self._reasoning.pop(key, [])).strip()
- if body:
+ if body and self.config.show_reasoning:
await self._create_activity(
chat_id,
metadata or {},
@@ -190,21 +250,24 @@ class LinearChannel(BaseChannel):
phase = str(item.get("phase") or "start")
call_id = str(item.get("call_id") or uuid.uuid4())
arguments = item.get("arguments")
- parameter = json.dumps(arguments, ensure_ascii=False, default=str)[:2000]
+ parameter = json.dumps(
+ _redact_sensitive(arguments), ensure_ascii=False, default=str
+ )[:2000]
content: dict[str, Any] = {
"type": "action",
- "action": name,
+ "action": _display_tool_name(name),
"parameter": parameter,
}
if phase == "end":
content["result"] = _compact_result(item.get("result"))
elif phase == "error":
- content["result"] = str(item.get("error") or "Tool execution failed")
+ content["result"] = _compact_result(item.get("error") or "Tool execution failed")
await self._create_activity(
msg.chat_id,
msg.metadata,
content,
key=f"tool:{call_id}:{phase}",
+ ephemeral=phase == "start",
)
async def _create_activity(
@@ -215,6 +278,8 @@ class LinearChannel(BaseChannel):
*,
key: str,
ephemeral: bool = False,
+ signal: str | None = None,
+ signal_metadata: dict[str, Any] | None = None,
) -> None:
client = self._client
if client is None:
@@ -237,6 +302,8 @@ class LinearChannel(BaseChannel):
content,
activity_id=activity_id,
ephemeral=ephemeral,
+ signal=signal,
+ signal_metadata=signal_metadata,
)
async def _process_queued_webhook(self, event: QueuedWebhook) -> None:
@@ -320,22 +387,94 @@ class LinearChannel(BaseChannel):
self._routes[agent_session_id] = cast(dict[str, Any], metadata["linear"])
if len(self._routes) > 1000:
self._routes.pop(next(iter(self._routes)))
- await self._create_activity(
- agent_session_id,
- metadata,
- {"type": "thought", "body": "Starting…"},
- key="accepted",
- ephemeral=True,
- )
+ if signal == "stop":
+ await self.bus.publish_inbound(
+ InboundMessage(
+ channel=self.name,
+ sender_id=sender_id,
+ chat_id=agent_session_id,
+ content=content,
+ metadata=metadata,
+ session_key_override=f"linear:{organization_id}:{agent_session_id}",
+ )
+ )
+ return
+ media: list[str] = []
+ if self.is_allowed(sender_id):
+ media, attachment_warnings = await self._download_prompt_media(
+ organization_id, content, delivery_id
+ )
+ if attachment_warnings:
+ content = "\n\n".join((content, *attachment_warnings))
+ await self._create_activity(
+ agent_session_id,
+ metadata,
+ {"type": "thought", "body": "Starting…"},
+ key="accepted",
+ ephemeral=True,
+ )
await self._handle_message(
sender_id=sender_id,
chat_id=agent_session_id,
content=content,
+ media=media,
metadata=metadata,
session_key=f"linear:{organization_id}:{agent_session_id}",
is_dm=True,
)
+ async def _download_prompt_media(
+ self,
+ organization_id: str,
+ content: str,
+ delivery_id: str,
+ ) -> tuple[list[str], list[str]]:
+ client = self._client
+ if client is None:
+ raise RuntimeError("Linear HTTP client is not initialized")
+ labeled: dict[str, str] = {
+ url: label.strip()
+ for label, url in cast(
+ list[tuple[str, str]], _LINEAR_MARKDOWN_UPLOAD_RE.findall(content)
+ )
+ }
+ urls = list(dict.fromkeys(cast(list[str], _LINEAR_UPLOAD_URL_RE.findall(content))))
+ warnings: list[str] = []
+ if len(urls) > MAX_PROMPT_ATTACHMENTS:
+ self.logger.warning(
+ "Linear prompt {} contains {} attachments; processing the first {}",
+ delivery_id,
+ len(urls),
+ MAX_PROMPT_ATTACHMENTS,
+ )
+ warnings.append(
+ f"[Only the first {MAX_PROMPT_ATTACHMENTS} attachments were accepted.]"
+ )
+ urls = urls[:MAX_PROMPT_ATTACHMENTS]
+ media: list[str] = []
+ remaining_bytes = MAX_DOWNLOAD_BYTES
+ for index, raw_url in enumerate(urls):
+ if remaining_bytes <= 0:
+ warnings.append("[Additional attachments were skipped: 40 MB total limit reached.]")
+ break
+ url = raw_url.rstrip(".,;:!?")
+ try:
+ body, content_type = await client.download_file(
+ organization_id, url, max_bytes=remaining_bytes
+ )
+ remaining_bytes -= len(body)
+ name = _download_filename(url, labeled.get(url, ""), content_type, index)
+ destination = get_media_dir("linear") / safe_filename(
+ f"{delivery_id}_{name}"
+ )
+ await asyncio.to_thread(destination.write_bytes, body)
+ media.append(str(destination))
+ except (LinearApiError, OSError, ValueError):
+ self.logger.exception("Failed to download Linear attachment {}", url)
+ label = labeled.get(url, "") or Path(urlparse(url).path).name or "attachment"
+ warnings.append(f"[Attachment unavailable: {safe_filename(label)}]")
+ return media, warnings
+
def _process_lifecycle_event(self, payload: dict[str, Any]) -> None:
action = str(payload.get("action") or "").lower()
organization_id = str(payload.get("organizationId") or "").strip()
@@ -404,7 +543,97 @@ def _signal_text(signal: str, activity: dict[str, Any]) -> str:
def _compact_result(value: object) -> str:
if isinstance(value, str):
- return value[:2000]
+ with suppress(json.JSONDecodeError):
+ parsed = cast(object, json.loads(value))
+ if isinstance(parsed, dict | list):
+ value = cast(object, parsed)
+ value = _redact_sensitive(cast(object, value))
+ if isinstance(value, str):
+ return _redact_sensitive_text(value)[:2000]
with suppress(TypeError, ValueError):
return json.dumps(value, ensure_ascii=False, default=str)[:2000]
return str(value)[:2000]
+
+
+_SENSITIVE_KEY_PARTS = (
+ "api_key",
+ "apikey",
+ "authorization",
+ "cookie",
+ "credential",
+ "password",
+ "secret",
+ "token",
+)
+
+_LINEAR_MARKDOWN_UPLOAD_RE = re.compile(
+ r"!?\[([^\]]*)\]\((https://uploads\.linear\.app/[^)\s]+)\)"
+)
+_LINEAR_UPLOAD_URL_RE = re.compile(r"https://uploads\.linear\.app/[^\s<>\"')\]]+")
+_SENSITIVE_TEXT_PATTERNS = (
+ re.compile(r"(?i)\b(authorization\s*[:=]\s*(?:bearer\s+)?)[^\s,;]+"),
+ re.compile(r"(?i)\b(bearer\s+)[A-Za-z0-9._~+/=-]+"),
+ re.compile(
+ r"(?i)(\b(?:[a-z0-9]+[._-])*(?:api[._ -]?key|cookie|credential|password|secret|token)"
+ r"\s*[:=]\s*)[^\s,;]+"
+ ),
+)
+
+
+def _redact_sensitive(value: object) -> object:
+ if isinstance(value, str):
+ return _redact_sensitive_text(value)
+ if isinstance(value, dict):
+ redacted: dict[str, object] = {}
+ for raw_key, item in cast(dict[object, object], value).items():
+ key = str(raw_key)
+ normalized = key.lower().replace("-", "_")
+ redacted[key] = (
+ "[redacted]"
+ if any(part in normalized for part in _SENSITIVE_KEY_PARTS)
+ else _redact_sensitive(item)
+ )
+ return redacted
+ if isinstance(value, list):
+ return [_redact_sensitive(item) for item in cast(list[object], value)]
+ if isinstance(value, tuple):
+ return tuple(_redact_sensitive(item) for item in cast(tuple[object, ...], value))
+ return value
+
+
+def _redact_sensitive_text(value: str) -> str:
+ for pattern in _SENSITIVE_TEXT_PATTERNS:
+ value = pattern.sub(r"\1[redacted]", value)
+ return value
+
+
+def _display_tool_name(value: str) -> str:
+ words = value.replace("-", " ").replace("_", " ").split()
+ return " ".join(word.upper() if word.lower() in {"api", "mcp", "url"} else word.capitalize()
+ for word in words) or "Tool"
+
+
+def _markdown_label(value: str) -> str:
+ return (value or "attachment").replace("\\", "\\\\").replace("[", "\\[").replace("]", "\\]")
+
+
+def _markdown_target(value: str) -> str:
+ return (
+ value.replace("\\", "%5C")
+ .replace(" ", "%20")
+ .replace("(", "%28")
+ .replace(")", "%29")
+ .replace("\r", "%0D")
+ .replace("\n", "%0A")
+ )
+
+
+def _download_filename(url: str, label: str, content_type: str, index: int) -> str:
+ candidate = safe_filename(Path(label).name) if label else ""
+ if not candidate:
+ candidate = safe_filename(Path(urlparse(url).path).name)
+ if not candidate:
+ candidate = f"attachment-{index + 1}"
+ if not Path(candidate).suffix:
+ candidate += mimetypes.guess_extension(content_type) or ".bin"
+ return candidate[:180]
diff --git a/nanobot/channels/linear/server.py b/nanobot/channels/linear/server.py
index 9e00608e9..836a4009b 100644
--- a/nanobot/channels/linear/server.py
+++ b/nanobot/channels/linear/server.py
@@ -136,13 +136,13 @@ class SharedLinearHttpServer:
code = _query_first(query, "code")
error = _query_first(query, "error")
if not state or (not code and not error):
- _handler_response(handler, HTTPStatus.BAD_REQUEST, _oauth_html(False))
+ _handler_response(handler, HTTPStatus.BAD_REQUEST, _oauth_html("invalid"))
return
completed = OAUTH_FLOWS.complete(state, code=code, error=error)
_handler_response(
handler,
HTTPStatus.OK if completed else HTTPStatus.BAD_REQUEST,
- _oauth_html(completed),
+ _oauth_html("cancelled" if error and completed else "received" if completed else "invalid"),
)
def _handle_webhook(self, handler: BaseHTTPRequestHandler) -> None:
@@ -243,13 +243,22 @@ def _handler_response(
handler.wfile.write(body)
-def _oauth_html(success: bool) -> bytes:
- title = "Linear connected" if success else "Linear connection failed"
- detail = (
- "Authorization received. You can close this window and return to nanobot."
- if success
- else "The authorization request is invalid or expired. Return to nanobot and try again."
- )
+def _oauth_html(status: str) -> bytes:
+ messages = {
+ "received": (
+ "Authorization received",
+ "Return to nanobot while it verifies the Linear workspace. You can close this window.",
+ ),
+ "cancelled": (
+ "Authorization not completed",
+ "Return to nanobot to try again or leave Linear disconnected.",
+ ),
+ "invalid": (
+ "Linear connection failed",
+ "This authorization request is invalid or expired. Return to nanobot and try again.",
+ ),
+ }
+ title, detail = messages.get(status, messages["invalid"])
return (
"
"
+ title
diff --git a/nanobot/channels/linear/state.py b/nanobot/channels/linear/state.py
index df1e1e818..7fd9cf50d 100644
--- a/nanobot/channels/linear/state.py
+++ b/nanobot/channels/linear/state.py
@@ -147,6 +147,27 @@ class LinearStateStore:
).fetchone()
return _installation_from_row(row) if row is not None else None
+ def list_installations(
+ self,
+ oauth_client_id: str | None = None,
+ ) -> list[LinearInstallation]:
+ """Return installations, optionally restricted to one OAuth client."""
+ with self._guard, self._connect() as connection:
+ if oauth_client_id is None:
+ rows = connection.execute(
+ "SELECT * FROM installations ORDER BY organization_name, organization_id"
+ ).fetchall()
+ else:
+ rows = connection.execute(
+ """
+ SELECT * FROM installations
+ WHERE oauth_client_id = ?
+ ORDER BY organization_name, organization_id
+ """,
+ (oauth_client_id,),
+ ).fetchall()
+ return [_installation_from_row(row) for row in rows]
+
def delete_installation(self, organization_id: str) -> None:
with self._guard, self._connect() as connection:
connection.execute(
diff --git a/nanobot/channels/linear/tests/test_linear.py b/nanobot/channels/linear/tests/test_linear.py
index b63579b81..3806773f5 100644
--- a/nanobot/channels/linear/tests/test_linear.py
+++ b/nanobot/channels/linear/tests/test_linear.py
@@ -25,7 +25,9 @@ from nanobot.bus.outbound_events import (
outbound_message_for_event,
)
from nanobot.bus.queue import MessageBus
+from nanobot.channels.linear import client as linear_client
from nanobot.channels.linear import connect as linear_connect
+from nanobot.channels.linear import runtime as linear_runtime
from nanobot.channels.linear.client import LinearApiError, LinearClient
from nanobot.channels.linear.config import LinearConfig, validate_public_base_url
from nanobot.channels.linear.oauth import OAUTH_FLOWS, authorization_url
@@ -55,7 +57,7 @@ def _installation() -> LinearInstallation:
access_token="access",
refresh_token="refresh",
expires_at=time.time() + 3600,
- scope=("read", "write", "app:mentionable"),
+ scope=("read", "write", "app:mentionable", "app:assignable"),
)
@@ -144,7 +146,7 @@ def test_linear_config_rejects_overlapping_callback_paths() -> None:
)
-def test_oauth_authorization_uses_app_actor_pkce_and_mention_scope() -> None:
+def test_oauth_authorization_uses_app_actor_pkce_and_agent_scopes() -> None:
flow = OAUTH_FLOWS.create()
try:
parsed = urlparse(authorization_url(_config(), flow))
@@ -153,7 +155,7 @@ def test_oauth_authorization_uses_app_actor_pkce_and_mention_scope() -> None:
assert "actor=app" in query
assert "code_challenge_method=S256" in query
assert "app%3Amentionable" in query
- assert "app%3Aassignable" not in query
+ assert "app%3Aassignable" in query
assert f"state={flow.state}" in query
finally:
OAUTH_FLOWS.remove(flow)
@@ -175,6 +177,7 @@ def test_state_store_persists_installations_and_deduplicates_webhooks(tmp_path:
assert store.installation("org-1") == installation
assert store.installation("org-2") == second_installation
+ assert store.list_installations("client-id") == [installation, second_installation]
assert store.enqueue_webhook("delivery-1", _agent_webhook()) is True
assert store.enqueue_webhook("delivery-1", _agent_webhook()) is False
@@ -243,15 +246,44 @@ def test_oauth_callback_completes_only_registered_state(tmp_path: Path) -> None:
f"/linear/oauth/callback?state={flow.state}&code=authorization-code",
)
response = connection.getresponse()
- response.read()
+ body = response.read()
connection.close()
assert response.status == 200
+ assert b"Authorization received" in body
+ assert b"Linear connected" not in body
assert flow.code == "authorization-code"
finally:
OAUTH_FLOWS.remove(flow)
lease.close()
+def test_oauth_callback_does_not_report_cancelled_authorization_as_connected(
+ tmp_path: Path,
+) -> None:
+ port = _free_port()
+ lease = acquire_http_server(
+ _config(port),
+ LinearStateStore(tmp_path / "linear.sqlite3"),
+ )
+ flow = OAUTH_FLOWS.create()
+ try:
+ connection = http.client.HTTPConnection("127.0.0.1", port, timeout=3)
+ connection.request(
+ "GET",
+ f"/linear/oauth/callback?state={flow.state}&error=access_denied",
+ )
+ response = connection.getresponse()
+ body = response.read()
+ connection.close()
+ assert response.status == 200
+ assert b"Authorization not completed" in body
+ assert b"Linear connected" not in body
+ assert flow.error == "access_denied"
+ finally:
+ OAUTH_FLOWS.remove(flow)
+ lease.close()
+
+
@pytest.mark.parametrize("concurrent", [False, True])
async def test_successful_authorization_survives_repeated_polls(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, concurrent: bool,
@@ -305,6 +337,71 @@ async def test_successful_authorization_survives_repeated_polls(
await store.cancel(session_id)
+@pytest.mark.asyncio
+async def test_connect_store_lists_and_disconnects_workspaces(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ state = LinearStateStore(tmp_path / "linear.sqlite3")
+ installation = _installation()
+ state.save_installation(installation)
+ monkeypatch.setattr(linear_connect, "_load_linear_config", _config)
+ monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: state)
+ client = SimpleNamespace(revoke_installation=AsyncMock(), close=AsyncMock())
+ monkeypatch.setattr(linear_connect, "LinearClient", lambda *_args: client)
+ store = linear_connect.LinearConnectStore()
+
+ inspected = await store.handle("start", {"operation": ["inspect"]})
+ assert inspected["status"] == "inspected"
+ assert inspected["installations"] == [{
+ "organization_id": "org-1",
+ "organization_name": "Example",
+ "scopes": ["read", "write", "app:mentionable", "app:assignable"],
+ "authorization_status": "authorized",
+ "missing_scopes": [],
+ }]
+
+ disconnected = await store.handle(
+ "start",
+ {"operation": ["disconnect"], "organization_id": ["org-1"]},
+ )
+ assert disconnected["status"] == "disconnected"
+ assert disconnected["installations"] == []
+ assert state.installation("org-1") is None
+ client.revoke_installation.assert_awaited_once_with(installation)
+
+ state.save_installation(replace(_installation(), scope=("read", "write", "app:mentionable")))
+ outdated = await store.handle("start", {"operation": ["inspect"]})
+ assert outdated["installations"][0]["authorization_status"] == "missing_scopes"
+ assert outdated["installations"][0]["missing_scopes"] == ["app:assignable"]
+
+
+@pytest.mark.asyncio
+async def test_disconnect_keeps_local_installation_when_revocation_fails(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ state = LinearStateStore(tmp_path / "linear.sqlite3")
+ installation = _installation()
+ state.save_installation(installation)
+ monkeypatch.setattr(linear_connect, "_load_linear_config", _config)
+ monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: state)
+ client = SimpleNamespace(
+ revoke_installation=AsyncMock(side_effect=LinearApiError("network unavailable")),
+ close=AsyncMock(),
+ )
+ monkeypatch.setattr(linear_connect, "LinearClient", lambda *_args: client)
+
+ with pytest.raises(linear_connect.ChannelConnectError, match="Unable to revoke"):
+ await linear_connect.LinearConnectStore().handle(
+ "start",
+ {"operation": ["disconnect"], "organization_id": ["org-1"]},
+ )
+
+ assert state.installation("org-1") == installation
+ client.close.assert_awaited_once()
+
+
@pytest.mark.asyncio
async def test_oauth_exchange_saves_workspace_app_identity_and_required_scopes(
tmp_path: Path,
@@ -317,7 +414,7 @@ async def test_oauth_exchange_saves_workspace_app_identity_and_required_scopes(
"access_token": "access",
"refresh_token": "refresh",
"expires_in": 86400,
- "scope": "read write app:mentionable",
+ "scope": "read write app:mentionable app:assignable",
},
)
return httpx.Response(
@@ -444,7 +541,7 @@ async def test_expired_workspace_token_is_refreshed_and_rotated(tmp_path: Path)
"access_token": "rotated-access",
"refresh_token": "rotated-refresh",
"expires_in": 86400,
- "scope": "read write app:mentionable",
+ "scope": "read write app:mentionable app:assignable",
},
)
assert request.headers["Authorization"] == "Bearer rotated-access"
@@ -468,9 +565,100 @@ async def test_expired_workspace_token_is_refreshed_and_rotated(tmp_path: Path)
assert refreshed.refresh_token == "rotated-refresh"
+@pytest.mark.asyncio
+async def test_client_uploads_attachment_with_linear_presigned_headers(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ attachment = tmp_path / "report.txt"
+ attachment.write_text("report body", encoding="utf-8")
+ seen_put = False
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ nonlocal seen_put
+ if request.url.host == "api.linear.app":
+ return httpx.Response(200, json={"data": {"fileUpload": {
+ "success": True,
+ "uploadFile": {
+ "uploadUrl": "https://uploads.linear.app/signed/report.txt",
+ "assetUrl": "https://uploads.linear.app/assets/report.txt",
+ "headers": [{"key": "x-upload-token", "value": "signed"}],
+ },
+ }}})
+ seen_put = True
+ assert request.content == b"report body"
+ assert request.headers["x-upload-token"] == "signed"
+ assert request.headers["content-type"].startswith("text/plain")
+ assert request.headers["cache-control"] == "public, max-age=31536000"
+ return httpx.Response(200)
+
+ monkeypatch.setattr(linear_client, "validate_url_target", lambda _url: (True, ""))
+ state = LinearStateStore(tmp_path / "linear.sqlite3")
+ state.save_installation(_installation())
+ http = httpx.AsyncClient(transport=httpx.MockTransport(handler))
+ client = LinearClient(_config(), state, http)
+ try:
+ asset_url = await client.upload_file("org-1", attachment)
+ finally:
+ await http.aclose()
+
+ assert seen_put is True
+ assert asset_url == "https://uploads.linear.app/assets/report.txt"
+
+
+@pytest.mark.asyncio
+async def test_client_downloads_private_linear_attachment_with_workspace_token(
+ tmp_path: Path,
+) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.url.host == "uploads.linear.app"
+ assert request.headers["Authorization"] == "Bearer access"
+ return httpx.Response(200, headers={"Content-Type": "image/png"}, content=b"png")
+
+ state = LinearStateStore(tmp_path / "linear.sqlite3")
+ state.save_installation(_installation())
+ http = httpx.AsyncClient(transport=httpx.MockTransport(handler))
+ client = LinearClient(_config(), state, http)
+ try:
+ body, content_type = await client.download_file(
+ "org-1", "https://uploads.linear.app/private/image"
+ )
+ finally:
+ await http.aclose()
+
+ assert body == b"png"
+ assert content_type == "image/png"
+
+
+@pytest.mark.asyncio
+async def test_client_revokes_access_and_refresh_tokens_before_disconnect(
+ tmp_path: Path,
+) -> None:
+ requests: list[dict[str, list[str]]] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.url == "https://api.linear.app/oauth/revoke"
+ requests.append(parse_qs(request.content.decode()))
+ return httpx.Response(200 if len(requests) == 1 else 400)
+
+ state = LinearStateStore(tmp_path / "linear.sqlite3")
+ http = httpx.AsyncClient(transport=httpx.MockTransport(handler))
+ client = LinearClient(_config(), state, http)
+ try:
+ await client.revoke_installation(_installation())
+ finally:
+ await http.aclose()
+
+ assert requests == [
+ {"token": ["access"], "token_type_hint": ["access_token"]},
+ {"token": ["refresh"], "token_type_hint": ["refresh_token"]},
+ ]
+
+
class _FakeLinearClient:
def __init__(self) -> None:
self.activities: list[dict[str, Any]] = []
+ self.downloads: list[str] = []
async def create_activity(
self,
@@ -480,6 +668,8 @@ class _FakeLinearClient:
*,
activity_id: str,
ephemeral: bool = False,
+ signal: str | None = None,
+ signal_metadata: dict[str, Any] | None = None,
) -> None:
self.activities.append(
{
@@ -488,9 +678,26 @@ class _FakeLinearClient:
"content": content,
"activity_id": activity_id,
"ephemeral": ephemeral,
+ "signal": signal,
+ "signal_metadata": signal_metadata,
}
)
+ async def upload_file(self, _organization_id: str, file_path: Path) -> str:
+ return f"https://uploads.linear.app/{file_path.name}"
+
+ async def download_file(
+ self,
+ _organization_id: str,
+ url: str,
+ *,
+ max_bytes: int = linear_client.MAX_DOWNLOAD_BYTES,
+ ) -> tuple[bytes, str]:
+ self.downloads.append(url)
+ if len(b"image") > max_bytes:
+ raise LinearApiError("Linear attachment exceeds the download budget")
+ return b"image", "image/png"
+
def _runtime(tmp_path: Path) -> tuple[LinearChannel, _FakeLinearClient]:
channel = LinearChannel(_config(), MessageBus())
@@ -516,9 +723,105 @@ 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_created_session_downloads_private_linear_attachments(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ channel, client = _runtime(tmp_path)
+ media_dir = tmp_path / "media"
+ media_dir.mkdir()
+ monkeypatch.setattr(linear_runtime, "get_media_dir", lambda _channel: media_dir)
+ payload = _agent_webhook()
+ payload["promptContext"] = (
+ "Review "
+ )
+
+ await channel._process_webhook("delivery-media", payload) # pyright: ignore[reportPrivateUsage]
+
+ inbound = await channel.bus.consume_inbound()
+ assert client.downloads == ["https://uploads.linear.app/private/image-1"]
+ assert len(inbound.media) == 1
+ assert Path(inbound.media[0]).name == "delivery-media_checkout.png"
+ assert Path(inbound.media[0]).read_bytes() == b"image"
+
+
+@pytest.mark.asyncio
+async def test_unpaired_session_does_not_download_private_attachments(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ channel, client = _runtime(tmp_path)
+ channel.config.allow_from = []
+ monkeypatch.setattr(channel, "is_allowed", lambda _sender_id: False)
+ media_dir = tmp_path / "media"
+ media_dir.mkdir()
+ monkeypatch.setattr(linear_runtime, "get_media_dir", lambda _channel: media_dir)
+ payload = _agent_webhook()
+ payload["promptContext"] = "Review https://uploads.linear.app/private/image-1"
+
+ await channel._process_webhook("delivery-unpaired", payload) # pyright: ignore[reportPrivateUsage]
+
+ assert client.downloads == []
+ assert list(media_dir.iterdir()) == []
+ assert client.activities[0]["content"]["type"] == "response"
+ assert "pairing" in client.activities[0]["content"]["body"].lower()
+
+
+@pytest.mark.asyncio
+async def test_inbound_attachments_share_one_total_download_budget(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ channel, client = _runtime(tmp_path)
+ media_dir = tmp_path / "media"
+ media_dir.mkdir()
+ monkeypatch.setattr(linear_runtime, "get_media_dir", lambda _channel: media_dir)
+ monkeypatch.setattr(linear_runtime, "MAX_DOWNLOAD_BYTES", 7)
+ payload = _agent_webhook()
+ payload["promptContext"] = (
+ "Review https://uploads.linear.app/private/one "
+ "and https://uploads.linear.app/private/two"
+ )
+
+ await channel._process_webhook("delivery-budget", payload) # pyright: ignore[reportPrivateUsage]
+
+ inbound = await channel.bus.consume_inbound()
+ assert len(inbound.media) == 1
+ assert client.downloads == [
+ "https://uploads.linear.app/private/one",
+ "https://uploads.linear.app/private/two",
+ ]
+ assert "[Attachment unavailable: two]" in inbound.content
+
+
+@pytest.mark.asyncio
+async def test_inbound_attachments_enforce_the_count_limit(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ channel, client = _runtime(tmp_path)
+ media_dir = tmp_path / "media"
+ media_dir.mkdir()
+ monkeypatch.setattr(linear_runtime, "get_media_dir", lambda _channel: media_dir)
+ monkeypatch.setattr(linear_runtime, "MAX_PROMPT_ATTACHMENTS", 1)
+ payload = _agent_webhook()
+ payload["promptContext"] = (
+ "Review https://uploads.linear.app/private/one "
+ "and https://uploads.linear.app/private/two"
+ )
+
+ await channel._process_webhook("delivery-count", payload) # pyright: ignore[reportPrivateUsage]
+
+ inbound = await channel.bus.consume_inbound()
+ assert client.downloads == ["https://uploads.linear.app/private/one"]
+ assert "[Only the first 1 attachments were accepted.]" in inbound.content
+
+
@pytest.mark.asyncio
async def test_prompted_stop_signal_becomes_priority_stop_command(tmp_path: Path) -> None:
- channel, _ = _runtime(tmp_path)
+ channel, client = _runtime(tmp_path)
+ channel.config.allow_from = []
await channel._process_webhook( # pyright: ignore[reportPrivateUsage]
"delivery-2",
_agent_webhook(action="prompted", signal="stop"),
@@ -527,6 +830,7 @@ async def test_prompted_stop_signal_becomes_priority_stop_command(tmp_path: Path
inbound = await channel.bus.consume_inbound()
assert inbound.content == "/stop"
assert inbound.metadata["linear"]["signal"] == "stop"
+ assert client.activities == []
@pytest.mark.asyncio
@@ -581,7 +885,149 @@ async def test_outbound_response_and_tool_progress_use_native_activity_shapes(
assert client.activities[0]["content"] == {"type": "response", "body": "Done"}
assert client.activities[1]["activity_id"] == activity_id
assert client.activities[2]["content"]["type"] == "action"
- assert client.activities[2]["content"]["action"] == "linear_get_issue"
+ assert client.activities[2]["content"]["action"] == "Linear Get Issue"
+
+
+@pytest.mark.asyncio
+async def test_outbound_buttons_keep_media_in_linear_select_elicitation(tmp_path: Path) -> None:
+ channel, client = _runtime(tmp_path)
+ attachment = tmp_path / "choice.png"
+ attachment.write_bytes(b"png")
+ await channel.send(OutboundMessage(
+ channel="linear",
+ chat_id="session-1",
+ content="Choose a priority",
+ media=[str(attachment)],
+ buttons=[["High", "Low"]],
+ metadata={
+ "linear": {"organization_id": "org-1", "agent_session_id": "session-1"}
+ },
+ ))
+
+ assert client.activities[0]["content"] == {
+ "type": "elicitation",
+ "body": (
+ "Choose a priority\n\n"
+ ""
+ ),
+ }
+ assert client.activities[0]["signal"] == "select"
+ assert client.activities[0]["signal_metadata"] == {
+ "options": [
+ {"label": "High", "value": "High"},
+ {"label": "Low", "value": "Low"},
+ ]
+ }
+
+
+@pytest.mark.asyncio
+async def test_outbound_local_media_is_uploaded_and_linked(tmp_path: Path) -> None:
+ channel, client = _runtime(tmp_path)
+ attachment = tmp_path / "diagram.png"
+ attachment.write_bytes(b"png")
+ await channel.send(OutboundMessage(
+ channel="linear",
+ chat_id="session-1",
+ content="Here is the diagram.",
+ media=[str(attachment)],
+ metadata={
+ "linear": {"organization_id": "org-1", "agent_session_id": "session-1"}
+ },
+ ))
+
+ assert client.activities[0]["content"] == {
+ "type": "response",
+ "body": (
+ "Here is the diagram.\n\n"
+ ""
+ ),
+ }
+
+
+@pytest.mark.asyncio
+async def test_tool_activities_redact_credentials_and_make_start_ephemeral(
+ tmp_path: Path,
+) -> None:
+ channel, client = _runtime(tmp_path)
+ metadata = {
+ "linear": {"organization_id": "org-1", "agent_session_id": "session-1"}
+ }
+ await channel.send(OutboundMessage(
+ channel="linear",
+ chat_id="session-1",
+ content="",
+ metadata=metadata,
+ event=ProgressEvent(tool_events=[{
+ "phase": "start",
+ "call_id": "call-secret",
+ "name": "call_api",
+ "arguments": {"api_key": "secret-value", "query": "safe"},
+ }]),
+ ))
+ await channel.send(OutboundMessage(
+ channel="linear",
+ chat_id="session-1",
+ content="",
+ metadata=metadata,
+ event=ProgressEvent(tool_events=[{
+ "phase": "error",
+ "call_id": "call-secret",
+ "name": "call_api",
+ "error": "Authorization: Bearer plaintext-secret",
+ }]),
+ ))
+ await channel.send(OutboundMessage(
+ channel="linear",
+ chat_id="session-1",
+ content="",
+ metadata=metadata,
+ event=ProgressEvent(tool_events=[{
+ "phase": "end",
+ "call_id": "call-secret",
+ "name": "call_api",
+ "arguments": {"api_key": "secret-value"},
+ "result": {"token": "result-secret", "status": "ok"},
+ }]),
+ ))
+
+ assert client.activities[0]["ephemeral"] is True
+ assert client.activities[0]["content"]["action"] == "Call API"
+ assert "secret-value" not in client.activities[0]["content"]["parameter"]
+ assert client.activities[1]["ephemeral"] is False
+ assert "plaintext-secret" not in client.activities[1]["content"]["result"]
+ assert "result-secret" not in client.activities[2]["content"]["result"]
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "token=plain-secret",
+ "client_secret=plain-secret",
+ "cookie=session-secret",
+ "credential: plain-secret",
+ "OPENAI_API_KEY=plain-secret",
+ ],
+)
+def test_tool_result_text_redacts_common_credential_assignments(value: str) -> None:
+ result = linear_runtime._compact_result(value) # pyright: ignore[reportPrivateUsage]
+
+ assert "plain-secret" not in result
+ assert "session-secret" not in result
+ assert "[redacted]" in result
+
+
+@pytest.mark.asyncio
+async def test_reasoning_can_be_hidden_for_linear(tmp_path: Path) -> None:
+ channel, client = _runtime(tmp_path)
+ channel.config.show_reasoning = False
+ metadata = {
+ "linear": {"organization_id": "org-1", "agent_session_id": "session-1"}
+ }
+
+ await channel.send_reasoning_delta("session-1", "private thought", metadata)
+ await channel.send_reasoning_end("session-1", metadata)
+
+ assert client.activities == []
@pytest.mark.parametrize("include_start", [True, False])
diff --git a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx
index ab9090ab3..eac904161 100644
--- a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx
+++ b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx
@@ -25,6 +25,7 @@ const linearSetup: ChannelSetupContract = {
field("webhookPath", "string", false, "/linear/webhook"),
field("oauthCallbackPath", "string", false, "/linear/oauth/callback"),
field("allowFrom", "list"),
+ field("showReasoning", "bool", false, "true"),
],
};
@@ -53,7 +54,7 @@ describe("Linear channel UI", () => {
expect(contribution?.ConnectFlow).toBeUndefined();
});
- it("creates a private mention-only Agent app manifest with exact callback routes", () => {
+ it("creates a private mentionable and assignable Agent app manifest with exact routes", () => {
const url = new URL(
linearManifestUrl(
"https://nanobot.example.com",
@@ -63,7 +64,8 @@ describe("Linear channel UI", () => {
);
const manifest = JSON.parse(url.searchParams.get("manifest") ?? "{}") as {
distribution?: string;
- oauth?: { redirect_uris?: string[] };
+ display?: { iconUrl?: string; description?: string };
+ oauth?: { client_uri?: string; redirect_uris?: string[] };
webhook?: { url?: string; resourceTypes?: string[] };
};
@@ -71,6 +73,9 @@ describe("Linear channel UI", () => {
"https://linear.app/settings/api/applications/new",
);
expect(manifest.distribution).toBe("private");
+ expect(manifest.display?.description).toContain("delegate issues");
+ expect(manifest.display?.iconUrl).toContain("nanobot_logo.png");
+ expect(manifest.oauth?.client_uri).toBe("https://github.com/HKUDS/nanobot");
expect(manifest.oauth?.redirect_uris).toEqual([
"https://nanobot.example.com/linear/oauth/callback",
]);
@@ -315,23 +320,43 @@ describe("Linear channel UI", () => {
it("restores a running connection on reopen without starting OAuth", async () => {
mockFeature({ ...savedFeature(), enabled: true, running: true, runtime_status: "running" });
+ requestMutationMock.mockResolvedValue({
+ session_id: "", status: "inspected", installations: [],
+ });
renderSettingsView({ initialSection: "channels" });
const open = await screen.findByRole("button", { name: "View Linear settings" });
fireEvent.click(open);
- expect(within(screen.getByRole("dialog")).getByText("Connected", { exact: true })).toBeVisible();
+ expect(within(screen.getByRole("dialog")).getByText("Channel running", { exact: true })).toBeVisible();
expect(screen.getByRole("button", { name: "Connect another workspace" })).toBeEnabled();
expect(screen.queryByRole("button", { name: "Connect Linear" })).not.toBeInTheDocument();
+ expect(await screen.findByText(/No workspaces are authorized/)).toBeVisible();
fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Close", exact: true }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
fireEvent.click(open);
- expect(within(screen.getByRole("dialog")).getByText("Connected", { exact: true })).toBeVisible();
+ expect(within(screen.getByRole("dialog")).getByText("Channel running", { exact: true })).toBeVisible();
expect(screen.getByRole("button", { name: "Connect another workspace" })).toBeEnabled();
- expect(requestMutationMock).not.toHaveBeenCalled();
+ expect(await screen.findByText(/No workspaces are authorized/)).toBeVisible();
+ expect(requestMutationMock).toHaveBeenCalledWith(
+ "settings.channel.connect.start", { channel: "linear", operation: "inspect" }, 150_000,
+ );
+ });
+
+ it("shows workspace inspection failures instead of a contradictory empty state", async () => {
+ mockFeature({ ...savedFeature(), enabled: true, running: true, runtime_status: "running" });
+ requestMutationMock.mockRejectedValueOnce(new Error("Workspace lookup failed"));
+
+ renderSettingsView({ initialSection: "channels" });
+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
+
+ expect(await screen.findByRole("alert")).toHaveTextContent("Workspace lookup failed");
+ expect(screen.queryByText(/No workspaces are authorized/)).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Refresh workspaces" })).toBeEnabled();
});
it("starts another workspace authorization directly and preserves the connection on cancel", async () => {
mockFeature({ ...savedFeature(), enabled: true, running: true, runtime_status: "running" });
requestMutationMock
+ .mockResolvedValueOnce({ session_id: "", status: "inspected", installations: [] })
.mockResolvedValueOnce({ session_id: "another-workspace", status: "pending",
qr_url: "https://linear.app/oauth/authorize?client_id=test" })
.mockResolvedValueOnce({ session_id: "another-workspace", status: "cancelled" });
@@ -344,7 +369,7 @@ describe("Linear channel UI", () => {
expect(await screen.findByRole("link", { name: "Continue in Linear" })).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(await screen.findByRole("button", { name: "Connect another workspace" })).toBeEnabled();
- expect(within(screen.getByRole("dialog")).getByText("Connected", { exact: true })).toBeVisible();
+ expect(within(screen.getByRole("dialog")).getByText("Channel running", { exact: true })).toBeVisible();
expect(screen.queryByText("Authorization stopped.")).not.toBeInTheDocument();
});
@@ -357,11 +382,11 @@ describe("Linear channel UI", () => {
features: [{ ...feature, enabled: true, running: true, runtime_status: "running" }],
enabled_count: 1,
},
- });
+ }).mockResolvedValueOnce({ session_id: "", status: "inspected", installations: [] });
renderSettingsView({ initialSection: "channels" });
fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
fireEvent.click(await screen.findByRole("button", { name: "Connect Linear" }));
- expect(await within(screen.getByRole("dialog")).findByText("Connected", { exact: true })).toBeVisible();
+ expect(await within(screen.getByRole("dialog")).findByText("Channel running", { exact: true })).toBeVisible();
expect(screen.getByRole("button", { name: "Connect another workspace" })).toBeEnabled();
});
@@ -370,10 +395,85 @@ describe("Linear channel UI", () => {
runtime_error: "Linear channel failed to start" });
renderSettingsView({ initialSection: "channels" });
fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
- expect(within(screen.getByRole("dialog")).queryByText("Connected", { exact: true })).not.toBeInTheDocument();
+ expect(within(screen.getByRole("dialog")).queryByText("Channel running", { exact: true })).not.toBeInTheDocument();
expect(screen.getByText("Linear channel failed to start")).toBeVisible();
expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled();
});
+
+ it("lists authorized workspaces and confirms disconnecting the last one", async () => {
+ const running = {
+ ...savedFeature(), enabled: true, running: true, runtime_status: "running" as const,
+ };
+ const disabled = {
+ ...savedFeature(), enabled: false, running: false, runtime_status: "stopped" as const,
+ };
+ mockFeature(running);
+ requestMutationMock
+ .mockResolvedValueOnce({
+ session_id: "",
+ status: "inspected",
+ installations: [{
+ organization_id: "org-1",
+ organization_name: "Example workspace",
+ scopes: ["read", "write", "app:mentionable", "app:assignable"],
+ authorization_status: "authorized",
+ }],
+ })
+ .mockResolvedValueOnce({
+ session_id: "",
+ status: "disconnected",
+ message: "Disconnected Example workspace.",
+ installations: [],
+ })
+ .mockResolvedValueOnce({ features: [disabled], enabled_count: 0 });
+
+ renderSettingsView({ initialSection: "channels" });
+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
+ expect(await screen.findByText("Example workspace")).toBeVisible();
+ expect(screen.getByText(/app:assignable/)).toBeVisible();
+ fireEvent.click(screen.getByRole("button", { name: "Disconnect" }));
+ fireEvent.click(screen.getByRole("button", { name: "Disconnect workspace" }));
+
+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
+ "settings.channel.connect.start",
+ { channel: "linear", operation: "disconnect", organization_id: "org-1" },
+ 150_000,
+ ));
+ expect(requestMutationMock).toHaveBeenCalledWith(
+ "settings.feature.disable", { name: "linear" }, 20_000,
+ );
+ });
+
+ it("prevents disconnecting a workspace while its status is refreshing", async () => {
+ const running = {
+ ...savedFeature(), enabled: true, running: true, runtime_status: "running" as const,
+ };
+ let finishRefresh: ((value: unknown) => void) | undefined;
+ const installation = {
+ organization_id: "org-1",
+ organization_name: "Example workspace",
+ authorization_status: "authorized",
+ };
+ mockFeature(running);
+ requestMutationMock
+ .mockResolvedValueOnce({
+ session_id: "", status: "inspected", installations: [installation],
+ })
+ .mockImplementationOnce(() => new Promise((resolve) => { finishRefresh = resolve; }));
+
+ renderSettingsView({ initialSection: "channels" });
+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
+ expect(await screen.findByText("Example workspace")).toBeVisible();
+ fireEvent.click(screen.getByRole("button", { name: "Disconnect" }));
+ fireEvent.click(screen.getByRole("button", { name: "Refresh workspaces" }));
+
+ expect(screen.getByRole("button", { name: "Disconnect workspace" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Cancel" })).toBeDisabled();
+ finishRefresh?.({ session_id: "", status: "inspected", installations: [installation] });
+ await waitFor(() => expect(
+ screen.getByRole("button", { name: "Disconnect workspace" }),
+ ).toBeEnabled());
+ });
});
function savedFeature(): NanobotFeatureInfo {
diff --git a/nanobot/channels/linear/webui/LinearPanel.tsx b/nanobot/channels/linear/webui/LinearPanel.tsx
index 11399c184..4f220ed26 100644
--- a/nanobot/channels/linear/webui/LinearPanel.tsx
+++ b/nanobot/channels/linear/webui/LinearPanel.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
-import { Check, ChevronDown, ExternalLink, Loader2 } from "lucide-react";
+import { Check, ChevronDown, ExternalLink, Loader2, RefreshCw, Unplug } from "lucide-react";
import { useTranslation } from "react-i18next";
import { channelTranslator } from "@/channel-plugins/i18n";
@@ -19,7 +19,8 @@ import {
import { Button } from "@/components/ui/button";
import { channelValidationStatusClass } from "@/components/settings/channels/ChannelValidationProgress";
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
-import { configureChannel } from "@/lib/api";
+import { configureChannel, disableNanobotFeature, startChannelConnect } from "@/lib/api";
+import type { ChannelInstallationSummary } from "@/lib/types";
import { cn } from "@/lib/utils";
import { useClient } from "@/providers/ClientProvider";
@@ -29,6 +30,7 @@ import { linearManifestUrl } from "./manifest";
const PUBLIC_BASE_URL_KEY = "channels.linear.publicBaseUrl";
const WEBHOOK_PATH_KEY = "channels.linear.webhookPath";
const CALLBACK_PATH_KEY = "channels.linear.oauthCallbackPath";
+const ALLOW_FROM_KEY = "channels.linear.allowFrom";
export function LinearPanel({
token,
@@ -62,6 +64,12 @@ export function LinearPanel({
const [connecting, setConnecting] = useState(false);
const [notice, setNotice] = useState(null);
const [saved, setSaved] = useState(false);
+ const [installations, setInstallations] = useState([]);
+ const [loadingInstallations, setLoadingInstallations] = useState(false);
+ const [disconnectingId, setDisconnectingId] = useState(null);
+ const [disconnectConfirmId, setDisconnectConfirmId] = useState(null);
+ const [workspaceNotice, setWorkspaceNotice] = useState(null);
+ const [workspaceError, setWorkspaceError] = useState(null);
const savePromiseRef = useRef | null>(null);
const advancedPanelId = useId();
@@ -96,6 +104,49 @@ export function LinearPanel({
feature.config_values?.[CALLBACK_PATH_KEY] || "/linear/oauth/callback",
)
: null;
+ const allowFrom = feature.config_values?.[ALLOW_FROM_KEY]?.trim() ?? "";
+
+ const loadInstallations = useCallback(async () => {
+ if (!credentialsSaved || dirty) return;
+ setLoadingInstallations(true);
+ setWorkspaceNotice(null);
+ setWorkspaceError(null);
+ try {
+ const payload = await startChannelConnect(client, "linear", { operation: "inspect" });
+ setInstallations(payload.installations ?? []);
+ } catch (err) {
+ setWorkspaceError((err as Error).message);
+ } finally {
+ setLoadingInstallations(false);
+ }
+ }, [client, credentialsSaved, dirty]);
+
+ useEffect(() => {
+ if (feature.runtime_status === "running") void loadInstallations();
+ }, [feature.runtime_status, loadInstallations]);
+
+ const disconnectWorkspace = async (installation: ChannelInstallationSummary) => {
+ setDisconnectingId(installation.organization_id);
+ setWorkspaceNotice(null);
+ setWorkspaceError(null);
+ try {
+ const payload = await startChannelConnect(client, "linear", {
+ operation: "disconnect",
+ organization_id: installation.organization_id,
+ });
+ const remaining = payload.installations ?? [];
+ setInstallations(remaining);
+ setWorkspaceNotice(payload.message ?? null);
+ setDisconnectConfirmId(null);
+ if (remaining.length === 0) {
+ onFeaturesUpdate(await disableNanobotFeature(client, "linear"));
+ }
+ } catch (err) {
+ setWorkspaceError((err as Error).message);
+ } finally {
+ setDisconnectingId(null);
+ }
+ };
const setFieldValue = (key: string, value: string) => {
setFieldValues((current) => ({ ...current, [key]: value }));
@@ -199,7 +250,7 @@ export function LinearPanel({
channelValidationStatusClass("connected"),
)}>
- {t("settings.channels.validation.connected", { defaultValue: "Connected" })}
+ {tx("custom.channelRunning", "Channel running")}
) : null}
) : null}
+
+
+
+ {tx("custom.accessTitle", "Access and issue tools")}
+
+
+ {allowFrom === "*"
+ ? tx("custom.accessAll", "Every member of an authorized workspace can run this agent.")
+ : allowFrom
+ ? tx("custom.accessRestricted", "Only the Linear user IDs listed in Advanced can run this agent.")
+ : tx("custom.accessPairing", "On first use, mention nanobot in Linear, approve the pairing code in Settings → Pairing, then mention it again.")}
+
+
+ {tx("custom.mcpDescription", "This channel handles agent conversations. Connect Linear tools to let the agent search or change issues.")}{" "}
+
+ {tx("custom.configureTools", "Configure Linear tools")}
+
+
+
+
+ {feature.runtime_status === "running" ? (
+
+
+
+ {tx("custom.workspacesTitle", "Authorized workspaces")}
+
+ void loadInstallations()}>
+
+ {tx("custom.refreshWorkspaces", "Refresh workspaces")}
+
+
+
+ {loadingInstallations ? tx("custom.loadingWorkspaces", "Loading workspaces") : ""}
+
+ {!loadingInstallations && !workspaceError && installations.length === 0 ? (
+
+ {tx("custom.noWorkspaces", "No workspaces are authorized. Connect a workspace to receive Linear agent requests.")}
+
+ ) : null}
+
+ {installations.map((installation) => {
+ const confirming = disconnectConfirmId === installation.organization_id;
+ const disconnecting = disconnectingId === installation.organization_id;
+ const name = installation.organization_name || installation.organization_id;
+ return (
+
+
+
{name}
+
+ {installation.authorization_status === "missing_scopes"
+ ? tx(
+ "custom.missingScopes",
+ "Reconnect to grant: {{scopes}}",
+ { scopes: installation.missing_scopes?.join(", ") || "required scopes" },
+ )
+ : installation.authorization_status === "refresh_required"
+ ? tx("custom.refreshRequired", "Authorization refresh required")
+ : tx("custom.authorized", "Authorized")}
+ {installation.scopes?.length ? ` · ${installation.scopes.join(", ")}` : ""}
+
+
+
+ {confirming ? (
+ setDisconnectConfirmId(null)}>
+ {t("settings.actions.cancel", { defaultValue: "Cancel" })}
+
+ ) : null}
+ confirming
+ ? void disconnectWorkspace(installation)
+ : setDisconnectConfirmId(installation.organization_id)}>
+ {disconnecting ?
+ : }
+ {confirming
+ ? tx("custom.confirmDisconnect", "Disconnect workspace")
+ : tx("custom.disconnect", "Disconnect")}
+
+
+
+ );
+ })}
+
+ {workspaceError ? (
+ {workspaceError}
+ ) : null}
+ {workspaceNotice ? (
+
+ {workspaceNotice}
+
+ ) : null}
+
+ ) : null}