Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
feat(linear): manage member access from WebUI
Xubin Rene78544fcaf2a
diff --git a/docs/guides/linear-agent.md b/docs/guides/linear-agent.mdindex 884067b50..805c73c97 100644--- a/docs/guides/linear-agent.md+++ b/docs/guides/linear-agent.md@@ -16,9 +16,9 @@ and confirm that webhook delivery is enabled before testing a task.- An ordinary issue comment does not invoke nanobot.- A follow-up inside the existing Agent Session continues the same nanobotsession without another @mention.-- 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.+- Linear's stop control asks nanobot to cancel the active turn. The sender must+ have access, just as for other requests. An activity already delivered to+ Linear cannot be recalled.- nanobot reports its acknowledgement, tool activity, reasoning, and finalanswer as native Linear Agent Activities.- Button choices are sent as Linear selection activities, and local outbound@@ -231,11 +231,37 @@ refreshes each workspace installation separately.4. Send a follow-up inside that Agent Session. You do not need to @mention theapp again there.-If **Allowed Linear users** is empty, the first mention returns a nanobot pairing-code. Approve the pending request in the WebUI pairing dialog, then repeat the-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.+Before inviting teammates, open **Member access** under the authorized workspace+in **Settings → Channels → Linear**. Search for a member and switch on **Allow+… to use nanobot**. Wait for **Member access saved.** They can then mention the+agent without copying a pairing code or authorizing another OAuth installation.++The list contains active human members of teams this app can access. It does not+grant access to additional Linear teams or to the nanobot admin UI. Names are for+display; permissions use stable user IDs scoped to the OAuth client and workspace.+Use **Refresh members** to refresh the directory and effective permission state.+If a read or save fails, the UI reports the failure and requires a refresh before+another edit; it does not pretend a switch was saved.++New members are off by default. Existing pairing approvals and **Advanced →+Allowed Linear users** remain valid until explicitly overridden by a member+switch. An explicit **off** wins over both legacy approvals and `*`, even if a+new pairing code is subsequently approved. Use the switch to enable that member+again. If you keep `*`, new members will still be allowed automatically; the UI+displays a warning. Remove `*` to require approval for new members.++Pairing remains a fallback for members without an explicit switch setting:+approve their pending request in the WebUI pairing dialog, then repeat the prompt+in the same Agent Session. You may also keep a static list of IDs in **Allowed+Linear users**. Other channels' pairing behavior is unchanged.++At request admission nanobot checks current team membership through the app's+Linear API authorization, including active status and excluding app accounts.+Directory/API failure does not authorize a task; transient failures use the+channel's bounded webhook retry path. This adds API requests and latency, rather+than relying on stale cached permissions. Turning a member off blocks new+requests (including stop requests); it does not cancel already admitted/running+tasks or recall replies. Administrators should stop ongoing tasks separately.By default, reasoning is posted as Linear thought activities. Turn off **Showreasoning** under **Advanced** for a quieter session. Use **Configure Linear@@ -243,6 +269,32 @@ MCP**, to the left of **Create Linear app**, to open Linear MCP's connectionsettings when prompts need to search, edit, or transition issues. Pairing andaccess guidance is available in the dialog's **Help** menu.+### Updating a remote installation++Member management includes both Python channel code and WebUI assets. A local+branch does not update an already running remote gateway, and the browser UI+served by that remote gateway is not replaced by installing a local client.++1. Develop and test in a separate checkout with test-only config/state. Do not+ copy production OAuth tokens, model keys, or pairing state into a development+ profile, or run a second gateway against the production webhook installation.+2. After review and deployment approval, back up the remote config, pairing file,+ and Linear SQLite state consistently (stop the gateway or use SQLite backup;+ copying just the database while WAL writes are active is not sufficient).+3. Update the remote source and dependencies to the reviewed revision, build the+ WebUI from that same revision, and restart the gateway. Preserve remote+ credentials and state. Existing OAuth scopes and webhook routes need not change.+4. Verify member listing, the existing owner's access, enable/disable behavior,+ and that the admin UI remains private. Grant teammate access only deliberately.++Member switches are stored in the instance's `linear/state.sqlite3`, separately+from legacy pairing and config. Older code ignores those overrides: **do not+blindly roll back after revoking access with a switch**, because old code could+re-enable a member through a retained pairing approval or wildcard. Keep the+channel disabled during rollback until the older allowlist/pairing configuration+has been reconciled. Ordinary restarts and reconnecting the same OAuth app keep+the saved member choices.+## Verify the setupThe setup is complete when all of these checks pass:@@ -338,7 +390,7 @@ secret.| The local health URL does not load | Start **Connect Linear** or enable the connected channel, then check the configured listen host and port. || **Agent didn't start**, **nanobot failed to start**, or a session stays on **Thinking…** without a response | First check **Webhooks → Delivery status** in the Linear app. If **Disabled**, enable it from **…**. Confirm the current Webhook URL and `AgentSessionEvent` subscription, then select **Retry** in the Linear session. OAuth success and a working `/linear/health` endpoint do not prove that Linear is sending events. || An @mention still gets no response with delivery enabled | Inspect **Webhook delivery failures** in the Linear app and run `nanobot gateway logs`. A 404 points to the webhook path; a 502 points to the listener or tunnel; a 401 can indicate a signing-secret mismatch or stale event timestamp. Confirm the Client ID and signing secret belong to the same app and the workspace authorization has not been revoked. |-| The first @mention returns a pairing code | Approve it in the WebUI pairing dialog, then repeat the prompt in the same Agent Session. Alternatively, configure a narrow **Allowed Linear users** list. |+| The first @mention returns a pairing code | Enable the member under the workspace's **Member access**, or approve the code in the WebUI pairing dialog, then repeat the prompt. An explicit off switch must be changed in **Member access**; pairing or allowlist changes do not override it. || Normal comments do nothing | This is intentional. Start a task by @mentioning the app, or continue inside an existing Agent Session. || Delegating an issue does not start a session | Reconnect the workspace so the installation grants `app:assignable`, then confirm the app can be selected as the issue delegate. || The agent can discuss an issue but cannot search or change it | Connect the Linear MCP app from **Configure Linear MCP**. The native channel transports the conversation but does not add issue-management tools. |diff --git a/nanobot/channels/linear/access.py b/nanobot/channels/linear/access.pynew file mode 100644index 000000000..09a31d017--- /dev/null+++ b/nanobot/channels/linear/access.py@@ -0,0 +1,21 @@+"""Installation-scoped member choices, with non-destructive legacy approval fallback."""++from nanobot.channels.linear.config import LinearConfig+from nanobot.channels.linear.state import LinearStateStore+from nanobot.pairing.store import is_approved+++def member_allowed(+ config: LinearConfig, state: LinearStateStore, organization_id: str, user_id: str,+) -> bool:+ installation = state.installation(organization_id)+ if installation is None or installation.oauth_client_id != config.client_id:+ return False+ choice = state.member_access(config.client_id, organization_id, user_id)+ if choice is not None:+ return choice+ return (+ "*" in config.allow_from+ or user_id in config.allow_from+ or is_approved("linear", user_id)+ )diff --git a/nanobot/channels/linear/client.py b/nanobot/channels/linear/client.pyindex 03498c3e7..e7169b2ec 100644--- a/nanobot/channels/linear/client.py+++ b/nanobot/channels/linear/client.py@@ -6,7 +6,7 @@ import asyncioimport mimetypesimport timefrom pathlib import Path-from typing import Any, cast+from typing import Any, TypedDict, castimport httpx@@ -22,6 +22,12 @@ MAX_UPLOAD_BYTES = 40 * 1024 * 1024MAX_DOWNLOAD_BYTES = 40 * 1024 * 1024+class LinearMember(TypedDict):+ id: str+ name: str+ teams: list[str]++class LinearApiError(RuntimeError):"""Linear returned a transport, authentication, or GraphQL error."""@@ -108,6 +114,83 @@ class LinearClient:installation = await self._refresh(organization_id, force=True)return await self._graphql_with_token(installation.access_token, query, variables)+ async def list_members(+ self, organization_id: str, *, user_id: str | None = None,+ ) -> list[LinearMember]:+ """Read active humans in teams visible to this app, never workspace-wide users.++ A filtered lookup is also used at request admission: departed members and+ revoked team access must not keep working through old local approvals.+ No stale directory cache is used to authorize a request.+ """+ teams = await self._connection_nodes(+ organization_id,+ """query NanobotMemberTeams($after: String) {+ teams(first: 50, after: $after) {+ nodes { id name } pageInfo { hasNextPage endCursor }+ }+ }""",+ {}, ("teams",),+ )+ members: dict[str, LinearMember] = {}+ for team in teams:+ team_id = _required_string(team, "id")+ team_name = _required_string(team, "name")+ nodes = await self._connection_nodes(+ organization_id,+ """query NanobotTeamMembers($team: String!, $after: String, $filter: UserFilter) {+ team(id: $team) {+ members(first: 50, after: $after, filter: $filter) {+ nodes { id name active app }+ pageInfo { hasNextPage endCursor }+ }+ }+ }""",+ {"team": team_id, "filter": {"id": {"eq": user_id}} if user_id else None},+ ("team", "members"),+ )+ for node in nodes:+ if not isinstance(node.get("active"), bool) or not isinstance(node.get("app"), bool):+ raise LinearApiError("Linear returned an incomplete member identity")+ if node["active"] is not True or node["app"] is True:+ continue+ member_id = _required_string(node, "id")+ name = _required_string(node, "name")+ if user_id is not None and member_id != user_id:+ raise LinearApiError("Linear returned an unexpected member identity")+ member = members.setdefault(member_id, {"id": member_id, "name": name, "teams": []})+ if team_name not in member["teams"]:+ member["teams"].append(team_name)+ return sorted(members.values(), key=lambda member: (member["name"].casefold(), member["id"]))++ async def _connection_nodes(+ self, organization_id: str, query: str, variables: dict[str, Any], path: tuple[str, ...],+ ) -> list[dict[str, Any]]:+ nodes: list[dict[str, Any]] = []+ cursor: str | None = None+ seen: set[str] = set()+ for _ in range(200):+ connection = await self.graphql(organization_id, query, {**variables, "after": cursor})+ for key in path:+ connection = _required_mapping(connection, key)+ raw_nodes = connection.get("nodes")+ if not isinstance(raw_nodes, list):+ raise LinearApiError("Linear returned an invalid member directory")+ for raw_node in cast(list[object], raw_nodes):+ if not isinstance(raw_node, dict):+ raise LinearApiError("Linear returned an invalid member directory")+ nodes.append(cast(dict[str, Any], raw_node))+ page = _required_mapping(connection, "pageInfo")+ if page.get("hasNextPage") is False:+ return nodes+ if page.get("hasNextPage") is not True:+ raise LinearApiError("Linear returned incomplete pagination information")+ cursor = _required_string(page, "endCursor")+ if cursor in seen:+ raise LinearApiError("Linear returned a repeated member directory cursor")+ seen.add(cursor)+ raise LinearApiError("Linear member directory is too large; no partial result was saved")+async def create_activity(self,organization_id: str,diff --git a/nanobot/channels/linear/connect.py b/nanobot/channels/linear/connect.pyindex 72ac6ccde..247f5fe2c 100644--- a/nanobot/channels/linear/connect.py+++ b/nanobot/channels/linear/connect.py@@ -8,6 +8,7 @@ from dataclasses import dataclass, fieldfrom typing import Any, castfrom nanobot.channels.connect import ChannelConnectError, QueryParams, query_first+from nanobot.channels.linear.access import member_allowedfrom nanobot.channels.linear.client import LinearApiError, LinearClientfrom nanobot.channels.linear.config import LinearConfigfrom nanobot.channels.linear.oauth import (@@ -49,6 +50,19 @@ class LinearConnectStore:if not organization_id:raise ChannelConnectError("missing Linear workspace")return await self.disconnect(organization_id)+ if operation in {"members", "member_access"}:+ organization_id = (query_first(query, "organization_id") or "").strip()+ if not organization_id:+ raise ChannelConnectError("missing Linear workspace")+ user_id: str | None = None+ allowed: bool | None = None+ if operation == "member_access":+ user_id = (query_first(query, "user_id") or "").strip()+ raw_allowed = query_first(query, "allowed")+ if not user_id or raw_allowed not in {"true", "false"}:+ raise ChannelConnectError("member access requires a user ID and true/false")+ allowed = raw_allowed == "true"+ return await self.members(organization_id, user_id=user_id, allowed=allowed)if operation != "connect":raise ChannelConnectError(f"unsupported Linear connect operation: {operation}")return await self.start(force=_query_bool(query, "force"))@@ -180,6 +194,39 @@ class LinearConnectStore:"redirect_uri": config.redirect_uri if config.public_base_url else "",}+ async def members(+ self, organization_id: str, *, user_id: str | None = None, allowed: bool | None = None,+ ) -> 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:+ members = await client.list_members(organization_id, user_id=user_id)+ except LinearApiError as exc:+ raise ChannelConnectError(f"Unable to read Linear members: {exc}", status=502) from exc+ finally:+ await client.close()+ if user_id is not None and allowed is not None:+ if not any(member["id"] == user_id for member in members):+ raise ChannelConnectError("Member is not active in an accessible Linear team", status=404)+ try:+ state.set_member_access(config.client_id, organization_id, user_id, allowed=allowed)+ except ValueError as exc:+ raise ChannelConnectError(str(exc), status=409) from exc+ return {+ "session_id": "",+ "status": "members" if allowed is None else "member_access_saved",+ "organization_id": organization_id,+ "legacy_allow_all": "*" in config.allow_from,+ "members": [+ {**member, "allowed": member_allowed(config, state, organization_id, member["id"])}+ for member in members+ ],+ }+async def disconnect(self, organization_id: str) -> dict[str, Any]:config = _load_linear_config()state = LinearStateStore()diff --git a/nanobot/channels/linear/runtime.py b/nanobot/channels/linear/runtime.pyindex e73fd07e8..03741edb1 100644--- a/nanobot/channels/linear/runtime.py+++ b/nanobot/channels/linear/runtime.py@@ -16,11 +16,13 @@ from nanobot.bus.events import InboundMessage, OutboundMessagefrom nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent, RetryWaitEventfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannel+from nanobot.channels.linear.access import member_allowedfrom nanobot.channels.linear.client import MAX_DOWNLOAD_BYTES, LinearApiError, LinearClientfrom nanobot.channels.linear.config import LinearConfigfrom nanobot.channels.linear.server import LinearServerLease, acquire_http_serverfrom nanobot.channels.linear.state import LinearStateStore, QueuedWebhookfrom nanobot.config.paths import get_media_dir+from nanobot.pairing import PAIRING_CODE_META_KEYfrom nanobot.security.network import validate_url_targetfrom nanobot.utils.helpers import safe_filename@@ -100,7 +102,29 @@ class LinearChannel(BaseChannel):def start_error_message(self, error: Exception) -> str | None:return f"Linear channel failed to start: {error}"+ def is_allowed(self, sender_id: str) -> bool:+ # _handle_message accepts a separate authorization subject, while the+ # actual sender ID (including legacy pairing codes) remains unchanged.+ try:+ subject: object = json.loads(sender_id)+ except (ValueError, TypeError):+ return False+ if not isinstance(subject, list):+ return False+ parts = cast(list[object], subject)+ if len(parts) != 2:+ return False+ organization_id, user_id = parts+ if not isinstance(organization_id, str) or not isinstance(user_id, str):+ return False+ return member_allowed(self.config, self._state, organization_id, user_id)+async def send(self, msg: OutboundMessage) -> None:+ if PAIRING_CODE_META_KEY in msg.metadata:+ msg.content = (+ "Ask your nanobot administrator to enable your access in Linear member settings. "+ "Alternatively, an administrator can approve this pairing request.\n\n" + msg.content+ )event = msg.eventif isinstance(event, ContextCompactionEvent):if event.phase == "succeeded":@@ -355,7 +379,7 @@ class LinearChannel(BaseChannel):if str(session.get("organizationId") or organization_id) != organization_id:raise LinearPayloadError("organization mismatch")installation = self._state.installation(organization_id)- if installation is None:+ if installation is None or installation.oauth_client_id != self.config.client_id:raise LinearPayloadError("organization is not installed")activity = _optional_object(payload.get("agentActivity"))if activity and str(activity.get("userId") or "") == installation.app_user_id:@@ -368,6 +392,7 @@ class LinearChannel(BaseChannel):).strip()if not sender_id:raise LinearPayloadError("missing sender identity")+ authorization_id = json.dumps([organization_id, sender_id])issue_context = _issue_context(session)prompt_content = _prompt_text(payload, session, activity, action, issue_context=issue_context,@@ -397,7 +422,25 @@ 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)))+ choice = self._state.member_access(self.config.client_id, organization_id, sender_id)+ if choice is False:+ await self._create_activity(+ agent_session_id, metadata,+ {"type": "response", "body": "Access is disabled. Ask your nanobot administrator to enable your access in Linear member settings."},+ key="access-denied",+ )+ return+ if self.is_allowed(authorization_id):+ client = self._client+ if client is None:+ raise RuntimeError("Linear HTTP client is not initialized")+ # Read current membership on admission, without caching grants. API+ # failures take the normal error path and never publish an agent turn.+ if not await client.list_members(organization_id, user_id=sender_id):+ raise LinearPayloadError("sender is not active in an accessible Linear team")if signal == "stop":+ if not self.is_allowed(authorization_id):+ returnawait self.bus.publish_inbound(InboundMessage(channel=self.name,@@ -411,7 +454,7 @@ class LinearChannel(BaseChannel):returnmedia: list[str] = []context_delivered = False- if self.is_allowed(sender_id):+ if self.is_allowed(authorization_id):await self._create_activity(agent_session_id,metadata,@@ -436,6 +479,7 @@ class LinearChannel(BaseChannel):metadata=metadata,session_key=f"linear:{organization_id}:{agent_session_id}",is_dm=True,+ authorization_id=authorization_id,)if context_delivered:self._issue_contexts[agent_session_id] = issue_contextdiff --git a/nanobot/channels/linear/state.py b/nanobot/channels/linear/state.pyindex 7fd9cf50d..546cdd864 100644--- a/nanobot/channels/linear/state.py+++ b/nanobot/channels/linear/state.py@@ -82,6 +82,13 @@ class LinearStateStore:delivery_id TEXT PRIMARY KEY,received_at REAL NOT NULL);+ CREATE TABLE IF NOT EXISTS member_access (+ oauth_client_id TEXT NOT NULL,+ organization_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ allowed INTEGER NOT NULL CHECK (allowed IN (0, 1)),+ PRIMARY KEY (oauth_client_id, organization_id, user_id)+ );""")columns = {@@ -175,6 +182,34 @@ class LinearStateStore:(organization_id,),)+ def member_access(self, client_id: str, organization_id: str, user_id: str) -> bool | None:+ """An explicit choice overrides legacy pairing and allowFrom, including '*'."""+ with self._guard, self._connect() as connection:+ row = connection.execute(+ "SELECT allowed FROM member_access "+ "WHERE oauth_client_id = ? AND organization_id = ? AND user_id = ?",+ (client_id, organization_id, user_id),+ ).fetchone()+ return bool(row["allowed"]) if row is not None else None++ def set_member_access(+ self, client_id: str, organization_id: str, user_id: str, *, allowed: bool,+ ) -> None:+ with self._guard, self._connect() as connection:+ connection.execute("BEGIN IMMEDIATE")+ installed = connection.execute(+ "SELECT 1 FROM installations WHERE oauth_client_id = ? AND organization_id = ?",+ (client_id, organization_id),+ ).fetchone()+ if installed is None:+ raise ValueError("Linear workspace is not connected")+ connection.execute(+ "INSERT INTO member_access (oauth_client_id, organization_id, user_id, allowed) "+ "VALUES (?, ?, ?, ?) ON CONFLICT(oauth_client_id, organization_id, user_id) "+ "DO UPDATE SET allowed = excluded.allowed",+ (client_id, organization_id, user_id, int(allowed)),+ )+def enqueue_webhook(self, delivery_id: str, payload: dict[str, Any]) -> bool:serialized = json.dumps(payload, separators=(",", ":"), ensure_ascii=False)with self._guard, self._connect() as connection:diff --git a/nanobot/channels/linear/tests/conftest.py b/nanobot/channels/linear/tests/conftest.pynew file mode 100644index 000000000..ca7fcf783--- /dev/null+++ b/nanobot/channels/linear/tests/conftest.py@@ -0,0 +1,12 @@+"""Keep Linear installation and permission state out of the user's real profile."""++from pathlib import Path++import pytest++[email protected](autouse=True)+def isolate_linear_state(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ "nanobot.channels.linear.state.get_runtime_subdir", lambda _name: tmp_path / "linear",+ )diff --git a/nanobot/channels/linear/tests/test_linear.py b/nanobot/channels/linear/tests/test_linear.pyindex 70361606d..0b9bb5603 100644--- a/nanobot/channels/linear/tests/test_linear.py+++ b/nanobot/channels/linear/tests/test_linear.py@@ -28,7 +28,7 @@ from nanobot.bus.queue import MessageBusfrom nanobot.channels.linear import client as linear_clientfrom nanobot.channels.linear import connect as linear_connectfrom nanobot.channels.linear import runtime as linear_runtime-from nanobot.channels.linear.client import LinearApiError, LinearClient+from nanobot.channels.linear.client import LinearApiError, LinearClient, LinearMemberfrom nanobot.channels.linear.config import LinearConfig, validate_public_base_urlfrom nanobot.channels.linear.oauth import OAUTH_FLOWS, authorization_urlfrom nanobot.channels.linear.runtime import LinearChannel@@ -660,6 +660,11 @@ class _FakeLinearClient:self.activities: list[dict[str, Any]] = []self.downloads: list[str] = []+ async def list_members(+ self, _organization_id: str, *, user_id: str | None = None,+ ) -> list[LinearMember]:+ return [{"id": user_id or "user-1", "name": "Member", "teams": ["Team"]}]+async def create_activity(self,organization_id: str,@@ -976,7 +981,6 @@ async def test_inbound_attachments_enforce_the_count_limit(@pytest.mark.asyncioasync def test_prompted_stop_signal_becomes_priority_stop_command(tmp_path: Path) -> None:channel, client = _runtime(tmp_path)- channel.config.allow_from = []await channel._process_webhook( # pyright: ignore[reportPrivateUsage]"delivery-2",_agent_webhook(action="prompted", signal="stop"),diff --git a/nanobot/channels/linear/tests/test_member_access.py b/nanobot/channels/linear/tests/test_member_access.pynew file mode 100644index 000000000..e8df60951--- /dev/null+++ b/nanobot/channels/linear/tests/test_member_access.py@@ -0,0 +1,217 @@+from __future__ import annotations++import json+from dataclasses import replace+from pathlib import Path+from typing import Any+from unittest.mock import AsyncMock++import httpx+import pytest++from nanobot.channels.linear import connect as linear_connect+from nanobot.channels.linear.access import member_allowed+from nanobot.channels.linear.client import LinearApiError, LinearClient+from nanobot.channels.linear.runtime import LinearPayloadError+from nanobot.channels.linear.state import LinearStateStore+from nanobot.channels.linear.tests.test_linear import (+ _agent_webhook,+ _config,+ _installation,+ _runtime,+)+from nanobot.pairing.store import approve_code, generate_code++[email protected]("legacy", ["pairing", "allowlist", "wildcard", "none"])+def test_member_choice_overrides_legacy_and_survives_restart(tmp_path: Path, legacy: str) -> None:+ config = _config()+ config.allow_from = ["*"] if legacy == "wildcard" else ["user-1"] if legacy == "allowlist" else []+ if legacy == "pairing":+ approve_code(generate_code("linear", "user-1"))+ state = LinearStateStore(tmp_path / "state.sqlite3")+ state.save_installation(_installation())+ assert member_allowed(config, state, "org-1", "user-1") is (legacy != "none")+ state.set_member_access(config.client_id, "org-1", "user-1", allowed=False)+ # A new legacy approval must not resurrect an explicit off switch.+ approve_code(generate_code("linear", "user-1"))+ reopened = LinearStateStore(state.path)+ assert not member_allowed(config, reopened, "org-1", "user-1")+ reopened.set_member_access(config.client_id, "org-1", "user-1", allowed=True)+ assert member_allowed(config, state, "org-1", "user-1")+++def test_access_is_scoped_to_app_and_workspace(tmp_path: Path) -> None:+ state = LinearStateStore(tmp_path / "state.sqlite3")+ state.save_installation(_installation())+ state.save_installation(replace(_installation(), organization_id="org-2"))+ config = _config()+ config.allow_from = []+ state.set_member_access(config.client_id, "org-1", "user-1", allowed=True)+ assert not member_allowed(config, state, "org-2", "user-1")+ with pytest.raises(ValueError, match="not connected"):+ state.set_member_access("other-client", "org-1", "user-1", allowed=True)+ state.save_installation(replace(_installation(), oauth_client_id="other-client"))+ assert not member_allowed(config, state, "org-1", "user-1")+ state.delete_installation("org-1")+ assert not member_allowed(config, state, "org-1", "user-1")+++def connection(nodes: list[dict[str, Any]], cursor: str | None = None) -> dict[str, Any]:+ return {"nodes": nodes, "pageInfo": {"hasNextPage": cursor is not None, "endCursor": cursor}}+++async def test_directory_paginates_teams_and_members_filters_apps_and_deduplicates(tmp_path: Path) -> None:+ state = LinearStateStore(tmp_path / "state.sqlite3")+ state.save_installation(_installation())+ calls: list[dict[str, Any]] = []++ def handler(request: httpx.Request) -> httpx.Response:+ body = json.loads(request.content)+ variables = body["variables"]+ calls.append(variables)+ assert request.headers["Authorization"] == "Bearer access"+ if "NanobotMemberTeams" in body["query"]:+ teams = connection([{"id": "t1", "name": "One"}], "team-next") if not variables["after"] else connection([{"id": "t2", "name": "Two"}])+ return httpx.Response(200, json={"data": {"teams": teams}})+ human = {"id": "u1", "name": "Yongru", "active": True, "app": False}+ if variables["team"] == "t1" and not variables["after"]:+ members = connection([human, {**human, "id": "bot", "app": True}], "member-next")+ elif variables["after"]:+ members = connection([{**human, "id": "inactive", "active": False}])+ else:+ members = connection([human])+ return httpx.Response(200, json={"data": {"team": {"members": members}}})++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:+ client = LinearClient(_config(), state, http)+ assert await client.list_members("org-1") == [{"id": "u1", "name": "Yongru", "teams": ["One", "Two"]}]+ assert len(calls) == 5+++async def test_filtered_lookup_sends_user_filter(tmp_path: Path) -> None:+ state = LinearStateStore(tmp_path / "state.sqlite3")+ client = LinearClient(_config(), state)+ client.graphql = AsyncMock(side_effect=[+ {"teams": connection([{"id": "t1", "name": "Team"}])},+ {"team": {"members": connection([{"id": "u1", "name": "Yongru", "active": True, "app": False}])}},+ ])+ try:+ assert len(await client.list_members("org-1", user_id="u1")) == 1+ assert client.graphql.call_args.args[2]["filter"] == {"id": {"eq": "u1"}}+ finally:+ await client.close()++[email protected]("response", [+ {"teams": {"nodes": []}},+ {"teams": {"nodes": [], "pageInfo": {"hasNextPage": True, "endCursor": None}}},+ {"teams": connection([{"id": "t1"}])},+])+async def test_incomplete_directory_fails_closed(tmp_path: Path, response: dict[str, Any]) -> None:+ client = LinearClient(_config(), LinearStateStore(tmp_path / "state.sqlite3"))+ client.graphql = AsyncMock(return_value=response)+ try:+ with pytest.raises(LinearApiError):+ await client.list_members("org-1")+ finally:+ await client.close()+++async def test_repeated_cursor_does_not_loop_or_return_partial_roster(tmp_path: Path) -> None:+ client = LinearClient(_config(), LinearStateStore(tmp_path / "state.sqlite3"))+ client.graphql = AsyncMock(return_value={"teams": connection([], "repeated")})+ try:+ with pytest.raises(LinearApiError, match="repeated"):+ await client.list_members("org-1")+ assert client.graphql.await_count == 2+ finally:+ await client.close()+++async def test_member_management_reads_effective_access_and_saves_without_pairing(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,+) -> None:+ config = _config()+ config.allow_from = []+ state = LinearStateStore(tmp_path / "state.sqlite3")+ state.save_installation(_installation())+ fake = AsyncMock()+ fake.list_members.return_value = [{"id": "user-1", "name": "Yongru", "teams": ["Team"]}]+ monkeypatch.setattr(linear_connect, "_load_linear_config", lambda: config)+ monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: state)+ monkeypatch.setattr(linear_connect, "LinearClient", lambda *_args: fake)+ store = linear_connect.LinearConnectStore()+ params = {"operation": ["members"], "organization_id": ["org-1"]}+ assert (await store.handle("start", params))["members"][0]["allowed"] is False+ for value in ("true", "false"):+ result = await store.handle("start", {**params, "operation": ["member_access"], "user_id": ["user-1"], "allowed": [value]})+ assert result["status"] == "member_access_saved"+ assert result["members"][0]["allowed"] is (value == "true")+ assert not member_allowed(config, state, "org-1", "user-1")+ fake.close.assert_awaited()++[email protected]("failure", ["unavailable", "out_of_scope", "invalid_boolean", "other_app"])+async def test_failed_management_does_not_grant_access(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failure: str,+) -> None:+ state = LinearStateStore(tmp_path / "state.sqlite3")+ state.save_installation(replace(_installation(), oauth_client_id="other" if failure == "other_app" else "client-id"))+ fake = AsyncMock()+ fake.list_members.return_value = []+ if failure == "unavailable":+ fake.list_members.side_effect = LinearApiError("Rate limited", retryable=True)+ monkeypatch.setattr(linear_connect, "_load_linear_config", _config)+ monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: state)+ monkeypatch.setattr(linear_connect, "LinearClient", lambda *_args: fake)+ with pytest.raises(linear_connect.ChannelConnectError):+ await linear_connect.LinearConnectStore().handle("start", {+ "operation": ["member_access"], "organization_id": ["org-1"],+ "user_id": ["user-1"], "allowed": ["yes" if failure == "invalid_boolean" else "true"],+ })+ assert state.member_access("client-id", "org-1", "user-1") is None+++async def test_enabled_member_can_run_without_pairing_and_disable_blocks_even_stop(tmp_path: Path) -> None:+ channel, client = _runtime(tmp_path)+ channel.config.allow_from = []+ channel._state.set_member_access("client-id", "org-1", "user-1", allowed=True)+ await channel._process_webhook("enabled", _agent_webhook())+ inbound = await channel.bus.consume_inbound()+ assert inbound.sender_id == "user-1"+ assert inbound.session_key == "linear:org-1:session-1"+ channel._state.set_member_access("client-id", "org-1", "user-1", allowed=False)+ channel.config.allow_from = ["*"]+ approve_code(generate_code("linear", "user-1"))+ await channel._process_webhook("disabled", _agent_webhook())+ await channel._process_webhook("disabled-stop", _agent_webhook(action="prompted", signal="stop"))+ assert channel.bus.inbound.empty()+ assert "Access is disabled" in client.activities[-1]["content"]["body"]++[email protected]("failure", ["departed", "api_error"])+async def test_admission_rechecks_membership_and_never_uses_stale_approvals(tmp_path: Path, failure: str) -> None:+ channel, client = _runtime(tmp_path)+ client.list_members = AsyncMock(return_value=[])+ expected = LinearPayloadError+ if failure == "api_error":+ client.list_members.side_effect = LinearApiError("Unavailable", retryable=True)+ expected = LinearApiError+ with pytest.raises(expected):+ await channel._process_webhook("no-access", _agent_webhook())+ assert channel.bus.inbound.empty()+ assert client.downloads == []+ assert client.activities == []+++async def test_revocation_during_attachment_download_is_checked_before_publish(tmp_path: Path) -> None:+ channel, client = _runtime(tmp_path)++ async def revoke_during_download(*_args: Any, **_kwargs: Any) -> tuple[list[str], list[str]]:+ channel._state.set_member_access("client-id", "org-1", "user-1", allowed=False)+ return [], []++ channel._download_prompt_media = revoke_during_download+ await channel._process_webhook("race", _agent_webhook())+ assert channel.bus.inbound.empty()diff --git a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsxindex 159346c46..7fdacb15c 100644--- a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx+++ b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx@@ -111,9 +111,9 @@ describe("Linear channel UI", () => {renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));await screen.findByRole("textbox", { name: "OAuth client ID" });- expect(screen.queryByText("Pair on first use; connect Linear MCP to search or edit issues.")).not.toBeInTheDocument();+ expect(screen.queryByText(/Use Member access to approve teammates/)).not.toBeInTheDocument();fireEvent.keyDown(screen.getByRole("button", { name: "Help" }), { key: "ArrowDown" });- expect(await screen.findByText("Pair on first use; connect Linear MCP to search or edit issues.")).toBeVisible();+ expect(await screen.findByText(/Use Member access to approve teammates/)).toBeVisible();fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });fireEvent.click(await screen.findByRole("button", { name: "Configure Linear MCP" }));const dialog = await screen.findByRole("dialog", { name: "Linear" });diff --git a/nanobot/channels/linear/webui/LinearHelpContent.tsx b/nanobot/channels/linear/webui/LinearHelpContent.tsxindex 8bfb4b0b4..4e8186fe9 100644--- a/nanobot/channels/linear/webui/LinearHelpContent.tsx+++ b/nanobot/channels/linear/webui/LinearHelpContent.tsx@@ -1,22 +1,16 @@import { useTranslation } from "react-i18next";import { channelTranslator } from "@/channel-plugins/i18n";-import type { ChannelPluginHelpProps } from "@/channel-plugins/types";import { DropdownMenuSeparator } from "@/components/ui/dropdown-menu";-export function LinearHelpContent({ feature }: ChannelPluginHelpProps) {+export function LinearHelpContent() {const { t } = useTranslation();const tx = channelTranslator(t, "linear");- const allowFrom = feature.config_values?.["channels.linear.allowFrom"]?.trim() ?? "";return (<><p className="max-w-72 px-3 py-2 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", "Pair on first use; connect Linear MCP to search or edit issues.")}+ {tx("members.guide", "Use Member access to approve teammates without pairing codes. Existing approvals still work unless switched off. Connect Linear MCP to search or edit issues.")}</p><DropdownMenuSeparator /></>diff --git a/nanobot/channels/linear/webui/LinearMemberAccess.tsx b/nanobot/channels/linear/webui/LinearMemberAccess.tsxnew file mode 100644index 000000000..63f8800ae--- /dev/null+++ b/nanobot/channels/linear/webui/LinearMemberAccess.tsx@@ -0,0 +1,142 @@+import { useEffect, useId, useRef, useState } from "react";+import { Check, ChevronDown, Loader2, RefreshCw } from "lucide-react";+import { useTranslation } from "react-i18next";++import { channelTranslator } from "@/channel-plugins/i18n";+import { ToggleButton } from "@/components/settings/ToggleButton";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { cn } from "@/lib/utils";+import { useClient } from "@/providers/ClientProvider";++import { manageLinearMembers } from "./api";+import type { LinearMember } from "./types";++export function LinearMemberAccess({ organizationId, disabled = false }: {+ organizationId: string;+ disabled?: boolean;+}) {+ const { client } = useClient();+ const { t } = useTranslation();+ const tx = channelTranslator(t, "linear");+ const panelId = useId();+ const [expanded, setExpanded] = useState(false);+ const [members, setMembers] = useState<LinearMember[]>([]);+ const [search, setSearch] = useState("");+ const [busy, setBusy] = useState(false);+ const [savingId, setSavingId] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [saved, setSaved] = useState(false);+ const [allowAll, setAllowAll] = useState(false);+ const generation = useRef(0);+ useEffect(() => () => { generation.current += 1; }, [organizationId]);++ const refresh = async () => {+ const request = ++generation.current;+ setBusy(true);+ setError(null);+ setSaved(false);+ try {+ const payload = await manageLinearMembers(client, { operation: "members", organization_id: organizationId });+ if (request !== generation.current) return;+ setMembers(payload.members);+ setAllowAll(payload.legacy_allow_all);+ } catch (err) {+ if (request === generation.current) setError((err as Error).message);+ } finally {+ if (request === generation.current) setBusy(false);+ }+ };++ const setAllowed = async (member: LinearMember, allowed: boolean) => {+ const request = ++generation.current;+ setBusy(true);+ setSavingId(member.id);+ setError(null);+ setSaved(false);+ try {+ const payload = await manageLinearMembers(client, {+ operation: "member_access", organization_id: organizationId, user_id: member.id, allowed,+ });+ if (request !== generation.current) return;+ const updated = payload.members.find((item) => item.id === member.id);+ if (!updated || updated.allowed !== allowed) throw new Error(tx("members.saveUnconfirmed", "Access was not confirmed. Refresh members before trying again."));+ setMembers((current) => current.map((item) => item.id === member.id ? updated : item));+ setAllowAll(payload.legacy_allow_all);+ setSaved(true);+ } catch (err) {+ if (request === generation.current) setError((err as Error).message);+ } finally {+ if (request === generation.current) {+ setBusy(false);+ setSavingId(null);+ }+ }+ };++ const needle = search.trim().toLocaleLowerCase();+ const visible = members.filter((member) => [member.name, member.id, ...member.teams]+ .some((value) => value.toLocaleLowerCase().includes(needle)));++ return (+ <section className="w-full border-t border-border/50 pt-2">+ <button type="button" aria-expanded={expanded} aria-controls={panelId}+ disabled={disabled || busy}+ className="flex min-h-10 w-full items-center justify-between gap-2 text-start text-[12px] font-medium disabled:opacity-50"+ onClick={() => {+ setExpanded(!expanded);+ if (!expanded) void refresh();+ }}>+ {tx("members.title", "Member access")}+ <ChevronDown className={cn("h-4 w-4", expanded && "rotate-180")} aria-hidden />+ </button>+ {expanded ? (+ <div id={panelId} className="space-y-3 pb-1">+ <p className="text-[12px] leading-5 text-muted-foreground">+ {tx("members.help", "Choose who can use nanobot in Linear without a pairing code. This does not grant access to the nanobot admin UI. Turning access off blocks new requests, not tasks already running.")}+ </p>+ {allowAll ? <p className="rounded-control bg-muted p-2 text-[12px] leading-5">+ {tx("members.allowAll", "Advanced settings currently allow all members (*), including new members. Individual off switches still take precedence. Remove * to require approval for new members.")}+ </p> : null}+ <div className="flex items-center gap-2">+ <Input value={search} onChange={(event) => setSearch(event.target.value)}+ aria-label={tx("members.search", "Search members")}+ placeholder={tx("members.search", "Search members")} className="min-w-0 text-[12px]" />+ <Button type="button" variant="ghost" size="sm" disabled={disabled || busy}+ onClick={() => void refresh()} aria-label={tx("members.refresh", "Refresh members")}>+ <RefreshCw className={cn("h-4 w-4", busy && !savingId && "animate-spin motion-reduce:animate-none")} aria-hidden />+ </Button>+ </div>+ <div role="status" aria-live="polite" className="text-[12px] text-muted-foreground">+ {busy ? tx("members.working", "Updating member access…") : saved ? <span className="inline-flex items-center gap-1">+ <Check className="h-3 w-3" aria-hidden />{tx("members.saved", "Member access saved.")}+ </span> : null}+ </div>+ {error ? <p role="alert" className="text-[12px] leading-5 text-destructive">+ {error} {tx("members.retry", "Refresh members to check the current state and try again.")}+ </p> : null}+ {!busy && !error && visible.length === 0 ? <p className="text-[12px] text-muted-foreground">+ {tx("members.empty", "No matching active members in the teams this app can access.")}+ </p> : null}+ <ul className="max-h-72 space-y-1 overflow-y-auto">+ {visible.map((member) => <li key={member.id} className="flex min-h-14 items-center gap-3 rounded-control px-2 py-2">+ <span aria-hidden className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted text-xs font-medium">+ {member.name.slice(0, 2).toLocaleUpperCase()}+ </span>+ <div className="min-w-0 flex-1">+ <p className="truncate text-[12.5px] font-medium" title={member.id}>{member.name}</p>+ <p className="truncate text-[11px] text-muted-foreground">{member.teams.join(" · ")}</p>+ {members.some((other) => other.id !== member.id && other.name === member.name) ?+ <p className="truncate text-[10px] text-muted-foreground">{member.id}</p> : null}+ </div>+ {savingId === member.id ? <Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden /> : null}+ <ToggleButton checked={member.allowed} disabled={disabled || busy || Boolean(error)}+ label={tx("members.allow", "Allow {{name}} to use nanobot", { name: member.name })}+ onChange={(allowed) => void setAllowed(member, allowed)} />+ </li>)}+ </ul>+ </div>+ ) : null}+ </section>+ );+}diff --git a/nanobot/channels/linear/webui/LinearPanel.tsx b/nanobot/channels/linear/webui/LinearPanel.tsxindex a9f4a8171..173340f6d 100644--- a/nanobot/channels/linear/webui/LinearPanel.tsx+++ b/nanobot/channels/linear/webui/LinearPanel.tsx@@ -36,6 +36,7 @@ import { useClient } from "@/providers/ClientProvider";import { manageLinearWorkspace } from "./api";import type { LinearInstallationSummary } from "./types";import { LinearConnectFlow } from "./LinearConnectFlow";+import { LinearMemberAccess } from "./LinearMemberAccess";import { linearManifestUrl } from "./manifest";const PUBLIC_BASE_URL_KEY = "channels.linear.publicBaseUrl";@@ -367,6 +368,8 @@ export function LinearPanel({: tx("custom.disconnect", "Disconnect")}</Button></div>+ <LinearMemberAccess organizationId={installation.organization_id}+ disabled={busy || dirty || connecting || loadingInstallations || disconnectingId !== null} /></article>);})}diff --git a/nanobot/channels/linear/webui/api.ts b/nanobot/channels/linear/webui/api.tsindex c448cfe42..0aa35254e 100644--- a/nanobot/channels/linear/webui/api.ts+++ b/nanobot/channels/linear/webui/api.ts@@ -1,6 +1,6 @@import { startChannelConnect, type WebUIMutationTransport } from "@/lib/api";-import type { LinearWorkspacePayload } from "./types";+import type { LinearMembersPayload, LinearWorkspacePayload } from "./types";export function manageLinearWorkspace(transport: WebUIMutationTransport,@@ -8,3 +8,11 @@ export function manageLinearWorkspace(): Promise<LinearWorkspacePayload> {return startChannelConnect<LinearWorkspacePayload>(transport, "linear", params);}++export function manageLinearMembers(+ transport: WebUIMutationTransport,+ params: { operation: "members"; organization_id: string }+ | { operation: "member_access"; organization_id: string; user_id: string; allowed: boolean },+): Promise<LinearMembersPayload> {+ return startChannelConnect<LinearMembersPayload>(transport, "linear", params);+}diff --git a/nanobot/channels/linear/webui/locales/en.json b/nanobot/channels/linear/webui/locales/en.jsonindex 3e730cc49..9fb8da9e9 100644--- a/nanobot/channels/linear/webui/locales/en.json+++ b/nanobot/channels/linear/webui/locales/en.json@@ -89,5 +89,19 @@"authorized": "Authorized","confirmDisconnect": "Disconnect workspace","disconnect": "Disconnect"+ },+ "members": {+ "title": "Member access",+ "help": "Choose who can use nanobot in Linear without a pairing code. This does not grant access to the nanobot admin UI. Turning access off blocks new requests, not tasks already running.",+ "allowAll": "Advanced settings currently allow all members (*), including new members. Individual off switches still take precedence. Remove * to require approval for new members.",+ "search": "Search members",+ "refresh": "Refresh members",+ "working": "Updating member access…",+ "saved": "Member access saved.",+ "retry": "Refresh members to check the current state and try again.",+ "empty": "No matching active members in the teams this app can access.",+ "allow": "Allow {{name}} to use nanobot",+ "saveUnconfirmed": "Access was not confirmed. Refresh members before trying again.",+ "guide": "Use Member access to approve teammates without pairing codes. Existing approvals still work unless switched off. Connect Linear MCP to search or edit issues."}}diff --git a/nanobot/channels/linear/webui/locales/es.json b/nanobot/channels/linear/webui/locales/es.jsonindex f95b331a7..3bdda1a12 100644--- a/nanobot/channels/linear/webui/locales/es.json+++ b/nanobot/channels/linear/webui/locales/es.json@@ -89,5 +89,19 @@"authorized": "Autorizado","confirmDisconnect": "Desconectar espacio","disconnect": "Desconectar"+ },+ "members": {+ "title": "Acceso de miembros",+ "help": "Elige quién puede usar nanobot en Linear sin código de vinculación. Esto no da acceso al panel de administración. Desactivar bloquea nuevas solicitudes, no tareas en curso.",+ "allowAll": "La configuración avanzada permite a todos los miembros (*), incluidos los nuevos. Los interruptores desactivados tienen prioridad. Elimina * para exigir aprobación a los nuevos miembros.",+ "search": "Buscar miembros",+ "refresh": "Actualizar miembros",+ "working": "Actualizando acceso…",+ "saved": "Acceso guardado.",+ "retry": "Actualiza los miembros para comprobar el estado actual y vuelve a intentarlo.",+ "empty": "No hay miembros activos coincidentes en los equipos accesibles para esta app.",+ "allow": "Permitir que {{name}} use nanobot",+ "saveUnconfirmed": "No se confirmó el acceso. Actualiza los miembros antes de reintentar.",+ "guide": "Usa Acceso de miembros para aprobar compañeros sin códigos. Las aprobaciones existentes siguen vigentes salvo que se desactiven. Conecta Linear MCP para buscar o editar issues."}}diff --git a/nanobot/channels/linear/webui/locales/fr.json b/nanobot/channels/linear/webui/locales/fr.jsonindex 5e83e11c3..ecff5d304 100644--- a/nanobot/channels/linear/webui/locales/fr.json+++ b/nanobot/channels/linear/webui/locales/fr.json@@ -89,5 +89,19 @@"authorized": "Autorisé","confirmDisconnect": "Déconnecter l’espace","disconnect": "Déconnecter"+ },+ "members": {+ "title": "Accès des membres",+ "help": "Choisissez qui peut utiliser nanobot dans Linear sans code d’association. Cela ne donne pas accès à l’administration. Désactiver bloque les nouvelles demandes, pas les tâches en cours.",+ "allowAll": "Les paramètres avancés autorisent tous les membres (*), y compris les nouveaux. Une désactivation individuelle reste prioritaire. Retirez * pour exiger l’approbation des nouveaux membres.",+ "search": "Rechercher des membres",+ "refresh": "Actualiser les membres",+ "working": "Mise à jour des accès…",+ "saved": "Accès enregistré.",+ "retry": "Actualisez les membres pour vérifier l’état actuel et réessayez.",+ "empty": "Aucun membre actif correspondant dans les équipes accessibles à cette application.",+ "allow": "Autoriser {{name}} à utiliser nanobot",+ "saveUnconfirmed": "L’accès n’a pas été confirmé. Actualisez les membres avant de réessayer.",+ "guide": "Utilisez Accès des membres pour approuver vos collègues sans code. Les autorisations existantes restent valables sauf désactivation. Connectez Linear MCP pour rechercher ou modifier des issues."}}diff --git a/nanobot/channels/linear/webui/locales/id.json b/nanobot/channels/linear/webui/locales/id.jsonindex 910bed2f1..77a4ade26 100644--- a/nanobot/channels/linear/webui/locales/id.json+++ b/nanobot/channels/linear/webui/locales/id.json@@ -89,5 +89,19 @@"authorized": "Diotorisasi","confirmDisconnect": "Putuskan workspace","disconnect": "Putuskan"+ },+ "members": {+ "title": "Akses anggota",+ "help": "Pilih siapa yang dapat memakai nanobot di Linear tanpa kode pairing. Ini tidak memberikan akses admin. Menonaktifkan memblokir permintaan baru, bukan tugas yang sedang berjalan.",+ "allowAll": "Pengaturan lanjutan mengizinkan semua anggota (*), termasuk anggota baru. Penonaktifan per anggota tetap diutamakan. Hapus * agar anggota baru memerlukan persetujuan.",+ "search": "Cari anggota",+ "refresh": "Segarkan anggota",+ "working": "Memperbarui akses…",+ "saved": "Akses anggota disimpan.",+ "retry": "Segarkan anggota untuk memeriksa status terkini, lalu coba lagi.",+ "empty": "Tidak ada anggota aktif yang cocok di tim yang dapat diakses aplikasi ini.",+ "allow": "Izinkan {{name}} memakai nanobot",+ "saveUnconfirmed": "Akses belum dikonfirmasi. Segarkan anggota sebelum mencoba lagi.",+ "guide": "Gunakan Akses anggota untuk menyetujui rekan tanpa kode pairing. Persetujuan lama tetap berlaku kecuali dinonaktifkan. Hubungkan Linear MCP untuk mencari atau mengedit issue."}}diff --git a/nanobot/channels/linear/webui/locales/ja.json b/nanobot/channels/linear/webui/locales/ja.jsonindex fd8e5999c..526e648b4 100644--- a/nanobot/channels/linear/webui/locales/ja.json+++ b/nanobot/channels/linear/webui/locales/ja.json@@ -89,5 +89,19 @@"authorized": "認証済み","confirmDisconnect": "ワークスペースを切断","disconnect": "切断"+ },+ "members": {+ "title": "メンバーのアクセス",+ "help": "ペアリングコードなしで Linear の nanobot を使えるメンバーを選びます。管理画面へのアクセスは付与されません。オフにすると新しいリクエストを拒否しますが、実行中のタスクは停止しません。",+ "allowAll": "詳細設定では新規メンバーを含む全員(*)が許可されています。個別のオフ設定が優先されます。新規メンバーに承認を必須とするには * を削除してください。",+ "search": "メンバーを検索",+ "refresh": "メンバーを更新",+ "working": "アクセスを更新中…",+ "saved": "アクセス設定を保存しました。",+ "retry": "メンバーを更新して現在の状態を確認し、再試行してください。",+ "empty": "アプリがアクセスできるチームに、条件に一致する有効なメンバーはいません。",+ "allow": "{{name}} に nanobot の利用を許可",+ "saveUnconfirmed": "保存を確認できませんでした。メンバーを更新してから再試行してください。",+ "guide": "「メンバーのアクセス」でコードなしで同僚を承認できます。既存の承認はオフにしない限り有効です。Issue の検索・編集には Linear MCP を接続してください。"}}diff --git a/nanobot/channels/linear/webui/locales/ko.json b/nanobot/channels/linear/webui/locales/ko.jsonindex 7246d7e39..1c82b0048 100644--- a/nanobot/channels/linear/webui/locales/ko.json+++ b/nanobot/channels/linear/webui/locales/ko.json@@ -89,5 +89,19 @@"authorized": "승인됨","confirmDisconnect": "워크스페이스 연결 해제","disconnect": "연결 해제"+ },+ "members": {+ "title": "멤버 접근 권한",+ "help": "페어링 코드 없이 Linear에서 nanobot을 사용할 멤버를 선택하세요. 관리자 화면 접근 권한은 부여하지 않습니다. 끄면 새 요청만 차단하며 실행 중인 작업은 취소하지 않습니다.",+ "allowAll": "고급 설정에서 신규 멤버를 포함한 모든 멤버(*)를 허용하고 있습니다. 개별 끄기 설정이 우선합니다. 신규 멤버의 승인을 요구하려면 *를 제거하세요.",+ "search": "멤버 검색",+ "refresh": "멤버 새로고침",+ "working": "접근 권한 업데이트 중…",+ "saved": "멤버 접근 권한을 저장했습니다.",+ "retry": "멤버를 새로고침하여 현재 상태를 확인한 후 다시 시도하세요.",+ "empty": "앱이 접근할 수 있는 팀에 일치하는 활성 멤버가 없습니다.",+ "allow": "{{name}}의 nanobot 사용 허용",+ "saveUnconfirmed": "권한 저장을 확인하지 못했습니다. 멤버를 새로고침한 후 다시 시도하세요.",+ "guide": "멤버 접근 권한에서 코드 없이 동료를 승인하세요. 기존 승인은 끄지 않는 한 유지됩니다. Issue 검색이나 수정에는 Linear MCP를 연결하세요."}}diff --git a/nanobot/channels/linear/webui/locales/pt-BR.json b/nanobot/channels/linear/webui/locales/pt-BR.jsonindex 142d06840..d297ac6df 100644--- a/nanobot/channels/linear/webui/locales/pt-BR.json+++ b/nanobot/channels/linear/webui/locales/pt-BR.json@@ -89,5 +89,19 @@"authorized": "Autorizado","confirmDisconnect": "Desconectar workspace","disconnect": "Desconectar"+ },+ "members": {+ "title": "Acesso de membros",+ "help": "Escolha quem pode usar nanobot no Linear sem código de pareamento. Isso não concede acesso ao painel administrativo. Desativar bloqueia novas solicitações, não tarefas em andamento.",+ "allowAll": "As configurações avançadas permitem todos os membros (*), inclusive novos. Desativações individuais têm prioridade. Remova * para exigir aprovação de novos membros.",+ "search": "Buscar membros",+ "refresh": "Atualizar membros",+ "working": "Atualizando acesso…",+ "saved": "Acesso dos membros salvo.",+ "retry": "Atualize os membros para conferir o estado atual e tente novamente.",+ "empty": "Nenhum membro ativo correspondente nas equipes acessíveis ao aplicativo.",+ "allow": "Permitir que {{name}} use nanobot",+ "saveUnconfirmed": "O acesso não foi confirmado. Atualize os membros antes de tentar novamente.",+ "guide": "Use Acesso de membros para aprovar colegas sem códigos. Aprovações existentes continuam válidas até serem desativadas. Conecte o Linear MCP para buscar ou editar issues."}}diff --git a/nanobot/channels/linear/webui/locales/vi.json b/nanobot/channels/linear/webui/locales/vi.jsonindex d365eb7d9..d316f3d9a 100644--- a/nanobot/channels/linear/webui/locales/vi.json+++ b/nanobot/channels/linear/webui/locales/vi.json@@ -89,5 +89,19 @@"authorized": "Đã cấp quyền","confirmDisconnect": "Ngắt kết nối workspace","disconnect": "Ngắt kết nối"+ },+ "members": {+ "title": "Quyền truy cập của thành viên",+ "help": "Chọn người được dùng nanobot trong Linear mà không cần mã ghép nối. Quyền này không cho phép truy cập trang quản trị. Tắt chỉ chặn yêu cầu mới, không hủy tác vụ đang chạy.",+ "allowAll": "Cài đặt nâng cao đang cho phép mọi thành viên (*), kể cả người mới. Lựa chọn tắt riêng vẫn được ưu tiên. Xóa * để yêu cầu phê duyệt thành viên mới.",+ "search": "Tìm thành viên",+ "refresh": "Làm mới thành viên",+ "working": "Đang cập nhật quyền…",+ "saved": "Đã lưu quyền truy cập.",+ "retry": "Làm mới danh sách để kiểm tra trạng thái hiện tại rồi thử lại.",+ "empty": "Không có thành viên đang hoạt động phù hợp trong các nhóm ứng dụng có thể truy cập.",+ "allow": "Cho phép {{name}} dùng nanobot",+ "saveUnconfirmed": "Chưa xác nhận được quyền. Hãy làm mới danh sách trước khi thử lại.",+ "guide": "Dùng Quyền truy cập của thành viên để phê duyệt đồng nghiệp không cần mã. Phê duyệt cũ vẫn có hiệu lực trừ khi bị tắt. Kết nối Linear MCP để tìm hoặc sửa issue."}}diff --git a/nanobot/channels/linear/webui/locales/zh-CN.json b/nanobot/channels/linear/webui/locales/zh-CN.jsonindex 8ee9a3ac6..78f8f2057 100644--- a/nanobot/channels/linear/webui/locales/zh-CN.json+++ b/nanobot/channels/linear/webui/locales/zh-CN.json@@ -1 +1 @@-{"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 委派给它。"],"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 应用。","removeCredentials":"删除已保存的凭据","retrySave":"重试","channelRunning":"Channel 正在运行","accessAll":"已授权工作区中的所有成员都可以运行此 Agent。","accessRestricted":"只有“高级”中列出的 Linear 用户 ID 可以运行此 Agent。","accessPairing":"首次使用需配对,连接 Linear MCP 后可搜索或修改 issue。","configureTools":"配置 Linear MCP","workspacesTitle":"已授权的工作区","refreshWorkspaces":"刷新工作区","loadingWorkspaces":"正在加载工作区","noWorkspaces":"尚未授权工作区。连接工作区后才能接收 Linear Agent 请求。","refreshRequired":"需要刷新授权","missingScopes":"重新连接以授予:{{scopes}}","authorized":"已授权","confirmDisconnect":"断开工作区连接","disconnect":"断开连接"}}+{"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 委派给它。"],"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 应用。","removeCredentials":"删除已保存的凭据","retrySave":"重试","channelRunning":"Channel 正在运行","accessAll":"已授权工作区中的所有成员都可以运行此 Agent。","accessRestricted":"只有“高级”中列出的 Linear 用户 ID 可以运行此 Agent。","accessPairing":"首次使用需配对,连接 Linear MCP 后可搜索或修改 issue。","configureTools":"配置 Linear MCP","workspacesTitle":"已授权的工作区","refreshWorkspaces":"刷新工作区","loadingWorkspaces":"正在加载工作区","noWorkspaces":"尚未授权工作区。连接工作区后才能接收 Linear Agent 请求。","refreshRequired":"需要刷新授权","missingScopes":"重新连接以授予:{{scopes}}","authorized":"已授权","confirmDisconnect":"断开工作区连接","disconnect":"断开连接"},"members":{"title":"成员访问","help":"选择可以在 Linear 中免配对使用 nanobot 的成员。这不会授予 nanobot 后台管理权限。关闭后会阻止新请求,但不会取消正在运行的任务。","allowAll":"高级设置目前允许所有成员(*),包括新成员。单独关闭的成员仍会被拒绝;若希望新成员须经批准,请移除 *。","search":"搜索成员","refresh":"刷新成员","working":"正在更新成员访问权限……","saved":"成员访问权限已保存。","retry":"请刷新成员列表确认当前状态后重试。","empty":"应用可访问的团队中没有匹配的活跃成员。","allow":"允许 {{name}} 使用 nanobot","saveUnconfirmed":"未能确认权限已保存,请刷新成员列表后重试。","guide":"在「成员访问」中为同事开通免配对使用。已有授权仍然有效,除非手动关闭。连接 Linear MCP 后可搜索或修改 issue。"}}diff --git a/nanobot/channels/linear/webui/locales/zh-TW.json b/nanobot/channels/linear/webui/locales/zh-TW.jsonindex 4c994c385..3701143da 100644--- a/nanobot/channels/linear/webui/locales/zh-TW.json+++ b/nanobot/channels/linear/webui/locales/zh-TW.json@@ -1 +1 @@-{"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 委派給它。"],"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 應用程式。","removeCredentials":"刪除已儲存的憑證","retrySave":"重試","channelRunning":"Channel 正在執行","accessAll":"已授權工作區中的所有成員都可以執行此 Agent。","accessRestricted":"只有「進階」中列出的 Linear 使用者 ID 可以執行此 Agent。","accessPairing":"首次使用需配對,連接 Linear MCP 後可搜尋或修改 issue。","configureTools":"設定 Linear MCP","workspacesTitle":"已授權的工作區","refreshWorkspaces":"重新整理工作區","loadingWorkspaces":"正在載入工作區","noWorkspaces":"尚未授權工作區。連接工作區後才能接收 Linear Agent 請求。","refreshRequired":"需要重新整理授權","missingScopes":"重新連接以授予:{{scopes}}","authorized":"已授權","confirmDisconnect":"中斷工作區連線","disconnect":"中斷連線"}}+{"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 委派給它。"],"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 應用程式。","removeCredentials":"刪除已儲存的憑證","retrySave":"重試","channelRunning":"Channel 正在執行","accessAll":"已授權工作區中的所有成員都可以執行此 Agent。","accessRestricted":"只有「進階」中列出的 Linear 使用者 ID 可以執行此 Agent。","accessPairing":"首次使用需配對,連接 Linear MCP 後可搜尋或修改 issue。","configureTools":"設定 Linear MCP","workspacesTitle":"已授權的工作區","refreshWorkspaces":"重新整理工作區","loadingWorkspaces":"正在載入工作區","noWorkspaces":"尚未授權工作區。連接工作區後才能接收 Linear Agent 請求。","refreshRequired":"需要重新整理授權","missingScopes":"重新連接以授予:{{scopes}}","authorized":"已授權","confirmDisconnect":"中斷工作區連線","disconnect":"中斷連線"},"members":{"title":"成員存取","help":"選擇可在 Linear 中免配對使用 nanobot 的成員。這不會授予 nanobot 後台管理權限。關閉後會阻止新請求,但不會取消正在執行的任務。","allowAll":"進階設定目前允許所有成員(*),包含新成員。個別關閉的成員仍會被拒絕;若希望新成員須經核准,請移除 *。","search":"搜尋成員","refresh":"重新整理成員","working":"正在更新成員存取權限……","saved":"成員存取權限已儲存。","retry":"請重新整理成員清單確認目前狀態後再試。","empty":"應用程式可存取的團隊中沒有符合的活躍成員。","allow":"允許 {{name}} 使用 nanobot","saveUnconfirmed":"無法確認權限已儲存,請重新整理成員清單後再試。","guide":"在「成員存取」中為同事開通免配對使用。既有授權仍然有效,除非手動關閉。連接 Linear MCP 後可搜尋或修改 issue。"}}diff --git a/nanobot/channels/linear/webui/types.ts b/nanobot/channels/linear/webui/types.tsindex 492bb9ad6..6572ee900 100644--- a/nanobot/channels/linear/webui/types.ts+++ b/nanobot/channels/linear/webui/types.ts@@ -15,3 +15,18 @@ export interface LinearWorkspacePayload {webhook_url?: string;redirect_uri?: string;}++export interface LinearMember {+ id: string;+ name: string;+ teams: string[];+ allowed: boolean;+}++export interface LinearMembersPayload {+ session_id: string;+ status: "members" | "member_access_saved";+ organization_id: string;+ legacy_allow_all: boolean;+ members: LinearMember[];+}diff --git a/webui/src/tests/linear-member-access.test.tsx b/webui/src/tests/linear-member-access.test.tsxnew file mode 100644index 000000000..843acc85b--- /dev/null+++ b/webui/src/tests/linear-member-access.test.tsx@@ -0,0 +1,104 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { LinearMemberAccess } from "../../../nanobot/channels/linear/webui/LinearMemberAccess";+import type { LinearMembersPayload } from "../../../nanobot/channels/linear/webui/types";++const { requestMutation } = vi.hoisted(() => ({ requestMutation: vi.fn() }));+vi.mock("@/providers/ClientProvider", () => {+ const client = { requestMutation };+ return { useClient: () => ({ client }) };+});++const roster: LinearMembersPayload = {+ session_id: "", status: "members", organization_id: "org-1", legacy_allow_all: false,+ members: [+ { id: "u1", name: "Xubin", teams: ["nanobot"], allowed: true },+ { id: "u2", name: "Yongru", teams: ["nanobot"], allowed: false },+ ],+};++beforeEach(() => requestMutation.mockReset().mockResolvedValue(roster));+afterEach(cleanup);++async function openMembers() {+ render(<LinearMemberAccess organizationId="org-1" />);+ expect(requestMutation).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Member access" }));+ return screen.findByRole("switch", { name: "Allow Yongru to use nanobot" });+}++describe("Linear member access", () => {+ it("loads the selected workspace, shows effective permissions and searches by name", async () => {+ const toggle = await openMembers();+ expect(toggle).not.toBeChecked();+ expect(screen.getByRole("switch", { name: "Allow Xubin to use nanobot" })).toBeChecked();+ expect(requestMutation).toHaveBeenCalledWith("settings.channel.connect.start", {+ channel: "linear", operation: "members", organization_id: "org-1",+ }, 150_000);+ expect(screen.getByText(/does not grant access/)).toBeVisible();+ fireEvent.change(screen.getByRole("textbox", { name: "Search members" }), { target: { value: "yong" } });+ expect(screen.queryByRole("switch", { name: "Allow Xubin to use nanobot" })).not.toBeInTheDocument();+ expect(toggle).toBeVisible();+ });++ it("changes the switch only after the server confirms and sends stable IDs", async () => {+ const toggle = await openMembers();+ let resolve!: (value: LinearMembersPayload) => void;+ requestMutation.mockImplementationOnce(() => new Promise<LinearMembersPayload>((done) => { resolve = done; }));+ fireEvent.click(toggle);+ expect(toggle).toBeDisabled();+ expect(toggle).not.toBeChecked();+ expect(requestMutation).toHaveBeenLastCalledWith("settings.channel.connect.start", {+ channel: "linear", operation: "member_access", organization_id: "org-1", user_id: "u2", allowed: true,+ }, 150_000);+ await act(async () => resolve({ ...roster, status: "member_access_saved", members: [{ ...roster.members[1], allowed: true }] }));+ expect(toggle).toBeChecked();+ expect(toggle).toBeEnabled();+ expect(screen.getByText("Member access saved.")).toBeVisible();+ expect(screen.getByRole("switch", { name: "Allow Xubin to use nanobot" })).toBeChecked();+ });++ it("does not fake success on save failure and requires refresh before retrying", async () => {+ const toggle = await openMembers();+ requestMutation.mockRejectedValueOnce(new Error("Could not save"));+ fireEvent.click(toggle);+ expect(await screen.findByRole("alert")).toHaveTextContent("Could not save");+ expect(toggle).not.toBeChecked();+ expect(toggle).toBeDisabled();+ expect(screen.queryByText("Member access saved.")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Refresh members" }));+ await waitFor(() => expect(toggle).toBeEnabled());+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });++ it("does not turn a failed roster load into an empty successful directory", async () => {+ requestMutation.mockRejectedValueOnce(new Error("Linear unavailable"));+ render(<LinearMemberAccess organizationId="org-1" />);+ fireEvent.click(screen.getByRole("button", { name: "Member access" }));+ expect(await screen.findByRole("alert")).toHaveTextContent("Linear unavailable");+ expect(screen.queryByRole("switch")).not.toBeInTheDocument();+ expect(screen.queryByText(/No matching active/)).not.toBeInTheDocument();+ });++ it("explains legacy wildcard access without hiding individual off switches", async () => {+ requestMutation.mockResolvedValue({ ...roster, legacy_allow_all: true });+ const toggle = await openMembers();+ expect(screen.getByText(/including new members/)).toBeVisible();+ expect(toggle).not.toBeChecked();+ });++ it("blocks edits while parent configuration is unsaved", () => {+ render(<LinearMemberAccess organizationId="org-1" disabled />);+ fireEvent.click(screen.getByRole("button", { name: "Member access" }));+ expect(requestMutation).not.toHaveBeenCalled();+ });++ it("disambiguates duplicate names with IDs", async () => {+ requestMutation.mockResolvedValue({ ...roster, members: roster.members.map((member) => ({ ...member, name: "Alex" })) });+ render(<LinearMemberAccess organizationId="org-1" />);+ fireEvent.click(screen.getByRole("button", { name: "Member access" }));+ expect(await screen.findByText("u1")).toBeVisible();+ expect(screen.getByText("u2")).toBeVisible();+ });+});