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): refine browser authorization and workspace lifecycle
Xubin Ren5375289ecd28
diff --git a/docs/guides/linear-agent.md b/docs/guides/linear-agent.mdindex 0423f3446..27400cd83 100644--- a/docs/guides/linear-agent.md+++ b/docs/guides/linear-agent.md@@ -39,6 +39,20 @@ the channel's OAuth installation, webhook, or Agent Session transport.## Before you start+There are two separate decisions: **connect a workspace**, then **choose who can+use nanobot**. The administrator sets up the app once; teammates do not need to+create their own apps, paste credentials, or scan a code.++```text+Prepare HTTPS → Create the Linear app → Save credentials in nanobot+ → Authorize a workspace → Enable members → Try an @mention+```++The HTTPS address receives Linear events. OAuth installs the app in a workspace.+Member access controls who may ask your nanobot to do work. These steps serve+different purposes; authorizing a workspace does not automatically approve all+its members.+Prepare these four things:| Requirement | What you need |@@ -94,6 +108,11 @@ network. Containers and separate reverse-proxy hosts may require `0.0.0.0`.The Linear listener serves plain HTTP locally; terminate HTTPS at the proxy ortunnel instead of exposing port `3979` directly to the internet.+Only the callback and webhook need public routes. Keep the nanobot WebUI and+admin API private, for example behind a VPN or SSH tunnel. Do not point your+public hostname at the WebUI port. An HTTPS endpoint is not an invitation to run+the agent: webhooks must pass signature checks, and senders must pass access checks.+### Temporary HTTPS for a local testInstall [cloudflared](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/),@@ -182,16 +201,20 @@ In the new Linear app's settings, copy these values:| Webhook signing secret | **Webhook signing secret** |Return to **Settings → Channels → Linear** and paste all three values. Ordinary-fields save automatically after a short pause; secret fields save when you leave-the field. Wait for **Settings saved.** before entering the next credential.+fields save automatically after a short pause. For each secret, select **Save**+beside that field and wait for its **Saved** status.**Connect Linear** becomes available once the required settings are saved.Listener settings, callback paths, and allowed users are in **Advanced**; setupguides are in the dialog's **Help** menu.-Closing the dialog waits for pending edits to save. If saving fails, the dialog-keeps your input and offers **Retry**. **Remove saved credentials** clears both-the client secret and webhook signing secret while keeping the client ID and-public URL.+A masked value with **Saved** means this instance already has the secret; it is+not an empty input. To change it, select **Replace**, enter the new secret, then+**Save**. **Cancel** or Escape leaves the saved secret unchanged. Leaving the+field or showing the newly typed value does not save it. A failed save retains+the draft for retry; the old secret is never sent back to the browser.++Closing the dialog waits for in-flight saves, but does not save an unsubmitted+secret draft. Save each secret explicitly before continuing.Treat the Client Secret and Webhook signing secret like passwords. They belongonly in the nanobot configuration and the Linear application settings.@@ -199,24 +222,41 @@ only in the nanobot configuration and the Linear application settings.### 4. Authorize the workspace1. 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.+2. Select **Continue in Linear** to open authorization in your browser. There is+ no QR step.+3. Choose the workspace, review the app's permissions and team access, and+ approve the installation as a workspace admin.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 mustremain running so Linear can deliver webhooks. Reopening the panel shows therunning 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.+attempt. Use **… → Remove workspace** on a workspace to revoke its Linear OAuth+tokens and remove the local installation; see the lifecycle controls below for+what is kept.The pre-filled manifest creates a private app for the current workspace. Adistributable OAuth app can authorize additional workspaces; nanobot stores andrefreshes each workspace installation separately.-### 5. Test the first task+### 5. Choose who can use nanobot++Under the workspace card, expand **Member access**, find yourself, and turn on+your switch. Do the same for any teammates you want to invite. Wait for **Saved**+beside each member; they can then use the agent without a pairing code.++You manage two levels here: **workspace → members**. A Linear team groups issues+and has its own workflow; it is not another installation to configure in nanobot.+The app can only work within the teams authorized in Linear. A member switch+does not expand that team access or grant access to the nanobot admin UI.++Pairing codes remain available as an alternative: a member without an explicit+switch setting can send a first prompt, have an administrator approve the code,+and repeat the prompt. An explicit **off** switch overrides pairing approval;+turn the switch on again to restore access.++### 6. Test the first task1. Open an issue in the connected Linear workspace.2. Add a comment that @mentions the app and includes a request, for example:@@ -231,10 +271,7 @@ refreshes each workspace installation separately.4. Send a follow-up inside that Agent Session. You do not need to @mention theapp again there.-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 **Saved** beside that member. They can then mention the-agent without copying a pairing code or authorizing another OAuth installation.+### Member access detailsThe list contains active human members of teams this app can access. It does notgrant access to additional Linear teams or to the nanobot admin UI. Names are for@@ -287,7 +324,37 @@ 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+## Connect, remove, or reset workspaces++Each nanobot instance uses one configured Linear OAuth app, which may have+multiple workspace installations. A **private** app can only be installed in its+own workspace. To use the same app in another workspace, its distribution must+allow that installation in Linear; changing a nanobot field cannot bypass this.++- **Connect workspace** uses the current app and opens the same browser+ authorization flow. Choose the other workspace in Linear, review team access,+ and authorize. You do not need another HTTPS address or another set of app+ credentials for the same app. Review member access in the new workspace.+- **… → Reauthorize** on a workspace updates its connection, without creating a+ duplicate or clearing its member choices. Use it to renew authorization or+ grant missing scopes. Cancelling authorization leaves existing connections alone.+- **… → Remove workspace** revokes that workspace's tokens and clears its local+ installation and member switches. Other workspaces are unaffected. Removing+ the last workspace also stops the channel. App credentials remain available+ for connecting again.+- **Advanced → Reset Linear connection** removes all installations for the+ current app, stops the channel, and clears this instance's Linear app settings,+ including its saved credentials. Use this when starting over or switching apps.+ If a step fails, the UI reports an incomplete reset; removed workspaces stay+ removed, and you can retry the remaining steps.++Neither removal nor reset deletes the Linear workspace, app, issues or comments,+nor nanobot conversation history or pairing approvals. Deleting the app itself+is a separate action in Linear. After removing and reconnecting a workspace,+member switches start fresh, but retained pairing approvals or an `allowFrom`+entry can still grant access. **Reset is not a wipe of all authorization history.**++## Updating a remote installationMember management includes both Python channel code and WebUI assets. A localbranch does not update an already running remote gateway, and the browser UI@@ -323,9 +390,10 @@ The setup is complete when all of these checks pass:- While the channel is running, opening`http://127.0.0.1:3979/linear/health` on the nanobot machine returns`{"ok":true}`. Use your configured host and port if you changed them.-- Opening `https://nanobot.example.com/linear/health` through the public route- also returns `{"ok":true}`. Substitute your actual public origin. This checks- tunnel or proxy reachability; the task checks below verify the Linear connection.+- If your proxy also forwards `/linear/health`, its public URL returns+ `{"ok":true}`. This is optional: a proxy exposing only the callback and webhook+ can correctly return 404 for public health. Use successful OAuth and webhook+ delivery to verify those two routes; do not expose the admin UI for this check.- A new comment with an explicit @mention creates an Agent Session and receivesa response.- Delegating an issue to the app creates an Agent Session and receives a response.@@ -405,6 +473,8 @@ secret.| Public health returns 502 | Start **Connect Linear** or enable the connected channel. Check local health first, then confirm the tunnel or proxy targets the same listener port. || OAuth opens but cannot finish | Keep `nanobot webui` running. Confirm the proxy forwards `/linear/oauth/callback` to the configured listen host and port. Then start **Connect Linear** again. || OAuth finishes in Linear but nanobot keeps waiting | Keep the nanobot connection dialog open. Confirm the Redirect URI reaches the same nanobot process, and inspect gateway logs for callback or token exchange errors. |+| A secret shows **Saved**, but no readable value | This is expected. The secret is stored on this instance and not returned to the browser. Use **Replace → Save** only when changing it. |+| Another workspace is unavailable during authorization | Check the current app's distribution and your installation permissions in Linear. A private app only works in its own workspace. **Connect workspace** does not create a new app. || 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. |diff --git a/nanobot/channels/linear/client.py b/nanobot/channels/linear/client.pyindex ff2d76563..a4cd91dea 100644--- a/nanobot/channels/linear/client.py+++ b/nanobot/channels/linear/client.py@@ -102,7 +102,7 @@ class LinearClient:expires_at=time.time() + _expires_in(token),scope=scopes,)- self.state.save_installation(installation)+ self.state.save_installation(installation, reauthorize=True)return installationasync def graphql(diff --git a/nanobot/channels/linear/runtime.py b/nanobot/channels/linear/runtime.pyindex 03741edb1..f0c8aa720 100644--- a/nanobot/channels/linear/runtime.py+++ b/nanobot/channels/linear/runtime.py@@ -8,6 +8,7 @@ import mimetypesimport reimport uuidfrom contextlib import suppress+from datetime import datetimefrom pathlib import Pathfrom typing import Any, castfrom urllib.parse import urlparse@@ -542,8 +543,19 @@ class LinearChannel(BaseChannel):action = str(payload.get("action") or "").lower()organization_id = str(payload.get("organizationId") or "").strip()if organization_id and action in {"remove", "removed", "revoke", "revoked"}:- self._state.delete_installation(organization_id)- self.logger.info("Removed revoked Linear workspace installation {}", organization_id)+ # Delivery may be retried or queued while stopped. Compare the action's+ # timestamp, not webhookTimestamp (delivery time), with the latest grant.+ try:+ created_at = datetime.fromisoformat(str(payload.get("createdAt") or ""))+ if created_at.tzinfo is None:+ raise ValueError("Missing timezone")+ except ValueError as exc:+ raise LinearPayloadError("Linear revocation is missing a valid createdAt") from exc+ if self._state.delete_installation(+ organization_id, oauth_client_id=self.config.client_id,+ revoked_at=created_at.timestamp(),+ ):+ self.logger.info("Removed revoked Linear workspace installation {}", organization_id)def _linear_route(metadata: dict[str, Any]) -> dict[str, Any] | None:diff --git a/nanobot/channels/linear/server.py b/nanobot/channels/linear/server.pyindex 836a4009b..1d0992627 100644--- a/nanobot/channels/linear/server.py+++ b/nanobot/channels/linear/server.py@@ -251,7 +251,7 @@ def _oauth_html(status: str) -> bytes:),"cancelled": ("Authorization not completed",- "Return to nanobot to try again or leave Linear disconnected.",+ "Existing workspace connections are unchanged. Return to nanobot to try again.",),"invalid": ("Linear connection failed",diff --git a/nanobot/channels/linear/state.py b/nanobot/channels/linear/state.pyindex 546cdd864..9e4f7d4d6 100644--- a/nanobot/channels/linear/state.py+++ b/nanobot/channels/linear/state.py@@ -99,6 +99,10 @@ class LinearStateStore:connection.execute("ALTER TABLE installations ADD COLUMN oauth_client_id TEXT NOT NULL DEFAULT ''")+ if "authorized_at" not in columns:+ connection.execute(+ "ALTER TABLE installations ADD COLUMN authorized_at REAL NOT NULL DEFAULT 0"+ )connection.execute("DELETE FROM webhook_receipts WHERE received_at < ?",(time.time() - 30 * 24 * 60 * 60,),@@ -115,14 +119,17 @@ class LinearStateStore:).fetchone()return row is not None- def save_installation(self, installation: LinearInstallation) -> None:+ def save_installation(+ self, installation: LinearInstallation, *, reauthorize: bool = False,+ ) -> None:+ now = time.time()with self._guard, self._connect() as connection:connection.execute("""INSERT INTO installations (organization_id, oauth_client_id, app_user_id, access_token, refresh_token,- expires_at, scope_json, organization_name, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)+ expires_at, scope_json, organization_name, updated_at, authorized_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)ON CONFLICT(organization_id) DO UPDATE SEToauth_client_id=excluded.oauth_client_id,app_user_id=excluded.app_user_id,@@ -131,7 +138,10 @@ class LinearStateStore:expires_at=excluded.expires_at,scope_json=excluded.scope_json,organization_name=excluded.organization_name,- updated_at=excluded.updated_at+ updated_at=excluded.updated_at,+ authorized_at=CASE+ WHEN ? OR installations.oauth_client_id != excluded.oauth_client_id+ THEN excluded.authorized_at ELSE installations.authorized_at END""",(installation.organization_id,@@ -142,7 +152,9 @@ class LinearStateStore:installation.expires_at,json.dumps(installation.scope),installation.organization_name,- time.time(),+ now,+ now,+ reauthorize,),)@@ -175,12 +187,34 @@ class LinearStateStore:).fetchall()return [_installation_from_row(row) for row in rows]- def delete_installation(self, organization_id: str) -> None:+ def delete_installation(+ self, organization_id: str, *, oauth_client_id: str | None = None,+ revoked_at: float | None = None,+ ) -> bool:+ """Remove an installation, ignoring revocations from an older authorization."""with self._guard, self._connect() as connection:+ connection.execute("BEGIN IMMEDIATE")+ current = connection.execute(+ "SELECT oauth_client_id, authorized_at FROM installations WHERE organization_id = ?",+ (organization_id,),+ ).fetchone()+ if current is None:+ return False+ if oauth_client_id is not None and current["oauth_client_id"] != oauth_client_id:+ return False+ if revoked_at is not None and revoked_at < float(current["authorized_at"]):+ return False+ connection.execute(+ "DELETE FROM member_access WHERE organization_id = ? "+ "AND oauth_client_id IN (SELECT oauth_client_id FROM installations "+ "WHERE organization_id = ?)",+ (organization_id, organization_id),+ )connection.execute("DELETE FROM installations WHERE organization_id = ?",(organization_id,),)+ return Truedef member_access(self, client_id: str, organization_id: str, user_id: str) -> bool | None:"""An explicit choice overrides legacy pairing and allowFrom, including '*'."""diff --git a/nanobot/channels/linear/tests/test_linear.py b/nanobot/channels/linear/tests/test_linear.pyindex 0b9bb5603..64144cdf8 100644--- a/nanobot/channels/linear/tests/test_linear.py+++ b/nanobot/channels/linear/tests/test_linear.py@@ -8,6 +8,7 @@ import jsonimport socketimport timefrom dataclasses import replace+from datetime import datetime, timezonefrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Any, Literal@@ -278,6 +279,8 @@ def test_oauth_callback_does_not_report_cancelled_authorization_as_connected(assert response.status == 200assert b"Authorization not completed" in bodyassert b"Linear connected" not in body+ assert b"Existing workspace connections are unchanged" in body+ assert b"leave Linear disconnected" not in bodyassert flow.error == "access_denied"finally:OAUTH_FLOWS.remove(flow)@@ -384,6 +387,8 @@ async def test_disconnect_keeps_local_installation_when_revocation_fails(state = LinearStateStore(tmp_path / "linear.sqlite3")installation = _installation()state.save_installation(installation)+ state.set_member_access(installation.oauth_client_id, installation.organization_id,+ "user-1", allowed=True)monkeypatch.setattr(linear_connect, "_load_linear_config", _config)monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: state)client = SimpleNamespace(@@ -399,6 +404,7 @@ async def test_disconnect_keeps_local_installation_when_revocation_fails()assert state.installation("org-1") == installation+ assert state.member_access(installation.oauth_client_id, "org-1", "user-1") is Trueclient.close.assert_awaited_once()@@ -1257,6 +1263,66 @@ def test_revocation_removes_workspace_installation(tmp_path: Path) -> None:"type": "OAuthApp","action": "revoked","organizationId": "org-1",+ "createdAt": datetime.now(timezone.utc).isoformat(),})assert channel._state.installation("org-1") is None # pyright: ignore[reportPrivateUsage]+++def test_delayed_revocation_does_not_remove_new_authorization(tmp_path: Path) -> None:+ channel, _ = _runtime(tmp_path)+ state = channel._state # pyright: ignore[reportPrivateUsage]+ state.delete_installation("org-1")+ revoked_at = datetime.now(timezone.utc).isoformat()+ state.enqueue_webhook("old-revocation", {+ "type": "OAuthApp", "action": "revoked", "organizationId": "org-1",+ "oauthClientId": "client-id", "createdAt": revoked_at,+ "webhookTimestamp": int(time.time() * 1000),+ })+ state.save_installation(replace(_installation(), access_token="new-access"))+ state.set_member_access("client-id", "org-1", "user-1", allowed=False)+ # The channel was stopped during removal, so the old notice is consumed+ # only after the user has authorized and enabled the channel again.+ event = state.claim_webhooks()[0]+ channel._process_lifecycle_event(event.payload) # pyright: ignore[reportPrivateUsage]+ current = state.installation("org-1")+ assert current is not None+ assert current.access_token == "new-access"+ assert state.member_access("client-id", "org-1", "user-1") is False++[email protected]("reauthorize", [False, True])+def test_revocation_boundary_changes_only_for_new_grants(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, reauthorize: bool,+) -> None:+ store = LinearStateStore(tmp_path / "state.sqlite3")+ monkeypatch.setattr(time, "time", lambda: 1000.0)+ store.save_installation(_installation())+ store.set_member_access("client-id", "org-1", "user-1", allowed=False)+ monkeypatch.setattr(time, "time", lambda: 3000.0)+ store.save_installation(+ replace(_installation(), access_token="renewed"), reauthorize=reauthorize,+ )+ removed = store.delete_installation("org-1", oauth_client_id="client-id", revoked_at=2000)+ assert removed is not reauthorize+ assert (store.installation("org-1") is not None) is reauthorize+ assert store.member_access("client-id", "org-1", "user-1") is (False if reauthorize else None)+++def test_revocation_cannot_remove_a_different_app(tmp_path: Path) -> None:+ store = LinearStateStore(tmp_path / "state.sqlite3")+ store.save_installation(_installation())+ assert not store.delete_installation(+ "org-1", oauth_client_id="other-app", revoked_at=time.time() + 10,+ )+ assert store.installation("org-1") is not None++[email protected]("created_at", [None, "invalid", "2026-09-26T11:00:00"])+def test_malformed_revocation_does_not_remove_authorization(tmp_path: Path, created_at: str | None) -> None:+ channel, _ = _runtime(tmp_path)+ with pytest.raises(linear_runtime.LinearPayloadError, match="createdAt"):+ channel._process_lifecycle_event({ # pyright: ignore[reportPrivateUsage]+ "action": "revoked", "organizationId": "org-1", "createdAt": created_at,+ })+ assert channel._state.installation("org-1") is not None # pyright: ignore[reportPrivateUsage]diff --git a/nanobot/channels/linear/tests/test_member_access.py b/nanobot/channels/linear/tests/test_member_access.pyindex 9a21503e1..b4f5f46d6 100644--- a/nanobot/channels/linear/tests/test_member_access.py+++ b/nanobot/channels/linear/tests/test_member_access.py@@ -57,6 +57,59 @@ def test_access_is_scoped_to_app_and_workspace(tmp_path: Path) -> None:assert not member_allowed(config, state, "org-1", "user-1")+def test_removing_workspace_forgets_member_choices_only_for_that_installation(tmp_path: Path) -> None:+ state = LinearStateStore(tmp_path / "state.sqlite3")+ first = _installation()+ second = replace(first, organization_id="org-2")+ state.save_installation(first)+ state.save_installation(second)+ state.set_member_access(first.oauth_client_id, "org-1", "user-1", allowed=True)+ state.set_member_access(first.oauth_client_id, "org-1", "user-2", allowed=False)+ state.set_member_access(first.oauth_client_id, "org-2", "user-1", allowed=True)++ state.delete_installation("org-1")++ assert state.installation("org-1") is None+ assert state.member_access(first.oauth_client_id, "org-1", "user-1") is None+ assert state.member_access(first.oauth_client_id, "org-1", "user-2") is None+ assert state.installation("org-2") == second+ assert state.member_access(first.oauth_client_id, "org-2", "user-1") is True+ state.save_installation(first)+ assert state.member_access(first.oauth_client_id, "org-1", "user-1") is None++[email protected]("paired", [False, True])[email protected]("allowed", [False, True])+def test_reauthorize_keeps_choices_but_remove_and_reconnect_uses_legacy_fallback(+ tmp_path: Path, paired: bool, allowed: bool,+) -> None:+ config = _config()+ config.allow_from = []+ if paired:+ approve_code(generate_code("linear", "user-1"))+ state = LinearStateStore(tmp_path / "state.sqlite3")+ first = _installation()+ state.save_installation(first)+ state.save_installation(replace(first, organization_id="org-2"))+ state.set_member_access(config.client_id, "org-1", "user-1", allowed=allowed)+ state.set_member_access(config.client_id, "org-2", "user-1", allowed=not allowed)++ # Reauthorization updates tokens without duplicating the workspace or resetting choices.+ renewed = replace(first, access_token="renewed", refresh_token="renewed-refresh")+ state.save_installation(renewed)+ reopened = LinearStateStore(state.path)+ assert len(reopened.list_installations(config.client_id)) == 2+ assert member_allowed(config, reopened, "org-1", "user-1") is allowed+ assert member_allowed(config, reopened, "org-2", "user-1") is not allowed++ # Deliberately removing a workspace clears only its explicit choices, not pairing.+ reopened.delete_installation("org-1")+ assert not member_allowed(config, reopened, "org-1", "user-1")+ reopened.save_installation(renewed)+ assert member_allowed(config, reopened, "org-1", "user-1") is paired+ assert member_allowed(config, reopened, "org-2", "user-1") is not allowed++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}}diff --git a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsxindex f895239c7..9acf45d3a 100644--- a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx+++ b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx@@ -1,6 +1,9 @@import { channelUiContribution } from "@/channel-plugins/registry";+import { NanobotClient } from "@/lib/nanobot-client";+import type { ConnectionStatus } from "@/lib/types";import type { ChannelSetupContract, ChannelSetupContractField, NanobotFeatureInfo } from "@/lib/types";import {+ act,fireEvent,installSettingsViewTestHooks,jsonResponse,@@ -13,6 +16,7 @@ import {} from "@/tests/settings-test-utils";import { linearManifestUrl } from "../../webui/manifest";+import { getLinearWorkspaceProfile } from "../../webui/api";vi.mock("../../webui/api", async (importOriginal) => ({...await importOriginal<typeof import("../../webui/api")>(),@@ -115,6 +119,7 @@ describe("Linear channel UI", () => {it("opens the Linear MCP connection settings without starting authorization", async () => {mockFeature(savedFeature());+ mockSavedInspection();renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));await screen.findByRole("textbox", { name: "OAuth client ID" });@@ -126,11 +131,12 @@ describe("Linear channel UI", () => {const dialog = await screen.findByRole("dialog", { name: "Linear" });expect(within(dialog).getByRole("button", { name: "Connect" })).toBeVisible();expect(screen.queryByRole("button", { name: "Configure Linear MCP" })).not.toBeInTheDocument();- expect(requestMutationMock).not.toHaveBeenCalled();+ expect(actionCalls()).toHaveLength(0);});it("keeps the channel draft open when saving before MCP setup fails", async () => {mockFeature(savedFeature());+ mockSavedInspection();requestMutationMock.mockRejectedValueOnce(new Error("Unable to save settings"));renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));@@ -215,6 +221,7 @@ describe("Linear channel UI", () => {it("preserves saved secrets and gates authorization on saving edited settings", async () => {const feature = savedFeature();mockFeature(feature);+ mockSavedInspection();requestMutationMock.mockResolvedValueOnce({saved: true,nanobot_features: {@@ -226,7 +233,7 @@ describe("Linear channel UI", () => {});renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));- expect(await screen.findByRole("button", { name: "Connect Linear" })).toBeEnabled();+ await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled());expect(screen.queryByRole("spinbutton", { name: "Listen port" })).not.toBeInTheDocument();fireEvent.click(screen.getByRole("button", { name: "Advanced" }));fireEvent.change(screen.getByRole("spinbutton", { name: "Listen port" }), {@@ -234,7 +241,7 @@ describe("Linear channel UI", () => {});expect(screen.getByRole("button", { name: "Connect Linear" })).toBeDisabled();await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled());- const params = requestMutationMock.mock.calls[0][1] as { values: Record<string, unknown> };+ const params = actionCalls()[0][1] as { values: Record<string, unknown> };expect(params.values["channels.linear.port"]).toBe("3980");expect(params.values).not.toHaveProperty("channels.linear.clientSecret");expect(params.values).not.toHaveProperty("channels.linear.webhookSigningSecret");@@ -242,6 +249,7 @@ describe("Linear channel UI", () => {it("keeps an unsaved draft when saving fails without enabling the channel", async () => {mockFeature(savedFeature());+ mockSavedInspection();requestMutationMock.mockRejectedValueOnce(new Error("Unable to save settings"));renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));@@ -253,60 +261,169 @@ describe("Linear channel UI", () => {expect(screen.getByRole("textbox", { name: "OAuth client ID" })).toHaveValue("replacement-client");expect(screen.getByRole("button", { name: "Connect Linear" })).toBeDisabled();await new Promise((resolve) => setTimeout(resolve, 750));- expect(requestMutationMock).toHaveBeenCalledTimes(1);- expect(requestMutationMock.mock.calls[0][1]).not.toHaveProperty("enable");+ expect(actionCalls()).toHaveLength(1);+ expect(actionCalls()[0][1]).not.toHaveProperty("enable");});- it("waits for a secret field to blur before saving its replacement", async () => {+ it("replaces a saved secret only on explicit save and submits just that field", async () => {const feature = savedFeature();mockFeature(feature);+ mockSavedInspection();requestMutationMock.mockResolvedValueOnce({saved: true, nanobot_features: { features: [feature], enabled_count: 0 },});renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));- const input = screen.getByLabelText("OAuth client secret", { exact: true });+ await screen.findByText(/No workspaces are authorized/);+ expect(screen.queryByPlaceholderText("Saved secret")).not.toBeInTheDocument();+ expect(screen.getAllByText("Saved", { exact: true })).toHaveLength(2);+ fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));+ const input = screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" });+ expect(input).toHaveFocus();fireEvent.change(input, { target: { value: "replacement-secret" } });+ fireEvent.blur(input);await new Promise((resolve) => setTimeout(resolve, 750));+ expect(actionCalls()).toHaveLength(0);+ fireEvent.click(screen.getByRole("button", { name: "Save", exact: true }));+ await waitFor(() => expect(actionCalls()).toHaveLength(1));+ const params = actionCalls()[0][1] as { values: Record<string, unknown> };+ expect(params.values).toEqual({ "channels.linear.clientSecret": "replacement-secret" });+ await waitFor(() => expect(screen.getByRole("button", { name: "Replace OAuth client secret" })).toHaveFocus());+ expect(screen.queryByDisplayValue("replacement-secret")).not.toBeInTheDocument();+ expect(screen.getAllByText("Saved", { exact: true })).toHaveLength(2);+ });++ it("cancels a replacement without submitting or blocking the existing connection", async () => {+ mockFeature(savedFeature());+ mockSavedInspection();+ renderSettingsView({ initialSection: "channels" });+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));+ await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled());+ fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));+ fireEvent.change(screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" }), {+ target: { value: "discarded-draft" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Cancel", exact: true }));+ expect(screen.getAllByText("Saved", { exact: true })).toHaveLength(2);+ expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled();+ await new Promise(resolve => setTimeout(resolve, 750));+ expect(actionCalls()).toHaveLength(0);+ fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));+ expect(screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" })).toHaveValue("");+ });++ it("keeps the draft after a failed secret save and does not report success", async () => {+ mockFeature(savedFeature());+ mockSavedInspection();+ requestMutationMock.mockResolvedValueOnce({ saved: false });+ renderSettingsView({ initialSection: "channels" });+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));+ await screen.findByText(/No workspaces are authorized/);+ fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));+ fireEvent.change(screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" }), {+ target: { value: "retry-draft" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Save", exact: true }));+ expect(await screen.findByRole("alert")).toHaveTextContent("Could not confirm the save");+ expect(screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" })).toHaveValue("retry-draft");+ expect(screen.queryByText("Settings saved.")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Cancel", exact: true }));+ expect(screen.getAllByText("Saved", { exact: true })).toHaveLength(2);+ });++ it("confirms a first secret save before enabling authorization", async () => {+ const feature = savedFeature();+ mockFeature({ ...feature, configured_fields: feature.configured_fields?.filter(+ key => key !== "channels.linear.clientSecret",+ ) });+ requestMutationMock.mockResolvedValueOnce({+ saved: true, nanobot_features: { features: [feature], enabled_count: 0 },+ });+ renderSettingsView({ initialSection: "channels" });+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));+ const input = screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" });+ fireEvent.change(input, { target: { value: "first-secret" } });+ expect(screen.getByRole("button", { name: "Connect Linear" })).toBeDisabled();expect(requestMutationMock).not.toHaveBeenCalled();- fireEvent.blur(input);- await waitFor(() => expect(requestMutationMock).toHaveBeenCalledTimes(1));- const params = requestMutationMock.mock.calls[0][1] as { values: Record<string, unknown> };- expect(params.values["channels.linear.clientSecret"]).toBe("replacement-secret");- expect(params.values).not.toHaveProperty("channels.linear.webhookSigningSecret");- await waitFor(() => expect(input).toHaveValue(""));- expect(input).toHaveAttribute("placeholder", "Saved secret");+ fireEvent.click(screen.getByRole("button", { name: "Save", exact: true }));+ await waitFor(() => expect(screen.getByRole("button", { name: "Replace OAuth client secret" })).toHaveFocus());+ expect(screen.getAllByText("Saved", { exact: true })).toHaveLength(2);+ expect(screen.queryByDisplayValue("first-secret")).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled();+ expect(actionCalls()[0][1].values).toEqual({ "channels.linear.clientSecret": "first-secret" });});- it("removes both saved secrets with one action while keeping the public URL and client ID", async () => {+ it("does not submit the other secret's unfinished replacement", async () => {const feature = savedFeature();mockFeature(feature);- const secretKeys = ["channels.linear.clientSecret", "channels.linear.webhookSigningSecret"];+ mockSavedInspection();requestMutationMock.mockResolvedValueOnce({- saved: true, nanobot_features: {- features: [{ ...feature, configured_fields: feature.configured_fields?.filter(- (key) => !secretKeys.includes(key),- ) }], enabled_count: 0,- },+ saved: true, nanobot_features: { features: [feature], enabled_count: 0 },});renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));- expect(screen.getAllByRole("button", { name: "Remove saved credentials" })).toHaveLength(1);- fireEvent.click(screen.getByRole("button", { name: "Remove saved credentials" }));- await waitFor(() => expect(requestMutationMock).toHaveBeenCalledTimes(1));- const params = requestMutationMock.mock.calls[0][1] as { values: Record<string, unknown> };- for (const key of secretKeys) expect(params.values[key]).toBeNull();- expect(params.values["channels.linear.clientId"]).toBe("client-id");- expect(params.values["channels.linear.publicBaseUrl"]).toBe("https://nanobot.example.com");- await waitFor(() => expect(screen.queryByRole("button", {- name: "Remove saved credentials",- })).not.toBeInTheDocument());- expect(screen.getByRole("button", { name: "Connect Linear" })).toBeDisabled();+ await screen.findByText(/No workspaces are authorized/);+ fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));+ fireEvent.click(screen.getByRole("button", { name: "Replace Webhook signing secret" }));+ const clientGroup = screen.getByRole("group", { name: "OAuth client secret" });+ const webhook = screen.getByLabelText("Webhook signing secret", { exact: true, selector: "input" });+ fireEvent.change(screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" }), {+ target: { value: "client-draft" },+ });+ fireEvent.change(webhook, { target: { value: "unfinished-webhook" } });+ fireEvent.click(within(clientGroup).getByRole("button", { name: "Save", exact: true }));+ await waitFor(() => expect(screen.getByRole("button", { name: "Replace OAuth client secret" })).toBeEnabled());+ expect(actionCalls()).toHaveLength(1);+ expect(actionCalls()[0][1].values).toEqual({ "channels.linear.clientSecret": "client-draft" });+ expect(webhook).toHaveValue("unfinished-webhook");+ fireEvent.click(screen.getByRole("button", { name: "Cancel", exact: true }));+ expect(screen.getAllByText("Saved", { exact: true })).toHaveLength(2);+ });++ it("waits before closing during a secret save and keeps the editor open if it fails", async () => {+ mockFeature(savedFeature());+ mockSavedInspection();+ let failSave!: (reason: Error) => void;+ requestMutationMock.mockImplementationOnce(() => new Promise((_resolve, reject) => { failSave = reject; }));+ renderSettingsView({ initialSection: "channels" });+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));+ await screen.findByText(/No workspaces are authorized/);+ fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));+ fireEvent.change(screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" }), {+ target: { value: "keep-draft" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Save", exact: true }));+ const dialog = screen.getByRole("dialog");+ fireEvent.click(within(dialog).getByRole("button", { name: "Close", exact: true }));+ expect(dialog).toBeVisible();+ expect(actionCalls()).toHaveLength(1);+ await act(async () => failSave(new Error("Network unavailable")));+ expect(await screen.findByRole("alert")).toHaveTextContent("Could not confirm the save");+ expect(dialog).toBeVisible();+ expect(screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" })).toHaveValue("keep-draft");+ });++ it("keeps global reset in Advanced and no longer exposes the ambiguous credential deletion", async () => {+ mockFeature(savedFeature());+ mockSavedInspection();+ renderSettingsView({ initialSection: "channels" });+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));+ expect(screen.queryByRole("button", { name: "Remove saved credentials" })).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Reset Linear connection" })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Advanced" }));+ await waitFor(() => expect(screen.getByRole("button", { name: "Reset Linear connection" })).toBeEnabled());+ fireEvent.click(screen.getByRole("button", { name: "Reset Linear connection" }));+ const confirm = await screen.findByRole("alertdialog", { name: "Reset Linear?" });+ expect(confirm).toHaveTextContent("all workspaces linked through this app");+ expect(actionCalls()).toHaveLength(0);+ fireEvent.click(within(confirm).getByRole("button", { name: "Cancel" }));+ expect(actionCalls()).toHaveLength(0);});it("flushes the draft on close and waits for one in-flight save", async () => {const feature = savedFeature();mockFeature(feature);+ mockSavedInspection();let finishSave: ((value: unknown) => void) | undefined;requestMutationMock.mockImplementationOnce(() => new Promise((resolve) => { finishSave = resolve; }));renderSettingsView({ initialSection: "channels" });@@ -316,10 +433,10 @@ describe("Linear channel UI", () => {});const dialog = screen.getByRole("dialog");fireEvent.click(within(dialog).getByRole("button", { name: "Close", exact: true }));- expect(requestMutationMock).toHaveBeenCalledTimes(1);+ expect(actionCalls()).toHaveLength(1);expect(dialog).toBeVisible();fireEvent.click(within(dialog).getByRole("button", { name: "Close", exact: true }));- expect(requestMutationMock).toHaveBeenCalledTimes(1);+ expect(actionCalls()).toHaveLength(1);finishSave?.({ saved: true, nanobot_features: { features: [{...feature, config_values: { ...feature.config_values, "channels.linear.clientId": "replacement-client" },}], enabled_count: 0 } });@@ -329,6 +446,7 @@ describe("Linear channel UI", () => {it("keeps the dialog and draft after a failed close save and allows retry", async () => {const feature = savedFeature();mockFeature(feature);+ mockSavedInspection();requestMutationMock.mockRejectedValueOnce(new Error("Connection lost"));renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));@@ -344,22 +462,27 @@ describe("Linear channel UI", () => {}], enabled_count: 0 } });fireEvent.click(screen.getByRole("button", { name: "Retry" }));await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled());- expect(requestMutationMock).toHaveBeenCalledTimes(2);+ expect(actionCalls()).toHaveLength(2);expect(screen.queryByRole("alert")).not.toBeInTheDocument();});it("shows the OAuth handoff and cancels a pending authorization", async () => {mockFeature(savedFeature());+ mockSavedInspection();requestMutationMock.mockResolvedValueOnce({ session_id: "linear-oauth", status: "pending",qr_url: "https://linear.app/oauth/authorize?client_id=test", interval_ms: 5000 }).mockResolvedValueOnce({ session_id: "linear-oauth", status: "cancelled" });renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));- fireEvent.click(await screen.findByRole("button", { name: "Connect Linear" }));+ await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled());+ fireEvent.click(screen.getByRole("button", { name: "Connect Linear" }));expect(await screen.findByRole("link", { name: "Continue in Linear" })).toHaveAttribute("href", "https://linear.app/oauth/authorize?client_id=test",);+ expect(screen.getByText("Continue in Linear to choose a workspace and authorize nanobot. Return here when you're done.")).toBeVisible();+ expect(screen.queryByRole("img", { name: /QR/i })).not.toBeInTheDocument();+ expect(screen.queryByText(/scan the QR code/i)).not.toBeInTheDocument();expect(screen.getByRole("textbox", { name: "OAuth client ID" })).toBeDisabled();expect(screen.queryByRole("button", { name: "Remove saved credentials" })).not.toBeInTheDocument();expect(screen.getByRole("button", { name: "Cancel" })).toBeEnabled();@@ -380,20 +503,39 @@ describe("Linear channel UI", () => {const open = await screen.findByRole("button", { name: "View Linear settings" });fireEvent.click(open);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();+ expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled();+ expect(screen.queryByRole("button", { name: "Connect another workspace" })).not.toBeInTheDocument();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("Channel running", { exact: true })).toBeVisible();- expect(screen.getByRole("button", { name: "Connect another workspace" })).toBeEnabled();+ expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled();expect(await screen.findByText(/No workspaces are authorized/)).toBeVisible();expect(requestMutationMock).toHaveBeenCalledWith("settings.channel.connect.start", { channel: "linear", operation: "inspect" }, 150_000,);});+ it.each(["stopped", "failed"])("keeps authorized workspaces manageable when the channel is %s", async (runtime_status) => {+ mockFeature({ ...savedFeature(), runtime_status });+ requestMutationMock.mockResolvedValue({+ session_id: "", status: "inspected", installations: [+ { organization_id: "org-1", organization_name: "nanobot", authorization_status: "authorized" },+ ],+ });+ renderSettingsView({ initialSection: "channels" });+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));+ expect(await screen.findByRole("article", { name: "nanobot" })).toBeVisible();+ expect(within(screen.getByRole("dialog")).queryByText("Channel running", { exact: true })).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Manage nanobot" })).toBeEnabled();+ expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled();+ expect(requestMutationMock).toHaveBeenCalledTimes(1);+ 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"));@@ -406,29 +548,64 @@ describe("Linear channel UI", () => {expect(screen.getByRole("button", { name: "Refresh workspaces" })).toBeEnabled();});- it("starts another workspace authorization directly and preserves the connection on cancel", async () => {+ it("offers an independent add-workspace entry using the existing app with forced consent", async () => {+ mockFeature({ ...savedFeature(), enabled: true, running: true, runtime_status: "running" });+ requestMutationMock+ .mockResolvedValueOnce({ session_id: "", status: "inspected", installations: [+ { organization_id: "org-1", organization_name: "nanobot", authorization_status: "authorized" },+ ] })+ .mockResolvedValueOnce({ session_id: "add", status: "pending",+ qr_url: "https://linear.app/oauth/authorize?client_id=test" });+ renderSettingsView({ initialSection: "channels" });+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));+ const add = await screen.findByRole("button", { name: "Connect workspace" });+ expect(screen.getByRole("button", { name: "About connecting workspaces" })).toBeVisible();+ fireEvent.click(add);+ expect(await screen.findByRole("link", { name: "Continue in Linear" })).toBeVisible();+ expect(screen.queryByRole("img", { name: /QR/i })).not.toBeInTheDocument();+ expect(screen.getByRole("article", { name: "nanobot" })).toBeVisible();+ expect(requestMutationMock).toHaveBeenLastCalledWith(+ "settings.channel.connect.start", { channel: "linear", force: true }, 150_000,+ );+ });++ it("reauthorizes from the workspace menu and preserves the connection on cancel", async () => {+ const reveal = vi.spyOn(HTMLElement.prototype, "scrollIntoView");mockFeature({ ...savedFeature(), enabled: true, running: true, runtime_status: "running" });requestMutationMock- .mockResolvedValueOnce({ session_id: "", status: "inspected", installations: [] })+ .mockResolvedValueOnce({ session_id: "", status: "inspected", installations: [+ { organization_id: "org-1", organization_name: "nanobot", authorization_status: "authorized" },+ ] }).mockResolvedValueOnce({ session_id: "another-workspace", status: "pending",qr_url: "https://linear.app/oauth/authorize?client_id=test" }).mockResolvedValueOnce({ session_id: "another-workspace", status: "cancelled" });renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));- fireEvent.click(screen.getByRole("button", { name: "Connect another workspace" }));+ const manage = await screen.findByRole("button", { name: "Manage nanobot" });+ expect(screen.queryByRole("button", { name: "Connect another workspace" })).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Reauthorize" })).not.toBeInTheDocument();+ fireEvent.keyDown(manage, { key: "ArrowDown" });+ fireEvent.click(await screen.findByRole("menuitem", { name: "Reauthorize" }));+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(+ "settings.channel.connect.start", { channel: "linear", force: true }, 150_000,+ ));expect(requestMutationMock).toHaveBeenCalledWith("settings.channel.connect.start", { channel: "linear", force: true }, 150_000,);expect(await screen.findByRole("link", { name: "Continue in Linear" })).toBeVisible();+ await waitFor(() => expect(screen.getByRole("link", { name: "Continue in Linear" })).toHaveFocus());+ expect(reveal).toHaveBeenCalledWith({ block: "nearest" });fireEvent.click(screen.getByRole("button", { name: "Cancel" }));- expect(await screen.findByRole("button", { name: "Connect another workspace" })).toBeEnabled();+ await waitFor(() => expect(screen.getByRole("button", { name: "Manage nanobot" })).toBeEnabled());expect(within(screen.getByRole("dialog")).getByText("Channel running", { exact: true })).toBeVisible();expect(screen.queryByText("Authorization stopped.")).not.toBeInTheDocument();+ expect(requestMutationMock.mock.calls.some(([, params]) => params.operation === "disconnect")).toBe(false);});it("updates the running status when an existing installation connects without OAuth", async () => {const feature = savedFeature();mockFeature(feature);+ mockSavedInspection();requestMutationMock.mockResolvedValueOnce({session_id: "", status: "succeeded",nanobot_features: {@@ -438,19 +615,70 @@ describe("Linear channel UI", () => {}).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" }));+ await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled());+ fireEvent.click(screen.getByRole("button", { name: "Connect Linear" }));expect(await within(screen.getByRole("dialog")).findByText("Channel running", { exact: true })).toBeVisible();- expect(screen.getByRole("button", { name: "Connect another workspace" })).toBeEnabled();+ expect(screen.queryByRole("button", { name: "Connect another workspace" })).not.toBeInTheDocument();+ });++ it("does not show OAuth success when the channel subsequently fails to start", async () => {+ const feature = savedFeature();+ mockFeature(feature);+ mockSavedInspection();+ requestMutationMock.mockResolvedValueOnce({+ session_id: "", status: "succeeded",+ nanobot_features: {+ features: [{ ...feature, enabled: true, runtime_status: "failed",+ runtime_error: "Linear channel failed to start" }], enabled_count: 1,+ },+ }).mockResolvedValueOnce({ session_id: "", status: "inspected", installations: [] });+ renderSettingsView({ initialSection: "channels" });+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));+ await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled());+ fireEvent.click(screen.getByRole("button", { name: "Connect Linear" }));+ expect(await screen.findByText("Linear channel failed to start")).toBeVisible();+ expect(screen.queryByText("Linear is connected.")).not.toBeInTheDocument();});it("does not mark saved credentials or a failed runtime as connected", async () => {mockFeature({ ...savedFeature(), enabled: true, configured: true, runtime_status: "failed",runtime_error: "Linear channel failed to start" });+ mockSavedInspection();renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));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();+ await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled());+ });++ it("recovers workspace inspection automatically when the WebUI reconnects", async () => {+ mockFeature({ ...savedFeature(), enabled: true, running: true, runtime_status: "running" });+ const client = new NanobotClient({ url: "ws://test.invalid", reconnect: false });+ let onStatus: ((status: ConnectionStatus) => void) | undefined;+ const unsubscribe = vi.fn();+ vi.spyOn(client, "onStatus").mockImplementation((handler) => {+ onStatus = handler;+ handler("reconnecting");+ return unsubscribe;+ });+ vi.spyOn(client, "requestMutation").mockImplementation(requestMutationMock);+ requestMutationMock+ .mockRejectedValueOnce(new Error("WebUI connection is not open"))+ .mockResolvedValue({ installations: [+ { organization_id: "org-1", organization_name: "nanobot", authorization_status: "authorized" },+ ] });+ renderSettingsView({ initialSection: "channels", client });+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));+ expect(await screen.findByText("WebUI connection is not open")).toBeVisible();+ act(() => onStatus?.("open"));+ expect(await screen.findByRole("article", { name: "nanobot" })).toBeVisible();+ expect(screen.queryByText("WebUI connection is not open")).not.toBeInTheDocument();+ expect(requestMutationMock).toHaveBeenCalledTimes(2);+ // A second reconnect must revalidate even while the display cache is fresh.+ act(() => { onStatus?.("reconnecting"); onStatus?.("open"); });+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledTimes(3));+ fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));+ expect(unsubscribe).toHaveBeenCalled();});it("lists authorized workspaces and confirms disconnecting the last one", async () => {@@ -491,8 +719,14 @@ describe("Linear channel UI", () => {fireEvent.click(screen.getByRole("button", { name: "Advanced" }));expect(screen.getByText(/Example workspace: read, write, app:mentionable, app:assignable/)).toBeVisible();fireEvent.click(screen.getByRole("button", { name: "Advanced" }));- fireEvent.click(screen.getByRole("button", { name: "Disconnect" }));- fireEvent.click(screen.getByRole("button", { name: "Disconnect workspace" }));+ expect(within(workspace).queryByRole("button", { name: "Remove workspace" })).not.toBeInTheDocument();+ fireEvent.keyDown(screen.getByRole("button", { name: "Manage Example workspace" }), { key: "ArrowDown" });+ fireEvent.click(await screen.findByRole("menuitem", { name: "Remove workspace" }));+ const confirm = await screen.findByRole("alertdialog", { name: "Remove Example workspace?" });+ expect(confirm).toHaveTextContent("Linear issues, comments, and nanobot conversation history will be kept.");+ expect(confirm).toHaveTextContent("the Linear channel will also be turned off");+ expect(requestMutationMock).toHaveBeenCalledTimes(1);+ fireEvent.click(within(confirm).getByRole("button", { name: "Remove workspace" }));await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith("settings.channel.connect.start",@@ -504,6 +738,119 @@ describe("Linear channel UI", () => {);});+ it("clears an old cancelled authorization after removing the last workspace", async () => {+ const installation = { organization_id: "org-1", organization_name: "nanobot",+ authorization_status: "authorized" };+ let removed = false;+ mockFeature({ ...savedFeature(), enabled: true, running: true, runtime_status: "running" });+ requestMutationMock.mockImplementation(async (method, params) => {+ if (method === "settings.feature.disable") return {+ features: [{ ...savedFeature(), enabled: false, running: false, runtime_status: "stopped" }],+ enabled_count: 0,+ };+ if (method === "settings.channel.connect.cancel") return {+ session_id: "attempt", status: "cancelled", message: "Linear authorization cancelled.",+ };+ if (params.operation === "disconnect") {+ removed = true;+ return { session_id: "", status: "disconnected", installations: [] };+ }+ if (params.operation === "inspect") return {+ session_id: "", status: "inspected", installations: removed ? [] : [installation],+ };+ return { session_id: "attempt", status: "pending", qr_url: "https://linear.app/oauth/authorize" };+ });+ renderSettingsView({ initialSection: "channels" });+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));+ fireEvent.click(await screen.findByRole("button", { name: "Connect workspace" }));+ await screen.findByRole("link", { name: "Continue in Linear" });+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));+ await waitFor(() => expect(screen.getByRole("button", { name: "Manage nanobot" })).toBeEnabled());+ fireEvent.keyDown(screen.getByRole("button", { name: "Manage nanobot" }), { key: "ArrowDown" });+ fireEvent.click(await screen.findByRole("menuitem", { name: "Remove workspace" }));+ const confirm = await screen.findByRole("alertdialog", { name: "Remove nanobot?" });+ fireEvent.click(within(confirm).getByRole("button", { name: "Remove workspace" }));+ expect(await screen.findByRole("button", { name: "Connect Linear" })).toBeEnabled();+ expect(screen.queryByText("Linear authorization cancelled.")).not.toBeInTheDocument();+ expect(screen.queryByRole("link", { name: "Continue in Linear" })).not.toBeInTheDocument();+ });++ it("cancels disconnect without a mutation and returns focus to workspace actions", async () => {+ mockFeature({ ...savedFeature(), enabled: true, running: true, runtime_status: "running" });+ requestMutationMock.mockResolvedValue({ session_id: "", status: "inspected", installations: [+ { organization_id: "org-1", organization_name: "nanobot", authorization_status: "authorized" },+ ] });+ renderSettingsView({ initialSection: "channels" });+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));+ const manage = await screen.findByRole("button", { name: "Manage nanobot" });+ manage.focus();+ fireEvent.keyDown(manage, { key: "ArrowDown" });+ fireEvent.click(await screen.findByRole("menuitem", { name: "Remove workspace" }));+ const confirm = await screen.findByRole("alertdialog", { name: "Remove nanobot?" });+ await waitFor(() => expect(within(confirm).getByRole("button", { name: "Cancel" })).toHaveFocus());+ fireEvent.click(within(confirm).getByRole("button", { name: "Cancel" }));+ await waitFor(() => expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument());+ await waitFor(() => expect(manage).toHaveFocus());+ expect(requestMutationMock).toHaveBeenCalledTimes(1);+ expect(screen.getByRole("article", { name: "nanobot" })).toBeVisible();+ });++ it("keeps a failed disconnect retryable and only removes the selected workspace after confirmation", async () => {+ const installations = [+ { organization_id: "org-1", organization_name: "nanobot", authorization_status: "authorized" },+ { organization_id: "org-2", organization_name: "Other workspace", authorization_status: "authorized" },+ ];+ let failDisconnect!: (error: Error) => void;+ mockFeature({ ...savedFeature(), enabled: true, running: true, runtime_status: "running" });+ requestMutationMock+ .mockResolvedValueOnce({ session_id: "", status: "inspected", installations })+ .mockImplementationOnce(() => new Promise((_resolve, reject) => { failDisconnect = reject; }))+ .mockResolvedValueOnce({ session_id: "", status: "disconnected", installations: [installations[1]] });+ renderSettingsView({ initialSection: "channels" });+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));+ fireEvent.keyDown(await screen.findByRole("button", { name: "Manage nanobot" }), { key: "ArrowDown" });+ fireEvent.click(await screen.findByRole("menuitem", { name: "Remove workspace" }));+ const confirm = await screen.findByRole("alertdialog", { name: "Remove nanobot?" });+ expect(confirm).not.toHaveTextContent("last connected workspace");+ fireEvent.click(within(confirm).getByRole("button", { name: "Remove workspace" }));+ expect(within(confirm).getByRole("button", { name: "Removing…" })).toBeDisabled();+ expect(within(confirm).getByRole("button", { name: "Cancel" })).toBeDisabled();+ failDisconnect(new Error("Could not revoke authorization"));+ expect(await within(confirm).findByRole("alert")).toHaveTextContent("Could not revoke authorization");+ expect(screen.getByRole("article", { name: "nanobot", hidden: true })).toBeInTheDocument();+ fireEvent.click(within(confirm).getByRole("button", { name: "Remove workspace" }));+ await waitFor(() => expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument());+ expect(screen.queryByRole("article", { name: "nanobot" })).not.toBeInTheDocument();+ expect(screen.getByRole("article", { name: "Other workspace" })).toBeVisible();+ expect(requestMutationMock).toHaveBeenLastCalledWith("settings.channel.connect.start", {+ channel: "linear", operation: "disconnect", organization_id: "org-1",+ }, 150_000);+ expect(requestMutationMock.mock.calls.some(([method]) => method === "settings.feature.disable")).toBe(false);+ });++ it("shows a workspace logo and member access without team controls", async () => {+ vi.mocked(getLinearWorkspaceProfile).mockResolvedValueOnce({+ organization_id: "org-1", logo_url: "https://uploads.linear.app/org-1/logo",+ });+ mockFeature({ ...savedFeature(), enabled: true, running: true, runtime_status: "running" });+ requestMutationMock.mockImplementation(async (_method, params) => params.operation === "members"+ ? { session_id: "", status: "members", organization_id: "org-1", legacy_allow_all: false,+ members: [{ id: "u1", name: "Xubin", teams: ["nanobot"], allowed: true }] }+ : { session_id: "", status: "inspected", installations: [+ { organization_id: "org-1", organization_name: "nanobot", authorization_status: "authorized" },+ ] });+ renderSettingsView({ initialSection: "channels" });+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));+ const workspace = await screen.findByRole("article", { name: "nanobot" });+ await waitFor(() => expect(workspace.querySelector("img")).toHaveAttribute("src", "https://uploads.linear.app/org-1/logo"));+ expect(within(workspace).queryByRole("button", { name: /team/i })).not.toBeInTheDocument();+ fireEvent.click(within(workspace).getByRole("button", { name: "Member access" }));+ expect(await within(workspace).findByRole("switch", { name: "Allow Xubin to use nanobot" })).toBeVisible();+ expect(within(workspace).getAllByRole("switch")).toHaveLength(1);+ expect(within(workspace).queryByRole("combobox")).not.toBeInTheDocument();+ expect(requestMutationMock.mock.calls.some(([, params]) => params.operation === "member_access")).toBe(false);+ });+it("keeps member access inside its own workspace card and leaves other cards collapsed", async () => {mockFeature({ ...savedFeature(), enabled: true, running: true, runtime_status: "running" });requestMutationMock.mockImplementation(async (_method, params) => {@@ -564,18 +911,27 @@ describe("Linear channel UI", () => {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();+ expect(screen.getByRole("button", { name: "Manage Example workspace" })).toBeDisabled();+ expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument();finishRefresh?.({ session_id: "", status: "inspected", installations: [installation] });await waitFor(() => expect(- screen.getByRole("button", { name: "Disconnect workspace" }),+ screen.getByRole("button", { name: "Manage Example workspace" }),).toBeEnabled());});});+function mockSavedInspection() {+ requestMutationMock.mockResolvedValueOnce({+ session_id: "", status: "inspected", installations: [],+ });+}++function actionCalls() {+ return requestMutationMock.mock.calls.filter(([, params]) => params?.operation !== "inspect");+}+function savedFeature(): NanobotFeatureInfo {return {...linearFeature,diff --git a/nanobot/channels/linear/webui/LinearAvatar.tsx b/nanobot/channels/linear/webui/LinearAvatar.tsxindex c3e143258..181881d58 100644--- a/nanobot/channels/linear/webui/LinearAvatar.tsx+++ b/nanobot/channels/linear/webui/LinearAvatar.tsx@@ -17,15 +17,17 @@ export function LinearAvatar({ name, url, workspace = false }: {source = parsed.href;}} catch { /* Missing or malformed images use the same fallback. */ }- const size = workspace ? 36 : 32;+ const size = workspace ? 28 : 32;+ const showImage = source !== null && source !== failedUrl;return <span aria-hidden className={cn(- "relative flex shrink-0 items-center justify-center overflow-hidden bg-muted text-xs font-medium text-muted-foreground",- workspace ? "h-9 w-9 rounded-control" : "h-8 w-8 rounded-full",+ "relative flex shrink-0 items-center justify-center text-xs font-medium text-muted-foreground",+ workspace ? "h-7 w-7" : "h-8 w-8 overflow-hidden rounded-full bg-muted",+ workspace && !showImage && "rounded-md bg-muted",)}>- {workspace ? <Building2 className="h-4 w-4" /> : name.slice(0, 2).toLocaleUpperCase()}- {source && source !== failedUrl ? <img src={source} alt="" width={size} height={size}+ {workspace ? !showImage ? <Building2 className="h-4 w-4" /> : null : name.slice(0, 2).toLocaleUpperCase()}+ {source && showImage ? <img src={source} alt="" width={size} height={size}loading="lazy" decoding="async" referrerPolicy="no-referrer"- className="absolute inset-0 h-full w-full bg-muted object-cover"+ className={cn("absolute inset-0 h-full w-full", workspace ? "object-contain" : "bg-muted object-cover")}onError={() => setFailedUrl(source)} /> : null}</span>;}diff --git a/nanobot/channels/linear/webui/LinearConnectFlow.tsx b/nanobot/channels/linear/webui/LinearConnectFlow.tsxindex 26b8d47b8..04b9a589a 100644--- a/nanobot/channels/linear/webui/LinearConnectFlow.tsx+++ b/nanobot/channels/linear/webui/LinearConnectFlow.tsx@@ -1,4 +1,4 @@-import type { ReactNode } from "react";+import { useCallback, useRef, type ReactNode } from "react";import { ExternalLink } from "lucide-react";import { useTranslation } from "react-i18next";@@ -12,41 +12,50 @@ export function LinearConnectFlow({feature,idleLabel,connectRequestId,+ connected = feature.runtime_status === "running",onFeaturesUpdate,onActiveChange,renderActions,}: ChannelPluginConnectFlowProps & {onActiveChange?: (active: boolean) => void;+ connected?: boolean;renderActions?: (connectButton: ReactNode) => ReactNode;}) {const { t } = useTranslation();const tx = channelTranslator(t, "linear");+ const flowRef = useRef<HTMLDivElement | null>(null);+ const revealAuthorization = useCallback((link: HTMLAnchorElement | null) => {+ if (!link) return;+ flowRef.current?.scrollIntoView({ block: "nearest" });+ link.focus({ preventScroll: true });+ }, []);return (- <div className="mt-3 space-y-3">+ <div ref={flowRef} className="mt-3 space-y-3"><ChannelQrConnectFlowtoken={token}channelName="linear"idleLabel={idleLabel}connectRequestId={connectRequestId}+ startParams={connectRequestId ? { force: true } : undefined}forceOnRepeat- connected={feature.runtime_status === "running"}- suppressSucceeded={feature.runtime_status === "running"}+ showQrCode={false}+ connected={connected}+ suppressSucceeded={feature.runtime_status === "running" || feature.runtime_status === "failed"}onFeaturesUpdate={onFeaturesUpdate}onActiveChange={onActiveChange}renderActions={renderActions}labels={{- qrAlt: tx("custom.qrAlt", "Linear authorization QR code"),scanTitle: tx("custom.authorizeTitle", "Authorize in Linear"),scanDescription: tx("custom.authorizeDescription",- "Open Linear in this browser or scan the QR code. nanobot enables the channel after authorization.",+ "Continue in Linear to choose a workspace and authorize nanobot. Return here when you're done.",),waiting: tx("custom.waiting", "Waiting for Linear authorization..."),connected: tx("custom.connected", "Linear is connected."),stopped: tx("custom.stopped", "Authorization stopped."),connecting: tx("custom.connecting", "Connecting..."),- scanAgain: tx("custom.reconnect", "Connect another workspace"),+ scanAgain: tx("custom.reauthorize", "Reauthorize"),connect: tx("custom.connect", "Connect Linear"),}}renderPending={({ connect }) => (@@ -61,7 +70,7 @@ export function LinearConnectFlow({size="sm"className="h-8 rounded-full px-3 text-[12px] font-semibold">- <a href={connect.qr_url} target="_blank" rel="noreferrer">+ <a ref={revealAuthorization} href={connect.qr_url} target="_blank" rel="noreferrer"><ExternalLink className="mr-1.5 h-3.5 w-3.5" aria-hidden />{tx("custom.openLinear", "Continue in Linear")}</a>diff --git a/nanobot/channels/linear/webui/LinearMemberAccess.tsx b/nanobot/channels/linear/webui/LinearMemberAccess.tsxindex d417d5924..1caa5924e 100644--- a/nanobot/channels/linear/webui/LinearMemberAccess.tsx+++ b/nanobot/channels/linear/webui/LinearMemberAccess.tsx@@ -37,7 +37,7 @@ export function LinearMemberAccess({ organizationId, configScope = "", disabledconst prefetch = () => { if (!disabled) void store.load(); };const needle = search.trim().toLocaleLowerCase();- const visible = members.filter((member) => [member.name, member.id, ...member.teams]+ const visible = members.filter((member) => [member.name, member.id].some((value) => value.toLocaleLowerCase().includes(needle)));const names = new Set<string>();const duplicateNames = new Set<string>();@@ -57,7 +57,7 @@ export function LinearMemberAccess({ organizationId, configScope = "", disabled<span role="status" aria-live="polite" className="text-end text-[11px] font-normal text-muted-foreground">{payload ? !expanded ? tx("members.summary", "{{allowed}} enabled", {allowed: members.filter((member) => member.allowed).length,- }) : null : loading ? tx("members.loading", "Finding your teammates…") : null}+ }) : null : loading ? tx("members.loading", "Finding members…") : null}</span><ChevronDown className={cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200 motion-reduce:transition-none", expanded && "rotate-180")} aria-hidden /></span>@@ -82,7 +82,7 @@ export function LinearMemberAccess({ organizationId, configScope = "", disabledtitle={tx("members.refresh", "Refresh members")}><RefreshCw className="h-4 w-4 text-muted-foreground" aria-hidden /></Button>- <SettingsHint description={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.")}>+ <SettingsHint description={tx("members.help", "Enable members to use nanobot without a pairing code. Linear's existing authorization still applies. This does not grant access to the nanobot admin UI. Turning access off blocks new requests, not tasks already running.")}><span className="flex h-9 w-9 items-center justify-center text-muted-foreground"><Info className="h-4 w-4" aria-hidden /><span className="sr-only">{tx("members.details", "About member access")}</span>@@ -93,7 +93,7 @@ export function LinearMemberAccess({ organizationId, configScope = "", disabled{error} {tx("members.retry", "Refresh members to check the current state and try again.")}</p> : null}{payload && !error && visible.length === 0 ? <p className="settings-list-inset py-3 text-[12px] text-muted-foreground">- {tx("members.empty", "No matching active members in the teams this app can access.")}+ {tx("members.empty", "No matching active members.")}</p> : null}<SettingsGroup><ul className="max-h-80 overflow-y-auto" aria-label={tx("members.title", "Member access")}>@@ -105,8 +105,7 @@ export function LinearMemberAccess({ organizationId, configScope = "", disabled<LinearAvatar name={member.name} url={member.avatar_url} /><div className="min-w-0"><p className="truncate" title={member.id}>{member.name}</p>- <div className="flex flex-wrap items-center gap-x-2 text-[12px] font-normal text-muted-foreground">- <span className="truncate">{member.teams.join(" · ")}</span>+ <div className="flex flex-wrap items-center gap-x-2 text-[12px] font-normal leading-4 text-muted-foreground"><span id={save?.status === "error" ? undefined : statusId} role="status" aria-live="polite" className="inline-flex items-center gap-1">{save?.status === "saving" ? tx("members.working", "Saving…") : null}{save?.status === "saved" ? <><Check className="h-3 w-3" aria-hidden />{tx("members.saved", "Saved")}</> : null}diff --git a/nanobot/channels/linear/webui/LinearPanel.tsx b/nanobot/channels/linear/webui/LinearPanel.tsxindex 1f5203812..ce96289da 100644--- a/nanobot/channels/linear/webui/LinearPanel.tsx+++ b/nanobot/channels/linear/webui/LinearPanel.tsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useId, useMemo, useRef, useState, useSyncExternalStore } from "react";-import { AlertCircle, Check, ChevronDown, ExternalLink, Loader2, RefreshCw, Unplug } from "lucide-react";+import { AlertCircle, Check, ChevronDown, ExternalLink, Info, Loader2, MoreHorizontal, Plus, RefreshCw, Unplug } from "lucide-react";import { useTranslation } from "react-i18next";import { channelTranslator } from "@/channel-plugins/i18n";@@ -18,6 +18,13 @@ import {localizedChannelDisplayName,} from "@/components/settings/channels/ChannelIdentity";import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";import {AlertDialog,AlertDialogCancel,@@ -29,7 +36,8 @@ import {} from "@/components/ui/alert-dialog";import { channelValidationStatusClass } from "@/components/settings/channels/ChannelValidationProgress";import { useAutoSave } from "@/components/settings/shared/useAutoSave";-import { configureChannel, disableNanobotFeature } from "@/lib/api";+import { SettingsHint } from "@/components/settings/shared/SettingsHint";+import { configureChannel, disableNanobotFeature, fetchNanobotFeatures } from "@/lib/api";import { cn } from "@/lib/utils";import { useClient } from "@/providers/ClientProvider";@@ -40,6 +48,9 @@ import { LinearMemberAccess } from "./LinearMemberAccess";import { LinearAvatar } from "./LinearAvatar";import { linearManifestUrl } from "./manifest";import { linearWorkspaceStore } from "./workspace-store";+import { linearMemberAccessStore } from "./member-access-store";+import { LinearResetConnection } from "./LinearResetConnection";+import { LinearSecretField } from "./LinearSecretField";const PUBLIC_BASE_URL_KEY = "channels.linear.publicBaseUrl";const WEBHOOK_PATH_KEY = "channels.linear.webhookPath";@@ -75,7 +86,10 @@ export function LinearPanel({const [clearedSecrets, setClearedSecrets] = useState<Set<string>>(() => new Set());const [advancedOpen, setAdvancedOpen] = useState(false);const [saving, setSaving] = useState(false);+ const [resetting, setResetting] = useState(false);const [connecting, setConnecting] = useState(false);+ const [connectRequestId, setConnectRequestId] = useState(0);+ const [connectionGeneration, setConnectionGeneration] = useState(0);const [notice, setNotice] = useState<string | null>(null);const [saved, setSaved] = useState(false);const [publicUrlPromptOpen, setPublicUrlPromptOpen] = useState(false);@@ -90,7 +104,11 @@ export function LinearPanel({const [disconnectConfirmId, setDisconnectConfirmId] = useState<string | null>(null);const [workspaceNotice, setWorkspaceNotice] = useState<string | null>(null);const [workspaceError, setWorkspaceError] = useState<string | null>(null);+ const workspaceActionRef = useRef<HTMLButtonElement | null>(null);+ const skipMenuRestoreFocus = useRef(false);+ const disconnectTarget = installations.find(item => item.organization_id === disconnectConfirmId);const savePromiseRef = useRef<Promise<boolean> | null>(null);+ const secretSavePromiseRef = useRef<Promise<void> | null>(null);const advancedPanelId = useId();useEffect(() => {@@ -100,7 +118,7 @@ export function LinearPanel({setClearedSecrets(new Set());}, [savedValuesKey, feature.name]);- const busy = saving || Boolean(actionKey);+ const busy = saving || resetting || Boolean(actionKey);const savedValues = defaultChannelFieldValues(editableFields, feature.config_values);const dirty = clearedSecrets.size > 0 || editableFields.some((field) => fieldValues[field.key] !== savedValues[field.key],@@ -110,12 +128,21 @@ export function LinearPanel({touchedFields.has(field.key) && Boolean(fieldValues[field.key]?.trim()),);const hasSavedSecrets = secretFields.some((field) => configuredFields.has(field.key));+ const memberConfigScope = JSON.stringify([+ feature.config_values?.["channels.linear.clientId"],+ feature.config_values?.["channels.linear.allowFrom"],+ ]);+ const forgetWorkspaceMembers = (organizationId: string) => {+ linearMemberAccessStore(client, token, memberConfigScope, organizationId).invalidate();+ };const manifestDirty = [PUBLIC_BASE_URL_KEY, WEBHOOK_PATH_KEY, CALLBACK_PATH_KEY].some((key) => fieldValues[key] !== savedValues[key],);const credentialsSaved = fields.filter((field) => !field.optional).every((field) =>configuredFields.has(field.key) || Boolean(feature.config_values?.[field.key]?.trim()),);+ const workspaceActionsDisabled = busy || dirty || connecting || loadingInstallations+ || disconnectingId !== null;const savedBaseUrl = feature.config_values?.[PUBLIC_BASE_URL_KEY]?.replace(/\/$/, "");const manifestUrl = savedBaseUrl? linearManifestUrl(@@ -133,8 +160,16 @@ export function LinearPanel({}, [workspaceStore, credentialsSaved, dirty]);useEffect(() => {- if (feature.runtime_status === "running") void loadInstallations();- }, [feature.runtime_status, loadInstallations]);+ // Stopping message delivery does not revoke workspace authorizations.+ void loadInstallations();+ let wasOpen = client.status === "open";+ return client.onStatus((status) => {+ // A gateway restart can interrupt the initial inspection. Recover without+ // making the user refresh or begin a second OAuth authorization.+ if (status === "open" && !wasOpen) void loadInstallations(true);+ wasOpen = status === "open";+ });+ }, [client, feature.runtime_status, loadInstallations]);const disconnectWorkspace = async (installation: LinearInstallationSummary) => {setDisconnectingId(installation.organization_id);@@ -145,10 +180,16 @@ export function LinearPanel({operation: "disconnect",organization_id: installation.organization_id,});- const remaining = payload.installations ?? [];+ const remaining = payload.installations;+ if (!remaining || remaining.some(item => item.organization_id === installation.organization_id)) {+ throw new Error(tx("custom.resetInspectFailed", "Could not verify connected workspaces. App settings were kept."));+ }+ forgetWorkspaceMembers(installation.organization_id);workspaceStore.replace(remaining);setWorkspaceNotice(payload.message ?? null);setDisconnectConfirmId(null);+ setConnectRequestId(0);+ setConnectionGeneration(value => value + 1);if (remaining.length === 0) {onFeaturesUpdate(await disableNanobotFeature(client, "linear"));}@@ -218,18 +259,34 @@ export function LinearPanel({);useEffect(() => {- onBeforeCloseChange?.(dirty ? saveSettings : null);+ onBeforeCloseChange?.(dirty || saving ? async () => {+ if (secretSavePromiseRef.current) {+ try { await secretSavePromiseRef.current; } catch { return false; }+ }+ return saveSettings();+ } : null);return () => onBeforeCloseChange?.(null);- }, [dirty, saveSettings, onBeforeCloseChange]);+ }, [dirty, saving, saveSettings, onBeforeCloseChange]);- const removeSavedCredentials = () => {- setClearedSecrets(new Set(secretFields.map((field) => field.key)));- setFieldValues((current) => ({- ...current,- ...Object.fromEntries(secretFields.map((field) => [field.key, ""])),- }));- setNotice(null);- setSaved(false);+ const saveSecret = async (key: string, value: string) => {+ if (busy || dirty || connecting || savePromiseRef.current || secretSavePromiseRef.current) {+ throw new Error("Settings are busy");+ }+ const save = (async () => {+ setSaving(true);+ setSaved(false);+ try {+ // Explicit, single-field commit: blur, visibility toggles and cancellation never save.+ const payload = await configureChannel(client, feature.name, { [key]: value });+ if (!payload.saved) throw new Error("Secret was not saved");+ onFeaturesUpdate(payload.nanobot_features ?? await fetchNanobotFeatures(token));+ setSaved(true);+ } finally {+ setSaving(false);+ }+ })();+ secretSavePromiseRef.current = save;+ try { await save; } finally { secretSavePromiseRef.current = null; }};const formProps = {@@ -282,7 +339,12 @@ export function LinearPanel({</div><ChannelRuntimeError message={feature.runtime_error} /><CredentialForm {...formProps} fields={fields.filter((field) => field.key === PUBLIC_BASE_URL_KEY)} />- <CredentialForm {...formProps} fields={fields.filter((field) => field.key !== PUBLIC_BASE_URL_KEY)} />+ <div className="grid gap-y-4">+ {fields.filter(field => field.key !== PUBLIC_BASE_URL_KEY).map(field => field.secret ? (+ <LinearSecretField key={`${field.key}:${connectionGeneration}`} field={field} configured={configuredFields.has(field.key)}+ disabled={busy || dirty || connecting} onSave={saveSecret} />+ ) : <CredentialForm key={field.key} {...formProps} fields={[field]} />)}+ </div><div id={advancedPanelId} hidden={!advancedOpen}><CredentialForm {...formProps} fields={advancedFields} />{installations.some(installation => installation.scopes?.length) ? (@@ -295,6 +357,18 @@ export function LinearPanel({))}</div>) : null}+ <LinearResetConnection fields={editableFields}+ disabled={busy || dirty || connecting || loadingInstallations || disconnectingId !== null+ || !(hasSavedSecrets || feature.config_values?.["channels.linear.clientId"] || savedBaseUrl)}+ onBusyChange={setResetting} onWorkspacesChange={workspaceStore.replace}+ onWorkspaceRemoved={forgetWorkspaceMembers} onFeaturesUpdate={onFeaturesUpdate}+ onComplete={() => {+ setConnectRequestId(0);+ setConnectionGeneration(value => value + 1);+ setAdvancedOpen(false);+ setWorkspaceNotice(null);+ setWorkspaceError(null);+ }} /></div>{notice ? (<div className="flex flex-wrap items-center justify-between gap-2 rounded-control bg-muted/55 px-3 py-2.5 text-[12px] leading-5">@@ -306,14 +380,14 @@ export function LinearPanel({</div>) : null}</form>- {feature.runtime_status === "running" ? (+ {credentialsSaved || installations.length > 0 ? (<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}+ disabled={busy || dirty || connecting || loadingInstallations || disconnectingId !== null}className="h-8 gap-2 rounded-full text-[12px] text-muted-foreground"onClick={() => void loadInstallations(true)}><RefreshCw className="h-3.5 w-3.5" aria-hidden />@@ -335,8 +409,6 @@ export function LinearPanel({) : 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;const needsAuthorization = installation.authorization_status === "missing_scopes"|| installation.authorization_status === "refresh_required";@@ -356,47 +428,75 @@ export function LinearPanel({<article key={installation.organization_id} aria-label={name}className="overflow-hidden rounded-panel border border-border/70 bg-background"><header className="flex flex-wrap items-center justify-between gap-3 p-4">- <div className="flex min-w-0 flex-1 items-center gap-3">+ <div className="flex min-w-0 flex-1 items-center gap-2.5"><LinearAvatar name={name} url={logos[installation.organization_id]} workspace /><div className="min-w-0"><h5 className="truncate text-[14px] font-semibold text-foreground" title={name}>{name}</h5>{authorizationWarning ? <div className="mt-1">{authorizationWarning}</div> : null}</div></div>- <div className="ms-auto flex flex-wrap items-center gap-2">- {confirming ? (- <Button type="button" variant="ghost" size="sm"- disabled={loadingInstallations || disconnecting}- className="h-8 rounded-full text-[12px]"- onClick={() => setDisconnectConfirmId(null)}>- {t("settings.actions.cancel", { defaultValue: "Cancel" })}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button type="button" variant="ghost" size="icon"+ disabled={workspaceActionsDisabled}+ onPointerDown={event => { workspaceActionRef.current = event.currentTarget; }}+ onFocus={event => { workspaceActionRef.current = event.currentTarget; }}+ aria-label={tx("custom.workspaceActions", "Manage {{name}}", { name })}+ title={tx("custom.workspaceActions", "Manage {{name}}", { name })}+ className="h-8 w-8 shrink-0 rounded-full text-muted-foreground">+ <MoreHorizontal className="h-4 w-4" aria-hidden /></Button>- ) : null}- <Button type="button" variant={confirming ? "destructive" : "ghost"} size="sm"- disabled={loadingInstallations || disconnectingId !== null}- className={cn("h-8 gap-2 rounded-full text-[12px]", !confirming && "text-muted-foreground")}- 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>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" onCloseAutoFocus={event => {+ if (skipMenuRestoreFocus.current) event.preventDefault();+ skipMenuRestoreFocus.current = false;+ }}>+ <DropdownMenuItem disabled={workspaceActionsDisabled || !credentialsSaved}+ onSelect={() => {+ skipMenuRestoreFocus.current = true;+ setConnectRequestId(id => id + 1);+ }}>+ <RefreshCw className="h-4 w-4" aria-hidden />+ {tx("custom.reauthorize", "Reauthorize")}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem tone="destructive" disabled={workspaceActionsDisabled}+ onSelect={() => {+ skipMenuRestoreFocus.current = true;+ setWorkspaceError(null);+ setDisconnectConfirmId(installation.organization_id);+ }}>+ <Unplug className="h-4 w-4" aria-hidden />+ {tx("custom.disconnect", "Remove workspace")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu></header><LinearMemberAccess organizationId={installation.organization_id}- configScope={JSON.stringify([- feature.config_values?.["channels.linear.clientId"],- feature.config_values?.["channels.linear.allowFrom"],- ])}+ configScope={memberConfigScope}disabled={busy || dirty || connecting || disconnectingId !== null} /></article>);})}</div>- {workspaceError || inspectionError ? (+ {installations.length > 0 ? (+ <div className="flex items-center gap-1">+ <Button type="button" variant="ghost" size="sm"+ disabled={workspaceActionsDisabled || !credentialsSaved}+ className="h-9 gap-2 rounded-full text-[12px] text-muted-foreground"+ onClick={() => setConnectRequestId(id => id + 1)}>+ <Plus className="h-3.5 w-3.5" aria-hidden />+ {tx("custom.addWorkspace", "Connect workspace")}+ </Button>+ <SettingsHint description={tx("custom.addWorkspaceHelp", "Uses the current Linear app. To connect another workspace, the app must allow installation in other workspaces; private apps only work in their own workspace. Authorizing an existing workspace updates its connection without creating a duplicate.")}>+ <span className="flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground">+ <Info className="h-3.5 w-3.5" aria-hidden />+ <span className="sr-only">{tx("custom.addWorkspaceDetails", "About connecting workspaces")}</span>+ </span>+ </SettingsHint>+ </div>+ ) : null}+ {(workspaceError && !disconnectTarget) || inspectionError ? (<p role="alert" className="text-[12px] leading-5 text-destructive">{workspaceError || inspectionError}</p>) : null}{workspaceNotice ? (@@ -406,7 +506,9 @@ export function LinearPanel({) : null}</section>) : null}- <LinearConnectFlow token={token} feature={feature}+ <LinearConnectFlow key={connectionGeneration} token={token} feature={feature}+ connectRequestId={connectRequestId}+ connected={feature.runtime_status === "running" && installations.length > 0}idleLabel={tx("custom.connect", "Connect Linear")} onFeaturesUpdate={(payload) => {onFeaturesUpdate(payload);void workspaceStore.load(true);@@ -440,19 +542,55 @@ export function LinearPanel({</Button>)}</div>- {hasSavedSecrets ? (- <Button type="button" variant="ghost" size="sm" disabled={busy || connecting}- className="h-auto min-h-10 whitespace-normal rounded-full text-[12px] text-muted-foreground"- onClick={removeSavedCredentials}>- {tx("custom.removeCredentials", "Remove saved credentials")}- </Button>+ {installations.length === 0 || feature.runtime_status !== "running" || connecting ? (+ <fieldset disabled={busy || dirty || !credentialsSaved || loadingInstallations || disconnectingId !== null}+ className="min-w-0 sm:col-start-3">+ <legend className="sr-only">{tx("custom.authorizeTitle", "Authorize in Linear")}</legend>+ {connectButton}+ </fieldset>) : null}- <fieldset disabled={busy || dirty || !credentialsSaved} className="min-w-0 sm:col-start-3">- <legend className="sr-only">{tx("custom.authorizeTitle", "Authorize in Linear")}</legend>- {connectButton}- </fieldset></div>)} />+ <AlertDialog open={Boolean(disconnectTarget)} onOpenChange={open => {+ if (!open && !disconnectingId) {+ setDisconnectConfirmId(null);+ setWorkspaceError(null);+ }+ }}>+ <AlertDialogContent onEscapeKeyDown={event => {+ if (disconnectingId) event.preventDefault();+ }} onCloseAutoFocus={event => {+ event.preventDefault();+ if (workspaceActionRef.current?.isConnected) workspaceActionRef.current.focus();+ else document.getElementById(channelFieldInputId(PUBLIC_BASE_URL_KEY))?.focus();+ }}>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {tx("custom.disconnectTitle", "Remove {{name}}?", {+ name: disconnectTarget?.organization_name || disconnectTarget?.organization_id || "",+ })}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {tx("custom.disconnectDescription", "Revoke this workspace's authorization and clear its member access settings in nanobot. Linear issues, comments, and nanobot conversation history will be kept. Other workspaces are not affected. You can authorize this workspace again later.")}+ {installations.length === 1 ? <> {tx("custom.disconnectLast", "This is the last connected workspace, so the Linear channel will also be turned off.")}</> : null}+ </AlertDialogDescription>+ </AlertDialogHeader>+ {workspaceError ? <p role="alert" className="text-[12px] leading-5 text-destructive">{workspaceError}</p> : null}+ <AlertDialogFooter>+ <AlertDialogCancel disabled={disconnectingId !== null}>+ {t("settings.actions.cancel", { defaultValue: "Cancel" })}+ </AlertDialogCancel>+ <Button type="button" variant="destructive"+ disabled={workspaceActionsDisabled || !disconnectTarget}+ onClick={() => { if (disconnectTarget) void disconnectWorkspace(disconnectTarget); }}>+ {disconnectingId ? <Loader2 className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden /> : null}+ {disconnectingId+ ? tx("custom.disconnecting", "Removing…")+ : tx("custom.confirmDisconnect", "Remove workspace")}+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog><AlertDialog open={publicUrlPromptOpen} onOpenChange={setPublicUrlPromptOpen}><AlertDialogContent onCloseAutoFocus={(event) => {event.preventDefault();diff --git a/nanobot/channels/linear/webui/LinearResetConnection.tsx b/nanobot/channels/linear/webui/LinearResetConnection.tsxnew file mode 100644index 000000000..d1f4a2a59--- /dev/null+++ b/nanobot/channels/linear/webui/LinearResetConnection.tsx@@ -0,0 +1,137 @@+import { useRef, useState } from "react";+import { Loader2 } from "lucide-react";+import { useTranslation } from "react-i18next";++import { channelTranslator } from "@/channel-plugins/i18n";+import type { ChannelConfigField } from "@/components/settings/channels/catalog";+import { channelFieldInputId, defaultChannelFieldValues } from "@/components/settings/channels/CredentialForm";+import { Button } from "@/components/ui/button";+import {+ AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription,+ AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { configureChannel, disableNanobotFeature } from "@/lib/api";+import type { NanobotFeaturesPayload } from "@/lib/types";+import { useClient } from "@/providers/ClientProvider";++import { manageLinearWorkspace } from "./api";+import type { LinearInstallationSummary } from "./types";++/** Keep credentials until every workspace has been revoked and the channel has stopped. */+export function LinearResetConnection({+ fields, disabled, onBusyChange, onWorkspacesChange, onWorkspaceRemoved, onFeaturesUpdate, onComplete,+}: {+ fields: ChannelConfigField[];+ disabled: boolean;+ onBusyChange: (busy: boolean) => void;+ onWorkspacesChange: (workspaces: LinearInstallationSummary[]) => void;+ onWorkspaceRemoved: (organizationId: string) => void;+ onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;+ onComplete?: () => void;+}) {+ const { client } = useClient();+ const { t } = useTranslation();+ const tx = channelTranslator(t, "linear");+ const [open, setOpen] = useState(false);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const inFlight = useRef(false);+ const triggerRef = useRef<HTMLButtonElement>(null);++ const reset = async () => {+ if (inFlight.current) return;+ inFlight.current = true;+ setBusy(true);+ onBusyChange(true);+ setError(null);+ try {+ // Inspect even when the channel is stopped or the display cache is empty/stale.+ const current = await manageLinearWorkspace(client, { operation: "inspect" });+ if (!current.installations) throw new Error(tx("custom.resetInspectFailed", "Could not verify connected workspaces. App settings were kept."));+ onWorkspacesChange(current.installations);+ for (const workspace of current.installations) {+ const result = await manageLinearWorkspace(client, {+ operation: "disconnect", organization_id: workspace.organization_id,+ });+ if (!result.installations || result.installations.some(item => item.organization_id === workspace.organization_id)) {+ throw new Error(tx("custom.resetInspectFailed", "Could not verify connected workspaces. App settings were kept."));+ }+ onWorkspaceRemoved(workspace.organization_id);+ onWorkspacesChange(result.installations);+ }+ const remaining = await manageLinearWorkspace(client, { operation: "inspect" });+ if (!remaining.installations) throw new Error(tx("custom.resetInspectFailed", "Could not verify connected workspaces. App settings were kept."));+ onWorkspacesChange(remaining.installations);+ if (remaining.installations.length) {+ throw new Error(tx("custom.resetChanged", "Another workspace was connected. Review the connections and try again."));+ }+ const stopped = await disableNanobotFeature(client, "linear");+ onFeaturesUpdate(stopped);+ const linear = stopped.features.find(item => item.name === "linear");+ if (!linear || linear.enabled || linear.runtime_status === "running"+ || stopped.requires_restart || stopped.last_action?.ok === false) {+ throw new Error(tx("custom.resetStopFailed", "The Linear channel could not be stopped. App settings were kept."));+ }+ const defaults = defaultChannelFieldValues(fields);+ const result = await configureChannel(client, "linear", Object.fromEntries(+ fields.map(field => [field.key, field.secret ? null : defaults[field.key]]),+ ));+ if (!result.saved) throw new Error(tx("custom.resetSaveFailed", "Could not clear the app settings. Please retry."));+ if (result.nanobot_features) onFeaturesUpdate(result.nanobot_features);+ onComplete?.();+ setOpen(false);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ inFlight.current = false;+ setBusy(false);+ onBusyChange(false);+ }+ };++ return <AlertDialog open={open} onOpenChange={value => {+ if (inFlight.current) return;+ setOpen(value);+ setError(null);+ }}>+ <div className="mt-4 border-t border-border/60 pt-3">+ <Button ref={triggerRef} type="button" variant="ghost" size="sm" disabled={disabled || busy}+ onClick={() => { setError(null); setOpen(true); }}+ className="h-8 rounded-full text-[12px] text-muted-foreground hover:text-destructive">+ {tx("custom.resetConnection", "Reset Linear connection")}+ </Button>+ </div>+ <AlertDialogContent className="max-w-md gap-5" onEscapeKeyDown={event => { if (inFlight.current) event.preventDefault(); }}+ onCloseAutoFocus={event => {+ event.preventDefault();+ if (triggerRef.current && !triggerRef.current.disabled) triggerRef.current.focus();+ else document.getElementById(channelFieldInputId("channels.linear.publicBaseUrl"))?.focus();+ }}>+ <AlertDialogHeader className="space-y-3 text-left">+ <AlertDialogTitle>{tx("custom.resetTitle", "Reset Linear?")}</AlertDialogTitle>+ <AlertDialogDescription asChild>+ <div className="space-y-4 text-sm leading-6">+ <p>{tx("custom.resetDescription", "Disconnect all workspaces linked through this app and stop the channel.")}</p>+ <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-3 rounded-xl bg-muted/40 p-4 text-[13px] leading-5">+ <dt className="font-medium text-foreground">{tx("custom.resetClears", "Clears")}</dt>+ <dd>{tx("custom.resetClearsDetail", "Member access settings and this instance’s app configuration, including saved credentials.")}</dd>+ <dt className="font-medium text-foreground">{tx("custom.resetKeeps", "Keeps")}</dt>+ <dd>{tx("custom.resetKeepsDetail", "Linear app, issues, comments, chat history and pairing approvals.")}</dd>+ </dl>+ </div>+ </AlertDialogDescription>+ </AlertDialogHeader>+ {error ? <div role="alert" className="space-y-1 text-[12px] leading-5 text-destructive">+ <p>{tx("custom.resetIncomplete", "Reset is incomplete. Workspaces already removed stay removed; retry to finish the remaining steps.")}</p>+ <p>{error}</p>+ </div> : null}+ <AlertDialogFooter>+ <AlertDialogCancel className="h-9 min-w-20 rounded-full text-[13px]" disabled={busy}>{t("settings.actions.cancel", { defaultValue: "Cancel" })}</AlertDialogCancel>+ <Button type="button" variant="destructive" size="sm" className="min-w-20 rounded-full px-4 text-[13px]" disabled={busy} onClick={() => void reset()}>+ {busy ? <Loader2 className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden /> : null}+ {busy ? tx("custom.resetting", "Resetting…") : tx("custom.resetConfirm", "Reset")}+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>;+}diff --git a/nanobot/channels/linear/webui/LinearSecretField.tsx b/nanobot/channels/linear/webui/LinearSecretField.tsxnew file mode 100644index 000000000..2d5b0fd75--- /dev/null+++ b/nanobot/channels/linear/webui/LinearSecretField.tsx@@ -0,0 +1,130 @@+import { useEffect, useRef, useState } from "react";+import { Eye, EyeOff } from "lucide-react";+import { useTranslation } from "react-i18next";++import { channelTranslator } from "@/channel-plugins/i18n";+import type { ChannelConfigField } from "@/components/settings/channels/catalog";+import { channelFieldInputId } from "@/components/settings/channels/CredentialForm";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";++/** A saved secret is a status, never a placeholder or a value sent back to the browser. */+export function LinearSecretField({ field, configured, disabled, onSave }: {+ field: ChannelConfigField;+ configured: boolean;+ disabled: boolean;+ onSave: (key: string, value: string) => Promise<void>;+}) {+ const { t } = useTranslation();+ const tx = channelTranslator(t, "linear");+ const [editing, setEditing] = useState(false);+ const [value, setValue] = useState("");+ const [visible, setVisible] = useState(false);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState(false);+ const inFlight = useRef(false);+ const inputRef = useRef<HTMLInputElement>(null);+ const replaceRef = useRef<HTMLButtonElement>(null);+ const restoreFocus = useRef(false);+ const inputId = channelFieldInputId(field.key);+ const displaySaved = configured && !editing;+ const locked = disabled || saving;++ useEffect(() => {+ if (editing && !disabled && !saving) inputRef.current?.focus();+ else if (!editing && restoreFocus.current && !disabled && !saving) {+ replaceRef.current?.focus();+ restoreFocus.current = false;+ }+ }, [editing, disabled, saving, configured]);++ const cancel = () => {+ if (inFlight.current) return;+ setValue("");+ setVisible(false);+ setError(false);+ restoreFocus.current = configured;+ setEditing(false);+ };++ const save = async () => {+ if (locked || inFlight.current || !value.trim()) return;+ inFlight.current = true;+ setSaving(true);+ setError(false);+ try {+ await onSave(field.key, value);+ setValue("");+ setVisible(false);+ restoreFocus.current = true;+ setEditing(false);+ } catch {+ // Keep the draft and existing configured state; never echo credentials from an error.+ setError(true);+ } finally {+ inFlight.current = false;+ setSaving(false);+ }+ };++ return <div className="grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)] items-start gap-x-4">+ <label id={`${inputId}-label`} htmlFor={displaySaved ? undefined : inputId}+ className="flex min-h-10 min-w-0 items-center self-start text-[11px] font-medium text-foreground/85 sm:min-h-9">+ {field.label}+ </label>+ <div className="min-w-0" role="group" aria-labelledby={`${inputId}-label`} aria-busy={saving}>+ {displaySaved ? (+ <div className="flex min-h-10 items-center justify-between gap-2 rounded-full border border-border/40 bg-background ps-3 pe-1 sm:min-h-9">+ <div className="flex min-w-0 flex-wrap items-center gap-x-2.5">+ <span aria-hidden className="text-[13px] tracking-[0.12em] text-foreground/70">••••••••</span>+ <span role="status" className="text-[11px] text-muted-foreground">+ {tx("custom.secretSaved", "Saved")}+ </span>+ </div>+ <Button ref={replaceRef} type="button" variant="ghost" size="sm" disabled={disabled}+ aria-label={tx("custom.replaceSecretLabel", "Replace {{name}}", { name: field.label })}+ className="h-8 shrink-0 rounded-full px-2.5 text-[12px] text-muted-foreground hover:text-foreground"+ onClick={() => { setVisible(false); setError(false); setEditing(true); }}>+ {tx("custom.replaceSecret", "Replace")}+ </Button>+ </div>+ ) : <>+ <div className="relative">+ <Input ref={inputRef} id={inputId} type={visible ? "text" : "password"}+ value={value} autoComplete="off" spellCheck={false} disabled={locked}+ placeholder={tx("custom.enterSecret", "Enter secret")}+ aria-invalid={error} aria-describedby={error ? `${inputId}-error` : undefined}+ onChange={event => { setValue(event.target.value); setError(false); }}+ onKeyDown={event => {+ if (event.key === "Enter") { event.preventDefault(); event.stopPropagation(); void save(); }+ if (event.key === "Escape" && (editing || value)) {+ event.preventDefault(); event.stopPropagation(); cancel();+ }+ }}+ className="h-10 rounded-full border-border/40 bg-background pe-10 text-base sm:h-9 sm:text-[13px]" />+ {value ? <Button type="button" variant="ghost" size="icon" disabled={locked}+ aria-label={visible ? t("settings.channels.hideSecret", { defaultValue: "Hide secret" })+ : t("settings.channels.showSecret", { defaultValue: "Show secret" })}+ onClick={() => setVisible(current => !current)}+ className="absolute end-1 top-1/2 h-8 w-8 -translate-y-1/2 rounded-full text-muted-foreground">+ {visible ? <EyeOff className="h-3.5 w-3.5" aria-hidden /> : <Eye className="h-3.5 w-3.5" aria-hidden />}+ </Button> : null}+ </div>+ {editing || value ? <div className="mt-1.5 flex min-h-8 flex-wrap items-center justify-end gap-1.5">+ <Button type="button" variant="ghost" size="sm" disabled={locked} onClick={cancel}+ className="h-8 rounded-full px-3 text-[12px] text-muted-foreground">+ {t("settings.actions.cancel", { defaultValue: "Cancel" })}+ </Button>+ <Button type="button" variant="secondary" size="sm" disabled={locked || !value.trim()}+ onClick={() => void save()} className="h-8 min-w-16 rounded-full px-3 text-[12px]">+ {saving ? t("settings.actions.saving", { defaultValue: "Saving" })+ : t("settings.actions.save", { defaultValue: "Save" })}+ </Button>+ </div> : null}+ {error ? <p id={`${inputId}-error`} role="alert" className="mt-1.5 text-[12px] leading-5 text-destructive">+ {tx("custom.secretSaveFailed", "Could not confirm the save. Try again or cancel.")}+ </p> : null}+ </>}+ </div>+ </div>;+}diff --git a/nanobot/channels/linear/webui/locales/en.json b/nanobot/channels/linear/webui/locales/en.jsonindex 3cbceb66c..695bbb112 100644--- a/nanobot/channels/linear/webui/locales/en.json+++ b/nanobot/channels/linear/webui/locales/en.json@@ -61,19 +61,21 @@}},"custom": {- "qrAlt": "Linear authorization QR code",+ "secretSaved": "Saved",+ "replaceSecret": "Replace",+ "replaceSecretLabel": "Replace {{name}}",+ "enterSecret": "Enter secret",+ "secretSaveFailed": "Could not confirm the save. Try again or cancel.","authorizeTitle": "Authorize in Linear",- "authorizeDescription": "Open Linear in this browser or scan the QR code. nanobot enables the channel after authorization.",+ "authorizeDescription": "Continue in Linear to choose a workspace and authorize nanobot. Return here when you're done.","waiting": "Waiting for Linear authorization...","connected": "Linear is connected.","stopped": "Authorization stopped.","connecting": "Connecting...",- "reconnect": "Connect another workspace","connect": "Connect Linear","openLinear": "Continue in Linear","createApp": "Create Linear app","savePublicUrl": "Enter a public HTTPS URL to create a Linear app.",- "removeCredentials": "Remove saved credentials","retrySave": "Retry","channelRunning": "Channel running","accessAll": "Every member of an authorized workspace can run this agent.",@@ -87,26 +89,49 @@"refreshRequired": "Authorization refresh required","missingScopes": "Reconnect to grant: {{scopes}}","authorized": "Authorized",- "confirmDisconnect": "Disconnect workspace",- "disconnect": "Disconnect"+ "confirmDisconnect": "Remove workspace",+ "disconnect": "Remove workspace",+ "workspaceActions": "Manage {{name}}",+ "reauthorize": "Reauthorize",+ "disconnectTitle": "Remove {{name}}?",+ "disconnectDescription": "Revoke this workspace's authorization and clear its member access settings in nanobot. Linear issues, comments, and nanobot conversation history will be kept. Other workspaces are not affected. You can authorize this workspace again later.",+ "disconnectLast": "This is the last connected workspace, so the Linear channel will also be turned off.",+ "disconnecting": "Removing…",+ "addWorkspace": "Connect workspace",+ "addWorkspaceDetails": "About connecting workspaces",+ "addWorkspaceHelp": "Uses the current Linear app. To connect another workspace, the app must allow installation in other workspaces; private apps only work in their own workspace. Authorizing an existing workspace updates its connection without creating a duplicate.",+ "resetConnection": "Reset Linear connection",+ "resetTitle": "Reset Linear?",+ "resetDescription": "Disconnect all workspaces linked through this app and stop the channel.",+ "resetClears": "Clears",+ "resetClearsDetail": "Member access settings and this instance’s app configuration, including saved credentials.",+ "resetKeeps": "Keeps",+ "resetKeepsDetail": "Linear app, issues, comments, chat history and pairing approvals.",+ "resetConfirm": "Reset",+ "resetting": "Resetting…",+ "resetIncomplete": "Reset is incomplete. Workspaces already removed stay removed; retry to finish the remaining steps.",+ "resetInspectFailed": "Could not verify connected workspaces. App settings were kept.",+ "resetChanged": "Another workspace was connected. Review the connections and try again.",+ "resetStopFailed": "The Linear channel could not be stopped. App settings were kept.",+ "resetSaveFailed": "Could not clear the app settings. Please retry."},"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.",+ "help": "Enable members to use nanobot without a pairing code. Linear's existing authorization still applies. 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": "Saving…","saved": "Saved","retry": "Refresh members to check the current state and try again.",- "empty": "No matching active members in the teams this app can access.",+ "empty": "No matching active members.","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.","intro": "Choose who can use nanobot in Linear. No pairing codes needed.","details": "About member access","summary": "{{allowed}} enabled",- "loading": "Finding your teammates…",+ "loading": "Finding members…","refreshing": "Checking for updates…"}}diff --git a/nanobot/channels/linear/webui/locales/es.json b/nanobot/channels/linear/webui/locales/es.jsonindex 01b51b50f..0c72f9d10 100644--- a/nanobot/channels/linear/webui/locales/es.json+++ b/nanobot/channels/linear/webui/locales/es.json@@ -61,19 +61,21 @@}},"custom": {- "qrAlt": "Código QR de autorización de Linear",+ "secretSaved": "Guardado",+ "replaceSecret": "Cambiar",+ "replaceSecretLabel": "Cambiar {{name}}",+ "enterSecret": "Introduce el secreto",+ "secretSaveFailed": "No se pudo confirmar el guardado. Reintenta o cancela.","authorizeTitle": "Autorizar en Linear",- "authorizeDescription": "Abre Linear en este navegador o escanea el código QR. nanobot habilitará el canal después de la autorización.",+ "authorizeDescription": "Continúa en Linear para elegir un espacio de trabajo y autorizar a nanobot. Vuelve aquí cuando termines.","waiting": "Esperando la autorización de Linear...","connected": "Linear está conectado.","stopped": "La autorización se detuvo.","connecting": "Conectando...",- "reconnect": "Conectar otro espacio de trabajo","connect": "Conectar Linear","openLinear": "Continuar en Linear","createApp": "Crear aplicación de Linear","savePublicUrl": "Introduce una URL HTTPS pública para crear una aplicación de Linear.",- "removeCredentials": "Eliminar credenciales guardadas","retrySave": "Reintentar","channelRunning": "Canal en ejecución","accessAll": "Todos los miembros de un espacio autorizado pueden ejecutar este agente.",@@ -87,26 +89,49 @@"refreshRequired": "Es necesario renovar la autorización","missingScopes": "Vuelve a conectar para conceder: {{scopes}}","authorized": "Autorizado",- "confirmDisconnect": "Desconectar espacio",- "disconnect": "Desconectar"+ "confirmDisconnect": "Eliminar conexión",+ "disconnect": "Eliminar conexión",+ "workspaceActions": "Administrar {{name}}",+ "reauthorize": "Volver a autorizar",+ "disconnectTitle": "¿Eliminar {{name}}?",+ "disconnectDescription": "Revoca la autorización y borra los ajustes de acceso de este espacio en nanobot. Se conservan las incidencias, los comentarios y el historial de nanobot. No afecta a otros espacios. Puedes volver a autorizarlo después.",+ "disconnectLast": "Es el último espacio de trabajo conectado, por lo que también se desactivará el canal de Linear.",+ "disconnecting": "Eliminando…",+ "addWorkspace": "Conectar espacio de trabajo",+ "addWorkspaceDetails": "Acerca de conectar espacios",+ "addWorkspaceHelp": "Usa la aplicación Linear actual. Para conectar otros espacios, debe permitir su instalación en ellos; las aplicaciones privadas solo funcionan en su propio espacio. Volver a autorizar un espacio actualiza su conexión sin duplicarlo.",+ "resetConnection": "Restablecer conexión con Linear",+ "resetTitle": "¿Restablecer Linear?",+ "resetDescription": "Desconecta todos los espacios vinculados a esta aplicación y detiene el canal.",+ "resetClears": "Elimina",+ "resetClearsDetail": "Ajustes de acceso de miembros y configuración de la aplicación en esta instancia, incluidas las credenciales guardadas.",+ "resetKeeps": "Conserva",+ "resetKeepsDetail": "La aplicación de Linear, las incidencias, los comentarios, el historial y los emparejamientos aprobados.",+ "resetConfirm": "Restablecer",+ "resetting": "Restableciendo…",+ "resetIncomplete": "Restablecimiento incompleto. Los espacios ya eliminados no se restauran; reintenta para terminar.",+ "resetInspectFailed": "No se pudieron verificar los espacios conectados. Se conservó la configuración.",+ "resetChanged": "Se conectó otro espacio. Revisa las conexiones y reintenta.",+ "resetStopFailed": "No se pudo detener el canal de Linear. Se conservó la configuración.",+ "resetSaveFailed": "No se pudo borrar la configuración. Reintenta."},"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.",+ "help": "Permite que los miembros usen nanobot sin código de vinculación. Se mantiene el alcance autorizado en Linear y no se concede acceso al panel de administración de nanobot. Desactivar el acceso bloquea nuevas solicitudes, no las 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": "Guardando…","saved": "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.",+ "empty": "No hay miembros activos que coincidan.","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.","intro": "Elige quién puede usar nanobot en Linear, sin códigos de vinculación.","details": "Acerca del acceso de miembros","summary": "{{allowed}} habilitados",- "loading": "Buscando a tus compañeros…",+ "loading": "Buscando miembros…","refreshing": "Buscando actualizaciones…"}}diff --git a/nanobot/channels/linear/webui/locales/fr.json b/nanobot/channels/linear/webui/locales/fr.jsonindex 1fe537d72..b32c1044a 100644--- a/nanobot/channels/linear/webui/locales/fr.json+++ b/nanobot/channels/linear/webui/locales/fr.json@@ -61,19 +61,21 @@}},"custom": {- "qrAlt": "Code QR d’autorisation Linear",+ "secretSaved": "Enregistré",+ "replaceSecret": "Remplacer",+ "replaceSecretLabel": "Remplacer {{name}}",+ "enterSecret": "Saisir le secret",+ "secretSaveFailed": "Impossible de confirmer l’enregistrement. Réessayez ou annulez.","authorizeTitle": "Autoriser dans Linear",- "authorizeDescription": "Ouvrez Linear dans ce navigateur ou scannez le code QR. nanobot activera le canal après l’autorisation.",+ "authorizeDescription": "Continuez dans Linear pour choisir un espace de travail et autoriser nanobot. Revenez ici une fois terminé.","waiting": "En attente de l’autorisation Linear...","connected": "Linear est connecté.","stopped": "L’autorisation a été interrompue.","connecting": "Connexion...",- "reconnect": "Connecter un autre espace de travail","connect": "Connecter Linear","openLinear": "Continuer dans Linear","createApp": "Créer une application Linear","savePublicUrl": "Saisissez une URL HTTPS publique pour créer une application Linear.",- "removeCredentials": "Supprimer les identifiants enregistrés","retrySave": "Réessayer","channelRunning": "Canal en cours d’exécution","accessAll": "Tous les membres d’un espace autorisé peuvent exécuter cet agent.",@@ -87,26 +89,49 @@"refreshRequired": "Actualisation de l’autorisation requise","missingScopes": "Reconnectez-vous pour accorder : {{scopes}}","authorized": "Autorisé",- "confirmDisconnect": "Déconnecter l’espace",- "disconnect": "Déconnecter"+ "confirmDisconnect": "Retirer l’espace",+ "disconnect": "Retirer l’espace",+ "workspaceActions": "Gérer {{name}}",+ "reauthorize": "Réautoriser",+ "disconnectTitle": "Retirer {{name}} ?",+ "disconnectDescription": "Révoque l’autorisation et efface les réglages d’accès de cet espace dans nanobot. Les tickets, commentaires et conversations nanobot sont conservés. Les autres espaces ne sont pas affectés. Vous pourrez le réautoriser plus tard.",+ "disconnectLast": "C’est le dernier espace de travail connecté : le canal Linear sera également désactivé.",+ "disconnecting": "Suppression…",+ "addWorkspace": "Connecter un espace",+ "addWorkspaceDetails": "À propos de la connexion",+ "addWorkspaceHelp": "Utilise l’application Linear actuelle. Pour connecter d’autres espaces, elle doit y autoriser son installation ; une application privée ne fonctionne que dans son propre espace. Réautoriser un espace met à jour sa connexion sans doublon.",+ "resetConnection": "Réinitialiser la connexion Linear",+ "resetTitle": "Réinitialiser Linear ?",+ "resetDescription": "Déconnecte tous les espaces liés à cette application et arrête le canal.",+ "resetClears": "Efface",+ "resetClearsDetail": "Les accès des membres et la configuration de l’application sur cette instance, identifiants enregistrés compris.",+ "resetKeeps": "Conserve",+ "resetKeepsDetail": "L’application Linear, les tickets, les commentaires, l’historique et les appairages approuvés.",+ "resetConfirm": "Réinitialiser",+ "resetting": "Réinitialisation…",+ "resetIncomplete": "Réinitialisation incomplète. Les espaces déjà retirés ne sont pas restaurés ; réessayez pour terminer.",+ "resetInspectFailed": "Impossible de vérifier les espaces connectés. La configuration a été conservée.",+ "resetChanged": "Un autre espace a été connecté. Vérifiez les connexions et réessayez.",+ "resetStopFailed": "Impossible d’arrêter le canal Linear. La configuration a été conservée.",+ "resetSaveFailed": "Impossible d’effacer la configuration. Réessayez."},"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.",+ "help": "Autorisez les membres à utiliser nanobot sans code d’association. Les autorisations existantes de Linear restent applicables, sans donner accès à l’interface d’administration de nanobot. Désactiver l’accès 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": "Enregistrement…","saved": "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.",+ "empty": "Aucun membre actif correspondant.","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.","intro": "Choisissez qui peut utiliser nanobot dans Linear, sans code d’association.","details": "À propos de l’accès des membres","summary": "{{allowed}} autorisés",- "loading": "Recherche des membres de votre équipe…",+ "loading": "Recherche des membres…","refreshing": "Recherche de mises à jour…"}}diff --git a/nanobot/channels/linear/webui/locales/id.json b/nanobot/channels/linear/webui/locales/id.jsonindex f4d52e286..8eca96b01 100644--- a/nanobot/channels/linear/webui/locales/id.json+++ b/nanobot/channels/linear/webui/locales/id.json@@ -61,19 +61,21 @@}},"custom": {- "qrAlt": "Kode QR otorisasi Linear",+ "secretSaved": "Tersimpan",+ "replaceSecret": "Ganti",+ "replaceSecretLabel": "Ganti {{name}}",+ "enterSecret": "Masukkan rahasia",+ "secretSaveFailed": "Penyimpanan belum dapat dikonfirmasi. Coba lagi atau batalkan.","authorizeTitle": "Otorisasi di Linear",- "authorizeDescription": "Buka Linear di browser ini atau pindai kode QR. nanobot akan mengaktifkan channel setelah otorisasi.",+ "authorizeDescription": "Lanjutkan di Linear untuk memilih workspace dan mengizinkan nanobot. Kembali ke sini setelah selesai.","waiting": "Menunggu otorisasi Linear...","connected": "Linear telah terhubung.","stopped": "Otorisasi dihentikan.","connecting": "Menghubungkan...",- "reconnect": "Hubungkan workspace lain","connect": "Hubungkan Linear","openLinear": "Lanjutkan di Linear","createApp": "Buat aplikasi Linear","savePublicUrl": "Masukkan URL HTTPS publik untuk membuat aplikasi Linear.",- "removeCredentials": "Hapus kredensial tersimpan","retrySave": "Coba lagi","channelRunning": "Channel berjalan","accessAll": "Semua anggota workspace yang diotorisasi dapat menjalankan agen ini.",@@ -87,26 +89,49 @@"refreshRequired": "Penyegaran otorisasi diperlukan","missingScopes": "Hubungkan ulang untuk memberikan: {{scopes}}","authorized": "Diotorisasi",- "confirmDisconnect": "Putuskan workspace",- "disconnect": "Putuskan"+ "confirmDisconnect": "Hapus ruang kerja",+ "disconnect": "Hapus ruang kerja",+ "workspaceActions": "Kelola {{name}}",+ "reauthorize": "Otorisasi ulang",+ "disconnectTitle": "Hapus {{name}}?",+ "disconnectDescription": "Cabut otorisasi ruang kerja ini dan hapus pengaturan akses anggotanya di nanobot. Issue, komentar, dan riwayat nanobot tetap disimpan. Ruang kerja lain tidak terpengaruh. Anda dapat mengotorisasi ulang nanti.",+ "disconnectLast": "Ini adalah ruang kerja terakhir yang terhubung, jadi kanal Linear juga akan dinonaktifkan.",+ "disconnecting": "Menghapus…",+ "addWorkspace": "Hubungkan ruang kerja",+ "addWorkspaceDetails": "Tentang koneksi ruang kerja",+ "addWorkspaceHelp": "Menggunakan aplikasi Linear saat ini. Aplikasi harus mengizinkan pemasangan di ruang kerja lain; aplikasi privat hanya untuk ruang kerjanya sendiri. Otorisasi ulang memperbarui koneksi tanpa duplikat.",+ "resetConnection": "Reset koneksi Linear",+ "resetTitle": "Reset Linear?",+ "resetDescription": "Putuskan semua workspace yang terhubung melalui aplikasi ini dan hentikan channel.",+ "resetClears": "Dihapus",+ "resetClearsDetail": "Pengaturan akses anggota dan konfigurasi aplikasi di instans ini, termasuk kredensial tersimpan.",+ "resetKeeps": "Disimpan",+ "resetKeepsDetail": "Aplikasi Linear, issue, komentar, riwayat percakapan, dan persetujuan pairing.",+ "resetConfirm": "Reset",+ "resetting": "Mereset…",+ "resetIncomplete": "Reset belum selesai. Ruang kerja yang sudah dihapus tidak dipulihkan; coba lagi untuk menyelesaikan.",+ "resetInspectFailed": "Tidak dapat memverifikasi ruang kerja. Konfigurasi aplikasi tetap disimpan.",+ "resetChanged": "Ruang kerja lain telah terhubung. Periksa koneksi lalu coba lagi.",+ "resetStopFailed": "Kanal Linear tidak dapat dihentikan. Konfigurasi aplikasi tetap disimpan.",+ "resetSaveFailed": "Konfigurasi aplikasi tidak dapat dihapus. Coba lagi."},"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.",+ "help": "Izinkan anggota menggunakan nanobot tanpa kode pemasangan. Cakupan izin Linear tetap berlaku dan tidak memberikan akses ke antarmuka admin nanobot. Menonaktifkan akses 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": "Menyimpan…","saved": "Tersimpan","retry": "Segarkan anggota untuk memeriksa status terkini, lalu coba lagi.",- "empty": "Tidak ada anggota aktif yang cocok di tim yang dapat diakses aplikasi ini.",+ "empty": "Tidak ada anggota aktif yang cocok.","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.","intro": "Pilih siapa yang boleh memakai nanobot di Linear, tanpa kode pairing.","details": "Tentang akses anggota","summary": "{{allowed}} diizinkan",- "loading": "Mencari anggota tim…",+ "loading": "Mencari anggota…","refreshing": "Memeriksa pembaruan…"}}diff --git a/nanobot/channels/linear/webui/locales/ja.json b/nanobot/channels/linear/webui/locales/ja.jsonindex 308357e88..60abf96b3 100644--- a/nanobot/channels/linear/webui/locales/ja.json+++ b/nanobot/channels/linear/webui/locales/ja.json@@ -61,19 +61,21 @@}},"custom": {- "qrAlt": "Linear 認証 QR コード",+ "secretSaved": "保存済み",+ "replaceSecret": "変更",+ "replaceSecretLabel": "{{name}}を変更",+ "enterSecret": "シークレットを入力",+ "secretSaveFailed": "保存を確認できませんでした。再試行するかキャンセルしてください。","authorizeTitle": "Linear で認証",- "authorizeDescription": "このブラウザで Linear を開くか、QR コードを読み取ってください。認証後、nanobot がチャンネルを有効にします。",+ "authorizeDescription": "Linear でワークスペースを選び、nanobot を認証してください。完了したらここに戻ってください。","waiting": "Linear の認証を待っています...","connected": "Linear に接続しました。","stopped": "認証を中止しました。","connecting": "接続しています...",- "reconnect": "別のワークスペースを接続","connect": "Linear に接続","openLinear": "Linear で続行","createApp": "Linear アプリを作成","savePublicUrl": "公開 HTTPS URL を入力してから Linear アプリを作成してください。",- "removeCredentials": "保存済みの認証情報を削除","retrySave": "再試行","channelRunning": "チャンネル実行中","accessAll": "認証済みワークスペースの全メンバーがこのエージェントを実行できます。",@@ -87,26 +89,49 @@"refreshRequired": "認証の更新が必要です","missingScopes": "再接続して権限を付与: {{scopes}}","authorized": "認証済み",- "confirmDisconnect": "ワークスペースを切断",- "disconnect": "切断"+ "confirmDisconnect": "ワークスペースを削除",+ "disconnect": "ワークスペースを削除",+ "workspaceActions": "{{name}} を管理",+ "reauthorize": "再認可",+ "disconnectTitle": "{{name}} を削除しますか?",+ "disconnectDescription": "このワークスペースの認可と nanobot のメンバーアクセス設定を削除します。Issue、コメント、nanobot の会話履歴は保持されます。他のワークスペースには影響しません。後で再認可できます。",+ "disconnectLast": "接続済みの最後のワークスペースのため、Linear チャンネルも無効になります。",+ "disconnecting": "削除中…",+ "addWorkspace": "ワークスペースを接続",+ "addWorkspaceDetails": "ワークスペース接続について",+ "addWorkspaceHelp": "現在の Linear アプリを使います。別のワークスペースに接続するには、他のワークスペースへのインストールを許可する必要があります。非公開アプリは所属先のみ接続できます。既存のワークスペースを選ぶと、重複せず認可が更新されます。",+ "resetConnection": "Linear 接続をリセット",+ "resetTitle": "Linear をリセット?",+ "resetDescription": "このアプリの全ワークスペースを切断し、チャンネルを停止します。",+ "resetClears": "削除",+ "resetClearsDetail": "メンバーのアクセス設定と、このインスタンスのアプリ設定(保存済み認証情報を含む)。",+ "resetKeeps": "保持",+ "resetKeepsDetail": "Linear アプリ、Issue、コメント、会話履歴、承認済みペアリング。",+ "resetConfirm": "リセット",+ "resetting": "リセット中…",+ "resetIncomplete": "リセットは未完了です。削除済みの接続は復元されません。再試行して残りの手順を完了してください。",+ "resetInspectFailed": "接続済みワークスペースを確認できません。アプリ設定は保持されました。",+ "resetChanged": "別のワークスペースが接続されました。確認して再試行してください。",+ "resetStopFailed": "Linear チャネルを停止できません。アプリ設定は保持されました。",+ "resetSaveFailed": "アプリ設定を消去できません。再試行してください。"},"members": {"title": "メンバーのアクセス",- "help": "ペアリングコードなしで Linear の nanobot を使えるメンバーを選びます。管理画面へのアクセスは付与されません。オフにすると新しいリクエストを拒否しますが、実行中のタスクは停止しません。",+ "help": "メンバーはペアリングコードなしで nanobot を利用できます。Linear の既存の認可範囲は変わらず、nanobot の管理画面へのアクセス権は付与されません。無効にすると新しいリクエストは拒否されますが、実行中のタスクは中断されません。","allowAll": "詳細設定では新規メンバーを含む全員(*)が許可されています。個別のオフ設定が優先されます。新規メンバーに承認を必須とするには * を削除してください。","search": "メンバーを検索","refresh": "メンバーを更新","working": "保存中…","saved": "保存済み","retry": "メンバーを更新して現在の状態を確認し、再試行してください。",- "empty": "アプリがアクセスできるチームに、条件に一致する有効なメンバーはいません。",+ "empty": "一致する有効なメンバーがいません。","allow": "{{name}} に nanobot の利用を許可","saveUnconfirmed": "保存を確認できませんでした。メンバーを更新してから再試行してください。","guide": "「メンバーのアクセス」でコードなしで同僚を承認できます。既存の承認はオフにしない限り有効です。Issue の検索・編集には Linear MCP を接続してください。","intro": "Linear で nanobot を使えるメンバーを選びます。ペアリングコードは不要です。","details": "メンバーのアクセスについて","summary": "{{allowed}} 人が利用可能",- "loading": "チームメンバーを取得中…",+ "loading": "メンバーを検索中…","refreshing": "更新を確認中…"}}diff --git a/nanobot/channels/linear/webui/locales/ko.json b/nanobot/channels/linear/webui/locales/ko.jsonindex 5f7887791..5fe17b62c 100644--- a/nanobot/channels/linear/webui/locales/ko.json+++ b/nanobot/channels/linear/webui/locales/ko.json@@ -61,19 +61,21 @@}},"custom": {- "qrAlt": "Linear 승인 QR 코드",+ "secretSaved": "저장됨",+ "replaceSecret": "변경",+ "replaceSecretLabel": "{{name}} 변경",+ "enterSecret": "시크릿 입력",+ "secretSaveFailed": "저장 결과를 확인할 수 없습니다. 다시 시도하거나 취소하세요.","authorizeTitle": "Linear에서 승인",- "authorizeDescription": "이 브라우저에서 Linear를 열거나 QR 코드를 스캔하세요. 승인 후 nanobot이 채널을 활성화합니다.",+ "authorizeDescription": "Linear에서 워크스페이스를 선택하고 nanobot을 승인하세요. 완료한 후 여기로 돌아오세요.","waiting": "Linear 승인을 기다리는 중...","connected": "Linear가 연결되었습니다.","stopped": "승인이 중지되었습니다.","connecting": "연결 중...",- "reconnect": "다른 워크스페이스 연결","connect": "Linear 연결","openLinear": "Linear에서 계속","createApp": "Linear 앱 만들기","savePublicUrl": "공개 HTTPS URL을 입력한 후 Linear 앱을 만드세요.",- "removeCredentials": "저장된 인증 정보 삭제","retrySave": "다시 시도","channelRunning": "채널 실행 중","accessAll": "승인된 워크스페이스의 모든 멤버가 이 에이전트를 실행할 수 있습니다.",@@ -87,26 +89,49 @@"refreshRequired": "승인 갱신 필요","missingScopes": "다시 연결하여 권한 부여: {{scopes}}","authorized": "승인됨",- "confirmDisconnect": "워크스페이스 연결 해제",- "disconnect": "연결 해제"+ "confirmDisconnect": "워크스페이스 제거",+ "disconnect": "워크스페이스 제거",+ "workspaceActions": "{{name}} 관리",+ "reauthorize": "다시 승인",+ "disconnectTitle": "{{name}}을(를) 제거할까요?",+ "disconnectDescription": "이 워크스페이스의 권한을 철회하고 nanobot의 멤버 접근 설정을 지웁니다. 이슈, 댓글 및 nanobot 대화 기록은 유지됩니다. 다른 워크스페이스에는 영향이 없으며 나중에 다시 승인할 수 있습니다.",+ "disconnectLast": "마지막으로 연결된 워크스페이스이므로 Linear 채널도 꺼집니다.",+ "disconnecting": "제거 중…",+ "addWorkspace": "워크스페이스 연결",+ "addWorkspaceDetails": "워크스페이스 연결 안내",+ "addWorkspaceHelp": "현재 Linear 앱을 사용합니다. 다른 워크스페이스를 연결하려면 앱이 다른 워크스페이스에 설치될 수 있어야 합니다. 비공개 앱은 소속 워크스페이스에서만 사용할 수 있습니다. 기존 워크스페이스를 선택하면 중복 없이 권한을 갱신합니다.",+ "resetConnection": "Linear 연결 초기화",+ "resetTitle": "Linear를 초기화할까요?",+ "resetDescription": "이 앱에 연결된 모든 워크스페이스의 연결을 해제하고 채널을 중지합니다.",+ "resetClears": "삭제",+ "resetClearsDetail": "멤버 접근 설정 및 저장된 자격 증명을 포함한 이 인스턴스의 앱 설정.",+ "resetKeeps": "유지",+ "resetKeepsDetail": "Linear 앱, 이슈, 댓글, 대화 기록 및 승인된 페어링.",+ "resetConfirm": "초기화",+ "resetting": "초기화 중…",+ "resetIncomplete": "초기화가 완료되지 않았습니다. 이미 제거한 연결은 복구되지 않습니다. 다시 시도하여 완료하세요.",+ "resetInspectFailed": "연결된 워크스페이스를 확인할 수 없습니다. 앱 설정은 유지됩니다.",+ "resetChanged": "다른 워크스페이스가 연결되었습니다. 확인 후 다시 시도하세요.",+ "resetStopFailed": "Linear 채널을 중지하지 못했습니다. 앱 설정은 유지됩니다.",+ "resetSaveFailed": "앱 설정을 지우지 못했습니다. 다시 시도하세요."},"members": {"title": "멤버 접근 권한",- "help": "페어링 코드 없이 Linear에서 nanobot을 사용할 멤버를 선택하세요. 관리자 화면 접근 권한은 부여하지 않습니다. 끄면 새 요청만 차단하며 실행 중인 작업은 취소하지 않습니다.",+ "help": "멤버가 페어링 코드 없이 nanobot을 사용할 수 있도록 허용합니다. Linear의 기존 권한 범위는 유지되며 nanobot 관리 화면 접근 권한은 부여되지 않습니다. 끄면 새 요청은 차단되지만 실행 중인 작업은 중단되지 않습니다.","allowAll": "고급 설정에서 신규 멤버를 포함한 모든 멤버(*)를 허용하고 있습니다. 개별 끄기 설정이 우선합니다. 신규 멤버의 승인을 요구하려면 *를 제거하세요.","search": "멤버 검색","refresh": "멤버 새로고침","working": "저장 중…","saved": "저장됨","retry": "멤버를 새로고침하여 현재 상태를 확인한 후 다시 시도하세요.",- "empty": "앱이 접근할 수 있는 팀에 일치하는 활성 멤버가 없습니다.",+ "empty": "일치하는 활성 멤버가 없습니다.","allow": "{{name}}의 nanobot 사용 허용","saveUnconfirmed": "권한 저장을 확인하지 못했습니다. 멤버를 새로고침한 후 다시 시도하세요.","guide": "멤버 접근 권한에서 코드 없이 동료를 승인하세요. 기존 승인은 끄지 않는 한 유지됩니다. Issue 검색이나 수정에는 Linear MCP를 연결하세요.","intro": "페어링 코드 없이 Linear에서 nanobot을 사용할 멤버를 선택하세요.","details": "멤버 접근 권한 안내","summary": "{{allowed}}명 사용 가능",- "loading": "팀 멤버를 불러오는 중…",+ "loading": "멤버를 찾는 중…","refreshing": "업데이트 확인 중…"}}diff --git a/nanobot/channels/linear/webui/locales/pt-BR.json b/nanobot/channels/linear/webui/locales/pt-BR.jsonindex 867ea695d..d0d0332e1 100644--- a/nanobot/channels/linear/webui/locales/pt-BR.json+++ b/nanobot/channels/linear/webui/locales/pt-BR.json@@ -61,19 +61,21 @@}},"custom": {- "qrAlt": "Código QR de autorização do Linear",+ "secretSaved": "Salvo",+ "replaceSecret": "Substituir",+ "replaceSecretLabel": "Substituir {{name}}",+ "enterSecret": "Insira o segredo",+ "secretSaveFailed": "Não foi possível confirmar o salvamento. Tente novamente ou cancele.","authorizeTitle": "Autorizar no Linear",- "authorizeDescription": "Abra o Linear neste navegador ou escaneie o código QR. O nanobot habilitará o canal após a autorização.",+ "authorizeDescription": "Continue no Linear para escolher um workspace e autorizar o nanobot. Volte aqui quando terminar.","waiting": "Aguardando autorização do Linear...","connected": "O Linear está conectado.","stopped": "A autorização foi interrompida.","connecting": "Conectando...",- "reconnect": "Conectar outro workspace","connect": "Conectar Linear","openLinear": "Continuar no Linear","createApp": "Criar aplicativo Linear","savePublicUrl": "Insira uma URL HTTPS pública para criar um aplicativo Linear.",- "removeCredentials": "Remover credenciais salvas","retrySave": "Tentar novamente","channelRunning": "Canal em execução","accessAll": "Todos os membros de um workspace autorizado podem executar este agente.",@@ -87,26 +89,49 @@"refreshRequired": "Atualização da autorização necessária","missingScopes": "Reconecte para conceder: {{scopes}}","authorized": "Autorizado",- "confirmDisconnect": "Desconectar workspace",- "disconnect": "Desconectar"+ "confirmDisconnect": "Remover workspace",+ "disconnect": "Remover workspace",+ "workspaceActions": "Gerenciar {{name}}",+ "reauthorize": "Autorizar novamente",+ "disconnectTitle": "Remover {{name}}?",+ "disconnectDescription": "Revoga a autorização e limpa as configurações de acesso deste workspace no nanobot. Issues, comentários e histórico serão mantidos. Outros workspaces não são afetados. Você pode autorizar novamente depois.",+ "disconnectLast": "Este é o último espaço de trabalho conectado, então o canal do Linear também será desativado.",+ "disconnecting": "Removendo…",+ "addWorkspace": "Conectar workspace",+ "addWorkspaceDetails": "Sobre conectar workspaces",+ "addWorkspaceHelp": "Usa o app Linear atual. Para conectar outros workspaces, o app deve permitir a instalação neles; apps privados só funcionam no próprio workspace. Autorizar novamente atualiza a conexão sem duplicá-la.",+ "resetConnection": "Redefinir conexão com Linear",+ "resetTitle": "Redefinir Linear?",+ "resetDescription": "Desconecta todos os espaços vinculados a este aplicativo e interrompe o canal.",+ "resetClears": "Limpa",+ "resetClearsDetail": "As permissões dos membros e a configuração do aplicativo nesta instância, incluindo credenciais salvas.",+ "resetKeeps": "Mantém",+ "resetKeepsDetail": "O aplicativo Linear, issues, comentários, histórico e pareamentos aprovados.",+ "resetConfirm": "Redefinir",+ "resetting": "Redefinindo…",+ "resetIncomplete": "Redefinição incompleta. Workspaces já removidos não serão restaurados; tente novamente para concluir.",+ "resetInspectFailed": "Não foi possível verificar os workspaces. A configuração do app foi mantida.",+ "resetChanged": "Outro workspace foi conectado. Revise as conexões e tente novamente.",+ "resetStopFailed": "Não foi possível parar o canal Linear. A configuração foi mantida.",+ "resetSaveFailed": "Não foi possível limpar a configuração. Tente novamente."},"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.",+ "help": "Permita que os membros usem o nanobot sem código de pareamento. As autorizações existentes do Linear continuam válidas e o acesso ao painel de administração do nanobot não é concedido. Desativar o acesso bloqueia novas solicitações, não as 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": "Salvando…","saved": "Salvo","retry": "Atualize os membros para conferir o estado atual e tente novamente.",- "empty": "Nenhum membro ativo correspondente nas equipes acessíveis ao aplicativo.",+ "empty": "Nenhum membro ativo correspondente.","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.","intro": "Escolha quem pode usar o nanobot no Linear, sem códigos de pareamento.","details": "Sobre o acesso de membros","summary": "{{allowed}} habilitados",- "loading": "Buscando membros da equipe…",+ "loading": "Buscando membros…","refreshing": "Verificando atualizações…"}}diff --git a/nanobot/channels/linear/webui/locales/vi.json b/nanobot/channels/linear/webui/locales/vi.jsonindex 87820bde3..ba18feeeb 100644--- a/nanobot/channels/linear/webui/locales/vi.json+++ b/nanobot/channels/linear/webui/locales/vi.json@@ -61,19 +61,21 @@}},"custom": {- "qrAlt": "Mã QR cấp quyền Linear",+ "secretSaved": "Đã lưu",+ "replaceSecret": "Thay thế",+ "replaceSecretLabel": "Thay thế {{name}}",+ "enterSecret": "Nhập khóa bí mật",+ "secretSaveFailed": "Chưa thể xác nhận đã lưu. Hãy thử lại hoặc hủy.","authorizeTitle": "Cấp quyền trong Linear",- "authorizeDescription": "Mở Linear trong trình duyệt này hoặc quét mã QR. nanobot sẽ bật channel sau khi được cấp quyền.",+ "authorizeDescription": "Tiếp tục trong Linear để chọn workspace và cấp quyền cho nanobot. Quay lại đây khi hoàn tất.","waiting": "Đang chờ cấp quyền Linear...","connected": "Linear đã được kết nối.","stopped": "Đã dừng cấp quyền.","connecting": "Đang kết nối...",- "reconnect": "Kết nối workspace khác","connect": "Kết nối Linear","openLinear": "Tiếp tục trong Linear","createApp": "Tạo ứng dụng Linear","savePublicUrl": "Nhập URL HTTPS công khai để tạo ứng dụng Linear.",- "removeCredentials": "Xóa thông tin xác thực đã lưu","retrySave": "Thử lại","channelRunning": "Channel đang chạy","accessAll": "Mọi thành viên trong workspace được cấp quyền đều có thể chạy agent này.",@@ -87,26 +89,49 @@"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"+ "confirmDisconnect": "Xóa kết nối",+ "disconnect": "Xóa kết nối",+ "workspaceActions": "Quản lý {{name}}",+ "reauthorize": "Cấp quyền lại",+ "disconnectTitle": "Xóa {{name}}?",+ "disconnectDescription": "Thu hồi quyền và xóa cài đặt quyền thành viên của không gian này trong nanobot. Giữ lại issue, bình luận và lịch sử nanobot. Không ảnh hưởng đến không gian khác. Có thể cấp quyền lại sau.",+ "disconnectLast": "Đây là không gian làm việc được kết nối cuối cùng, nên kênh Linear cũng sẽ bị tắt.",+ "disconnecting": "Đang xóa…",+ "addWorkspace": "Kết nối không gian làm việc",+ "addWorkspaceDetails": "Về kết nối không gian làm việc",+ "addWorkspaceHelp": "Dùng ứng dụng Linear hiện tại. Để kết nối nơi khác, ứng dụng phải cho phép cài đặt ở không gian làm việc khác; ứng dụng riêng tư chỉ dùng trong không gian của nó. Cấp quyền lại sẽ cập nhật kết nối mà không tạo bản trùng.",+ "resetConnection": "Đặt lại kết nối Linear",+ "resetTitle": "Đặt lại Linear?",+ "resetDescription": "Ngắt kết nối mọi không gian làm việc của ứng dụng này và dừng kênh.",+ "resetClears": "Xóa",+ "resetClearsDetail": "Quyền truy cập thành viên và cấu hình ứng dụng của phiên bản này, gồm thông tin xác thực đã lưu.",+ "resetKeeps": "Giữ lại",+ "resetKeepsDetail": "Ứng dụng Linear, issue, bình luận, lịch sử trò chuyện và các ghép đôi đã duyệt.",+ "resetConfirm": "Đặt lại",+ "resetting": "Đang đặt lại…",+ "resetIncomplete": "Chưa đặt lại hoàn tất. Kết nối đã xóa sẽ không được khôi phục; hãy thử lại để hoàn tất.",+ "resetInspectFailed": "Không thể xác minh các kết nối. Cấu hình ứng dụng được giữ lại.",+ "resetChanged": "Một không gian khác vừa được kết nối. Kiểm tra rồi thử lại.",+ "resetStopFailed": "Không thể dừng kênh Linear. Cấu hình được giữ lại.",+ "resetSaveFailed": "Không thể xóa cấu hình ứng dụng. Hãy thử lạ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.",+ "help": "Cho phép thành viên dùng nanobot mà không cần mã ghép nối. Phạm vi cấp quyền hiện có của Linear vẫn áp dụng và không cấp quyền truy cập giao diện quản trị nanobot. Tắt quyền truy cập sẽ chặn yêu cầu mới, không dừng 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 lưu…","saved": "Đã lưu","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.",+ "empty": "Không có thành viên đang hoạt động phù hợ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.","intro": "Chọn ai có thể dùng nanobot trong Linear mà không cần mã ghép nối.","details": "Về quyền truy cập của thành viên","summary": "{{allowed}} người được phép",- "loading": "Đang tìm thành viên nhóm…",+ "loading": "Đang tìm thành viên…","refreshing": "Đang kiểm tra cập nhật…"}}diff --git a/nanobot/channels/linear/webui/locales/zh-CN.json b/nanobot/channels/linear/webui/locales/zh-CN.jsonindex 23748bf75..ff72357a4 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":"断开连接"},"members":{"title":"成员访问","help":"选择可以在 Linear 中免配对使用 nanobot 的成员。这不会授予 nanobot 后台管理权限。关闭后会阻止新请求,但不会取消正在运行的任务。","allowAll":"高级设置目前允许所有成员(*),包括新成员。单独关闭的成员仍会被拒绝;若希望新成员须经批准,请移除 *。","search":"搜索成员","refresh":"刷新成员","working":"保存中…","saved":"已保存","retry":"请刷新成员列表确认当前状态后重试。","empty":"应用可访问的团队中没有匹配的活跃成员。","allow":"允许 {{name}} 使用 nanobot","saveUnconfirmed":"未能确认权限已保存,请刷新成员列表后重试。","guide":"在「成员访问」中为同事开通免配对使用。已有授权仍然有效,除非手动关闭。连接 Linear MCP 后可搜索或修改 issue。","intro":"选择哪些成员可以在 Linear 中使用 nanobot,无需配对码。","details":"关于成员访问权限","summary":"{{allowed}} 人可用","loading":"正在获取团队成员…","refreshing":"正在检查更新…"}}+{"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":{"authorizeTitle":"在 Linear 中授权","authorizeDescription":"前往 Linear 选择工作区并授权 nanobot,完成后回到这里。","waiting":"正在等待 Linear 授权……","connected":"Linear 已连接。","stopped":"授权已停止。","connecting":"正在连接……","connect":"连接 Linear","openLinear":"前往 Linear","createApp":"创建 Linear 应用","savePublicUrl":"请先填写公网 HTTPS 地址,再创建 Linear 应用。","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":"移除工作区","workspaceActions":"管理 {{name}}","reauthorize":"重新授权","disconnectTitle":"移除 {{name}}?","disconnectDescription":"撤销此工作区的授权,并清除它在 nanobot 中的成员访问设置。保留 Linear 中的任务、评论和 nanobot 历史会话,不影响其他工作区。之后可以重新授权连接。","disconnectLast":"这是最后一个已连接的工作区,断开后也会停用 Linear channel。","disconnecting":"正在移除…","addWorkspace":"连接工作区","addWorkspaceDetails":"关于连接工作区","addWorkspaceHelp":"使用当前 Linear 应用。连接其他工作区需允许跨工作区安装;私有应用只能连接它所属的工作区。选择已有工作区会更新授权,不会重复添加。","resetConnection":"重置 Linear 连接","resetTitle":"重置 Linear?","resetDescription":"断开此应用连接的全部工作区,并停用频道。","resetClears":"清除","resetClearsDetail":"成员访问设置,以及此实例的应用配置和已保存密钥。","resetKeeps":"保留","resetKeepsDetail":"Linear 应用、任务、评论、历史会话和已有配对。","resetConfirm":"重置","resetting":"正在重置…","resetIncomplete":"重置尚未完成。已移除的工作区不会恢复,可重试完成剩余步骤。","resetInspectFailed":"无法确认已连接的工作区,已保留应用配置。","resetChanged":"有新的工作区被连接,请检查后重试。","resetStopFailed":"未能停止 Linear channel,已保留应用配置。","resetSaveFailed":"未能清空应用配置,请重试。","secretSaved":"已保存","replaceSecret":"更换","replaceSecretLabel":"更换{{name}}","enterSecret":"输入密钥","secretSaveFailed":"暂时无法确认保存结果,请重试或取消。"},"members":{"title":"成员访问","help":"开启后,成员无需配对码即可使用 nanobot,仍受 Linear 的授权范围限制,不会获得 nanobot 后台访问权限。关闭后将阻止新请求,不会中断已在运行的任务。","allowAll":"高级设置目前允许所有成员(*),包括新成员。单独关闭的成员仍会被拒绝;若希望新成员须经批准,请移除 *。","search":"搜索成员","refresh":"刷新成员","working":"保存中…","saved":"已保存","retry":"请刷新成员列表确认当前状态后重试。","empty":"没有匹配的活跃成员。","allow":"允许 {{name}} 使用 nanobot","saveUnconfirmed":"未能确认权限已保存,请刷新成员列表后重试。","guide":"在「成员访问」中为同事开通免配对使用。已有授权仍然有效,除非手动关闭。连接 Linear MCP 后可搜索或修改 issue。","intro":"选择哪些成员可以在 Linear 中使用 nanobot,无需配对码。","details":"关于成员访问权限","summary":"{{allowed}} 人可用","loading":"正在查找成员…","refreshing":"正在检查更新…"}}diff --git a/nanobot/channels/linear/webui/locales/zh-TW.json b/nanobot/channels/linear/webui/locales/zh-TW.jsonindex 4c6deaef4..83953ae59 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":"中斷連線"},"members":{"title":"成員存取","help":"選擇可在 Linear 中免配對使用 nanobot 的成員。這不會授予 nanobot 後台管理權限。關閉後會阻止新請求,但不會取消正在執行的任務。","allowAll":"進階設定目前允許所有成員(*),包含新成員。個別關閉的成員仍會被拒絕;若希望新成員須經核准,請移除 *。","search":"搜尋成員","refresh":"重新整理成員","working":"儲存中…","saved":"已儲存","retry":"請重新整理成員清單確認目前狀態後再試。","empty":"應用程式可存取的團隊中沒有符合的活躍成員。","allow":"允許 {{name}} 使用 nanobot","saveUnconfirmed":"無法確認權限已儲存,請重新整理成員清單後再試。","guide":"在「成員存取」中為同事開通免配對使用。既有授權仍然有效,除非手動關閉。連接 Linear MCP 後可搜尋或修改 issue。","intro":"選擇哪些成員可以在 Linear 中使用 nanobot,無需配對碼。","details":"關於成員存取權限","summary":"{{allowed}} 人可用","loading":"正在取得團隊成員…","refreshing":"正在檢查更新…"}}+{"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":{"authorizeTitle":"在 Linear 中授權","authorizeDescription":"前往 Linear 選擇工作區並授權 nanobot,完成後回到這裡。","waiting":"正在等待 Linear 授權……","connected":"Linear 已連接。","stopped":"授權已停止。","connecting":"正在連接……","connect":"連接 Linear","openLinear":"前往 Linear","createApp":"建立 Linear 應用程式","savePublicUrl":"請先填寫公網 HTTPS 網址,再建立 Linear 應用程式。","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":"移除工作區","workspaceActions":"管理 {{name}}","reauthorize":"重新授權","disconnectTitle":"移除 {{name}}?","disconnectDescription":"撤銷此工作區的授權,並清除其在 nanobot 中的成員存取設定。保留 Linear 中的任務、留言及 nanobot 對話記錄,不影響其他工作區。之後可重新授權連接。","disconnectLast":"這是最後一個已連線的工作區,中斷後也會停用 Linear channel。","disconnecting":"正在移除…","addWorkspace":"連接工作區","addWorkspaceDetails":"關於連接工作區","addWorkspaceHelp":"使用目前的 Linear 應用程式。連接其他工作區需允許跨工作區安裝;私人應用程式只能連接所屬工作區。選擇已有工作區會更新授權,不會重複新增。","resetConnection":"重設 Linear 連線","resetTitle":"重設 Linear?","resetDescription":"中斷此應用程式連接的所有工作區,並停用頻道。","resetClears":"清除","resetClearsDetail":"成員存取設定,以及此執行個體的應用程式設定和已儲存金鑰。","resetKeeps":"保留","resetKeepsDetail":"Linear 應用程式、任務、留言、對話記錄和既有配對。","resetConfirm":"重設","resetting":"正在重設…","resetIncomplete":"重設尚未完成。已移除的工作區不會恢復,可重試完成剩餘步驟。","resetInspectFailed":"無法確認已連接的工作區,已保留應用程式設定。","resetChanged":"有新的工作區被連接,請檢查後重試。","resetStopFailed":"未能停止 Linear channel,已保留應用程式設定。","resetSaveFailed":"未能清空應用程式設定,請重試。","secretSaved":"已儲存","replaceSecret":"更換","replaceSecretLabel":"更換{{name}}","enterSecret":"輸入金鑰","secretSaveFailed":"暫時無法確認儲存結果,請重試或取消。"},"members":{"title":"成員存取","help":"開啟後,成員無需配對碼即可使用 nanobot,仍受 Linear 的授權範圍限制,不會取得 nanobot 後台存取權限。關閉後將阻止新請求,不會中斷已在執行的任務。","allowAll":"進階設定目前允許所有成員(*),包含新成員。個別關閉的成員仍會被拒絕;若希望新成員須經核准,請移除 *。","search":"搜尋成員","refresh":"重新整理成員","working":"儲存中…","saved":"已儲存","retry":"請重新整理成員清單確認目前狀態後再試。","empty":"沒有符合條件的活躍成員。","allow":"允許 {{name}} 使用 nanobot","saveUnconfirmed":"無法確認權限已儲存,請重新整理成員清單後再試。","guide":"在「成員存取」中為同事開通免配對使用。既有授權仍然有效,除非手動關閉。連接 Linear MCP 後可搜尋或修改 issue。","intro":"選擇哪些成員可以在 Linear 中使用 nanobot,無需配對碼。","details":"關於成員存取權限","summary":"{{allowed}} 人可用","loading":"正在尋找成員…","refreshing":"正在檢查更新…"}}diff --git a/nanobot/channels/linear/webui/member-access-store.ts b/nanobot/channels/linear/webui/member-access-store.tsindex 735603010..9d6d8dbd2 100644--- a/nanobot/channels/linear/webui/member-access-store.ts+++ b/nanobot/channels/linear/webui/member-access-store.ts@@ -19,6 +19,7 @@ class LinearMemberAccessStore {private listeners = new Set<() => void>();private readVersion = 0;private fetchedAt = 0;+ private generation = 0;constructor(private client: WebUIMutationTransport, private organizationId: string) {}@@ -41,6 +42,13 @@ class LinearMemberAccessStore {return !this.listeners.size && !this.saving && !this.snapshot.loading;}+ invalidate = () => {+ this.generation += 1;+ this.readVersion += 1;+ this.fetchedAt = 0;+ this.update({ payload: null, loading: false, error: null, saves: {} });+ };+load = async (force = false) => {if (this.snapshot.loading || this.saving) return;if (!force && this.snapshot.payload && Date.now() - this.fetchedAt < FRESH_FOR_MS) return;@@ -63,6 +71,7 @@ class LinearMemberAccessStore {const previous = this.snapshot.saves[userId];if (previous?.status === "saving" || previous?.status === "error") return;if (!this.snapshot.payload?.members.some((member) => member.id === userId)) return;+ const generation = this.generation;// An older directory response must not overwrite a newer permission change.this.readVersion += 1;this.update({ loading: false, saves: { ...this.snapshot.saves, [userId]: { status: "saving" } } });@@ -70,6 +79,7 @@ class LinearMemberAccessStore {const payload = await manageLinearMembers(this.client, {operation: "member_access", organization_id: this.organizationId, user_id: userId, allowed,});+ if (generation !== this.generation) return;const updated = payload.members.find((member) => member.id === userId);if (payload.organization_id !== this.organizationId || !updated || updated.allowed !== allowed) {throw new Error(unconfirmedMessage);@@ -86,6 +96,7 @@ class LinearMemberAccessStore {});} catch (error) {// A timeout can mean the server saved the change. Re-read before retrying this member.+ if (generation !== this.generation) return;this.fetchedAt = 0;this.update({ saves: { ...this.snapshot.saves, [userId]: {status: "error", message: error instanceof Error ? error.message : String(error),diff --git a/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx b/webui/src/components/settings/channels/ChannelQrConnectFlow.tsxindex 3a6d26989..3967830bb 100644--- a/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx+++ b/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx@@ -18,7 +18,7 @@ import type {import { useClient } from "@/providers/ClientProvider";export type ChannelQrConnectLabels = {- qrAlt: string;+ qrAlt?: string;scanTitle: string;scanDescription: string;waiting: string;@@ -46,6 +46,7 @@ export function ChannelQrConnectFlow({connected = false,autoStart = false,minimalPending = false,+ showQrCode = true,labels,onFeaturesUpdate,pausePolling,@@ -64,6 +65,8 @@ export function ChannelQrConnectFlow({connected?: boolean;autoStart?: boolean;minimalPending?: boolean;+ /** Browser-based authorization can reuse the flow without generating or showing a QR code. */+ showQrCode?: boolean;labels: ChannelQrConnectLabels;onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;pausePolling?: (payload: ChannelConnectPayload) => boolean;@@ -97,7 +100,7 @@ export function ChannelQrConnectFlow({: undefined;useEffect(() => {- if (!connect?.qr_url) {+ if (!showQrCode || !connect?.qr_url) {setQrDataUrl("");return;}@@ -116,7 +119,7 @@ export function ChannelQrConnectFlow({return () => {cancelled = true;};- }, [connect?.qr_url]);+ }, [connect?.qr_url, showQrCode]);useEffect(() => {if (@@ -267,13 +270,13 @@ export function ChannelQrConnectFlow({<span className="sr-only">{labels.connecting}</span></div>) : null}- {pending && minimalPending ? (+ {pending && minimalPending && showQrCode ? (<div className="flex min-h-[228px] flex-col items-center justify-center gap-4 py-4"><div className="grid h-[196px] w-[196px] place-items-center rounded-control bg-background shadow-[inset_0_0_0_1px_oklch(0_0_0/0.1)] dark:shadow-[inset_0_0_0_1px_oklch(1_0_0/0.1)]">{qrDataUrl ? (<imgsrc={qrDataUrl}- alt={labels.qrAlt}+ alt={labels.qrAlt ?? labels.scanTitle}className="h-[184px] w-[184px]"/>) : (@@ -283,29 +286,29 @@ export function ChannelQrConnectFlow({{renderPending?.({ connect, busy, poll: submitPoll })}</div>) : pending ? (- <div className="grid gap-4 rounded-control border border-border/70 p-4 sm:grid-cols-[auto_minmax(0,1fr)]">- <div className="grid h-[196px] w-[196px] place-items-center rounded-control border border-border/60 bg-background">+ <div className={`grid gap-4 rounded-control border border-border/70 p-4 ${showQrCode ? "sm:grid-cols-[auto_minmax(0,1fr)]" : ""}`}>+ {showQrCode ? <div className="grid h-[196px] w-[196px] place-items-center rounded-control border border-border/60 bg-background">{qrDataUrl ? (<imgsrc={qrDataUrl}- alt={labels.qrAlt}+ alt={labels.qrAlt ?? labels.scanTitle}className="h-[184px] w-[184px]"/>) : (<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />)}- </div>+ </div> : null}<div className="flex min-w-0 flex-col justify-center"><div className="text-[13px] font-semibold text-foreground">{labels.scanTitle}</div><p className="mt-1 text-[12.5px] leading-5 text-muted-foreground">- {qrDataUrl ? labels.scanDescription : null}+ {!showQrCode || qrDataUrl ? labels.scanDescription : null}</p>{renderPending?.({ connect, busy, poll: submitPoll }) ?? (<div className="mt-3 flex items-center gap-2 text-[12px] text-muted-foreground"><Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />- {qrDataUrl ? labels.waiting : labels.connecting}+ {!showQrCode || qrDataUrl ? labels.waiting : labels.connecting}</div>)}<div className="mt-4 flex flex-wrap justify-end gap-2">diff --git a/webui/src/tests/channel-qr-connect.test.tsx b/webui/src/tests/channel-qr-connect.test.tsxindex 20ba07688..5cec4a47f 100644--- a/webui/src/tests/channel-qr-connect.test.tsx+++ b/webui/src/tests/channel-qr-connect.test.tsx@@ -1,5 +1,6 @@import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import QRCode from "qrcode";import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";import { FeishuConnectFlow } from "../../../nanobot/channels/feishu/webui/FeishuConnectFlow";@@ -30,9 +31,61 @@ beforeEach(() => {});});-afterEach(cleanup);+afterEach(() => { cleanup(); vi.restoreAllMocks(); });describe("channel QR connect parameters", () => {+ it.each([false, true])("keeps QR generation enabled by default (minimal=%s)", async (minimalPending) => {+ const generateQr = vi.spyOn(QRCode, "toDataURL").mockResolvedValue("data:image/png;base64,preview");+ requestMutation.mockResolvedValueOnce({+ session_id: "qr-session", status: "pending", qr_url: "https://example.com/connect",+ });+ render(<ChannelQrConnectFlow token="tok" channelName="plugin-chat" labels={labels}+ minimalPending={minimalPending} onFeaturesUpdate={vi.fn()} />);+ fireEvent.click(screen.getByRole("button", { name: "Connect", exact: true }));+ expect(await screen.findByRole("img", { name: "Connection QR code" })).toHaveAttribute("src", "data:image/png;base64,preview");+ expect(generateQr).toHaveBeenCalledOnce();+ });++ it("does not generate or reserve space for QR when disabled, and still allows cancellation", async () => {+ const generateQr = vi.spyOn(QRCode, "toDataURL").mockRejectedValue(new Error("QR must not run"));+ requestMutation+ .mockResolvedValueOnce({ session_id: "browser-session", status: "pending", qr_url: "https://example.com/authorize" })+ .mockResolvedValueOnce({ session_id: "browser-session", status: "cancelled" });+ render(<ChannelQrConnectFlow token="tok" channelName="plugin-chat" showQrCode={false}+ labels={{ ...labels, scanTitle: "Authorize in browser", scanDescription: "Continue in the browser." }}+ onFeaturesUpdate={vi.fn()} />);+ fireEvent.click(screen.getByRole("button", { name: "Connect", exact: true }));+ expect(await screen.findByText("Continue in the browser.")).toBeVisible();+ expect(screen.getByText("Waiting")).toBeVisible();+ expect(generateQr).not.toHaveBeenCalled();+ expect(screen.queryByRole("img")).not.toBeInTheDocument();+ expect(screen.getByText("Authorize in browser").parentElement?.parentElement)+ .not.toHaveClass("sm:grid-cols-[auto_minmax(0,1fr)]");+ fireEvent.click(screen.getByRole("button", { name: "Cancel", exact: true }));+ expect(await screen.findByText("Stopped")).toBeVisible();+ expect(requestMutation).toHaveBeenLastCalledWith("settings.channel.connect.cancel", {+ channel: "plugin-chat", session_id: "browser-session",+ }, 20_000);+ });++ it("polls browser-only authorization to completion without generating QR", async () => {+ const generateQr = vi.spyOn(QRCode, "toDataURL").mockResolvedValue("data:image/png;base64,unused");+ const onFeaturesUpdate = vi.fn();+ const features = { features: [], enabled_count: 0 };+ requestMutation+ .mockResolvedValueOnce({ session_id: "browser-session", status: "pending", qr_url: "https://example.com/authorize" })+ .mockResolvedValueOnce({ session_id: "browser-session", status: "succeeded", nanobot_features: features });+ render(<ChannelQrConnectFlow token="tok" channelName="plugin-chat" showQrCode={false}+ labels={labels} onFeaturesUpdate={onFeaturesUpdate} />);+ fireEvent.click(screen.getByRole("button", { name: "Connect", exact: true }));+ expect(await screen.findByText("Connected", {}, { timeout: 2000 })).toBeVisible();+ expect(onFeaturesUpdate).toHaveBeenCalledWith(features);+ expect(requestMutation).toHaveBeenLastCalledWith("settings.channel.connect.poll", {+ channel: "plugin-chat", session_id: "browser-session",+ }, 150_000);+ expect(generateQr).not.toHaveBeenCalled();+ });+it("forwards current channel parameters without restarting on rerender and preserves forced retries", async () => {const props = {token: "tok",diff --git a/webui/src/tests/linear-avatar.test.tsx b/webui/src/tests/linear-avatar.test.tsxindex f52f41670..fbb986289 100644--- a/webui/src/tests/linear-avatar.test.tsx+++ b/webui/src/tests/linear-avatar.test.tsx@@ -5,13 +5,16 @@ import { LinearAvatar } from "../../../nanobot/channels/linear/webui/LinearAvataafterEach(cleanup);describe("Linear workspace logo", () => {- it("loads a real CDN logo in a fixed-size square and recovers to the workspace icon", () => {+ it("keeps workspace artwork uncropped without a background plate and recovers to an icon", () => {const view = render(<LinearAvatar workspace name="nanobot" url="https://public.linear.app/org/logo" />);const image = view.container.querySelector("img")!;- expect(image).toHaveAttribute("width", "36");- expect(image).toHaveAttribute("height", "36");+ expect(image).toHaveAttribute("width", "28");+ expect(image).toHaveAttribute("height", "28");expect(image).toHaveAttribute("referrerpolicy", "no-referrer");- expect(image.parentElement).toHaveClass("h-9", "w-9", "rounded-control");+ expect(image.parentElement).toHaveClass("h-7", "w-7");+ expect(image.parentElement).not.toHaveClass("overflow-hidden", "bg-muted");+ expect(image).toHaveClass("object-contain");+ expect(view.container.querySelector("svg")).toBeNull();fireEvent.error(image);expect(view.container.querySelector("img")).toBeNull();expect(view.container.querySelector("svg")).not.toBeNull();diff --git a/webui/src/tests/linear-member-access.test.tsx b/webui/src/tests/linear-member-access.test.tsxindex 247dff535..0ba902c1b 100644--- a/webui/src/tests/linear-member-access.test.tsx+++ b/webui/src/tests/linear-member-access.test.tsx@@ -2,6 +2,7 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-libraimport { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { LinearMemberAccess } from "../../../nanobot/channels/linear/webui/LinearMemberAccess";+import { linearMemberAccessStore } from "../../../nanobot/channels/linear/webui/member-access-store";import type { LinearMembersPayload } from "../../../nanobot/channels/linear/webui/types";const { requestMutation, context } = vi.hoisted(() => {@@ -49,6 +50,61 @@ async function openMembers() {}describe("Linear member access", () => {+ it("forgets a removed workspace's cached permissions and ignores its old in-flight save", async () => {+ const store = linearMemberAccessStore(context.client, context.token, "", "org-1");+ await store.load();+ const deferred = deferNextRequest();+ const saving = store.setAllowed("u2", true, "not confirmed");+ store.invalidate();+ deferred.resolve({ ...roster, members: roster.members.map(member => ({ ...member, allowed: true })) });+ await saving;+ expect(store.getSnapshot()).toMatchObject({ payload: null, saves: {}, loading: false });+ requestMutation.mockResolvedValue({ ...roster, members: roster.members.map(member => ({ ...member, allowed: false })) });+ await store.load();+ expect(store.getSnapshot().payload?.members.every(member => !member.allowed)).toBe(true);+ });++ it("shows members without team subtitles or a team filter", async () => {+ await openMembers();+ expect(screen.queryByRole("combobox", { name: "Filter by team" })).not.toBeInTheDocument();+ expect(screen.queryByText("nanobot", { exact: true })).not.toBeInTheDocument();+ });++ it("keeps one workspace-level switch per member regardless of team membership", async () => {+ requestMutation.mockResolvedValue({ ...roster, members: [+ { ...roster.members[0], teams: ["Core", "Desktop"] },+ { ...roster.members[1], teams: ["Core"] },+ ] });+ await openMembers();+ expect(screen.queryByRole("combobox")).not.toBeInTheDocument();+ expect(screen.queryByText(/Core|Desktop/)).not.toBeInTheDocument();+ expect(requestMutation).toHaveBeenCalledTimes(1);+ expect(xubin()).toBeChecked();+ expect(yongru()).not.toBeChecked();+ expect(screen.getAllByRole("switch")).toHaveLength(2);+ });++ it("searches names and user IDs, not hidden team metadata", async () => {+ requestMutation.mockResolvedValue({ ...roster, members: [+ { ...roster.members[0], teams: ["Core", "Desktop"] },+ { ...roster.members[1], teams: ["Core"] },+ ] });+ await openMembers();+ const search = screen.getByRole("textbox", { name: "Search members" });+ fireEvent.change(search, { target: { value: " xubin " } });+ expect(xubin()).toBeVisible();+ expect(screen.getAllByRole("switch")).toHaveLength(1);+ fireEvent.change(search, { target: { value: "u2" } });+ expect(yongru()).toBeVisible();+ expect(screen.getAllByRole("switch")).toHaveLength(1);+ fireEvent.change(search, { target: { value: "Desktop" } });+ expect(screen.queryByRole("switch")).not.toBeInTheDocument();+ expect(screen.getByText("No matching active members.")).toBeVisible();+ fireEvent.change(search, { target: { value: "" } });+ expect(screen.getAllByRole("switch")).toHaveLength(2);+ expect(requestMutation).toHaveBeenCalledTimes(1);+ });+it("renders Linear avatars without referrers and falls back when an image fails", async () => {const avatar = "https://public.linear.app/u2/avatar";requestMutation.mockResolvedValue({ ...roster, members: roster.members.map(member => ({@@ -112,7 +168,7 @@ describe("Linear member access", () => {expect(requestMutation).toHaveBeenCalledTimes(1);fireEvent.click(header());expect(requestMutation).toHaveBeenCalledTimes(1);- expect(screen.getByText("Finding your teammates…")).toBeVisible();+ expect(screen.getByText("Finding members…")).toBeVisible();expect(screen.getByRole("textbox", { name: "Search members" })).toBeEnabled();expect(header()).toBeEnabled();expect(document.querySelector(".animate-spin")).toBeNull();@@ -139,7 +195,7 @@ describe("Linear member access", () => {fireEvent.click(header());expect(yongru()).toBeVisible();expect(requestMutation).toHaveBeenCalledTimes(1);- expect(screen.queryByText("Finding your teammates…")).not.toBeInTheDocument();+ expect(screen.queryByText("Finding members…")).not.toBeInTheDocument();});it("shows a stale list immediately while revalidating, without disabling the list", async () => {diff --git a/webui/src/tests/linear-reset-connection.test.tsx b/webui/src/tests/linear-reset-connection.test.tsxnew file mode 100644index 000000000..3c0d1558d--- /dev/null+++ b/webui/src/tests/linear-reset-connection.test.tsx@@ -0,0 +1,167 @@+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { LinearResetConnection } from "../../../nanobot/channels/linear/webui/LinearResetConnection";+import type { ChannelConfigField } from "@/components/settings/channels/catalog";++const { requestMutation } = vi.hoisted(() => ({ requestMutation: vi.fn() }));+vi.mock("@/providers/ClientProvider", () => ({+ useClient: () => ({ client: { requestMutation }, token: "preview-only" }),+}));++const fields: ChannelConfigField[] = [+ { key: "channels.linear.clientId", label: "Client ID" },+ { key: "channels.linear.publicBaseUrl", label: "URL" },+ { key: "channels.linear.clientSecret", label: "Secret", secret: true },+ { key: "channels.linear.webhookSigningSecret", label: "Webhook secret", secret: true },+ { key: "channels.linear.port", label: "Port", defaultValue: "3979" },+];+const orgs = [+ { organization_id: "one", organization_name: "One" },+ { organization_id: "two", organization_name: "Two" },+];+let remaining = [...orgs];+let failWorkspace: string | null = null;+let failStop = false;+let failSave = false;++beforeEach(() => {+ remaining = [...orgs];+ failWorkspace = null;+ failStop = false;+ failSave = false;+ requestMutation.mockReset().mockImplementation(async (method, params) => {+ if (params.operation === "inspect") return { installations: [...remaining] };+ if (params.operation === "disconnect") {+ if (params.organization_id === failWorkspace) throw new Error("Linear unavailable");+ remaining = remaining.filter(item => item.organization_id !== params.organization_id);+ return { installations: [...remaining] };+ }+ if (method === "settings.feature.disable") return {+ features: [{ name: "linear", enabled: false, runtime_status: failStop ? "running" : "stopped" }],+ enabled_count: 0,+ };+ if (method === "settings.channel.configure") {+ if (failSave) throw new Error("Save failed");+ return { saved: true };+ }+ throw new Error(`Unexpected mutation: ${method}`);+ });+});+afterEach(cleanup);++async function openReset() {+ const onWorkspaceRemoved = vi.fn();+ const onWorkspacesChange = vi.fn();+ render(<LinearResetConnection fields={fields} disabled={false} onBusyChange={vi.fn()}+ onFeaturesUpdate={vi.fn()} onWorkspaceRemoved={onWorkspaceRemoved}+ onWorkspacesChange={onWorkspacesChange} />);+ fireEvent.click(screen.getByRole("button", { name: "Reset Linear connection" }));+ const dialog = await screen.findByRole("alertdialog");+ return { dialog, onWorkspaceRemoved, onWorkspacesChange,+ confirm: () => fireEvent.click(within(dialog).getByRole("button", { name: "Reset", exact: true })) };+}++describe("reset Linear connection", () => {+ it("does nothing before confirmation, and cancellation preserves everything", async () => {+ const { dialog } = await openReset();+ expect(requestMutation).not.toHaveBeenCalled();+ expect(dialog).toHaveTextContent("Linear app, issues, comments, chat history and pairing approvals.");+ fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));+ expect(requestMutation).not.toHaveBeenCalled();+ });++ it("separates what is cleared from what is kept and focuses the safe action", async () => {+ const { dialog } = await openReset();+ expect(dialog).toHaveAccessibleName("Reset Linear?");+ expect(dialog).toHaveAccessibleDescription(/Disconnect all workspaces linked through this app and stop the channel/);+ expect(within(dialog).getByText("Clears").tagName).toBe("DT");+ expect(within(dialog).getByText("Keeps").tagName).toBe("DT");+ expect(within(dialog).getByText("Member access settings and this instance’s app configuration, including saved credentials.").tagName).toBe("DD");+ expect(within(dialog).getByRole("button", { name: "Cancel" })).toHaveFocus();+ expect(within(dialog).getByRole("button", { name: "Reset", exact: true })).toBeEnabled();+ });++ it("inspects fresh installations, revokes each, stops the channel, then clears settings", async () => {+ const { confirm, onWorkspaceRemoved } = await openReset();+ confirm();+ await waitFor(() => expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument());+ expect(onWorkspaceRemoved.mock.calls).toEqual([["one"], ["two"]]);+ expect(requestMutation.mock.calls.map(([method, params]) => params.operation ?? method)).toEqual([+ "inspect", "disconnect", "disconnect", "inspect", "settings.feature.disable", "settings.channel.configure",+ ]);+ expect(requestMutation).toHaveBeenLastCalledWith("settings.channel.configure", {+ name: "linear", values: {+ "channels.linear.clientId": "", "channels.linear.publicBaseUrl": "",+ "channels.linear.clientSecret": null, "channels.linear.webhookSigningSecret": null,+ "channels.linear.port": "3979",+ },+ }, 150_000);+ });++ it("preserves credentials and the remaining workspace on partial failure, then resumes", async () => {+ failWorkspace = "two";+ const { confirm, dialog, onWorkspacesChange } = await openReset();+ confirm();+ expect(await within(dialog).findByRole("alert")).toHaveTextContent("Reset is incomplete");+ expect(remaining).toEqual([orgs[1]]);+ expect(onWorkspacesChange).toHaveBeenLastCalledWith([orgs[1]]);+ expect(requestMutation.mock.calls.some(([method]) => method === "settings.channel.configure")).toBe(false);+ failWorkspace = null;+ confirm();+ await waitFor(() => expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument());+ expect(requestMutation.mock.calls.filter(([, params]) => params.operation === "disconnect" && params.organization_id === "one")).toHaveLength(1);+ });++ it("does not interpret a missing installation list as an empty one", async () => {+ requestMutation.mockResolvedValueOnce({});+ const { confirm, dialog } = await openReset();+ confirm();+ expect(await within(dialog).findByRole("alert")).toHaveTextContent("Could not verify");+ expect(requestMutation).toHaveBeenCalledTimes(1);+ });++ it("does not clear settings while the channel is still running", async () => {+ failStop = true;+ const { confirm, dialog } = await openReset();+ confirm();+ expect(await within(dialog).findByRole("alert")).toHaveTextContent("could not be stopped");+ expect(requestMutation.mock.calls.some(([method]) => method === "settings.channel.configure")).toBe(false);+ });++ it("keeps settings when a new workspace appears during reset", async () => {+ requestMutation.mockImplementationOnce(async () => {+ remaining = [orgs[1]];+ return { installations: [] };+ });+ const { confirm, dialog } = await openReset();+ confirm();+ expect(await within(dialog).findByRole("alert")).toHaveTextContent("Another workspace was connected");+ expect(requestMutation.mock.calls.some(([method]) => method === "settings.channel.configure")).toBe(false);+ expect(remaining).toEqual([orgs[1]]);+ });++ it("can retry a failed config save without revoking removed workspaces again", async () => {+ failSave = true;+ const { confirm, dialog } = await openReset();+ confirm();+ expect(await within(dialog).findByRole("alert")).toHaveTextContent("Save failed");+ failSave = false;+ confirm();+ await waitFor(() => expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument());+ expect(requestMutation.mock.calls.filter(([, params]) => params.operation === "disconnect")).toHaveLength(2);+ });++ it("prevents repeat submissions or dismissal while resetting", async () => {+ let finish!: (value: unknown) => void;+ requestMutation.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ const { confirm, dialog } = await openReset();+ confirm();+ expect(within(dialog).getByRole("button", { name: "Resetting…" })).toBeDisabled();+ expect(within(dialog).getByRole("button", { name: "Cancel" })).toBeDisabled();+ fireEvent.keyDown(dialog, { key: "Escape" });+ expect(dialog).toBeVisible();+ finish({});+ await within(dialog).findByRole("alert");+ });+});diff --git a/webui/src/tests/linear-secret-field.test.tsx b/webui/src/tests/linear-secret-field.test.tsxnew file mode 100644index 000000000..35b6b8cb1--- /dev/null+++ b/webui/src/tests/linear-secret-field.test.tsx@@ -0,0 +1,91 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++import { LinearSecretField } from "../../../nanobot/channels/linear/webui/LinearSecretField";++const field = { key: "channels.linear.clientSecret", label: "OAuth client secret", secret: true };+afterEach(cleanup);++function setup(onSave = vi.fn(async () => {}), configured = true) {+ const rendered = render(<LinearSecretField field={field} configured={configured} disabled={false} onSave={onSave} />);+ return { ...rendered, onSave };+}+function edit() {+ fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));+ return screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" });+}++describe("Linear saved secret", () => {+ it("shows a saved status rather than an empty editable field", () => {+ setup();+ expect(screen.getByRole("status")).toHaveTextContent("Saved");+ expect(screen.getByRole("group", { name: field.label }).querySelector("input")).toBeNull();+ expect(screen.queryByRole("button", { name: "Show secret" })).not.toBeInTheDocument();+ });++ it("starts with an ordinary blank input when not configured", () => {+ const { onSave } = setup(undefined, false);+ const input = screen.getByLabelText(field.label, { exact: true, selector: "input" });+ expect(input).toHaveValue("");+ expect(input).toHaveAttribute("placeholder", "Enter secret");+ expect(screen.queryByText("Saved")).not.toBeInTheDocument();+ fireEvent.change(input, { target: { value: " " } });+ expect(screen.getByRole("button", { name: "Save", exact: true })).toBeDisabled();+ fireEvent.keyDown(input, { key: "Enter" });+ expect(onSave).not.toHaveBeenCalled();+ });++ it("does not save on blur or revealing the new draft; Escape restores saved state", () => {+ const { onSave } = setup();+ const input = edit();+ expect(input).toHaveFocus();+ fireEvent.change(input, { target: { value: "new-draft" } });+ fireEvent.blur(input);+ fireEvent.click(screen.getByRole("button", { name: "Show secret" }));+ expect(input).toHaveAttribute("type", "text");+ expect(onSave).not.toHaveBeenCalled();+ fireEvent.keyDown(input, { key: "Escape" });+ expect(screen.getByRole("status")).toHaveTextContent("Saved");+ expect(screen.getByRole("button", { name: "Replace OAuth client secret" })).toHaveFocus();+ expect(edit()).toHaveValue("");+ expect(screen.getByLabelText(field.label, { exact: true, selector: "input" })).toHaveAttribute("type", "password");+ });++ it("keeps the editor stable during a slow save and prevents duplicate commits", async () => {+ let finish!: () => void;+ const onSave = vi.fn(() => new Promise<void>(resolve => { finish = resolve; }));+ setup(onSave);+ const input = edit();+ fireEvent.change(input, { target: { value: "new-draft" } });+ fireEvent.keyDown(input, { key: "Enter" });+ fireEvent.keyDown(input, { key: "Enter" });+ expect(onSave).toHaveBeenCalledTimes(1);+ expect(onSave).toHaveBeenCalledWith(field.key, "new-draft");+ expect(input).toBeInTheDocument();+ expect(input).toHaveValue("new-draft");+ expect(screen.getByRole("group", { name: field.label })).toHaveAttribute("aria-busy", "true");+ expect(screen.getByRole("button", { name: "Cancel" })).toBeDisabled();+ expect(screen.queryByText("Saved")).not.toBeInTheDocument();+ fireEvent.keyDown(input, { key: "Escape" });+ expect(input).toHaveValue("new-draft");+ await act(async () => finish());+ expect(screen.getByRole("status")).toHaveTextContent("Saved");+ expect(screen.queryByDisplayValue("new-draft")).not.toBeInTheDocument();+ });++ it("retains a failed draft for retry without exposing raw server errors", async () => {+ const onSave = vi.fn().mockRejectedValueOnce(new Error("transport: new-draft"))+ .mockResolvedValueOnce(undefined);+ setup(onSave);+ const input = edit();+ fireEvent.change(input, { target: { value: "new-draft" } });+ fireEvent.click(screen.getByRole("button", { name: "Save", exact: true }));+ expect(await screen.findByRole("alert")).toHaveTextContent("Could not confirm the save");+ expect(screen.getByRole("alert")).not.toHaveTextContent("new-draft");+ expect(input).toHaveAccessibleDescription(/Could not confirm/);+ expect(input).toHaveValue("new-draft");+ fireEvent.click(screen.getByRole("button", { name: "Save", exact: true }));+ await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Saved"));+ expect(onSave).toHaveBeenCalledTimes(2);+ });+});diff --git a/webui/src/tests/settings-test-utils.tsx b/webui/src/tests/settings-test-utils.tsxindex 5fcdce550..366feb30f 100644--- a/webui/src/tests/settings-test-utils.tsx+++ b/webui/src/tests/settings-test-utils.tsx@@ -4,8 +4,9 @@ import { afterEach, beforeEach, vi } from "vitest";import { SettingsView } from "@/components/settings/SettingsView";import { ClientProvider } from "@/providers/ClientProvider";import type { SettingsPayload } from "@/lib/types";+import type { NanobotClient } from "@/lib/nanobot-client";-export { fireEvent, screen, waitFor, within } from "@testing-library/react";+export { act, fireEvent, screen, waitFor, within } from "@testing-library/react";export const requestMutationMock = vi.fn();@@ -126,6 +127,7 @@ export function settingsPayload(): SettingsPayload {export function renderSettingsView(options: {+ client?: NanobotClient;initialSection?:| "overview"| "appearance"@@ -149,7 +151,14 @@ export function renderSettingsView(} = {},) {render(- <ClientProvider client={{ requestMutation: requestMutationMock } as never} token="tok">+ <ClientProvider client={options.client ?? {+ requestMutation: requestMutationMock,+ status: "open",+ onStatus: (handler: (status: "open") => void) => {+ handler("open");+ return () => {};+ },+ } as never} token="tok"><SettingsViewtheme="light"initialSection={options.initialSection ?? "apps"}