feat(linear): improve native agent UX
This commit is contained in:
1 parent
c75192975c
commit
d699088705
25 files changed
+1510
-92
No files matched your search
+36
-14
@@ -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),
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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]
|
||||
@@ -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 (
|
||||
"<!doctype html><html><head><meta charset=utf-8><title>"
|
||||
+ title
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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])
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<string | null>(null);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const [installations, setInstallations] = useState<ChannelInstallationSummary[]>([]);
|
||||
const [loadingInstallations, setLoadingInstallations] = useState(false);
|
||||
const [disconnectingId, setDisconnectingId] = useState<string | null>(null);
|
||||
const [disconnectConfirmId, setDisconnectConfirmId] = useState<string | null>(null);
|
||||
const [workspaceNotice, setWorkspaceNotice] = useState<string | null>(null);
|
||||
const [workspaceError, setWorkspaceError] = useState<string | null>(null);
|
||||
const savePromiseRef = useRef<Promise<boolean> | 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"),
|
||||
)}>
|
||||
<Check className="h-3.5 w-3.5" aria-hidden />
|
||||
{t("settings.channels.validation.connected", { defaultValue: "Connected" })}
|
||||
{tx("custom.channelRunning", "Channel running")}
|
||||
</span>
|
||||
) : null}
|
||||
<span role="status" aria-live="polite" aria-atomic="true" className={cn(
|
||||
@@ -243,6 +294,107 @@ export function LinearPanel({
|
||||
</div>
|
||||
) : null}
|
||||
</form>
|
||||
<section className="mt-5 space-y-3" aria-labelledby="linear-access-heading">
|
||||
<div>
|
||||
<h4 id="linear-access-heading" className="text-[13px] font-semibold text-foreground">
|
||||
{tx("custom.accessTitle", "Access and issue tools")}
|
||||
</h4>
|
||||
<p className="mt-1 text-[12px] leading-5 text-muted-foreground">
|
||||
{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.")}
|
||||
</p>
|
||||
<p className="mt-2 text-[12px] leading-5 text-muted-foreground">
|
||||
{tx("custom.mcpDescription", "This channel handles agent conversations. Connect Linear tools to let the agent search or change issues.")}{" "}
|
||||
<a href="#/apps" className="font-medium text-foreground underline underline-offset-4">
|
||||
{tx("custom.configureTools", "Configure Linear tools")}
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
{feature.runtime_status === "running" ? (
|
||||
<section className="mt-5 space-y-3" aria-labelledby="linear-workspaces-heading">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h4 id="linear-workspaces-heading" className="text-[13px] font-semibold text-foreground">
|
||||
{tx("custom.workspacesTitle", "Authorized workspaces")}
|
||||
</h4>
|
||||
<Button type="button" variant="ghost" size="sm"
|
||||
disabled={loadingInstallations || disconnectingId !== null}
|
||||
className="min-h-10 gap-2 rounded-full text-[12px]"
|
||||
onClick={() => void loadInstallations()}>
|
||||
<RefreshCw className={cn("h-3.5 w-3.5", loadingInstallations && "animate-spin motion-reduce:animate-none")} aria-hidden />
|
||||
{tx("custom.refreshWorkspaces", "Refresh workspaces")}
|
||||
</Button>
|
||||
</div>
|
||||
<div role="status" aria-live="polite" className="sr-only">
|
||||
{loadingInstallations ? tx("custom.loadingWorkspaces", "Loading workspaces") : ""}
|
||||
</div>
|
||||
{!loadingInstallations && !workspaceError && installations.length === 0 ? (
|
||||
<p className="rounded-control bg-muted/45 px-3 py-2.5 text-[12px] leading-5 text-muted-foreground">
|
||||
{tx("custom.noWorkspaces", "No workspaces are authorized. Connect a workspace to receive Linear agent requests.")}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="space-y-2">
|
||||
{installations.map((installation) => {
|
||||
const confirming = disconnectConfirmId === installation.organization_id;
|
||||
const disconnecting = disconnectingId === installation.organization_id;
|
||||
const name = installation.organization_name || installation.organization_id;
|
||||
return (
|
||||
<article key={installation.organization_id}
|
||||
className="flex flex-wrap items-center justify-between gap-3 rounded-control bg-muted/45 px-3 py-2.5">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-[12.5px] font-medium text-foreground">{name}</p>
|
||||
<p className="mt-0.5 text-[11px] leading-4 text-muted-foreground">
|
||||
{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(", ")}` : ""}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{confirming ? (
|
||||
<Button type="button" variant="ghost" size="sm"
|
||||
disabled={loadingInstallations || disconnecting}
|
||||
className="min-h-10 rounded-full text-[12px]"
|
||||
onClick={() => setDisconnectConfirmId(null)}>
|
||||
{t("settings.actions.cancel", { defaultValue: "Cancel" })}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button type="button" variant={confirming ? "destructive" : "outline"} size="sm"
|
||||
disabled={loadingInstallations || disconnectingId !== null}
|
||||
className="min-h-10 gap-2 rounded-full text-[12px]"
|
||||
onClick={() => confirming
|
||||
? void disconnectWorkspace(installation)
|
||||
: setDisconnectConfirmId(installation.organization_id)}>
|
||||
{disconnecting ? <Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden />
|
||||
: <Unplug className="h-3.5 w-3.5" aria-hidden />}
|
||||
{confirming
|
||||
? tx("custom.confirmDisconnect", "Disconnect workspace")
|
||||
: tx("custom.disconnect", "Disconnect")}
|
||||
</Button>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{workspaceError ? (
|
||||
<p role="alert" className="text-[12px] leading-5 text-destructive">{workspaceError}</p>
|
||||
) : null}
|
||||
{workspaceNotice ? (
|
||||
<p role="status" className="text-[12px] leading-5 text-muted-foreground">
|
||||
{workspaceNotice}
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
) : null}
|
||||
<LinearConnectFlow token={token} feature={feature}
|
||||
idleLabel={tx("custom.connect", "Connect Linear")} onFeaturesUpdate={onFeaturesUpdate}
|
||||
onActiveChange={setConnecting}
|
||||
|
||||
@@ -32,6 +32,7 @@ export default {
|
||||
{ key: "channels.linear.webhookPath" },
|
||||
{ key: "channels.linear.oauthCallbackPath" },
|
||||
{ key: "channels.linear.allowFrom" },
|
||||
{ key: "channels.linear.showReasoning" },
|
||||
],
|
||||
},
|
||||
},
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
"setup": {
|
||||
"docsLabel": "Open Linear setup guide",
|
||||
"officialLabel": "Create Linear OAuth app",
|
||||
"tryIt": "Mention the app in an issue comment. Follow-ups inside its Agent Session do not need another mention.",
|
||||
"summary": "Create a private Linear OAuth app, save its credentials and public URL, then authorize each workspace. New sessions require an explicit @mention; ordinary comments are ignored.",
|
||||
"tryIt": "Mention the app in an issue comment or delegate an issue to it. Follow-ups inside its Agent Session do not need another mention.",
|
||||
"summary": "Create a private Linear OAuth app, save its credentials and public URL, then authorize each workspace. Start a session by mentioning the app or delegating an issue to it; ordinary comments are ignored.",
|
||||
"steps": [
|
||||
"Expose this nanobot instance through a stable HTTPS URL (a tunnel is fine).",
|
||||
"Create a private OAuth app in Linear with read, write, and app:mentionable scopes. Do not add app:assignable.",
|
||||
"Create a private OAuth app in Linear with read, write, app:mentionable, and app:assignable scopes.",
|
||||
"Subscribe the app webhook to AgentSessionEvent, PermissionChange, and OAuthAuthorization using the generated webhook URL.",
|
||||
"Enter the app credentials, wait for them to save automatically, connect the workspace with OAuth, then @mention the app on an issue."
|
||||
],
|
||||
@@ -53,6 +53,10 @@
|
||||
"label": "Allowed Linear users",
|
||||
"placeholder": "Linear user IDs, comma separated",
|
||||
"help": "Leave empty to use nanobot pairing, or use * to allow every user in connected workspaces."
|
||||
},
|
||||
"showReasoning": {
|
||||
"label": "Show reasoning",
|
||||
"help": "Post model reasoning as thought activities in Linear. Turn this off for a quieter session."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -71,6 +75,22 @@
|
||||
"savePublicUrl": "Enter a public HTTPS URL to create a prefilled Linear app.",
|
||||
"saveBeforeConnect": "Enter the app credentials and wait for them to save before connecting.",
|
||||
"removeCredentials": "Remove saved credentials",
|
||||
"retrySave": "Retry"
|
||||
"retrySave": "Retry",
|
||||
"channelRunning": "Channel running",
|
||||
"accessTitle": "Access and issue tools",
|
||||
"accessAll": "Every member of an authorized workspace can run this agent.",
|
||||
"accessRestricted": "Only the Linear user IDs listed in Advanced can run this agent.",
|
||||
"accessPairing": "On first use, mention nanobot in Linear, approve the pairing code in Settings → Pairing, then mention it again.",
|
||||
"mcpDescription": "This channel handles agent conversations. Connect Linear tools to let the agent search or change issues.",
|
||||
"configureTools": "Configure Linear tools",
|
||||
"workspacesTitle": "Authorized workspaces",
|
||||
"refreshWorkspaces": "Refresh workspaces",
|
||||
"loadingWorkspaces": "Loading workspaces",
|
||||
"noWorkspaces": "No workspaces are authorized. Connect a workspace to receive Linear agent requests.",
|
||||
"refreshRequired": "Authorization refresh required",
|
||||
"missingScopes": "Reconnect to grant: {{scopes}}",
|
||||
"authorized": "Authorized",
|
||||
"confirmDisconnect": "Disconnect workspace",
|
||||
"disconnect": "Disconnect"
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
"summary": "Crea una aplicación OAuth privada de Linear, guarda sus credenciales y la URL pública y, después, autoriza el espacio de trabajo. Cada sesión nueva requiere una @mención explícita; los comentarios normales se ignoran.",
|
||||
"steps": [
|
||||
"Expón esta instancia de nanobot mediante una URL HTTPS estable (puedes usar un túnel).",
|
||||
"Crea una aplicación OAuth privada en Linear con los permisos read, write y app:mentionable. No añadas app:assignable.",
|
||||
"Crea una aplicación OAuth privada en Linear con los permisos read, write, app:mentionable y app:assignable.",
|
||||
"Suscribe el webhook de la aplicación a AgentSessionEvent, PermissionChange y OAuthAuthorization con la URL generada.",
|
||||
"Introduce las credenciales de la aplicación, espera a que se guarden automáticamente, conecta el espacio de trabajo con OAuth y menciona la aplicación con @ en una incidencia."
|
||||
],
|
||||
@@ -53,6 +53,10 @@
|
||||
"label": "Usuarios de Linear permitidos",
|
||||
"placeholder": "ID de usuarios de Linear separados por comas",
|
||||
"help": "Déjalo vacío para usar el emparejamiento de nanobot, o usa * para permitir a todos los usuarios de los espacios conectados."
|
||||
},
|
||||
"showReasoning": {
|
||||
"label": "Mostrar razonamiento",
|
||||
"help": "Publica el razonamiento del modelo como actividades de pensamiento en Linear. Desactívalo para una sesión más limpia."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -71,6 +75,22 @@
|
||||
"savePublicUrl": "Introduce una URL HTTPS pública para crear una aplicación de Linear preconfigurada.",
|
||||
"saveBeforeConnect": "Introduce las credenciales de la aplicación y espera a que se guarden antes de conectar.",
|
||||
"removeCredentials": "Eliminar credenciales guardadas",
|
||||
"retrySave": "Reintentar"
|
||||
"retrySave": "Reintentar",
|
||||
"channelRunning": "Canal en ejecución",
|
||||
"accessTitle": "Acceso y herramientas de incidencias",
|
||||
"accessAll": "Todos los miembros de un espacio autorizado pueden ejecutar este agente.",
|
||||
"accessRestricted": "Solo los ID de usuario de Linear indicados en Avanzado pueden ejecutar este agente.",
|
||||
"accessPairing": "En el primer uso, menciona a nanobot en Linear, aprueba el código en Ajustes → Emparejamiento y vuelve a mencionarlo.",
|
||||
"mcpDescription": "Este canal gestiona las conversaciones del agente. Conecta las herramientas de Linear para buscar o modificar incidencias.",
|
||||
"configureTools": "Configurar herramientas de Linear",
|
||||
"workspacesTitle": "Espacios autorizados",
|
||||
"refreshWorkspaces": "Actualizar espacios",
|
||||
"loadingWorkspaces": "Cargando espacios",
|
||||
"noWorkspaces": "No hay espacios autorizados. Conecta uno para recibir solicitudes del agente de Linear.",
|
||||
"refreshRequired": "Es necesario renovar la autorización",
|
||||
"missingScopes": "Vuelve a conectar para conceder: {{scopes}}",
|
||||
"authorized": "Autorizado",
|
||||
"confirmDisconnect": "Desconectar espacio",
|
||||
"disconnect": "Desconectar"
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
"summary": "Créez une application OAuth Linear privée, enregistrez ses identifiants et son URL publique, puis autorisez l’espace de travail. Chaque nouvelle session exige une @mention explicite ; les commentaires ordinaires sont ignorés.",
|
||||
"steps": [
|
||||
"Exposez cette instance nanobot avec une URL HTTPS stable (un tunnel convient).",
|
||||
"Créez une application OAuth privée dans Linear avec les autorisations read, write et app:mentionable. N’ajoutez pas app:assignable.",
|
||||
"Créez une application OAuth privée dans Linear avec les autorisations read, write, app:mentionable et app:assignable.",
|
||||
"Abonnez le webhook de l’application à AgentSessionEvent, PermissionChange et OAuthAuthorization avec l’URL générée.",
|
||||
"Saisissez les identifiants de l’application, attendez leur enregistrement automatique, connectez l’espace de travail avec OAuth, puis mentionnez l’application avec @ dans une issue."
|
||||
],
|
||||
@@ -53,6 +53,10 @@
|
||||
"label": "Utilisateurs Linear autorisés",
|
||||
"placeholder": "ID utilisateur Linear séparés par des virgules",
|
||||
"help": "Laissez vide pour utiliser l’association nanobot, ou saisissez * pour autoriser tous les utilisateurs des espaces connectés."
|
||||
},
|
||||
"showReasoning": {
|
||||
"label": "Afficher le raisonnement",
|
||||
"help": "Publie le raisonnement du modèle comme activités de réflexion dans Linear. Désactivez cette option pour une session plus sobre."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -71,6 +75,22 @@
|
||||
"savePublicUrl": "Saisissez une URL HTTPS publique pour créer une application Linear préremplie.",
|
||||
"saveBeforeConnect": "Saisissez les identifiants de l’application et attendez leur enregistrement avant de vous connecter.",
|
||||
"removeCredentials": "Supprimer les identifiants enregistrés",
|
||||
"retrySave": "Réessayer"
|
||||
"retrySave": "Réessayer",
|
||||
"channelRunning": "Canal en cours d’exécution",
|
||||
"accessTitle": "Accès et outils pour les tickets",
|
||||
"accessAll": "Tous les membres d’un espace autorisé peuvent exécuter cet agent.",
|
||||
"accessRestricted": "Seuls les ID utilisateur Linear répertoriés dans Avancé peuvent exécuter cet agent.",
|
||||
"accessPairing": "À la première utilisation, mentionnez nanobot dans Linear, approuvez le code dans Paramètres → Association, puis mentionnez-le à nouveau.",
|
||||
"mcpDescription": "Ce canal gère les conversations de l’agent. Connectez les outils Linear pour rechercher ou modifier des tickets.",
|
||||
"configureTools": "Configurer les outils Linear",
|
||||
"workspacesTitle": "Espaces autorisés",
|
||||
"refreshWorkspaces": "Actualiser les espaces",
|
||||
"loadingWorkspaces": "Chargement des espaces",
|
||||
"noWorkspaces": "Aucun espace n’est autorisé. Connectez-en un pour recevoir les demandes de l’agent Linear.",
|
||||
"refreshRequired": "Actualisation de l’autorisation requise",
|
||||
"missingScopes": "Reconnectez-vous pour accorder : {{scopes}}",
|
||||
"authorized": "Autorisé",
|
||||
"confirmDisconnect": "Déconnecter l’espace",
|
||||
"disconnect": "Déconnecter"
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
"summary": "Buat aplikasi OAuth Linear privat, simpan kredensial dan URL publiknya, lalu otorisasi workspace. Setiap sesi baru memerlukan @mention eksplisit; komentar biasa akan diabaikan.",
|
||||
"steps": [
|
||||
"Ekspos instans nanobot ini melalui URL HTTPS yang stabil (tunnel dapat digunakan).",
|
||||
"Buat aplikasi OAuth privat di Linear dengan scope read, write, dan app:mentionable. Jangan tambahkan app:assignable.",
|
||||
"Buat aplikasi OAuth privat di Linear dengan scope read, write, app:mentionable, dan app:assignable.",
|
||||
"Daftarkan webhook aplikasi untuk AgentSessionEvent, PermissionChange, dan OAuthAuthorization menggunakan URL yang dibuat.",
|
||||
"Masukkan kredensial aplikasi, tunggu hingga tersimpan otomatis, hubungkan ruang kerja dengan OAuth, lalu sebut aplikasi dengan @ dalam issue."
|
||||
],
|
||||
@@ -53,6 +53,10 @@
|
||||
"label": "Pengguna Linear yang diizinkan",
|
||||
"placeholder": "ID pengguna Linear, dipisahkan koma",
|
||||
"help": "Biarkan kosong untuk memakai pairing nanobot, atau gunakan * untuk mengizinkan semua pengguna di workspace yang terhubung."
|
||||
},
|
||||
"showReasoning": {
|
||||
"label": "Tampilkan penalaran",
|
||||
"help": "Kirim penalaran model sebagai aktivitas pemikiran di Linear. Nonaktifkan untuk sesi yang lebih ringkas."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -71,6 +75,22 @@
|
||||
"savePublicUrl": "Masukkan URL HTTPS publik untuk membuat aplikasi Linear yang sudah terisi.",
|
||||
"saveBeforeConnect": "Masukkan kredensial aplikasi dan tunggu hingga tersimpan sebelum menghubungkan.",
|
||||
"removeCredentials": "Hapus kredensial tersimpan",
|
||||
"retrySave": "Coba lagi"
|
||||
"retrySave": "Coba lagi",
|
||||
"channelRunning": "Channel berjalan",
|
||||
"accessTitle": "Akses dan alat issue",
|
||||
"accessAll": "Semua anggota workspace yang diotorisasi dapat menjalankan agen ini.",
|
||||
"accessRestricted": "Hanya ID pengguna Linear yang tercantum di Lanjutan yang dapat menjalankan agen ini.",
|
||||
"accessPairing": "Saat pertama digunakan, mention nanobot di Linear, setujui kode pairing di Pengaturan → Pairing, lalu mention lagi.",
|
||||
"mcpDescription": "Channel ini menangani percakapan agen. Hubungkan alat Linear agar agen dapat mencari atau mengubah issue.",
|
||||
"configureTools": "Konfigurasi alat Linear",
|
||||
"workspacesTitle": "Workspace yang diotorisasi",
|
||||
"refreshWorkspaces": "Muat ulang workspace",
|
||||
"loadingWorkspaces": "Memuat workspace",
|
||||
"noWorkspaces": "Belum ada workspace yang diotorisasi. Hubungkan workspace untuk menerima permintaan agen Linear.",
|
||||
"refreshRequired": "Penyegaran otorisasi diperlukan",
|
||||
"missingScopes": "Hubungkan ulang untuk memberikan: {{scopes}}",
|
||||
"authorized": "Diotorisasi",
|
||||
"confirmDisconnect": "Putuskan workspace",
|
||||
"disconnect": "Putuskan"
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
"summary": "非公開の Linear OAuth アプリを作成し、認証情報と公開 URL を保存してからワークスペースを認証します。新しいセッションの開始には明示的な @メンションが必要で、通常のコメントは無視されます。",
|
||||
"steps": [
|
||||
"この nanobot インスタンスを安定した HTTPS URL で公開します(トンネルも利用できます)。",
|
||||
"Linear で read、write、app:mentionable スコープを持つ非公開 OAuth アプリを作成します。app:assignable は追加しないでください。",
|
||||
"Linear で read、write、app:mentionable、app:assignable スコープを持つ非公開 OAuth アプリを作成します。",
|
||||
"生成された URL を使い、アプリの webhook を AgentSessionEvent、PermissionChange、OAuthAuthorization に登録します。",
|
||||
"アプリの認証情報を入力し、自動保存の完了後に OAuth でワークスペースを接続して、issue でアプリを @メンションします。"
|
||||
],
|
||||
@@ -53,6 +53,10 @@
|
||||
"label": "許可する Linear ユーザー",
|
||||
"placeholder": "Linear ユーザー ID(カンマ区切り)",
|
||||
"help": "nanobot のペアリングを使う場合は空欄にします。接続済みワークスペースの全ユーザーを許可する場合のみ * を指定してください。"
|
||||
},
|
||||
"showReasoning": {
|
||||
"label": "推論を表示",
|
||||
"help": "モデルの推論を Linear の思考アクティビティとして投稿します。静かなセッションにするにはオフにします。"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -71,6 +75,22 @@
|
||||
"savePublicUrl": "公開 HTTPS URL を入力すると、入力済みの Linear アプリを作成できます。",
|
||||
"saveBeforeConnect": "アプリの認証情報を入力し、自動保存が完了してから接続してください。",
|
||||
"removeCredentials": "保存済みの認証情報を削除",
|
||||
"retrySave": "再試行"
|
||||
"retrySave": "再試行",
|
||||
"channelRunning": "チャンネル実行中",
|
||||
"accessTitle": "アクセスと issue ツール",
|
||||
"accessAll": "認証済みワークスペースの全メンバーがこのエージェントを実行できます。",
|
||||
"accessRestricted": "詳細設定に記載された Linear ユーザー ID のみがこのエージェントを実行できます。",
|
||||
"accessPairing": "初回は Linear で nanobot をメンションし、設定 → ペアリングでコードを承認してから、もう一度メンションしてください。",
|
||||
"mcpDescription": "このチャンネルはエージェントとの会話を処理します。issue の検索や変更には Linear ツールを接続してください。",
|
||||
"configureTools": "Linear ツールを設定",
|
||||
"workspacesTitle": "認証済みワークスペース",
|
||||
"refreshWorkspaces": "ワークスペースを更新",
|
||||
"loadingWorkspaces": "ワークスペースを読み込み中",
|
||||
"noWorkspaces": "認証済みワークスペースがありません。Linear エージェントのリクエストを受け取るには接続してください。",
|
||||
"refreshRequired": "認証の更新が必要です",
|
||||
"missingScopes": "再接続して権限を付与: {{scopes}}",
|
||||
"authorized": "認証済み",
|
||||
"confirmDisconnect": "ワークスペースを切断",
|
||||
"disconnect": "切断"
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
"summary": "비공개 Linear OAuth 앱을 만들고 인증 정보와 공개 URL을 저장한 다음 워크스페이스를 승인하세요. 새 세션은 명시적인 @멘션으로만 시작되며 일반 댓글은 무시됩니다.",
|
||||
"steps": [
|
||||
"이 nanobot 인스턴스를 안정적인 HTTPS URL로 공개하세요(터널을 사용할 수 있습니다).",
|
||||
"Linear에서 read, write, app:mentionable 범위가 있는 비공개 OAuth 앱을 만드세요. app:assignable은 추가하지 마세요.",
|
||||
"Linear에서 read, write, app:mentionable, app:assignable 범위가 있는 비공개 OAuth 앱을 만드세요.",
|
||||
"생성된 URL로 앱 webhook을 AgentSessionEvent, PermissionChange, OAuthAuthorization에 구독하세요.",
|
||||
"앱 인증 정보를 입력하고 자동 저장이 완료되면 OAuth로 워크스페이스를 연결한 후 이슈에서 앱을 @멘션하세요."
|
||||
],
|
||||
@@ -53,6 +53,10 @@
|
||||
"label": "허용된 Linear 사용자",
|
||||
"placeholder": "쉼표로 구분한 Linear 사용자 ID",
|
||||
"help": "nanobot 페어링을 사용하려면 비워 두세요. 연결된 워크스페이스의 모든 사용자를 허용하려면 *를 사용하세요."
|
||||
},
|
||||
"showReasoning": {
|
||||
"label": "추론 표시",
|
||||
"help": "모델의 추론을 Linear에 생각 활동으로 게시합니다. 더 간결한 세션을 원하면 끄세요."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -71,6 +75,22 @@
|
||||
"savePublicUrl": "공개 HTTPS URL을 입력하면 미리 채워진 Linear 앱을 만들 수 있습니다.",
|
||||
"saveBeforeConnect": "앱 인증 정보를 입력하고 자동 저장이 완료된 후 연결하세요.",
|
||||
"removeCredentials": "저장된 인증 정보 삭제",
|
||||
"retrySave": "다시 시도"
|
||||
"retrySave": "다시 시도",
|
||||
"channelRunning": "채널 실행 중",
|
||||
"accessTitle": "접근 및 이슈 도구",
|
||||
"accessAll": "승인된 워크스페이스의 모든 멤버가 이 에이전트를 실행할 수 있습니다.",
|
||||
"accessRestricted": "고급 설정에 나열된 Linear 사용자 ID만 이 에이전트를 실행할 수 있습니다.",
|
||||
"accessPairing": "처음 사용할 때 Linear에서 nanobot을 멘션하고 설정 → 페어링에서 코드를 승인한 뒤 다시 멘션하세요.",
|
||||
"mcpDescription": "이 채널은 에이전트 대화를 처리합니다. 이슈 검색이나 변경을 위해 Linear 도구를 연결하세요.",
|
||||
"configureTools": "Linear 도구 구성",
|
||||
"workspacesTitle": "승인된 워크스페이스",
|
||||
"refreshWorkspaces": "워크스페이스 새로 고침",
|
||||
"loadingWorkspaces": "워크스페이스 불러오는 중",
|
||||
"noWorkspaces": "승인된 워크스페이스가 없습니다. Linear 에이전트 요청을 받으려면 연결하세요.",
|
||||
"refreshRequired": "승인 갱신 필요",
|
||||
"missingScopes": "다시 연결하여 권한 부여: {{scopes}}",
|
||||
"authorized": "승인됨",
|
||||
"confirmDisconnect": "워크스페이스 연결 해제",
|
||||
"disconnect": "연결 해제"
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
"summary": "Crie um aplicativo OAuth privado do Linear, salve as credenciais e a URL pública e autorize o workspace. Cada nova sessão exige uma @menção explícita; comentários comuns são ignorados.",
|
||||
"steps": [
|
||||
"Exponha esta instância do nanobot por uma URL HTTPS estável (um túnel pode ser usado).",
|
||||
"Crie um aplicativo OAuth privado no Linear com os escopos read, write e app:mentionable. Não adicione app:assignable.",
|
||||
"Crie um aplicativo OAuth privado no Linear com os escopos read, write, app:mentionable e app:assignable.",
|
||||
"Inscreva o webhook do aplicativo em AgentSessionEvent, PermissionChange e OAuthAuthorization usando a URL gerada.",
|
||||
"Insira as credenciais do aplicativo, aguarde o salvamento automático, conecte o espaço de trabalho com OAuth e mencione o aplicativo com @ em uma issue."
|
||||
],
|
||||
@@ -53,6 +53,10 @@
|
||||
"label": "Usuários do Linear permitidos",
|
||||
"placeholder": "IDs de usuário do Linear separados por vírgulas",
|
||||
"help": "Deixe vazio para usar o pareamento do nanobot ou use * para permitir todos os usuários dos workspaces conectados."
|
||||
},
|
||||
"showReasoning": {
|
||||
"label": "Mostrar raciocínio",
|
||||
"help": "Publica o raciocínio do modelo como atividades de pensamento no Linear. Desative para uma sessão mais limpa."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -71,6 +75,22 @@
|
||||
"savePublicUrl": "Insira uma URL HTTPS pública para criar um aplicativo Linear pré-preenchido.",
|
||||
"saveBeforeConnect": "Insira as credenciais do aplicativo e aguarde o salvamento antes de conectar.",
|
||||
"removeCredentials": "Remover credenciais salvas",
|
||||
"retrySave": "Tentar novamente"
|
||||
"retrySave": "Tentar novamente",
|
||||
"channelRunning": "Canal em execução",
|
||||
"accessTitle": "Acesso e ferramentas de issues",
|
||||
"accessAll": "Todos os membros de um workspace autorizado podem executar este agente.",
|
||||
"accessRestricted": "Somente os IDs de usuário do Linear listados em Avançado podem executar este agente.",
|
||||
"accessPairing": "No primeiro uso, mencione o nanobot no Linear, aprove o código em Configurações → Pareamento e mencione-o novamente.",
|
||||
"mcpDescription": "Este canal gerencia conversas do agente. Conecte as ferramentas do Linear para pesquisar ou alterar issues.",
|
||||
"configureTools": "Configurar ferramentas do Linear",
|
||||
"workspacesTitle": "Workspaces autorizados",
|
||||
"refreshWorkspaces": "Atualizar workspaces",
|
||||
"loadingWorkspaces": "Carregando workspaces",
|
||||
"noWorkspaces": "Nenhum workspace está autorizado. Conecte um para receber solicitações do agente Linear.",
|
||||
"refreshRequired": "Atualização da autorização necessária",
|
||||
"missingScopes": "Reconecte para conceder: {{scopes}}",
|
||||
"authorized": "Autorizado",
|
||||
"confirmDisconnect": "Desconectar workspace",
|
||||
"disconnect": "Desconectar"
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
"summary": "Tạo ứng dụng OAuth Linear riêng tư, lưu thông tin xác thực và URL công khai, rồi cấp quyền cho workspace. Mỗi phiên mới cần @mention rõ ràng; bình luận thông thường sẽ bị bỏ qua.",
|
||||
"steps": [
|
||||
"Công khai phiên bản nanobot này qua URL HTTPS ổn định (có thể dùng tunnel).",
|
||||
"Tạo ứng dụng OAuth riêng tư trong Linear với các scope read, write và app:mentionable. Không thêm app:assignable.",
|
||||
"Tạo ứng dụng OAuth riêng tư trong Linear với các scope read, write, app:mentionable và app:assignable.",
|
||||
"Đăng ký webhook của ứng dụng cho AgentSessionEvent, PermissionChange và OAuthAuthorization bằng URL được tạo.",
|
||||
"Nhập thông tin xác thực của ứng dụng, chờ lưu tự động, kết nối không gian làm việc bằng OAuth, rồi nhắc đến ứng dụng bằng @ trong issue."
|
||||
],
|
||||
@@ -53,6 +53,10 @@
|
||||
"label": "Người dùng Linear được phép",
|
||||
"placeholder": "ID người dùng Linear, phân tách bằng dấu phẩy",
|
||||
"help": "Để trống để dùng ghép đôi nanobot, hoặc dùng * để cho phép mọi người dùng trong các workspace đã kết nối."
|
||||
},
|
||||
"showReasoning": {
|
||||
"label": "Hiển thị suy luận",
|
||||
"help": "Đăng suy luận của mô hình dưới dạng hoạt động suy nghĩ trong Linear. Tắt để phiên gọn hơn."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -71,6 +75,22 @@
|
||||
"savePublicUrl": "Nhập URL HTTPS công khai để tạo ứng dụng Linear được điền sẵn.",
|
||||
"saveBeforeConnect": "Nhập thông tin xác thực của ứng dụng và chờ lưu xong trước khi kết nối.",
|
||||
"removeCredentials": "Xóa thông tin xác thực đã lưu",
|
||||
"retrySave": "Thử lại"
|
||||
"retrySave": "Thử lại",
|
||||
"channelRunning": "Channel đang chạy",
|
||||
"accessTitle": "Quyền truy cập và công cụ issue",
|
||||
"accessAll": "Mọi thành viên trong workspace được cấp quyền đều có thể chạy agent này.",
|
||||
"accessRestricted": "Chỉ ID người dùng Linear được liệt kê trong Nâng cao mới có thể chạy agent này.",
|
||||
"accessPairing": "Khi dùng lần đầu, hãy nhắc nanobot trong Linear, duyệt mã tại Cài đặt → Ghép đôi, rồi nhắc lại.",
|
||||
"mcpDescription": "Channel này xử lý hội thoại với agent. Kết nối công cụ Linear để agent tìm kiếm hoặc thay đổi issue.",
|
||||
"configureTools": "Cấu hình công cụ Linear",
|
||||
"workspacesTitle": "Workspace được cấp quyền",
|
||||
"refreshWorkspaces": "Làm mới workspace",
|
||||
"loadingWorkspaces": "Đang tải workspace",
|
||||
"noWorkspaces": "Chưa có workspace nào được cấp quyền. Hãy kết nối để nhận yêu cầu agent Linear.",
|
||||
"refreshRequired": "Cần làm mới quyền",
|
||||
"missingScopes": "Kết nối lại để cấp: {{scopes}}",
|
||||
"authorized": "Đã cấp quyền",
|
||||
"confirmDisconnect": "Ngắt kết nối workspace",
|
||||
"disconnect": "Ngắt kết nối"
|
||||
}
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
{"description":"通过 Linear 原生 Agent Session 在 issue 中使用 nanobot。","requirements":"一个私有 Linear OAuth 应用和稳定的公网 HTTPS 回调地址","setup":{"docsLabel":"打开 Linear 配置指南","officialLabel":"创建 Linear OAuth 应用","tryIt":"在 issue 评论中 @ 应用;进入 Agent Session 后,后续对话无需重复 @。","summary":"创建私有 Linear OAuth 应用,保存凭据和公网地址,再授权工作区。新会话必须显式 @ 应用,普通评论会被忽略。","steps":["用稳定的 HTTPS 地址暴露此 nanobot 实例(可以使用隧道)。","在 Linear 创建私有 OAuth 应用,启用 read、write 和 app:mentionable;不要启用 app:assignable。","将应用 webhook 订阅 AgentSessionEvent、PermissionChange 和 OAuthAuthorization,并填写生成的 webhook 地址。","填写应用凭据,等待自动保存完成,通过 OAuth 连接工作区,然后在 issue 中 @ 应用。"],"fields":{"clientId":{"label":"OAuth Client ID","placeholder":"Linear OAuth Client ID","help":"从 Linear 私有 OAuth 应用中复制。"},"clientSecret":{"label":"OAuth Client Secret","placeholder":"••••••","help":"只保存在此 nanobot 实例中。"},"webhookSigningSecret":{"label":"Webhook 签名密钥","placeholder":"••••••","help":"在解析 webhook 内容前验证 Linear-Signature。"},"publicBaseUrl":{"label":"公网 HTTPS 地址","placeholder":"https://nanobot.example.com","help":"稳定且能转发到下方监听端口的 HTTPS 源地址,不要包含路径。"},"host":{"label":"监听地址","placeholder":"0.0.0.0"},"port":{"label":"监听端口","placeholder":"3979"},"webhookPath":{"label":"Webhook 路径","placeholder":"/linear/webhook"},"oauthCallbackPath":{"label":"OAuth 回调路径","placeholder":"/linear/oauth/callback"},"allowFrom":{"label":"允许的 Linear 用户","placeholder":"用逗号分隔 Linear 用户 ID","help":"留空使用 nanobot 配对;填写 * 允许已连接工作区内的所有用户。"}}},"custom":{"qrAlt":"Linear 授权二维码","authorizeTitle":"在 Linear 中授权","authorizeDescription":"在当前浏览器打开 Linear 或扫描二维码;授权后 nanobot 会自动启用 channel。","waiting":"正在等待 Linear 授权……","connected":"Linear 已连接。","stopped":"授权已停止。","connecting":"正在连接……","reconnect":"连接另一个工作区","connect":"连接 Linear","openLinear":"前往 Linear","createApp":"创建预填的 Linear 应用","savePublicUrl":"填写公网 HTTPS 地址后,即可创建预填的 Linear 应用。","saveBeforeConnect":"填写应用凭据,等待自动保存完成后再连接。","removeCredentials":"删除已保存的凭据","retrySave":"重试"}}
|
||||
{"description":"通过 Linear 原生 Agent Session 在 issue 中使用 nanobot。","requirements":"一个私有 Linear OAuth 应用和稳定的公网 HTTPS 回调地址","setup":{"docsLabel":"打开 Linear 配置指南","officialLabel":"创建 Linear OAuth 应用","tryIt":"在 issue 评论中 @ 应用或把 issue 委派给它;进入 Agent Session 后,后续对话无需重复 @。","summary":"创建私有 Linear OAuth 应用,保存凭据和公网地址,再授权工作区。可通过 @ 应用或委派 issue 开启会话,普通评论会被忽略。","steps":["用稳定的 HTTPS 地址暴露此 nanobot 实例(可以使用隧道)。","在 Linear 创建私有 OAuth 应用,启用 read、write、app:mentionable 和 app:assignable。","将应用 webhook 订阅 AgentSessionEvent、PermissionChange 和 OAuthAuthorization,并填写生成的 webhook 地址。","填写应用凭据,等待自动保存完成,通过 OAuth 连接工作区,然后在 issue 中 @ 应用或把 issue 委派给它。"],"fields":{"clientId":{"label":"OAuth Client ID","placeholder":"Linear OAuth Client ID","help":"从 Linear 私有 OAuth 应用中复制。"},"clientSecret":{"label":"OAuth Client Secret","placeholder":"••••••","help":"只保存在此 nanobot 实例中。"},"webhookSigningSecret":{"label":"Webhook 签名密钥","placeholder":"••••••","help":"在解析 webhook 内容前验证 Linear-Signature。"},"publicBaseUrl":{"label":"公网 HTTPS 地址","placeholder":"https://nanobot.example.com","help":"稳定且能转发到下方监听端口的 HTTPS 源地址,不要包含路径。"},"host":{"label":"监听地址","placeholder":"0.0.0.0"},"port":{"label":"监听端口","placeholder":"3979"},"webhookPath":{"label":"Webhook 路径","placeholder":"/linear/webhook"},"oauthCallbackPath":{"label":"OAuth 回调路径","placeholder":"/linear/oauth/callback"},"allowFrom":{"label":"允许的 Linear 用户","placeholder":"用逗号分隔 Linear 用户 ID","help":"留空使用 nanobot 配对;填写 * 允许已连接工作区内的所有用户。"},"showReasoning":{"label":"显示推理过程","help":"把模型推理作为思考动态发布到 Linear;关闭后会话更简洁。"}}},"custom":{"qrAlt":"Linear 授权二维码","authorizeTitle":"在 Linear 中授权","authorizeDescription":"在当前浏览器打开 Linear 或扫描二维码;授权后 nanobot 会自动启用 channel。","waiting":"正在等待 Linear 授权……","connected":"Linear 已连接。","stopped":"授权已停止。","connecting":"正在连接……","reconnect":"连接另一个工作区","connect":"连接 Linear","openLinear":"前往 Linear","createApp":"创建预填的 Linear 应用","savePublicUrl":"填写公网 HTTPS 地址后,即可创建预填的 Linear 应用。","saveBeforeConnect":"填写应用凭据,等待自动保存完成后再连接。","removeCredentials":"删除已保存的凭据","retrySave":"重试","channelRunning":"Channel 正在运行","accessTitle":"访问权限和 issue 工具","accessAll":"已授权工作区中的所有成员都可以运行此 Agent。","accessRestricted":"只有“高级”中列出的 Linear 用户 ID 可以运行此 Agent。","accessPairing":"首次使用时,请在 Linear 中 @nanobot,在“设置 → 配对”中批准配对码,然后再次 @ 它。","mcpDescription":"此 channel 负责 Agent 对话。连接 Linear 工具后,Agent 才能搜索或修改 issue。","configureTools":"配置 Linear 工具","workspacesTitle":"已授权的工作区","refreshWorkspaces":"刷新工作区","loadingWorkspaces":"正在加载工作区","noWorkspaces":"尚未授权工作区。连接工作区后才能接收 Linear Agent 请求。","refreshRequired":"需要刷新授权","missingScopes":"重新连接以授予:{{scopes}}","authorized":"已授权","confirmDisconnect":"断开工作区连接","disconnect":"断开连接"}}
|
||||
@@ -1 +1 @@
|
||||
{"description":"透過 Linear 原生 Agent Session 在 issue 中使用 nanobot。","requirements":"一個私有 Linear OAuth 應用程式和穩定的公網 HTTPS 回呼網址","setup":{"docsLabel":"開啟 Linear 設定指南","officialLabel":"建立 Linear OAuth 應用程式","tryIt":"在 issue 評論中 @ 應用程式;進入 Agent Session 後,後續對話無需重複 @。","summary":"建立私有 Linear OAuth 應用程式,儲存憑證和公網網址,再授權工作區。新會話必須明確 @ 應用程式,普通評論會被忽略。","steps":["用穩定的 HTTPS 網址公開此 nanobot 實例(可以使用隧道)。","在 Linear 建立私有 OAuth 應用程式,啟用 read、write 和 app:mentionable;不要啟用 app:assignable。","將應用程式 webhook 訂閱 AgentSessionEvent、PermissionChange 和 OAuthAuthorization,並填入產生的 webhook 網址。","填寫應用程式憑證,等待自動儲存完成,透過 OAuth 連接工作區,然後在 issue 中 @ 應用程式。"],"fields":{"clientId":{"label":"OAuth Client ID","placeholder":"Linear OAuth Client ID","help":"從 Linear 私有 OAuth 應用程式中複製。"},"clientSecret":{"label":"OAuth Client Secret","placeholder":"••••••","help":"只儲存在此 nanobot 實例中。"},"webhookSigningSecret":{"label":"Webhook 簽署密鑰","placeholder":"••••••","help":"在解析 webhook 內容前驗證 Linear-Signature。"},"publicBaseUrl":{"label":"公網 HTTPS 網址","placeholder":"https://nanobot.example.com","help":"穩定且能轉送到下方監聽連接埠的 HTTPS 來源網址,不要包含路徑。"},"host":{"label":"監聽位址","placeholder":"0.0.0.0"},"port":{"label":"監聽連接埠","placeholder":"3979"},"webhookPath":{"label":"Webhook 路徑","placeholder":"/linear/webhook"},"oauthCallbackPath":{"label":"OAuth 回呼路徑","placeholder":"/linear/oauth/callback"},"allowFrom":{"label":"允許的 Linear 使用者","placeholder":"以逗號分隔 Linear 使用者 ID","help":"留空使用 nanobot 配對;填寫 * 允許已連接工作區內的所有使用者。"}}},"custom":{"qrAlt":"Linear 授權 QR code","authorizeTitle":"在 Linear 中授權","authorizeDescription":"在目前瀏覽器開啟 Linear 或掃描 QR code;授權後 nanobot 會自動啟用 channel。","waiting":"正在等待 Linear 授權……","connected":"Linear 已連接。","stopped":"授權已停止。","connecting":"正在連接……","reconnect":"連接另一個工作區","connect":"連接 Linear","openLinear":"前往 Linear","createApp":"建立預填的 Linear 應用程式","savePublicUrl":"填寫公開 HTTPS 網址後,即可建立預填的 Linear 應用程式。","saveBeforeConnect":"填寫應用程式憑證,等待自動儲存完成後再連線。","removeCredentials":"刪除已儲存的憑證","retrySave":"重試"}}
|
||||
{"description":"透過 Linear 原生 Agent Session 在 issue 中使用 nanobot。","requirements":"一個私有 Linear OAuth 應用程式和穩定的公網 HTTPS 回呼網址","setup":{"docsLabel":"開啟 Linear 設定指南","officialLabel":"建立 Linear OAuth 應用程式","tryIt":"在 issue 評論中 @ 應用程式或將 issue 委派給它;進入 Agent Session 後,後續對話無需重複 @。","summary":"建立私有 Linear OAuth 應用程式,儲存憑證和公網網址,再授權工作區。可透過 @ 應用程式或委派 issue 開啟會話,普通評論會被忽略。","steps":["用穩定的 HTTPS 網址公開此 nanobot 實例(可以使用隧道)。","在 Linear 建立私有 OAuth 應用程式,啟用 read、write、app:mentionable 和 app:assignable。","將應用程式 webhook 訂閱 AgentSessionEvent、PermissionChange 和 OAuthAuthorization,並填入產生的 webhook 網址。","填寫應用程式憑證,等待自動儲存完成,透過 OAuth 連接工作區,然後在 issue 中 @ 應用程式或將 issue 委派給它。"],"fields":{"clientId":{"label":"OAuth Client ID","placeholder":"Linear OAuth Client ID","help":"從 Linear 私有 OAuth 應用程式中複製。"},"clientSecret":{"label":"OAuth Client Secret","placeholder":"••••••","help":"只儲存在此 nanobot 實例中。"},"webhookSigningSecret":{"label":"Webhook 簽署密鑰","placeholder":"••••••","help":"在解析 webhook 內容前驗證 Linear-Signature。"},"publicBaseUrl":{"label":"公網 HTTPS 網址","placeholder":"https://nanobot.example.com","help":"穩定且能轉送到下方監聽連接埠的 HTTPS 來源網址,不要包含路徑。"},"host":{"label":"監聽位址","placeholder":"0.0.0.0"},"port":{"label":"監聽連接埠","placeholder":"3979"},"webhookPath":{"label":"Webhook 路徑","placeholder":"/linear/webhook"},"oauthCallbackPath":{"label":"OAuth 回呼路徑","placeholder":"/linear/oauth/callback"},"allowFrom":{"label":"允許的 Linear 使用者","placeholder":"以逗號分隔 Linear 使用者 ID","help":"留空使用 nanobot 配對;填寫 * 允許已連接工作區內的所有使用者。"},"showReasoning":{"label":"顯示推理過程","help":"將模型推理作為思考動態發佈到 Linear;關閉後會話更簡潔。"}}},"custom":{"qrAlt":"Linear 授權 QR code","authorizeTitle":"在 Linear 中授權","authorizeDescription":"在目前瀏覽器開啟 Linear 或掃描 QR code;授權後 nanobot 會自動啟用 channel。","waiting":"正在等待 Linear 授權……","connected":"Linear 已連接。","stopped":"授權已停止。","connecting":"正在連接……","reconnect":"連接另一個工作區","connect":"連接 Linear","openLinear":"前往 Linear","createApp":"建立預填的 Linear 應用程式","savePublicUrl":"填寫公開 HTTPS 網址後,即可建立預填的 Linear 應用程式。","saveBeforeConnect":"填寫應用程式憑證,等待自動儲存完成後再連線。","removeCredentials":"刪除已儲存的憑證","retrySave":"重試","channelRunning":"Channel 正在執行","accessTitle":"存取權限和 issue 工具","accessAll":"已授權工作區中的所有成員都可以執行此 Agent。","accessRestricted":"只有「進階」中列出的 Linear 使用者 ID 可以執行此 Agent。","accessPairing":"首次使用時,請在 Linear 中 @nanobot,在「設定 → 配對」中核准配對碼,然後再次 @ 它。","mcpDescription":"此 channel 負責 Agent 對話。連接 Linear 工具後,Agent 才能搜尋或修改 issue。","configureTools":"設定 Linear 工具","workspacesTitle":"已授權的工作區","refreshWorkspaces":"重新整理工作區","loadingWorkspaces":"正在載入工作區","noWorkspaces":"尚未授權工作區。連接工作區後才能接收 Linear Agent 請求。","refreshRequired":"需要重新整理授權","missingScopes":"重新連接以授予:{{scopes}}","authorized":"已授權","confirmDisconnect":"中斷工作區連線","disconnect":"中斷連線"}}
|
||||
@@ -8,12 +8,13 @@ export function linearManifestUrl(
|
||||
schemaVersion: "1.0.0",
|
||||
distribution: "private",
|
||||
display: {
|
||||
description: "Use nanobot as a native issue agent.",
|
||||
description: "Mention or delegate issues to nanobot as a native Linear agent.",
|
||||
iconUrl: "https://raw.githubusercontent.com/HKUDS/nanobot/main/images/nanobot_logo.png",
|
||||
},
|
||||
developer: { name: "nanobot" },
|
||||
oauth: {
|
||||
client_name: "nanobot Agent",
|
||||
client_uri: publicBaseUrl,
|
||||
client_uri: "https://github.com/HKUDS/nanobot",
|
||||
redirect_uris: [`${publicBaseUrl}${callbackPath}`],
|
||||
grant_types: ["authorization_code"],
|
||||
},
|
||||
|
||||
+21
-1
@@ -1212,7 +1212,22 @@ export interface McpPresetsPayload {
|
||||
};
|
||||
}
|
||||
|
||||
type ChannelConnectStatus = "pending" | "succeeded" | "expired" | "cancelled" | "failed";
|
||||
type ChannelConnectStatus =
|
||||
| "pending"
|
||||
| "succeeded"
|
||||
| "expired"
|
||||
| "cancelled"
|
||||
| "failed"
|
||||
| "inspected"
|
||||
| "disconnected";
|
||||
|
||||
export interface ChannelInstallationSummary {
|
||||
organization_id: string;
|
||||
organization_name?: string;
|
||||
scopes?: string[];
|
||||
authorization_status?: "authorized" | "refresh_required" | "missing_scopes";
|
||||
missing_scopes?: string[];
|
||||
}
|
||||
|
||||
export interface ChannelConnectPayload {
|
||||
session_id: string;
|
||||
@@ -1222,6 +1237,11 @@ export interface ChannelConnectPayload {
|
||||
qr_url?: string;
|
||||
interval_ms?: number;
|
||||
expires_at_ms?: number;
|
||||
organization_id?: string;
|
||||
organization_name?: string;
|
||||
installations?: ChannelInstallationSummary[];
|
||||
webhook_url?: string;
|
||||
redirect_uri?: string;
|
||||
nanobot_features?: NanobotFeaturesPayload;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user