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): simplify member settings and cache workspace profiles
Xubin Rena9412aedd0c7
diff --git a/docs/guides/linear-agent.md b/docs/guides/linear-agent.mdindex 97a30b9b7..0423f3446 100644--- a/docs/guides/linear-agent.md+++ b/docs/guides/linear-agent.md@@ -242,11 +242,19 @@ display; permissions use stable user IDs scoped to the OAuth client and workspacProfile images come from Linear's `avatarUrl` field and load directly from its`public.linear.app` or `uploads.linear.app` CDN without a referrer. Missing,unsupported or failed images fall back to initials; no extra account linking is needed.+Workspace logos use Linear's optional `Organization.logoUrl` field with the same+CDN restrictions. They load independently of the workspace and member lists; a+missing or unavailable logo falls back to a workspace icon. Existing installations+do not need to authorize again to retrieve a logo.Use **Refresh members** to refresh the directory and effective permission state.The UI prefetches on hover or keyboard focus and keeps visited lists in memory,scoped to this gateway, admin login, app configuration and workspace. Lists olderthan one minute stay visible while refreshing. This display cache is not used toauthorize agent requests.+Workspace cards are also cached for one minute within the current gateway, admin+login and app configuration. Refreshing keeps existing cards visible, and a slow+logo request never blocks member access controls. Expand **Advanced** to inspect+OAuth scopes; authorization problems remain visible on the workspace card.Each switch changes only after the server confirms the save; other members remaineditable while it saves. A failed save may have an uncertain outcome (for example,diff --git a/nanobot/channels/linear/client.py b/nanobot/channels/linear/client.pyindex 7796e6437..ff2d76563 100644--- a/nanobot/channels/linear/client.py+++ b/nanobot/channels/linear/client.py@@ -29,6 +29,11 @@ class LinearMember(TypedDict):avatar_url: NotRequired[str | None]+class LinearWorkspaceProfile(TypedDict):+ organization_id: str+ logo_url: str | None++class LinearApiError(RuntimeError):"""Linear returned a transport, authentication, or GraphQL error."""@@ -115,6 +120,25 @@ class LinearClient:installation = await self._refresh(organization_id, force=True)return await self._graphql_with_token(installation.access_token, query, variables)+ async def workspace_profile(self, organization_id: str) -> LinearWorkspaceProfile:+ """Optional display metadata must not race token rotation for real agent work."""+ installation = self.state.installation(organization_id)+ if (installation is None or installation.oauth_client_id != self.config.client_id+ or installation.expires_at <= time.time()):+ raise LinearApiError("No current Linear authorization for workspace profile")+ # Cosmetic prefetch never refreshes credentials. A failed/expired read uses+ # the UI fallback and can be retried after normal channel work refreshes OAuth.+ data = await self._graphql_with_token(+ installation.access_token,+ "query NanobotWorkspaceProfile { organization { id logoUrl } }",+ {},+ )+ organization = _required_mapping(data, "organization")+ if _required_string(organization, "id") != organization_id:+ raise LinearApiError("Linear returned an unexpected workspace identity")+ logo = organization.get("logoUrl")+ return {"organization_id": organization_id, "logo_url": logo if isinstance(logo, str) else None}+async def list_members(self, organization_id: str, *, user_id: str | None = None,) -> list[LinearMember]:diff --git a/nanobot/channels/linear/connect.py b/nanobot/channels/linear/connect.pyindex 247f5fe2c..eb989dd67 100644--- a/nanobot/channels/linear/connect.py+++ b/nanobot/channels/linear/connect.py@@ -45,6 +45,11 @@ class LinearConnectStore:operation = (query_first(query, "operation") or "connect").strip().lower()if operation == "inspect":return self.inspect()+ if operation == "workspace_profile":+ organization_id = (query_first(query, "organization_id") or "").strip()+ if not organization_id:+ raise ChannelConnectError("missing Linear workspace")+ return await self.workspace_profile(organization_id)if operation == "disconnect":organization_id = (query_first(query, "organization_id") or "").strip()if not organization_id:@@ -194,6 +199,21 @@ class LinearConnectStore:"redirect_uri": config.redirect_uri if config.public_base_url else "",}+ async def workspace_profile(self, organization_id: str) -> dict[str, Any]:+ config = _load_linear_config()+ state = LinearStateStore()+ installation = state.installation(organization_id)+ if installation is None or installation.oauth_client_id != config.client_id:+ raise ChannelConnectError("Linear workspace is not connected", status=404)+ client = LinearClient(config, state)+ try:+ profile = await client.workspace_profile(organization_id)+ except LinearApiError as exc:+ raise ChannelConnectError("Unable to read Linear workspace profile", status=502) from exc+ finally:+ await client.close()+ return {"session_id": "", "status": "workspace_profile", **profile}+async def members(self, organization_id: str, *, user_id: str | None = None, allowed: bool | None = None,) -> dict[str, Any]:diff --git a/nanobot/channels/linear/tests/test_workspace_profile.py b/nanobot/channels/linear/tests/test_workspace_profile.pynew file mode 100644index 000000000..199c7238d--- /dev/null+++ b/nanobot/channels/linear/tests/test_workspace_profile.py@@ -0,0 +1,101 @@+from __future__ import annotations++from dataclasses import replace+from pathlib import Path+from typing import Any+from unittest.mock import AsyncMock++import pytest++from nanobot.channels.linear import connect as linear_connect+from nanobot.channels.linear.client import LinearApiError, LinearClient+from nanobot.channels.linear.state import LinearStateStore+from nanobot.channels.linear.tests.test_linear import _config, _installation++[email protected]("logo", [None, "https://public.linear.app/workspace/logo", 42, {"url": "bad"}])+async def test_workspace_profile_normalizes_optional_logo(+ tmp_path: Path, logo: Any, monkeypatch: pytest.MonkeyPatch,+) -> None:+ state = LinearStateStore(tmp_path / "state.sqlite3")+ state.save_installation(_installation())+ client = LinearClient(_config(), state)+ query = AsyncMock(return_value={"organization": {"id": "org-1", "logoUrl": logo}})+ monkeypatch.setattr(client, "_graphql_with_token", query)+ try:+ assert await client.workspace_profile("org-1") == {+ "organization_id": "org-1", "logo_url": logo if isinstance(logo, str) else None,+ }+ assert query.call_args.args[0] == "access"+ assert "logoUrl" in query.call_args.args[1]+ finally:+ await client.close()+++async def test_workspace_profile_rejects_different_workspace(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,+) -> None:+ state = LinearStateStore(tmp_path / "state.sqlite3")+ state.save_installation(_installation())+ client = LinearClient(_config(), state)+ monkeypatch.setattr(client, "_graphql_with_token", AsyncMock(return_value={"organization": {"id": "other"}}))+ try:+ with pytest.raises(LinearApiError, match="unexpected workspace"):+ await client.workspace_profile("org-1")+ finally:+ await client.close()+++async def test_cosmetic_profile_does_not_rotate_expired_credentials(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,+) -> None:+ state = LinearStateStore(tmp_path / "state.sqlite3")+ expired = replace(_installation(), expires_at=0)+ state.save_installation(expired)+ client = LinearClient(_config(), state)+ token_request = AsyncMock()+ monkeypatch.setattr(client, "_token_request", token_request)+ try:+ with pytest.raises(LinearApiError, match="No current"):+ await client.workspace_profile("org-1")+ token_request.assert_not_awaited()+ assert state.installation("org-1") == expired+ finally:+ await client.close()++[email protected]("scenario", ["connected", "other_app", "disconnected", "api_error"])+async def test_profile_operation_is_scoped_and_never_changes_access(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, scenario: str,+) -> None:+ state = LinearStateStore(tmp_path / "state.sqlite3")+ installation = replace(_installation(), oauth_client_id="other" if scenario == "other_app" else "client-id")+ if scenario != "disconnected":+ state.save_installation(installation)+ fake = AsyncMock()+ fake.workspace_profile.return_value = {"organization_id": "org-1", "logo_url": None}+ if scenario == "api_error":+ fake.workspace_profile.side_effect = LinearApiError("Unavailable")+ monkeypatch.setattr(linear_connect, "_load_linear_config", _config)+ monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: state)+ monkeypatch.setattr(linear_connect, "LinearClient", lambda *_args: fake)+ store = linear_connect.LinearConnectStore()+ params = {"operation": ["workspace_profile"], "organization_id": ["org-1"]}+ if scenario == "connected":+ assert await store.handle("start", params) == {+ "session_id": "", "status": "workspace_profile", "organization_id": "org-1", "logo_url": None,+ }+ else:+ with pytest.raises(linear_connect.ChannelConnectError):+ await store.handle("start", params)+ if scenario in {"connected", "api_error"}:+ fake.close.assert_awaited_once()+ else:+ fake.workspace_profile.assert_not_awaited()+ assert state.installation("org-1") == (None if scenario == "disconnected" else installation)+ assert state.member_access("client-id", "org-1", "user-1") is None+++async def test_profile_requires_explicit_workspace() -> None:+ with pytest.raises(linear_connect.ChannelConnectError, match="missing Linear workspace"):+ await linear_connect.LinearConnectStore().handle("start", {"operation": ["workspace_profile"]})diff --git a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsxindex 5ae58a8cd..f895239c7 100644--- a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx+++ b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx@@ -14,6 +14,13 @@ import {import { linearManifestUrl } from "../../webui/manifest";+vi.mock("../../webui/api", async (importOriginal) => ({+ ...await importOriginal<typeof import("../../webui/api")>(),+ getLinearWorkspaceProfile: vi.fn(async (_client: unknown, organizationId: string) => ({+ organization_id: organizationId, logo_url: null,+ })),+}));+const linearSetup: ChannelSetupContract = {fields: [field("clientId", "string", true),@@ -479,10 +486,11 @@ describe("Linear channel UI", () => {const workspace = screen.getByRole("article", { name: "Example workspace" });expect(within(workspace).getByRole("heading", { name: "Example workspace", level: 5 })).toBeVisible();expect(within(workspace).getByRole("button", { name: "Member access" })).toBeVisible();- expect(screen.queryByText(/app:assignable/)).not.toBeInTheDocument();- fireEvent.click(within(workspace).getByRole("button", { name: "Authorized" }));- expect(await screen.findByRole("tooltip")).toHaveTextContent("read, write, app:mentionable, app:assignable");- fireEvent.keyDown(document, { key: "Escape" });+ expect(within(workspace).queryByText("Authorized")).not.toBeInTheDocument();+ expect(screen.getByText(/Example workspace: read, write/)).not.toBeVisible();+ 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" }));diff --git a/nanobot/channels/linear/webui/LinearAvatar.tsx b/nanobot/channels/linear/webui/LinearAvatar.tsxnew file mode 100644index 000000000..c3e143258--- /dev/null+++ b/nanobot/channels/linear/webui/LinearAvatar.tsx@@ -0,0 +1,31 @@+import { useState } from "react";+import { Building2 } from "lucide-react";++import { cn } from "@/lib/utils";++/** Fixed-size, display-only images. Never send admin-page referrers to the CDN. */+export function LinearAvatar({ name, url, workspace = false }: {+ name: string; url?: string | null; workspace?: boolean;+}) {+ const [failedUrl, setFailedUrl] = useState<string | null>(null);+ let source: string | null = null;+ try {+ const parsed = new URL(url ?? "");+ if (parsed.protocol === "https:" && !parsed.username && !parsed.password+ && (!parsed.port || parsed.port === "443")+ && ["public.linear.app", "uploads.linear.app"].includes(parsed.hostname)) {+ source = parsed.href;+ }+ } catch { /* Missing or malformed images use the same fallback. */ }+ const size = workspace ? 36 : 32;+ 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",+ )}>+ {workspace ? <Building2 className="h-4 w-4" /> : name.slice(0, 2).toLocaleUpperCase()}+ {source && source !== failedUrl ? <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"+ onError={() => setFailedUrl(source)} /> : null}+ </span>;+}diff --git a/nanobot/channels/linear/webui/LinearMemberAccess.tsx b/nanobot/channels/linear/webui/LinearMemberAccess.tsxindex 4c63bd9a5..d417d5924 100644--- a/nanobot/channels/linear/webui/LinearMemberAccess.tsx+++ b/nanobot/channels/linear/webui/LinearMemberAccess.tsx@@ -13,28 +13,7 @@ import { cn } from "@/lib/utils";import { useClient } from "@/providers/ClientProvider";import { linearMemberAccessStore } from "./member-access-store";--function LinearMemberAvatar({ name, url }: { name: string; url?: string | null }) {- const [failedUrl, setFailedUrl] = useState<string | null>(null);- let source: string | null = null;- try {- const parsed = new URL(url ?? "");- // Keep image requests on Linear's CDNs rather than arbitrary profile URLs.- // Unknown sources fall back to initials.- if (parsed.protocol === "https:" && !parsed.username && !parsed.password- && (!parsed.port || parsed.port === "443")- && ["public.linear.app", "uploads.linear.app"].includes(parsed.hostname)) {- source = parsed.href;- }- } catch { /* Missing or malformed avatars use the same fallback. */ }- return <span aria-hidden className="relative flex h-8 w-8 shrink-0 items-center justify-center overflow-hidden rounded-full bg-muted text-xs font-medium text-muted-foreground">- {name.slice(0, 2).toLocaleUpperCase()}- {source && source !== failedUrl ? <img src={source} alt="" width={32} height={32}- loading="lazy" decoding="async" referrerPolicy="no-referrer"- className="absolute inset-0 h-full w-full object-cover"- onError={() => setFailedUrl(source)} /> : null}- </span>;-}+import { LinearAvatar } from "./LinearAvatar";export function LinearMemberAccess({ organizationId, configScope = "", disabled = false }: {organizationId: string;@@ -76,24 +55,17 @@ export function LinearMemberAccess({ organizationId, configScope = "", disabled<span className="shrink-0">{tx("members.title", "Member access")}</span><span className="flex min-w-0 items-center gap-2"><span role="status" aria-live="polite" className="text-end text-[11px] font-normal text-muted-foreground">- {loading ? payload- ? tx("members.refreshing", "Checking for updates…")- : tx("members.loading", "Finding your teammates…")- : payload ? tx("members.summary", "{{allowed}} of {{total}} enabled", {- allowed: members.filter((member) => member.allowed).length, total: members.length,- }) : null}+ {payload ? !expanded ? tx("members.summary", "{{allowed}} enabled", {+ allowed: members.filter((member) => member.allowed).length,+ }) : null : loading ? tx("members.loading", "Finding your teammates…") : 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></button>+ <span role="status" aria-live="polite" className="sr-only">+ {payload && loading ? tx("members.refreshing", "Checking for updates…") : null}+ </span><DisclosureContent id={panelId} open={expanded} className="space-y-3 pb-2">- <div className="settings-list-inset flex items-center gap-2 text-[12px] leading-5 text-muted-foreground">- <p>{tx("members.intro", "Choose who can use nanobot in Linear. No pairing codes needed.")}</p>- <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.")}>- <Info className="h-4 w-4 shrink-0" aria-hidden />- <span className="sr-only">{tx("members.details", "About member access")}</span>- </SettingsHint>- </div>{payload?.legacy_allow_all ? <p className="settings-list-inset rounded-control bg-muted py-2 text-[12px] leading-5">{tx("members.allowAll", "Advanced settings currently allow all members (*), including new members. Individual off switches still take precedence. Remove * to require approval for new members.")}</p> : null}@@ -110,6 +82,12 @@ 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.")}>+ <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>+ </span>+ </SettingsHint></div>{error ? <p role="alert" className="settings-list-inset break-words text-[12px] leading-5 text-destructive">{error} {tx("members.retry", "Refresh members to check the current state and try again.")}@@ -124,7 +102,7 @@ export function LinearMemberAccess({ organizationId, configScope = "", disabledconst statusId = `${panelId}-${member.id}-status`;return <li key={member.id}><SettingsRow title={<div className="flex min-w-0 items-center gap-3">- <LinearMemberAvatar name={member.name} url={member.avatar_url} />+ <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">diff --git a/nanobot/channels/linear/webui/LinearPanel.tsx b/nanobot/channels/linear/webui/LinearPanel.tsxindex e8f53af45..1f5203812 100644--- a/nanobot/channels/linear/webui/LinearPanel.tsx+++ b/nanobot/channels/linear/webui/LinearPanel.tsx@@ -1,5 +1,5 @@-import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";-import { AlertCircle, Building2, Check, ChevronDown, ExternalLink, Info, Loader2, RefreshCw, Unplug } from "lucide-react";+import { useCallback, useEffect, useId, useMemo, useRef, useState, useSyncExternalStore } from "react";+import { AlertCircle, Check, ChevronDown, ExternalLink, Loader2, RefreshCw, Unplug } from "lucide-react";import { useTranslation } from "react-i18next";import { channelTranslator } from "@/channel-plugins/i18n";@@ -29,7 +29,6 @@ import {} from "@/components/ui/alert-dialog";import { channelValidationStatusClass } from "@/components/settings/channels/ChannelValidationProgress";import { useAutoSave } from "@/components/settings/shared/useAutoSave";-import { SettingsHint } from "@/components/settings/shared/SettingsHint";import { configureChannel, disableNanobotFeature } from "@/lib/api";import { cn } from "@/lib/utils";import { useClient } from "@/providers/ClientProvider";@@ -38,7 +37,9 @@ import { manageLinearWorkspace } from "./api";import type { LinearInstallationSummary } from "./types";import { LinearConnectFlow } from "./LinearConnectFlow";import { LinearMemberAccess } from "./LinearMemberAccess";+import { LinearAvatar } from "./LinearAvatar";import { linearManifestUrl } from "./manifest";+import { linearWorkspaceStore } from "./workspace-store";const PUBLIC_BASE_URL_KEY = "channels.linear.publicBaseUrl";const WEBHOOK_PATH_KEY = "channels.linear.webhookPath";@@ -78,8 +79,13 @@ export function LinearPanel({const [notice, setNotice] = useState<string | null>(null);const [saved, setSaved] = useState(false);const [publicUrlPromptOpen, setPublicUrlPromptOpen] = useState(false);- const [installations, setInstallations] = useState<LinearInstallationSummary[]>([]);- const [loadingInstallations, setLoadingInstallations] = useState(false);+ const workspaceStore = linearWorkspaceStore(client, token, JSON.stringify([+ feature.config_values?.["channels.linear.clientId"],+ feature.config_values?.[PUBLIC_BASE_URL_KEY],+ ]));+ const { installations: cachedInstallations, logos, loading: loadingInstallations,+ error: inspectionError } = useSyncExternalStore(workspaceStore.subscribe, workspaceStore.getSnapshot);+ const installations = cachedInstallations ?? [];const [disconnectingId, setDisconnectingId] = useState<string | null>(null);const [disconnectConfirmId, setDisconnectConfirmId] = useState<string | null>(null);const [workspaceNotice, setWorkspaceNotice] = useState<string | null>(null);@@ -119,20 +125,12 @@ export function LinearPanel({): null;- const loadInstallations = useCallback(async () => {+ const loadInstallations = useCallback(async (force = false) => {if (!credentialsSaved || dirty) return;- setLoadingInstallations(true);setWorkspaceNotice(null);setWorkspaceError(null);- try {- const payload = await manageLinearWorkspace(client, { operation: "inspect" });- setInstallations(payload.installations ?? []);- } catch (err) {- setWorkspaceError((err as Error).message);- } finally {- setLoadingInstallations(false);- }- }, [client, credentialsSaved, dirty]);+ await workspaceStore.load(force);+ }, [workspaceStore, credentialsSaved, dirty]);useEffect(() => {if (feature.runtime_status === "running") void loadInstallations();@@ -148,7 +146,7 @@ export function LinearPanel({organization_id: installation.organization_id,});const remaining = payload.installations ?? [];- setInstallations(remaining);+ workspaceStore.replace(remaining);setWorkspaceNotice(payload.message ?? null);setDisconnectConfirmId(null);if (remaining.length === 0) {@@ -287,6 +285,16 @@ export function LinearPanel({<CredentialForm {...formProps} fields={fields.filter((field) => field.key !== PUBLIC_BASE_URL_KEY)} /><div id={advancedPanelId} hidden={!advancedOpen}><CredentialForm {...formProps} fields={advancedFields} />+ {installations.some(installation => installation.scopes?.length) ? (+ <div className="mt-3 space-y-2 rounded-control bg-muted/45 p-3 text-[12px] text-muted-foreground">+ <p className="font-medium">{tx("custom.workspacesTitle", "Authorized workspaces")}</p>+ {installations.filter(installation => installation.scopes?.length).map(installation => (+ <p key={installation.organization_id} className="break-words">+ {installation.organization_name || installation.organization_id}: {installation.scopes?.join(", ")}+ </p>+ ))}+ </div>+ ) : 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">@@ -307,15 +315,20 @@ export function LinearPanel({<Button type="button" variant="ghost" size="sm"disabled={loadingInstallations || disconnectingId !== null}className="h-8 gap-2 rounded-full text-[12px] text-muted-foreground"- onClick={() => void loadInstallations()}>- <RefreshCw className={cn("h-3.5 w-3.5", loadingInstallations && "animate-spin motion-reduce:animate-none")} aria-hidden />+ onClick={() => void loadInstallations(true)}>+ <RefreshCw className="h-3.5 w-3.5" aria-hidden />{tx("custom.refreshWorkspaces", "Refresh workspaces")}</Button></div><div role="status" aria-live="polite" className="sr-only">{loadingInstallations ? tx("custom.loadingWorkspaces", "Loading workspaces") : ""}</div>- {!loadingInstallations && !workspaceError && installations.length === 0 ? (+ {loadingInstallations && !cachedInstallations ? (+ <p className="px-3 py-2.5 text-[12px] text-muted-foreground">+ {tx("custom.loadingWorkspaces", "Loading workspaces")}+ </p>+ ) : null}+ {!loadingInstallations && !workspaceError && !inspectionError && cachedInstallations?.length === 0 ? (<p className="rounded-control bg-muted/45 px-3 py-2.5 text-[12px] leading-5 text-muted-foreground">{tx("custom.noWorkspaces", "No workspaces are authorized. Connect a workspace to receive Linear agent requests.")}</p>@@ -327,11 +340,9 @@ export function LinearPanel({const name = installation.organization_name || installation.organization_id;const needsAuthorization = installation.authorization_status === "missing_scopes"|| installation.authorization_status === "refresh_required";- const authorizationLabel = (+ const authorizationWarning = needsAuthorization ? (<span className="inline-flex items-center gap-1.5 text-[11px] leading-4 text-muted-foreground">- {needsAuthorization- ? <AlertCircle className="h-3 w-3 shrink-0" aria-hidden />- : <Check className="h-3 w-3 shrink-0" aria-hidden />}+ <AlertCircle className="h-3 w-3 shrink-0" aria-hidden />{installation.authorization_status === "missing_scopes"? tx("custom.missingScopes", "Reconnect to grant: {{scopes}}", {scopes: installation.missing_scopes?.join(", ") || "required scopes",@@ -339,26 +350,17 @@ export function LinearPanel({: installation.authorization_status === "refresh_required"? tx("custom.refreshRequired", "Authorization refresh required"): tx("custom.authorized", "Authorized")}- {installation.scopes?.length ? <Info className="h-3 w-3 shrink-0" aria-hidden /> : null}</span>- );+ ) : null;return (<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">- <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-control bg-muted text-muted-foreground">- <Building2 className="h-4 w-4" aria-hidden />- </span>+ <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>- <div className="mt-1">- {installation.scopes?.length ? (- <SettingsHint description={installation.scopes.join(", ")}>- {authorizationLabel}- </SettingsHint>- ) : authorizationLabel}- </div>+ {authorizationWarning ? <div className="mt-1">{authorizationWarning}</div> : null}</div></div><div className="ms-auto flex flex-wrap items-center gap-2">@@ -389,13 +391,13 @@ export function LinearPanel({feature.config_values?.["channels.linear.clientId"],feature.config_values?.["channels.linear.allowFrom"],])}- disabled={busy || dirty || connecting || loadingInstallations || disconnectingId !== null} />+ disabled={busy || dirty || connecting || disconnectingId !== null} /></article>);})}</div>- {workspaceError ? (- <p role="alert" className="text-[12px] leading-5 text-destructive">{workspaceError}</p>+ {workspaceError || inspectionError ? (+ <p role="alert" className="text-[12px] leading-5 text-destructive">{workspaceError || inspectionError}</p>) : null}{workspaceNotice ? (<p role="status" className="text-[12px] leading-5 text-muted-foreground">@@ -405,7 +407,10 @@ export function LinearPanel({</section>) : null}<LinearConnectFlow token={token} feature={feature}- idleLabel={tx("custom.connect", "Connect Linear")} onFeaturesUpdate={onFeaturesUpdate}+ idleLabel={tx("custom.connect", "Connect Linear")} onFeaturesUpdate={(payload) => {+ onFeaturesUpdate(payload);+ void workspaceStore.load(true);+ }}onActiveChange={setConnecting}renderActions={(connectButton) => (<div className="flex flex-wrap items-center justify-end gap-2 sm:grid sm:grid-cols-[minmax(0,1fr)_auto_auto]">diff --git a/nanobot/channels/linear/webui/api.ts b/nanobot/channels/linear/webui/api.tsindex 0aa35254e..2daaa3d37 100644--- a/nanobot/channels/linear/webui/api.ts+++ b/nanobot/channels/linear/webui/api.ts@@ -1,6 +1,14 @@import { startChannelConnect, type WebUIMutationTransport } from "@/lib/api";-import type { LinearMembersPayload, LinearWorkspacePayload } from "./types";+import type { LinearMembersPayload, LinearWorkspacePayload, LinearWorkspaceProfile } from "./types";++export function getLinearWorkspaceProfile(+ transport: WebUIMutationTransport, organizationId: string,+): Promise<LinearWorkspaceProfile> {+ return startChannelConnect<LinearWorkspaceProfile>(transport, "linear", {+ operation: "workspace_profile", organization_id: organizationId,+ });+}export function manageLinearWorkspace(transport: WebUIMutationTransport,diff --git a/nanobot/channels/linear/webui/locales/en.json b/nanobot/channels/linear/webui/locales/en.jsonindex 2076b1f6d..3cbceb66c 100644--- a/nanobot/channels/linear/webui/locales/en.json+++ b/nanobot/channels/linear/webui/locales/en.json@@ -105,7 +105,7 @@"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}} of {{total}} enabled",+ "summary": "{{allowed}} enabled","loading": "Finding your teammates…","refreshing": "Checking for updates…"}diff --git a/nanobot/channels/linear/webui/locales/es.json b/nanobot/channels/linear/webui/locales/es.jsonindex dc371b584..01b51b50f 100644--- a/nanobot/channels/linear/webui/locales/es.json+++ b/nanobot/channels/linear/webui/locales/es.json@@ -105,7 +105,7 @@"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}} de {{total}} habilitados",+ "summary": "{{allowed}} habilitados","loading": "Buscando a tus compañeros…","refreshing": "Buscando actualizaciones…"}diff --git a/nanobot/channels/linear/webui/locales/fr.json b/nanobot/channels/linear/webui/locales/fr.jsonindex 381544238..1fe537d72 100644--- a/nanobot/channels/linear/webui/locales/fr.json+++ b/nanobot/channels/linear/webui/locales/fr.json@@ -105,7 +105,7 @@"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}} sur {{total}} autorisés",+ "summary": "{{allowed}} autorisés","loading": "Recherche des membres de votre équipe…","refreshing": "Recherche de mises à jour…"}diff --git a/nanobot/channels/linear/webui/locales/id.json b/nanobot/channels/linear/webui/locales/id.jsonindex 730dfbde0..f4d52e286 100644--- a/nanobot/channels/linear/webui/locales/id.json+++ b/nanobot/channels/linear/webui/locales/id.json@@ -105,7 +105,7 @@"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}} dari {{total}} diizinkan",+ "summary": "{{allowed}} diizinkan","loading": "Mencari anggota tim…","refreshing": "Memeriksa pembaruan…"}diff --git a/nanobot/channels/linear/webui/locales/ja.json b/nanobot/channels/linear/webui/locales/ja.jsonindex 83b933294..308357e88 100644--- a/nanobot/channels/linear/webui/locales/ja.json+++ b/nanobot/channels/linear/webui/locales/ja.json@@ -105,7 +105,7 @@"guide": "「メンバーのアクセス」でコードなしで同僚を承認できます。既存の承認はオフにしない限り有効です。Issue の検索・編集には Linear MCP を接続してください。","intro": "Linear で nanobot を使えるメンバーを選びます。ペアリングコードは不要です。","details": "メンバーのアクセスについて",- "summary": "{{total}} 人中 {{allowed}} 人が有効",+ "summary": "{{allowed}} 人が利用可能","loading": "チームメンバーを取得中…","refreshing": "更新を確認中…"}diff --git a/nanobot/channels/linear/webui/locales/ko.json b/nanobot/channels/linear/webui/locales/ko.jsonindex a4683cbfc..5f7887791 100644--- a/nanobot/channels/linear/webui/locales/ko.json+++ b/nanobot/channels/linear/webui/locales/ko.json@@ -105,7 +105,7 @@"guide": "멤버 접근 권한에서 코드 없이 동료를 승인하세요. 기존 승인은 끄지 않는 한 유지됩니다. Issue 검색이나 수정에는 Linear MCP를 연결하세요.","intro": "페어링 코드 없이 Linear에서 nanobot을 사용할 멤버를 선택하세요.","details": "멤버 접근 권한 안내",- "summary": "{{total}}명 중 {{allowed}}명 허용",+ "summary": "{{allowed}}명 사용 가능","loading": "팀 멤버를 불러오는 중…","refreshing": "업데이트 확인 중…"}diff --git a/nanobot/channels/linear/webui/locales/pt-BR.json b/nanobot/channels/linear/webui/locales/pt-BR.jsonindex c8ddb083b..867ea695d 100644--- a/nanobot/channels/linear/webui/locales/pt-BR.json+++ b/nanobot/channels/linear/webui/locales/pt-BR.json@@ -105,7 +105,7 @@"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}} de {{total}} habilitados",+ "summary": "{{allowed}} habilitados","loading": "Buscando membros da equipe…","refreshing": "Verificando atualizações…"}diff --git a/nanobot/channels/linear/webui/locales/vi.json b/nanobot/channels/linear/webui/locales/vi.jsonindex 8f151510f..87820bde3 100644--- a/nanobot/channels/linear/webui/locales/vi.json+++ b/nanobot/channels/linear/webui/locales/vi.json@@ -105,7 +105,7 @@"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": "Đã cho phép {{allowed}} / {{total}} người",+ "summary": "{{allowed}} người được phép","loading": "Đang tìm thành viên nhóm…","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 546e80e3f..23748bf75 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}} / {{total}} 人","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":{"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":"正在检查更新…"}}diff --git a/nanobot/channels/linear/webui/locales/zh-TW.json b/nanobot/channels/linear/webui/locales/zh-TW.jsonindex 10edde4c8..4c6deaef4 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}} / {{total}} 人","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":{"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":"正在檢查更新…"}}diff --git a/nanobot/channels/linear/webui/types.ts b/nanobot/channels/linear/webui/types.tsindex f0a859d58..4ffc4e576 100644--- a/nanobot/channels/linear/webui/types.ts+++ b/nanobot/channels/linear/webui/types.ts@@ -6,6 +6,11 @@ export interface LinearInstallationSummary {missing_scopes?: string[];}+export interface LinearWorkspaceProfile {+ organization_id: string;+ logo_url: string | null;+}+export interface LinearWorkspacePayload {session_id: string;status: "inspected" | "disconnected";diff --git a/nanobot/channels/linear/webui/workspace-store.ts b/nanobot/channels/linear/webui/workspace-store.tsnew file mode 100644index 000000000..9d7e9a341--- /dev/null+++ b/nanobot/channels/linear/webui/workspace-store.ts@@ -0,0 +1,93 @@+import type { WebUIMutationTransport } from "@/lib/api";++import { getLinearWorkspaceProfile, manageLinearWorkspace } from "./api";+import type { LinearInstallationSummary } from "./types";++interface WorkspaceSnapshot {+ installations: LinearInstallationSummary[] | null;+ logos: Record<string, string | null>;+ loading: boolean;+ error: string | null;+}++/** Display cache only: access writes and request admission still validate on the server. */+class LinearWorkspaceStore {+ private snapshot: WorkspaceSnapshot = { installations: null, logos: {}, loading: false, error: null };+ private listeners = new Set<() => void>();+ private version = 0;+ private fetchedAt = 0;++ constructor(private client: WebUIMutationTransport) {}+ getSnapshot = () => this.snapshot;+ subscribe = (listener: () => void) => {+ this.listeners.add(listener);+ return () => { this.listeners.delete(listener); };+ };+ get canEvict() { return !this.listeners.size && !this.snapshot.loading; }+ private update(patch: Partial<WorkspaceSnapshot>) {+ this.snapshot = { ...this.snapshot, ...patch };+ this.listeners.forEach(listener => listener());+ }++ replace = (installations: LinearInstallationSummary[]) => {+ this.version += 1;+ this.fetchedAt = Date.now();+ const ids = new Set(installations.map(item => item.organization_id));+ this.update({ installations, loading: false, error: null,+ logos: Object.fromEntries(Object.entries(this.snapshot.logos).filter(([id]) => ids.has(id))),+ });+ };++ load = async (force = false) => {+ if (this.snapshot.loading) return;+ if (!force && this.snapshot.installations && Date.now() - this.fetchedAt < 60_000) return;+ const version = ++this.version;+ this.update({ loading: true, error: null });+ try {+ const payload = await manageLinearWorkspace(this.client, { operation: "inspect" });+ if (version !== this.version) return;+ this.fetchedAt = Date.now();+ const installations = payload.installations ?? [];+ const ids = new Set(installations.map(item => item.organization_id));+ this.update({ installations, loading: false,+ logos: Object.fromEntries(Object.entries(this.snapshot.logos).filter(([id]) => ids.has(id))),+ });+ // Logos must never delay cards, member lists, or other workspace logos.+ for (const installation of installations) void this.loadLogo(installation.organization_id, version);+ } catch (error) {+ if (version === this.version) this.update({ loading: false,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ };++ private async loadLogo(id: string, version: number) {+ try {+ const profile = await getLinearWorkspaceProfile(this.client, id);+ if (version !== this.version || profile.organization_id !== id+ || !this.snapshot.installations?.some(item => item.organization_id === id)) return;+ this.update({ logos: { ...this.snapshot.logos, [id]: profile.logo_url } });+ } catch { /* Cosmetic metadata failure must not hide a usable workspace. */ }+ }+}++const caches = new WeakMap<WebUIMutationTransport, { token: string; stores: Map<string, LinearWorkspaceStore> }>();++export function linearWorkspaceStore(client: WebUIMutationTransport, token: string, configScope: string) {+ let cache = caches.get(client);+ if (!cache || cache.token !== token) {+ cache = { token, stores: new Map() };+ caches.set(client, cache);+ }+ let store = cache.stores.get(configScope);+ if (!store) {+ if (cache.stores.size >= 16) {+ for (const [key, entry] of cache.stores) {+ if (entry.canEvict) { cache.stores.delete(key); break; }+ }+ }+ store = new LinearWorkspaceStore(client);+ cache.stores.set(configScope, store);+ }+ return store;+}diff --git a/webui/src/tests/linear-avatar.test.tsx b/webui/src/tests/linear-avatar.test.tsxnew file mode 100644index 000000000..f52f41670--- /dev/null+++ b/webui/src/tests/linear-avatar.test.tsx@@ -0,0 +1,29 @@+import { cleanup, fireEvent, render } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";++import { LinearAvatar } from "../../../nanobot/channels/linear/webui/LinearAvatar";++afterEach(cleanup);+describe("Linear workspace logo", () => {+ it("loads a real CDN logo in a fixed-size square and recovers to the workspace 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("referrerpolicy", "no-referrer");+ expect(image.parentElement).toHaveClass("h-9", "w-9", "rounded-control");+ fireEvent.error(image);+ expect(view.container.querySelector("img")).toBeNull();+ expect(view.container.querySelector("svg")).not.toBeNull();+ view.rerender(<LinearAvatar workspace name="nanobot" url="https://uploads.linear.app/org/new-logo" />);+ expect(view.container.querySelector("img")).toHaveAttribute("src", "https://uploads.linear.app/org/new-logo");+ });++ it.each([null, "https://untrusted.example/logo", "http://public.linear.app/logo"])(+ "uses an icon for missing or untrusted logo %s", url => {+ const view = render(<LinearAvatar workspace name="nanobot" url={url} />);+ 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 48261c11b..247dff535 100644--- a/webui/src/tests/linear-member-access.test.tsx+++ b/webui/src/tests/linear-member-access.test.tsx@@ -88,11 +88,14 @@ describe("Linear member access", () => {await openMembers();expect(yongru()).not.toBeChecked();expect(xubin()).toBeChecked();- expect(header()).toHaveTextContent("1 of 2 enabled");+ expect(header()).not.toHaveTextContent("1 enabled");+ fireEvent.click(header());+ expect(header()).toHaveTextContent("1 enabled");+ fireEvent.click(header());expect(requestMutation).toHaveBeenCalledWith("settings.channel.connect.start", {channel: "linear", operation: "members", organization_id: "org-1",}, 150_000);- expect(screen.getByText(/No pairing codes needed/)).toBeVisible();+ expect(screen.queryByText(/No pairing codes needed/)).not.toBeInTheDocument();expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();fireEvent.click(screen.getByRole("button", { name: "About member access" }));expect(await screen.findByRole("tooltip")).toHaveTextContent("does not grant access");diff --git a/webui/src/tests/linear-workspace-store.test.ts b/webui/src/tests/linear-workspace-store.test.tsnew file mode 100644index 000000000..dae7b9ee0--- /dev/null+++ b/webui/src/tests/linear-workspace-store.test.ts@@ -0,0 +1,120 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import type { WebUIMutationTransport } from "@/lib/api";++import { linearWorkspaceStore } from "../../../nanobot/channels/linear/webui/workspace-store";++const installation = { organization_id: "org-1", organization_name: "nanobot" };+const logo = "https://public.linear.app/org-1/logo";+function fixture() {+ const requestMutation = vi.fn<WebUIMutationTransport["requestMutation"]>(async (_action, params) =>+ params?.operation === "inspect"+ ? { installations: [installation] }+ : { organization_id: "org-1", logo_url: logo });+ const client = { requestMutation };+ const store = linearWorkspaceStore(client, "session", "app");+ return { requestMutation, client, store };+}+afterEach(() => vi.restoreAllMocks());++describe("Linear workspace display cache", () => {+ it("publishes the workspace before the logo arrives and caches both on reopen", async () => {+ const { requestMutation, client, store } = fixture();+ let finish!: (value: unknown) => void;+ requestMutation.mockImplementation(async (_action, params) => params?.operation === "inspect"+ ? { installations: [installation] } : new Promise(resolve => { finish = resolve; }));+ await store.load();+ expect(store.getSnapshot().installations).toEqual([installation]);+ expect(store.getSnapshot().loading).toBe(false);+ expect(store.getSnapshot().logos).toEqual({});+ finish({ organization_id: "org-1", logo_url: logo });+ await vi.waitFor(() => expect(store.getSnapshot().logos["org-1"]).toBe(logo));+ const reopened = linearWorkspaceStore(client, "session", "app");+ expect(reopened).toBe(store);+ await reopened.load();+ expect(requestMutation).toHaveBeenCalledTimes(2);+ });++ it("keeps stale workspaces visible while refreshing and after a failed refresh", async () => {+ const { requestMutation, store } = fixture();+ await store.load();+ await vi.waitFor(() => expect(store.getSnapshot().logos["org-1"]).toBe(logo));+ vi.spyOn(Date, "now").mockReturnValue(Date.now() + 61_000);+ let fail!: (error: Error) => void;+ requestMutation.mockImplementationOnce(() => new Promise((_resolve, reject) => { fail = reject; }));+ const refresh = store.load();+ expect(store.getSnapshot().installations).toEqual([installation]);+ expect(store.getSnapshot().logos["org-1"]).toBe(logo);+ expect(store.getSnapshot().loading).toBe(true);+ fail(new Error("Offline"));+ await refresh;+ expect(store.getSnapshot().installations).toEqual([installation]);+ expect(store.getSnapshot().error).toBe("Offline");+ });++ it("does not let an old read resurrect a disconnected workspace", async () => {+ const { requestMutation, store } = fixture();+ let finish!: (value: unknown) => void;+ requestMutation.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ const load = store.load();+ store.replace([]);+ finish({ installations: [installation] });+ await load;+ expect(store.getSnapshot().installations).toEqual([]);+ expect(requestMutation).toHaveBeenCalledTimes(1);+ });++ it("ignores a late logo after disconnect and treats a removed logo as empty", async () => {+ const { requestMutation, store } = fixture();+ let finish!: (value: unknown) => void;+ requestMutation.mockImplementation(async (_action, params) => params?.operation === "inspect"+ ? { installations: [installation] } : new Promise(resolve => { finish = resolve; }));+ await store.load();+ store.replace([]);+ finish({ organization_id: "org-1", logo_url: logo });+ await Promise.resolve();+ expect(store.getSnapshot().logos).toEqual({});+ requestMutation.mockImplementation(async (_action, params) => params?.operation === "inspect"+ ? { installations: [installation] } : { organization_id: "org-1", logo_url: null });+ await store.load(true);+ await vi.waitFor(() => expect(store.getSnapshot().logos).toEqual({ "org-1": null }));+ });++ it("keeps usable workspaces when their optional profile fails", async () => {+ const { requestMutation, store } = fixture();+ requestMutation.mockImplementation(async (_action, params) => {+ if (params?.operation === "inspect") return { installations: [installation] };+ throw new Error("Profile unavailable");+ });+ await store.load();+ await Promise.resolve();+ expect(store.getSnapshot().installations).toEqual([installation]);+ expect(store.getSnapshot().error).toBeNull();+ expect(store.getSnapshot().logos).toEqual({});+ });++ it("isolates gateways, admin sessions, and app configurations", async () => {+ const { client, store } = fixture();+ await store.load();+ expect(linearWorkspaceStore({ requestMutation: client.requestMutation }, "session", "app").getSnapshot().installations).toBeNull();+ expect(linearWorkspaceStore(client, "session", "other-app").getSnapshot().installations).toBeNull();+ expect(linearWorkspaceStore(client, "other-session", "app").getSnapshot().installations).toBeNull();+ });++ it("deduplicates pending inspections and notifies subscribers", async () => {+ const { requestMutation, store } = fixture();+ let finish!: (value: unknown) => void;+ requestMutation.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ const listener = vi.fn();+ const unsubscribe = store.subscribe(listener);+ const pending = store.load();+ await store.load();+ expect(requestMutation).toHaveBeenCalledTimes(1);+ expect(listener).toHaveBeenCalledOnce();+ finish({ installations: [] });+ await pending;+ expect(listener).toHaveBeenCalledTimes(2);+ unsubscribe();+ store.replace([]);+ expect(listener).toHaveBeenCalledTimes(2);+ });+});