Skip to content

Your lightweight open-source personal agent.

fix(linear): refresh setup UI and preserve channel lifecycle state

chengyongru3c7ebd6cd84a
diff --git a/docs/guides/linear-agent.md b/docs/guides/linear-agent.md
index 9400905cb..00aeaa00f 100644
--- a/docs/guides/linear-agent.md
+++ b/docs/guides/linear-agent.md
@@ -131,8 +131,9 @@ In the new Linear app's settings, copy these values:
| Webhook signing secret | **Webhook signing secret** |
Return to **Settings → Channels → Linear**, paste all three values, and select
-**Save settings** again. A successful validation lists the complete webhook and
-OAuth callback URLs.
+**Save settings** again. **Connect Linear** becomes available once the required
+settings are saved. Listener settings, callback paths, and allowed users are in
+**Advanced**; setup guides are in the dialog's **Help** menu.
Treat the Client Secret and Webhook signing secret like passwords. They belong
only in the nanobot configuration and the Linear application settings.
diff --git a/nanobot/channels/linear/config.py b/nanobot/channels/linear/config.py
index 809ffb59e..9ab43a402 100644
--- a/nanobot/channels/linear/config.py
+++ b/nanobot/channels/linear/config.py
@@ -27,9 +27,6 @@ class LinearConfig(Base):
webhook_path: str = DEFAULT_WEBHOOK_PATH
oauth_callback_path: str = DEFAULT_OAUTH_CALLBACK_PATH
allow_from: list[str] = Field(default_factory=list)
- send_progress: bool = True
- send_tool_hints: bool = True
- show_reasoning: bool = True
@field_validator("webhook_path", "oauth_callback_path")
@classmethod
diff --git a/nanobot/channels/linear/connect.py b/nanobot/channels/linear/connect.py
index 8029aedc1..e13ebf2a8 100644
--- a/nanobot/channels/linear/connect.py
+++ b/nanobot/channels/linear/connect.py
@@ -28,6 +28,7 @@ class LinearConnectSession:
state: LinearStateStore
server: LinearServerLease
completion_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
+ result: dict[str, str] | None = None
class LinearConnectStore:
@@ -96,6 +97,8 @@ class LinearConnectStore:
async with session.completion_lock:
if self._sessions.get(session_id) is not session:
return _terminal(session_id, "cancelled", "Linear authorization cancelled.")
+ if session.result is not None:
+ return dict(session.result)
flow = session.flow
if time.monotonic() >= flow.deadline:
await self._close_session(session_id)
@@ -125,14 +128,18 @@ class LinearConnectStore:
)
finally:
await client.close()
- await self._close_session(session_id)
- return {
+ session.result = {
"session_id": session_id,
"status": "succeeded",
"message": "Linear is connected.",
"organization_id": installation.organization_id,
"organization_name": installation.organization_name,
}
+ # A browser may miss the first successful poll while switching tabs.
+ # Retain its result until the session expires, but release the callback listener.
+ OAUTH_FLOWS.remove(flow)
+ await asyncio.to_thread(session.server.close)
+ return dict(session.result)
async def cancel(self, session_id: str) -> dict[str, Any]:
session = self._sessions.get(session_id)
diff --git a/nanobot/channels/linear/manifest.py b/nanobot/channels/linear/manifest.py
index 066f73ee2..dafd71a48 100644
--- a/nanobot/channels/linear/manifest.py
+++ b/nanobot/channels/linear/manifest.py
@@ -7,6 +7,7 @@ from nanobot.channels.linear.validation import validate
from nanobot.channels.plugin import ChannelPlugin
SETUP_SPEC = ChannelSetupSpec(
+ official_url="https://linear.app/settings/api/applications/new",
fields={
"clientId": field(),
"clientSecret": field("secret"),
diff --git a/nanobot/channels/linear/runtime.py b/nanobot/channels/linear/runtime.py
index 0f90a73c7..61d71dcf6 100644
--- a/nanobot/channels/linear/runtime.py
+++ b/nanobot/channels/linear/runtime.py
@@ -9,7 +9,7 @@ from contextlib import suppress
from typing import Any, cast
from nanobot.bus.events import OutboundMessage
-from nanobot.bus.outbound_events import ProgressEvent, RetryWaitEvent, outbound_event_from_message
+from nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent, RetryWaitEvent
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.channels.linear.client import LinearApiError, LinearClient
@@ -43,9 +43,6 @@ class LinearChannel(BaseChannel):
self._reasoning: dict[tuple[str, str], list[str]] = {}
self._routes: dict[str, dict[str, Any]] = {}
- def progress_transport_defaults(self) -> tuple[bool, bool] | None:
- return self.config.send_progress, self.config.send_tool_hints
-
async def start(self) -> None:
self.config.validate_runtime()
if not self._state.has_installations(self.config.client_id):
@@ -93,7 +90,16 @@ class LinearChannel(BaseChannel):
return f"Linear channel failed to start: {error}"
async def send(self, msg: OutboundMessage) -> None:
- event = outbound_event_from_message(msg)
+ event = msg.event
+ if isinstance(event, ContextCompactionEvent):
+ await self._create_activity(
+ msg.chat_id,
+ msg.metadata,
+ {"type": "thought", "body": msg.content},
+ key=f"compaction:{event.compaction_id}:{event.phase}",
+ ephemeral=event.phase == "started",
+ )
+ return
if isinstance(event, ProgressEvent):
if event.tool_events:
for item in event.tool_events:
diff --git a/nanobot/channels/linear/tests/test_linear.py b/nanobot/channels/linear/tests/test_linear.py
index 5cc873603..29291306d 100644
--- a/nanobot/channels/linear/tests/test_linear.py
+++ b/nanobot/channels/linear/tests/test_linear.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import asyncio
import hashlib
import hmac
import http.client
@@ -8,20 +9,27 @@ import socket
import time
from dataclasses import replace
from pathlib import Path
-from typing import Any
+from types import SimpleNamespace
+from typing import Any, Literal
+from unittest.mock import AsyncMock, Mock
from urllib.parse import parse_qs, urlparse
import httpx
import pytest
from nanobot.bus.events import OutboundMessage
-from nanobot.bus.outbound_events import ProgressEvent
+from nanobot.bus.outbound_events import (
+ ContextCompactionEvent,
+ ProgressEvent,
+ outbound_message_for_event,
+)
from nanobot.bus.queue import MessageBus
+from nanobot.channels.linear import connect as linear_connect
from nanobot.channels.linear.client import LinearApiError, LinearClient
from nanobot.channels.linear.config import LinearConfig, validate_public_base_url
from nanobot.channels.linear.oauth import OAUTH_FLOWS, authorization_url
from nanobot.channels.linear.runtime import LinearChannel
-from nanobot.channels.linear.server import acquire_http_server
+from nanobot.channels.linear.server import LinearServerLease, acquire_http_server
from nanobot.channels.linear.state import LinearInstallation, LinearStateStore
@@ -243,6 +251,59 @@ def test_oauth_callback_completes_only_registered_state(tmp_path: Path) -> None:
lease.close()
[email protected]("concurrent", [False, True])
+async def test_successful_authorization_survives_repeated_polls(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, concurrent: bool,
+) -> None:
+ state = LinearStateStore(tmp_path / "linear.sqlite3")
+ lease = Mock(spec=LinearServerLease)
+
+ async def exchange_code(_code: str, _verifier: str) -> LinearInstallation:
+ await asyncio.sleep(0)
+ installation = _installation()
+ state.save_installation(installation)
+ return installation
+
+ client = Mock(spec=LinearClient)
+ client.exchange_code = AsyncMock(side_effect=exchange_code)
+ client.close = AsyncMock()
+ monkeypatch.setattr(linear_connect, "_load_linear_config", _config)
+ monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: state)
+ monkeypatch.setattr(linear_connect, "LinearClient", lambda *_args: client)
+ monkeypatch.setattr(linear_connect, "acquire_http_server", lambda *_args: lease)
+ store = linear_connect.LinearConnectStore()
+ started_at = time.monotonic()
+ started = await store.handle("start", {})
+ session_id = started["session_id"]
+ query = {"session_id": [session_id]}
+ oauth_state = parse_qs(urlparse(started["authorization_url"]).query)["state"][0]
+ try:
+ assert OAUTH_FLOWS.complete(oauth_state, code="authorization-code", error=None)
+ if concurrent:
+ first, repeated = await asyncio.gather(
+ store.handle("poll", query), store.handle("poll", query),
+ )
+ else:
+ first = await store.handle("poll", query)
+ repeated = await store.handle("poll", query)
+ assert first["status"] == "succeeded"
+ assert repeated == first
+ assert (await store.handle("poll", query)) == first
+ assert state.has_installations("client-id")
+ client.exchange_code.assert_awaited_once()
+ lease.close.assert_called_once()
+ assert (await store.handle("poll", {"session_id": ["unknown"]}))["status"] == "expired"
+
+ monkeypatch.setattr(
+ linear_connect, "time",
+ SimpleNamespace(monotonic=lambda: started_at + linear_connect.FLOW_TTL_SECONDS + 10),
+ )
+ assert (await store.handle("poll", query))["status"] == "expired"
+ assert state.has_installations("client-id")
+ finally:
+ await store.cancel(session_id)
+
+
@pytest.mark.asyncio
async def test_oauth_exchange_saves_workspace_app_identity_and_required_scopes(
tmp_path: Path,
@@ -522,6 +583,46 @@ async def test_outbound_response_and_tool_progress_use_native_activity_shapes(
assert client.activities[2]["content"]["action"] == "linear_get_issue"
[email protected]("include_start", [True, False])
[email protected]("phase", ["succeeded", "failed", "cancelled"])
+async def test_compaction_uses_temporary_progress_and_a_persistent_outcome(
+ tmp_path: Path,
+ include_start: bool,
+ phase: Literal["succeeded", "failed", "cancelled"],
+) -> None:
+ channel, client = _runtime(tmp_path)
+ metadata: dict[str, Any] = {
+ "linear": {"organization_id": "org-1", "agent_session_id": "session-1"},
+ }
+ if include_start:
+ await channel.send(outbound_message_for_event(
+ channel="linear",
+ chat_id="session-1",
+ metadata=metadata,
+ event=ContextCompactionEvent(compaction_id="compaction-1", phase="started"),
+ ))
+ assert client.activities[0]["content"] == {
+ "type": "thought", "body": "Compressing context\u2026",
+ }
+ assert client.activities[0]["ephemeral"] is True
+
+ outcome = outbound_message_for_event(
+ channel="linear",
+ chat_id="session-1",
+ metadata=metadata,
+ event=ContextCompactionEvent(compaction_id="compaction-1", phase=phase),
+ )
+ await channel.send(outcome)
+ assert client.activities[-1]["content"] == {"type": "thought", "body": outcome.content}
+ assert client.activities[-1]["ephemeral"] is False
+
+ await channel.send(OutboundMessage(
+ channel="linear", chat_id="session-1", content="Done", metadata=outcome.metadata,
+ ))
+ assert client.activities[-1]["content"] == {"type": "response", "body": "Done"}
+ assert len({activity["activity_id"] for activity in client.activities}) == len(client.activities)
+
+
def test_revocation_removes_workspace_installation(tmp_path: Path) -> None:
channel, _ = _runtime(tmp_path)
channel._process_lifecycle_event( # pyright: ignore[reportPrivateUsage]
diff --git a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx
new file mode 100644
index 000000000..e869b52b3
--- /dev/null
+++ b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx
@@ -0,0 +1,265 @@
+import { channelUiContribution } from "@/channel-plugins/registry";
+import type { ChannelSetupContract, ChannelSetupContractField, NanobotFeatureInfo } from "@/lib/types";
+import {
+ fireEvent,
+ installSettingsViewTestHooks,
+ jsonResponse,
+ renderSettingsView,
+ requestMutationMock,
+ screen,
+ settingsPayload,
+ waitFor,
+} from "@/tests/settings-test-utils";
+
+import { linearManifestUrl } from "../../webui/manifest";
+
+const linearSetup: ChannelSetupContract = {
+ fields: [
+ field("clientId", "string", true),
+ field("clientSecret", "secret", true),
+ field("webhookSigningSecret", "secret", true),
+ field("publicBaseUrl", "string", true),
+ field("host", "string", false, "0.0.0.0"),
+ field("port", "int", false, "3979"),
+ field("webhookPath", "string", false, "/linear/webhook"),
+ field("oauthCallbackPath", "string", false, "/linear/oauth/callback"),
+ field("allowFrom", "list"),
+ ],
+};
+
+const linearFeature: NanobotFeatureInfo = {
+ name: "linear",
+ display_name: "Linear",
+ webui: "webui/index.tsx",
+ type: "channel",
+ enabled: false,
+ configured: false,
+ installed: true,
+ ready: false,
+ status: "not_enabled",
+ install_supported: true,
+ requires_restart: false,
+ setup: linearSetup,
+};
+
+describe("Linear channel UI", () => {
+ installSettingsViewTestHooks();
+
+ it("owns its complete setup panel inside the channel package", () => {
+ const contribution = channelUiContribution("linear", "webui/index.tsx");
+
+ expect(contribution?.Panel).toBeDefined();
+ expect(contribution?.ConnectFlow).toBeUndefined();
+ });
+
+ it("creates a private mention-only Agent app manifest with exact callback routes", () => {
+ const url = new URL(
+ linearManifestUrl(
+ "https://nanobot.example.com",
+ "/linear/webhook",
+ "/linear/oauth/callback",
+ ),
+ );
+ const manifest = JSON.parse(url.searchParams.get("manifest") ?? "{}") as {
+ distribution?: string;
+ oauth?: { redirect_uris?: string[] };
+ webhook?: { url?: string; resourceTypes?: string[] };
+ };
+
+ expect(url.origin + url.pathname).toBe(
+ "https://linear.app/settings/api/applications/new",
+ );
+ expect(manifest.distribution).toBe("private");
+ expect(manifest.oauth?.redirect_uris).toEqual([
+ "https://nanobot.example.com/linear/oauth/callback",
+ ]);
+ expect(manifest.webhook?.url).toBe(
+ "https://nanobot.example.com/linear/webhook",
+ );
+ expect(manifest.webhook?.resourceTypes).toEqual([
+ "AgentSessionEvent",
+ "PermissionChange",
+ "OAuthAuthorization",
+ ]);
+ expect(manifest.webhook?.resourceTypes).not.toContain("Comment");
+ });
+
+ it("saves a public URL before OAuth credentials and reveals the app manifest", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url === "/api/settings") return jsonResponse(settingsPayload());
+ if (url === "/api/settings/cli-apps") {
+ return jsonResponse({ apps: [], installed_count: 0 });
+ }
+ if (url === "/api/settings/mcp-presets") {
+ return jsonResponse({ presets: [], installed_count: 0 });
+ }
+ if (url === "/api/settings/nanobot-features") {
+ return jsonResponse({ features: [linearFeature], enabled_count: 0 });
+ }
+ return { ok: false, status: 404, json: async () => ({}) } as Response;
+ }),
+ );
+ requestMutationMock.mockResolvedValueOnce({
+ name: "linear",
+ saved: true,
+ saved_keys: ["channels.linear.publicBaseUrl"],
+ nanobot_features: {
+ features: [{
+ ...linearFeature,
+ config_values: {
+ "channels.linear.publicBaseUrl": "https://nanobot.example.com",
+ "channels.linear.host": "0.0.0.0",
+ "channels.linear.port": "3979",
+ "channels.linear.webhookPath": "/linear/webhook",
+ "channels.linear.oauthCallbackPath": "/linear/oauth/callback",
+ },
+ configured_fields: ["channels.linear.publicBaseUrl"],
+ }],
+ enabled_count: 0,
+ requires_restart: false,
+ },
+ });
+
+ renderSettingsView({ initialSection: "channels" });
+
+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
+ expect(await screen.findByRole("button", { name: "Connect Linear" })).toBeDisabled();
+ fireEvent.change(await screen.findByPlaceholderText("https://nanobot.example.com"), {
+ target: { value: "https://nanobot.example.com" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: /^Save/ }));
+
+ await waitFor(() =>
+ expect(requestMutationMock).toHaveBeenCalledWith(
+ "settings.channel.configure",
+ expect.objectContaining({
+ name: "linear",
+ values: expect.objectContaining({
+ "channels.linear.publicBaseUrl": "https://nanobot.example.com",
+ }),
+ }),
+ 150_000,
+ ),
+ );
+ expect(
+ await screen.findByText("Settings saved."),
+ ).toBeInTheDocument();
+ expect(
+ await screen.findByRole("link", { name: "Create prefilled Linear app" }),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Connect Linear" })).toBeDisabled();
+ });
+
+ it("preserves saved secrets and gates authorization on saving edited settings", async () => {
+ const feature = savedFeature();
+ mockFeature(feature);
+ requestMutationMock.mockResolvedValueOnce({
+ saved: true,
+ nanobot_features: {
+ features: [{ ...feature, config_values: {
+ ...feature.config_values, "channels.linear.port": "3980",
+ } }],
+ enabled_count: 0,
+ },
+ });
+ renderSettingsView({ initialSection: "channels" });
+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
+ expect(await screen.findByRole("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" }), {
+ target: { value: "3980" },
+ });
+ expect(screen.getByRole("button", { name: "Connect Linear" })).toBeDisabled();
+ fireEvent.click(screen.getByRole("button", { name: /^Save/ }));
+ await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled());
+ const params = requestMutationMock.mock.calls[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");
+ });
+
+ it("keeps an unsaved draft when saving fails without enabling the channel", async () => {
+ mockFeature(savedFeature());
+ requestMutationMock.mockRejectedValueOnce(new Error("Unable to save settings"));
+ renderSettingsView({ initialSection: "channels" });
+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
+ fireEvent.change(await screen.findByRole("textbox", { name: "OAuth client ID" }), {
+ target: { value: "replacement-client" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: /^Save/ }));
+ expect(await screen.findByText("Unable to save settings")).toBeVisible();
+ expect(screen.getByRole("textbox", { name: "OAuth client ID" })).toHaveValue("replacement-client");
+ expect(screen.getByRole("button", { name: "Connect Linear" })).toBeDisabled();
+ expect(requestMutationMock).toHaveBeenCalledTimes(1);
+ expect(requestMutationMock.mock.calls[0][1]).not.toHaveProperty("enable");
+ });
+
+ it("shows the OAuth handoff and cancels a pending authorization", async () => {
+ mockFeature(savedFeature());
+ 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" }));
+ expect(await screen.findByRole("link", { name: "Continue in Linear" })).toHaveAttribute(
+ "href", "https://linear.app/oauth/authorize?client_id=test",
+ );
+ expect(screen.getByRole("textbox", { name: "OAuth client ID" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: /^Save/ })).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Cancel" })).toBeEnabled();
+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
+ expect(await screen.findByText("Authorization stopped.")).toBeVisible();
+ expect(screen.getByRole("textbox", { name: "OAuth client ID" })).toBeEnabled();
+ expect(requestMutationMock).toHaveBeenCalledWith(
+ "settings.channel.connect.cancel", { channel: "linear", session_id: "linear-oauth" }, 20_000,
+ );
+ });
+});
+
+function savedFeature(): NanobotFeatureInfo {
+ return {
+ ...linearFeature,
+ configured_fields: linearSetup.fields.filter((field) => field.required).map((field) => field.key),
+ config_values: {
+ "channels.linear.publicBaseUrl": "https://nanobot.example.com",
+ "channels.linear.clientId": "client-id",
+ "channels.linear.host": "0.0.0.0",
+ "channels.linear.port": "3979",
+ "channels.linear.webhookPath": "/linear/webhook",
+ "channels.linear.oauthCallbackPath": "/linear/oauth/callback",
+ },
+ };
+}
+
+function mockFeature(feature: NanobotFeatureInfo) {
+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url === "/api/settings") return jsonResponse(settingsPayload());
+ if (url === "/api/settings/cli-apps") return jsonResponse({ apps: [], installed_count: 0 });
+ if (url === "/api/settings/mcp-presets") return jsonResponse({ presets: [], installed_count: 0 });
+ if (url === "/api/settings/nanobot-features") return jsonResponse({ features: [feature], enabled_count: 0 });
+ return { ok: false, status: 404, json: async () => ({}) } as Response;
+ }));
+}
+
+function field(
+ name: string,
+ kind: ChannelSetupContractField["kind"],
+ required = false,
+ defaultValue?: string,
+): ChannelSetupContractField {
+ return {
+ key: `channels.linear.${name}`,
+ field: name,
+ kind,
+ choices: [],
+ required,
+ ...(defaultValue === undefined ? {} : { default_value: defaultValue }),
+ };
+}
diff --git a/nanobot/channels/linear/webui/LinearConnectFlow.tsx b/nanobot/channels/linear/webui/LinearConnectFlow.tsx
index 558424cdd..188cc944a 100644
--- a/nanobot/channels/linear/webui/LinearConnectFlow.tsx
+++ b/nanobot/channels/linear/webui/LinearConnectFlow.tsx
@@ -8,36 +8,16 @@ import type { ChannelPluginConnectFlowProps } from "@/channel-plugins/types";
export function LinearConnectFlow({
token,
- feature,
idleLabel,
connectRequestId,
onFeaturesUpdate,
-}: ChannelPluginConnectFlowProps) {
+ onActiveChange,
+}: ChannelPluginConnectFlowProps & { onActiveChange?: (active: boolean) => void }) {
const { t } = useTranslation();
const tx = channelTranslator(t, "linear");
- const publicBaseUrl = feature.config_values?.["channels.linear.publicBaseUrl"]?.replace(/\/$/, "");
- const webhookPath = feature.config_values?.["channels.linear.webhookPath"] || "/linear/webhook";
- const callbackPath = feature.config_values?.["channels.linear.oauthCallbackPath"] || "/linear/oauth/callback";
- const manifestUrl = publicBaseUrl
- ? linearManifestUrl(publicBaseUrl, webhookPath, callbackPath)
- : null;
return (
<div className="mt-3 space-y-3">
- {manifestUrl ? (
- <div className="flex justify-end">
- <Button
- type="button"
- size="sm"
- variant="outline"
- className="h-8 rounded-full px-3 text-[12px] font-semibold"
- onClick={() => window.open(manifestUrl, "_blank", "noopener,noreferrer")}
- >
- <ExternalLink className="mr-1.5 h-3.5 w-3.5" aria-hidden />
- {t("settings.channels.createApp", { defaultValue: "Create prefilled Linear app" })}
- </Button>
- </div>
- ) : null}
<ChannelQrConnectFlow
token={token}
channelName="linear"
@@ -45,6 +25,7 @@ export function LinearConnectFlow({
connectRequestId={connectRequestId}
forceOnRepeat
onFeaturesUpdate={onFeaturesUpdate}
+ onActiveChange={onActiveChange}
labels={{
qrAlt: tx("custom.qrAlt", "Linear authorization QR code"),
scanTitle: tx("custom.authorizeTitle", "Authorize in Linear"),
@@ -62,18 +43,19 @@ export function LinearConnectFlow({
renderPending={({ connect }) => (
<div className="mt-3 space-y-3">
<div className="flex items-center gap-2 text-[12px] text-muted-foreground">
- <span className="h-2 w-2 animate-pulse rounded-full bg-[#5E6AD2]" aria-hidden />
+ <span className="h-2 w-2 animate-pulse rounded-full bg-[#5E6AD2] motion-reduce:animate-none" aria-hidden />
{tx("custom.waiting", "Waiting for Linear authorization...")}
</div>
{connect.qr_url ? (
<Button
- type="button"
+ asChild
size="sm"
className="h-8 rounded-full px-3 text-[12px] font-semibold"
- onClick={() => window.open(connect.qr_url, "_blank", "noopener,noreferrer")}
>
- <ExternalLink className="mr-1.5 h-3.5 w-3.5" aria-hidden />
- {tx("custom.openLinear", "Continue in Linear")}
+ <a 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>
</Button>
) : null}
</div>
@@ -82,37 +64,3 @@ export function LinearConnectFlow({
</div>
);
}
-
-export function linearManifestUrl(
- publicBaseUrl: string,
- webhookPath: string,
- callbackPath: string,
-): string {
- const manifest = {
- $schema: "https://linear.app/.well-known/oauth-app-manifest.schema.json",
- schemaVersion: "1.0.0",
- distribution: "private",
- display: {
- description: "Use nanobot as a native issue agent.",
- },
- developer: { name: "nanobot" },
- oauth: {
- client_name: "nanobot Agent",
- client_uri: publicBaseUrl,
- redirect_uris: [`${publicBaseUrl}${callbackPath}`],
- grant_types: ["authorization_code"],
- },
- webhook: {
- enabled: true,
- url: `${publicBaseUrl}${webhookPath}`,
- resourceTypes: [
- "AgentSessionEvent",
- "PermissionChange",
- "OAuthAuthorization",
- ],
- },
- };
- return `https://linear.app/settings/api/applications/new?${new URLSearchParams({
- manifest: JSON.stringify(manifest),
- })}`;
-}
diff --git a/nanobot/channels/linear/webui/LinearPanel.tsx b/nanobot/channels/linear/webui/LinearPanel.tsx
new file mode 100644
index 000000000..2467ff06b
--- /dev/null
+++ b/nanobot/channels/linear/webui/LinearPanel.tsx
@@ -0,0 +1,203 @@
+import { useEffect, useId, useMemo, useState } from "react";
+import { ChevronDown, ExternalLink, Loader2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { channelTranslator } from "@/channel-plugins/i18n";
+import type { ChannelPluginPanelProps } from "@/channel-plugins/types";
+import {
+ CredentialForm,
+ channelValuesForSubmit,
+ defaultChannelFieldValues,
+} from "@/components/settings/channels/CredentialForm";
+import {
+ CHANNEL_SETUP_PANEL_CLASS_NAME,
+ ChannelLogo,
+ ChannelRuntimeError,
+ channelSetup,
+ localizedChannelDisplayName,
+} from "@/components/settings/channels/ChannelIdentity";
+import { Button } from "@/components/ui/button";
+import { configureChannel } from "@/lib/api";
+import { cn } from "@/lib/utils";
+import { useClient } from "@/providers/ClientProvider";
+
+import { LinearConnectFlow } from "./LinearConnectFlow";
+import { linearManifestUrl } from "./manifest";
+
+const PUBLIC_BASE_URL_KEY = "channels.linear.publicBaseUrl";
+const WEBHOOK_PATH_KEY = "channels.linear.webhookPath";
+const CALLBACK_PATH_KEY = "channels.linear.oauthCallbackPath";
+
+export function LinearPanel({
+ token,
+ feature,
+ actionKey,
+ showBrandLogos,
+ onFeaturesUpdate,
+}: ChannelPluginPanelProps) {
+ const { client } = useClient();
+ const { t, i18n } = useTranslation();
+ const tx = channelTranslator(t, "linear");
+ const displayName = localizedChannelDisplayName(feature, t);
+ const setup = channelSetup(feature, i18n.resolvedLanguage ?? i18n.language);
+ const fields = setup.fields ?? [];
+ const advancedFields = setup.manualFields ?? [];
+ const editableFields = [...fields, ...advancedFields];
+ const configuredFields = useMemo(
+ () => new Set(feature.configured_fields ?? []),
+ [feature.configured_fields],
+ );
+ const savedValuesKey = JSON.stringify([feature.config_values, feature.configured_fields]);
+ const [fieldValues, setFieldValues] = useState<Record<string, string>>(() =>
+ defaultChannelFieldValues(editableFields, feature.config_values),
+ );
+ const [touchedFields, setTouchedFields] = useState<Set<string>>(() => new Set());
+ const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});
+ const [clearedSecrets, setClearedSecrets] = useState<Set<string>>(() => new Set());
+ const [advancedOpen, setAdvancedOpen] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [connecting, setConnecting] = useState(false);
+ const [notice, setNotice] = useState<string | null>(null);
+ const advancedPanelId = useId();
+
+ useEffect(() => {
+ setFieldValues(defaultChannelFieldValues(editableFields, feature.config_values));
+ setTouchedFields(new Set());
+ setVisibleSecrets({});
+ setClearedSecrets(new Set());
+ }, [savedValuesKey, feature.name]);
+
+ const busy = saving || Boolean(actionKey);
+ const savedValues = defaultChannelFieldValues(editableFields, feature.config_values);
+ const dirty = clearedSecrets.size > 0 || editableFields.some(
+ (field) => fieldValues[field.key] !== savedValues[field.key],
+ );
+ 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 savedBaseUrl = feature.config_values?.[PUBLIC_BASE_URL_KEY]?.replace(/\/$/, "");
+ const manifestUrl = savedBaseUrl
+ ? linearManifestUrl(
+ savedBaseUrl,
+ feature.config_values?.[WEBHOOK_PATH_KEY] || "/linear/webhook",
+ feature.config_values?.[CALLBACK_PATH_KEY] || "/linear/oauth/callback",
+ )
+ : null;
+
+ const setFieldValue = (key: string, value: string) => {
+ setFieldValues((current) => ({ ...current, [key]: value }));
+ setTouchedFields((current) => new Set(current).add(key));
+ setNotice(null);
+ };
+
+ const saveSettings = async () => {
+ if (busy || connecting) return;
+ setSaving(true);
+ setNotice(null);
+ try {
+ const payload = await configureChannel(
+ client,
+ feature.name,
+ channelValuesForSubmit(editableFields, fieldValues, touchedFields, clearedSecrets),
+ );
+ if (payload.nanobot_features) onFeaturesUpdate(payload.nanobot_features);
+ setTouchedFields(new Set());
+ setClearedSecrets(new Set());
+ setVisibleSecrets({});
+ setFieldValues((current) => Object.fromEntries(
+ editableFields.map((field) => [field.key, field.secret ? "" : current[field.key] ?? ""]),
+ ));
+ setNotice(t("settings.channels.savedSettings", { defaultValue: "Settings saved." }));
+ } catch (err) {
+ setNotice((err as Error).message);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const formProps = {
+ values: fieldValues,
+ configuredFields,
+ visibleSecrets,
+ clearedSecrets,
+ onChange: setFieldValue,
+ onToggleSecret: (key: string) => {
+ setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }));
+ },
+ onClearSecret: (key: string, clear: boolean) => {
+ setClearedSecrets((current) => {
+ const next = new Set(current);
+ if (clear) next.add(key);
+ else next.delete(key);
+ return next;
+ });
+ },
+ showSecretActions: true,
+ disabled: busy || connecting,
+ compact: true,
+ };
+
+ return (
+ <aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>
+ <form className="flex min-w-0 flex-col gap-4" onSubmit={(event) => {
+ event.preventDefault();
+ void saveSettings();
+ }}>
+ <div className="flex flex-wrap items-center justify-between gap-3 pe-20">
+ <ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
+ <h3 className="sr-only">{displayName}</h3>
+ <button type="button"
+ className="inline-flex min-h-8 items-center gap-1.5 rounded px-1 text-[12px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-offset-2"
+ aria-expanded={advancedOpen} aria-controls={advancedPanelId}
+ onClick={() => setAdvancedOpen((current) => !current)}>
+ {t("settings.channels.advanced", { defaultValue: "Advanced" })}
+ <ChevronDown className={cn(
+ "h-3.5 w-3.5 transition-transform motion-reduce:transition-none",
+ advancedOpen && "rotate-180",
+ )} aria-hidden />
+ </button>
+ </div>
+ <ChannelRuntimeError message={feature.runtime_error} />
+ <CredentialForm {...formProps} fields={fields.filter((field) => field.key === PUBLIC_BASE_URL_KEY)} />
+ <div className="text-[12px] leading-5 text-muted-foreground">
+ {manifestUrl && !manifestDirty ? (
+ <a href={manifestUrl} target="_blank" rel="noreferrer"
+ className="inline-flex min-h-8 items-center gap-1.5 rounded text-foreground underline decoration-border underline-offset-4">
+ {tx("custom.createApp", "Create prefilled Linear app")}
+ <ExternalLink className="h-3.5 w-3.5" aria-hidden />
+ </a>
+ ) : tx("custom.savePublicUrl", "Save the public URL to create a prefilled Linear app.")}
+ </div>
+ <CredentialForm {...formProps} fields={fields.filter((field) => field.key !== PUBLIC_BASE_URL_KEY)} />
+ <div id={advancedPanelId} hidden={!advancedOpen}>
+ <CredentialForm {...formProps} fields={advancedFields} />
+ </div>
+ <div className="flex flex-wrap items-center justify-end gap-3">
+ <Button type="submit" size="sm" variant="secondary" disabled={busy || connecting}
+ className="h-10 rounded-full px-3 text-[12px] font-semibold sm:h-9">
+ {saving ? <Loader2 className="me-1.5 h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden /> : null}
+ {t("settings.actions.save", { defaultValue: "Save settings" })}
+ </Button>
+ </div>
+ <div role="status" aria-live="polite" className={cn(
+ "rounded-control bg-muted/55 px-3 py-2.5 text-[12px] leading-5 text-muted-foreground",
+ !notice && "sr-only",
+ )}>{notice ?? ""}</div>
+ </form>
+ <fieldset disabled={busy || dirty || !credentialsSaved} className="min-w-0">
+ <legend className="sr-only">{tx("custom.authorizeTitle", "Authorize in Linear")}</legend>
+ <LinearConnectFlow token={token} feature={feature}
+ idleLabel={tx("custom.connect", "Connect Linear")} onFeaturesUpdate={onFeaturesUpdate}
+ onActiveChange={setConnecting} />
+ </fieldset>
+ {dirty || !credentialsSaved ? (
+ <p className="mt-2 text-[12px] leading-5 text-muted-foreground">
+ {tx("custom.saveBeforeConnect", "Save the app credentials before authorizing a workspace.")}
+ </p>
+ ) : null}
+ </aside>
+ );
+}
diff --git a/nanobot/channels/linear/webui/index.tsx b/nanobot/channels/linear/webui/index.tsx
index a1d298151..40dc533b6 100644
--- a/nanobot/channels/linear/webui/index.tsx
+++ b/nanobot/channels/linear/webui/index.tsx
@@ -3,14 +3,14 @@ import { lazy } from "react";
import type { ChannelUiContribution } from "@/channel-plugins/types";
import { chatAppGuideUrl } from "@/components/settings/channels/catalog";
-const LinearConnectFlow = lazy(() =>
- import("./LinearConnectFlow").then(({ LinearConnectFlow: component }) => ({
+const LinearPanel = lazy(() =>
+ import("./LinearPanel").then(({ LinearPanel: component }) => ({
default: component,
})),
);
export default {
- ConnectFlow: LinearConnectFlow,
+ Panel: LinearPanel,
presentation: {
displayName: "Linear",
initials: "LI",
diff --git a/nanobot/channels/linear/webui/locales/en.json b/nanobot/channels/linear/webui/locales/en.json
index 846bbabc0..04bcb04b8 100644
--- a/nanobot/channels/linear/webui/locales/en.json
+++ b/nanobot/channels/linear/webui/locales/en.json
@@ -66,6 +66,9 @@
"connecting": "Connecting...",
"reconnect": "Connect another workspace",
"connect": "Connect Linear",
- "openLinear": "Continue in Linear"
+ "openLinear": "Continue in Linear",
+ "createApp": "Create prefilled Linear app",
+ "savePublicUrl": "Save the public URL to create a prefilled Linear app.",
+ "saveBeforeConnect": "Save the app credentials before authorizing a workspace."
}
}
diff --git a/nanobot/channels/linear/webui/locales/es.json b/nanobot/channels/linear/webui/locales/es.json
index eb5deb090..0a4b2d4ec 100644
--- a/nanobot/channels/linear/webui/locales/es.json
+++ b/nanobot/channels/linear/webui/locales/es.json
@@ -66,6 +66,9 @@
"connecting": "Conectando...",
"reconnect": "Conectar otro espacio de trabajo",
"connect": "Conectar Linear",
- "openLinear": "Continuar en Linear"
+ "openLinear": "Continuar en Linear",
+ "createApp": "Crear app de Linear preconfigurada",
+ "savePublicUrl": "Guarda la URL pública para crear una app de Linear preconfigurada.",
+ "saveBeforeConnect": "Guarda las credenciales de la app antes de autorizar un espacio de trabajo."
}
}
diff --git a/nanobot/channels/linear/webui/locales/fr.json b/nanobot/channels/linear/webui/locales/fr.json
index 53742c966..ed2ec43b1 100644
--- a/nanobot/channels/linear/webui/locales/fr.json
+++ b/nanobot/channels/linear/webui/locales/fr.json
@@ -66,6 +66,9 @@
"connecting": "Connexion...",
"reconnect": "Connecter un autre espace de travail",
"connect": "Connecter Linear",
- "openLinear": "Continuer dans Linear"
+ "openLinear": "Continuer dans Linear",
+ "createApp": "Créer une application Linear préremplie",
+ "savePublicUrl": "Enregistrez l’URL publique pour créer une application Linear préremplie.",
+ "saveBeforeConnect": "Enregistrez les identifiants de l’application avant d’autoriser un espace de travail."
}
}
diff --git a/nanobot/channels/linear/webui/locales/id.json b/nanobot/channels/linear/webui/locales/id.json
index d00e5907c..6a51bc160 100644
--- a/nanobot/channels/linear/webui/locales/id.json
+++ b/nanobot/channels/linear/webui/locales/id.json
@@ -66,6 +66,9 @@
"connecting": "Menghubungkan...",
"reconnect": "Hubungkan workspace lain",
"connect": "Hubungkan Linear",
- "openLinear": "Lanjutkan di Linear"
+ "openLinear": "Lanjutkan di Linear",
+ "createApp": "Buat aplikasi Linear yang sudah diisi",
+ "savePublicUrl": "Simpan URL publik untuk membuat aplikasi Linear yang sudah diisi.",
+ "saveBeforeConnect": "Simpan kredensial aplikasi sebelum mengotorisasi ruang kerja."
}
}
diff --git a/nanobot/channels/linear/webui/locales/ja.json b/nanobot/channels/linear/webui/locales/ja.json
index 847799155..dc154eff4 100644
--- a/nanobot/channels/linear/webui/locales/ja.json
+++ b/nanobot/channels/linear/webui/locales/ja.json
@@ -66,6 +66,9 @@
"connecting": "接続しています...",
"reconnect": "別のワークスペースを接続",
"connect": "Linear に接続",
- "openLinear": "Linear で続行"
+ "openLinear": "Linear で続行",
+ "createApp": "入力済みの Linear アプリを作成",
+ "savePublicUrl": "公開 URL を保存すると、入力済みの Linear アプリを作成できます。",
+ "saveBeforeConnect": "ワークスペースを認証する前にアプリの認証情報を保存してください。"
}
}
diff --git a/nanobot/channels/linear/webui/locales/ko.json b/nanobot/channels/linear/webui/locales/ko.json
index 34bf8cbdb..265c28665 100644
--- a/nanobot/channels/linear/webui/locales/ko.json
+++ b/nanobot/channels/linear/webui/locales/ko.json
@@ -66,6 +66,9 @@
"connecting": "연결 중...",
"reconnect": "다른 워크스페이스 연결",
"connect": "Linear 연결",
- "openLinear": "Linear에서 계속"
+ "openLinear": "Linear에서 계속",
+ "createApp": "미리 입력된 Linear 앱 만들기",
+ "savePublicUrl": "공개 URL을 저장하면 미리 입력된 Linear 앱을 만들 수 있습니다.",
+ "saveBeforeConnect": "워크스페이스를 승인하기 전에 앱 자격 증명을 저장하세요."
}
}
diff --git a/nanobot/channels/linear/webui/locales/pt-BR.json b/nanobot/channels/linear/webui/locales/pt-BR.json
index caa01e3d7..bb77f2d35 100644
--- a/nanobot/channels/linear/webui/locales/pt-BR.json
+++ b/nanobot/channels/linear/webui/locales/pt-BR.json
@@ -66,6 +66,9 @@
"connecting": "Conectando...",
"reconnect": "Conectar outro workspace",
"connect": "Conectar Linear",
- "openLinear": "Continuar no Linear"
+ "openLinear": "Continuar no Linear",
+ "createApp": "Criar app Linear pré-preenchido",
+ "savePublicUrl": "Salve a URL pública para criar um app Linear pré-preenchido.",
+ "saveBeforeConnect": "Salve as credenciais do app antes de autorizar um espaço de trabalho."
}
}
diff --git a/nanobot/channels/linear/webui/locales/vi.json b/nanobot/channels/linear/webui/locales/vi.json
index 9f68506d0..1e3128476 100644
--- a/nanobot/channels/linear/webui/locales/vi.json
+++ b/nanobot/channels/linear/webui/locales/vi.json
@@ -66,6 +66,9 @@
"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"
+ "openLinear": "Tiếp tục trong Linear",
+ "createApp": "Tạo ứng dụng Linear điền sẵn",
+ "savePublicUrl": "Lưu URL công khai để tạo ứng dụng Linear điền sẵn.",
+ "saveBeforeConnect": "Lưu thông tin xác thực ứng dụng trước khi cấp quyền cho không gian làm việc."
}
}
diff --git a/nanobot/channels/linear/webui/locales/zh-CN.json b/nanobot/channels/linear/webui/locales/zh-CN.json
index 4326166d5..c79ff8151 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 评论中 @ 应用;进入 Agent Session 后,后续对话无需重复 @。","summary":"创建私有 Linear OAuth 应用,保存凭据和公网地址,再授权工作区。新会话必须显式 @ 应用,普通评论会被忽略。","steps":["用稳定的 HTTPS 地址暴露此 nanobot 实例(可以使用隧道)。","在 Linear 创建私有 OAuth 应用,启用 read、write 和 app:mentionable;不要启用 app:assignable。","将应用 webhook 订阅 AgentSessionEvent、PermissionChange 和 OAuthAuthorization,并填写生成的 webhook 地址。","保存设置、通过 OAuth 连接工作区,然后在 issue 中 @ 应用。"],"fields":{"clientId":{"label":"OAuth Client ID","placeholder":"Linear OAuth Client ID","help":"从 Linear 私有 OAuth 应用中复制。"},"clientSecret":{"label":"OAuth Client Secret","placeholder":"••••••","help":"只保存在此 nanobot 实例中。"},"webhookSigningSecret":{"label":"Webhook 签名密钥","placeholder":"••••••","help":"在解析 webhook 内容前验证 Linear-Signature。"},"publicBaseUrl":{"label":"公网 HTTPS 地址","placeholder":"https://nanobot.example.com","help":"稳定且能转发到下方监听端口的 HTTPS 源地址,不要包含路径。"},"host":{"label":"监听地址","placeholder":"0.0.0.0"},"port":{"label":"监听端口","placeholder":"3979"},"webhookPath":{"label":"Webhook 路径","placeholder":"/linear/webhook"},"oauthCallbackPath":{"label":"OAuth 回调路径","placeholder":"/linear/oauth/callback"},"allowFrom":{"label":"允许的 Linear 用户","placeholder":"用逗号分隔 Linear 用户 ID","help":"留空使用 nanobot 配对;填写 * 允许已连接工作区内的所有用户。"}}},"custom":{"qrAlt":"Linear 授权二维码","authorizeTitle":"在 Linear 中授权","authorizeDescription":"在当前浏览器打开 Linear 或扫描二维码;授权后 nanobot 会自动启用 channel。","waiting":"正在等待 Linear 授权……","connected":"Linear 已连接。","stopped":"授权已停止。","connecting":"正在连接……","reconnect":"连接另一个工作区","connect":"连接 Linear","openLinear":"前往 Linear"}}
+{"description":"通过 Linear 原生 Agent Session 在 issue 中使用 nanobot。","requirements":"一个私有 Linear OAuth 应用和稳定的公网 HTTPS 回调地址","setup":{"docsLabel":"打开 Linear 配置指南","officialLabel":"创建 Linear OAuth 应用","tryIt":"在 issue 评论中 @ 应用;进入 Agent Session 后,后续对话无需重复 @。","summary":"创建私有 Linear OAuth 应用,保存凭据和公网地址,再授权工作区。新会话必须显式 @ 应用,普通评论会被忽略。","steps":["用稳定的 HTTPS 地址暴露此 nanobot 实例(可以使用隧道)。","在 Linear 创建私有 OAuth 应用,启用 read、write 和 app:mentionable;不要启用 app:assignable。","将应用 webhook 订阅 AgentSessionEvent、PermissionChange 和 OAuthAuthorization,并填写生成的 webhook 地址。","保存设置、通过 OAuth 连接工作区,然后在 issue 中 @ 应用。"],"fields":{"clientId":{"label":"OAuth Client ID","placeholder":"Linear OAuth Client ID","help":"从 Linear 私有 OAuth 应用中复制。"},"clientSecret":{"label":"OAuth Client Secret","placeholder":"••••••","help":"只保存在此 nanobot 实例中。"},"webhookSigningSecret":{"label":"Webhook 签名密钥","placeholder":"••••••","help":"在解析 webhook 内容前验证 Linear-Signature。"},"publicBaseUrl":{"label":"公网 HTTPS 地址","placeholder":"https://nanobot.example.com","help":"稳定且能转发到下方监听端口的 HTTPS 源地址,不要包含路径。"},"host":{"label":"监听地址","placeholder":"0.0.0.0"},"port":{"label":"监听端口","placeholder":"3979"},"webhookPath":{"label":"Webhook 路径","placeholder":"/linear/webhook"},"oauthCallbackPath":{"label":"OAuth 回调路径","placeholder":"/linear/oauth/callback"},"allowFrom":{"label":"允许的 Linear 用户","placeholder":"用逗号分隔 Linear 用户 ID","help":"留空使用 nanobot 配对;填写 * 允许已连接工作区内的所有用户。"}}},"custom":{"qrAlt":"Linear 授权二维码","authorizeTitle":"在 Linear 中授权","authorizeDescription":"在当前浏览器打开 Linear 或扫描二维码;授权后 nanobot 会自动启用 channel。","waiting":"正在等待 Linear 授权……","connected":"Linear 已连接。","stopped":"授权已停止。","connecting":"正在连接……","reconnect":"连接另一个工作区","connect":"连接 Linear","openLinear":"前往 Linear","createApp":"创建预填的 Linear 应用","savePublicUrl":"保存公网地址后,即可创建预填的 Linear 应用。","saveBeforeConnect":"请先保存应用凭据,再授权工作区。"}}
diff --git a/nanobot/channels/linear/webui/locales/zh-TW.json b/nanobot/channels/linear/webui/locales/zh-TW.json
index fefe5e27a..477ffb1b7 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 評論中 @ 應用程式;進入 Agent Session 後,後續對話無需重複 @。","summary":"建立私有 Linear OAuth 應用程式,儲存憑證和公網網址,再授權工作區。新會話必須明確 @ 應用程式,普通評論會被忽略。","steps":["用穩定的 HTTPS 網址公開此 nanobot 實例(可以使用隧道)。","在 Linear 建立私有 OAuth 應用程式,啟用 read、write 和 app:mentionable;不要啟用 app:assignable。","將應用程式 webhook 訂閱 AgentSessionEvent、PermissionChange 和 OAuthAuthorization,並填入產生的 webhook 網址。","儲存設定、透過 OAuth 連接工作區,然後在 issue 中 @ 應用程式。"],"fields":{"clientId":{"label":"OAuth Client ID","placeholder":"Linear OAuth Client ID","help":"從 Linear 私有 OAuth 應用程式中複製。"},"clientSecret":{"label":"OAuth Client Secret","placeholder":"••••••","help":"只儲存在此 nanobot 實例中。"},"webhookSigningSecret":{"label":"Webhook 簽署密鑰","placeholder":"••••••","help":"在解析 webhook 內容前驗證 Linear-Signature。"},"publicBaseUrl":{"label":"公網 HTTPS 網址","placeholder":"https://nanobot.example.com","help":"穩定且能轉送到下方監聽連接埠的 HTTPS 來源網址,不要包含路徑。"},"host":{"label":"監聽位址","placeholder":"0.0.0.0"},"port":{"label":"監聽連接埠","placeholder":"3979"},"webhookPath":{"label":"Webhook 路徑","placeholder":"/linear/webhook"},"oauthCallbackPath":{"label":"OAuth 回呼路徑","placeholder":"/linear/oauth/callback"},"allowFrom":{"label":"允許的 Linear 使用者","placeholder":"以逗號分隔 Linear 使用者 ID","help":"留空使用 nanobot 配對;填寫 * 允許已連接工作區內的所有使用者。"}}},"custom":{"qrAlt":"Linear 授權 QR code","authorizeTitle":"在 Linear 中授權","authorizeDescription":"在目前瀏覽器開啟 Linear 或掃描 QR code;授權後 nanobot 會自動啟用 channel。","waiting":"正在等待 Linear 授權……","connected":"Linear 已連接。","stopped":"授權已停止。","connecting":"正在連接……","reconnect":"連接另一個工作區","connect":"連接 Linear","openLinear":"前往 Linear"}}
+{"description":"透過 Linear 原生 Agent Session 在 issue 中使用 nanobot。","requirements":"一個私有 Linear OAuth 應用程式和穩定的公網 HTTPS 回呼網址","setup":{"docsLabel":"開啟 Linear 設定指南","officialLabel":"建立 Linear OAuth 應用程式","tryIt":"在 issue 評論中 @ 應用程式;進入 Agent Session 後,後續對話無需重複 @。","summary":"建立私有 Linear OAuth 應用程式,儲存憑證和公網網址,再授權工作區。新會話必須明確 @ 應用程式,普通評論會被忽略。","steps":["用穩定的 HTTPS 網址公開此 nanobot 實例(可以使用隧道)。","在 Linear 建立私有 OAuth 應用程式,啟用 read、write 和 app:mentionable;不要啟用 app:assignable。","將應用程式 webhook 訂閱 AgentSessionEvent、PermissionChange 和 OAuthAuthorization,並填入產生的 webhook 網址。","儲存設定、透過 OAuth 連接工作區,然後在 issue 中 @ 應用程式。"],"fields":{"clientId":{"label":"OAuth Client ID","placeholder":"Linear OAuth Client ID","help":"從 Linear 私有 OAuth 應用程式中複製。"},"clientSecret":{"label":"OAuth Client Secret","placeholder":"••••••","help":"只儲存在此 nanobot 實例中。"},"webhookSigningSecret":{"label":"Webhook 簽署密鑰","placeholder":"••••••","help":"在解析 webhook 內容前驗證 Linear-Signature。"},"publicBaseUrl":{"label":"公網 HTTPS 網址","placeholder":"https://nanobot.example.com","help":"穩定且能轉送到下方監聽連接埠的 HTTPS 來源網址,不要包含路徑。"},"host":{"label":"監聽位址","placeholder":"0.0.0.0"},"port":{"label":"監聽連接埠","placeholder":"3979"},"webhookPath":{"label":"Webhook 路徑","placeholder":"/linear/webhook"},"oauthCallbackPath":{"label":"OAuth 回呼路徑","placeholder":"/linear/oauth/callback"},"allowFrom":{"label":"允許的 Linear 使用者","placeholder":"以逗號分隔 Linear 使用者 ID","help":"留空使用 nanobot 配對;填寫 * 允許已連接工作區內的所有使用者。"}}},"custom":{"qrAlt":"Linear 授權 QR code","authorizeTitle":"在 Linear 中授權","authorizeDescription":"在目前瀏覽器開啟 Linear 或掃描 QR code;授權後 nanobot 會自動啟用 channel。","waiting":"正在等待 Linear 授權……","connected":"Linear 已連接。","stopped":"授權已停止。","connecting":"正在連接……","reconnect":"連接另一個工作區","connect":"連接 Linear","openLinear":"前往 Linear","createApp":"建立預填的 Linear 應用程式","savePublicUrl":"儲存公開網址後,即可建立預填的 Linear 應用程式。","saveBeforeConnect":"請先儲存應用程式憑證,再授權工作區。"}}
diff --git a/nanobot/channels/linear/webui/manifest.ts b/nanobot/channels/linear/webui/manifest.ts
new file mode 100644
index 000000000..8844585c3
--- /dev/null
+++ b/nanobot/channels/linear/webui/manifest.ts
@@ -0,0 +1,33 @@
+export function linearManifestUrl(
+ publicBaseUrl: string,
+ webhookPath: string,
+ callbackPath: string,
+): string {
+ const manifest = {
+ $schema: "https://linear.app/.well-known/oauth-app-manifest.schema.json",
+ schemaVersion: "1.0.0",
+ distribution: "private",
+ display: {
+ description: "Use nanobot as a native issue agent.",
+ },
+ developer: { name: "nanobot" },
+ oauth: {
+ client_name: "nanobot Agent",
+ client_uri: publicBaseUrl,
+ redirect_uris: [`${publicBaseUrl}${callbackPath}`],
+ grant_types: ["authorization_code"],
+ },
+ webhook: {
+ enabled: true,
+ url: `${publicBaseUrl}${webhookPath}`,
+ resourceTypes: [
+ "AgentSessionEvent",
+ "PermissionChange",
+ "OAuthAuthorization",
+ ],
+ },
+ };
+ return `https://linear.app/settings/api/applications/new?${new URLSearchParams({
+ manifest: JSON.stringify(manifest),
+ })}`;
+}
diff --git a/webui/eslint.config.js b/webui/eslint.config.js
index 1107c78ed..f422efad8 100644
--- a/webui/eslint.config.js
+++ b/webui/eslint.config.js
@@ -13,7 +13,11 @@ export default tseslint.config(
js.configs.recommended,
...tseslint.configs.recommended,
{
- files: ["webui/src/**/*.{ts,tsx}", "nanobot/channels/*/webui/**/*.{ts,tsx}"],
+ files: [
+ "webui/src/**/*.{ts,tsx}",
+ "nanobot/channels/*/webui/**/*.{ts,tsx}",
+ "nanobot/channels/*/tests/webui/**/*.{ts,tsx}",
+ ],
languageOptions: {
ecmaVersion: 2020,
globals: {
diff --git a/webui/package.json b/webui/package.json
index 8ba16f05e..0ad328f2e 100644
--- a/webui/package.json
+++ b/webui/package.json
@@ -10,7 +10,7 @@
"test": "vitest run",
"test:coverage": "vitest run --coverage",
"test:watch": "vitest",
- "lint": "cd .. && eslint --config webui/eslint.config.js webui/src \"nanobot/channels/*/webui/**/*.{ts,tsx}\" --max-warnings 0"
+ "lint": "cd .. && eslint --config webui/eslint.config.js webui/src \"nanobot/channels/*/webui/**/*.{ts,tsx}\" \"nanobot/channels/*/tests/webui/**/*.{ts,tsx}\" --max-warnings 0"
},
"dependencies": {
"@radix-ui/react-alert-dialog": "^1.1.4",
diff --git a/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx b/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx
index a3edb4bfc..a14e35400 100644
--- a/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx
+++ b/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx
@@ -51,6 +51,7 @@ export function ChannelQrConnectFlow({
renderPending,
resolveMessage,
suppressSucceeded = false,
+ onActiveChange,
}: {
token: string;
channelName: string;
@@ -66,6 +67,7 @@ export function ChannelQrConnectFlow({
renderPending?: (context: ChannelQrConnectPendingContext) => ReactNode;
resolveMessage?: (payload: ChannelConnectPayload) => string | undefined;
suppressSucceeded?: boolean;
+ onActiveChange?: (active: boolean) => void;
}) {
const { client } = useClient();
const pageVisible = usePageVisibility();
@@ -82,6 +84,9 @@ export function ChannelQrConnectFlow({
const pending = connect?.status === "pending";
const succeeded = connect?.status === "succeeded";
const canStart = !pending && !busy;
+ useEffect(() => {
+ onActiveChange?.(pending || busy);
+ }, [pending, busy, onActiveChange]);
const pollingPaused = Boolean(connect && pausePolling?.(connect));
const displayMessage = connect
? resolveMessage?.(connect) ?? (connect.message ? channelValidationMessage(connect.message, t) : undefined)
diff --git a/webui/src/tests/channel-ui-registry.test.ts b/webui/src/tests/channel-ui-registry.test.ts
index 1d6b1d669..fc83dfc58 100644
--- a/webui/src/tests/channel-ui-registry.test.ts
+++ b/webui/src/tests/channel-ui-registry.test.ts
@@ -13,6 +13,7 @@ import {
describe("channel UI contributions", () => {
it("selects channel-owned UI only through the backend manifest entry", () => {
expect(channelUiContribution("feishu", "webui/index.tsx")?.Panel).toBeDefined();
+ expect(channelUiContribution("linear", "webui/index.tsx")?.Panel).toBeDefined();
expect(channelUiContribution("weixin", "webui/index.tsx")?.ConnectFlow).toBeDefined();
expect(channelUiContribution("feishu", undefined)).toBeUndefined();
expect(channelUiContribution("feishu", "webui/missing.tsx")).toBeUndefined();
@@ -20,7 +21,7 @@ describe("channel UI contributions", () => {
const registrations = registeredChannelUiContributions();
const channels = registrations.map((entry) => entry.channel);
- expect(channels).toEqual(expect.arrayContaining(["feishu", "weixin"]));
+ expect(channels).toEqual(expect.arrayContaining(["feishu", "linear", "weixin"]));
expect(new Set(channels).size).toBe(channels.length);
expect(registrations.every((entry) => /^webui\/index\.tsx?$/.test(entry.webui))).toBe(true);
expect(channelUiContribution("slack", "webui/index.ts")?.presentation.displayName).toBe("Slack");
diff --git a/webui/src/tests/linear-channel-ui.test.ts b/webui/src/tests/linear-channel-ui.test.ts
deleted file mode 100644
index 895f4c629..000000000
--- a/webui/src/tests/linear-channel-ui.test.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { linearManifestUrl } from "../../../nanobot/channels/linear/webui/LinearConnectFlow";
-
-describe("Linear channel UI", () => {
- it("creates a private mention-only Agent app manifest with exact callback routes", () => {
- const url = new URL(
- linearManifestUrl(
- "https://nanobot.example.com",
- "/linear/webhook",
- "/linear/oauth/callback",
- ),
- );
- const manifest = JSON.parse(url.searchParams.get("manifest") ?? "{}") as {
- distribution?: string;
- oauth?: { redirect_uris?: string[] };
- webhook?: { url?: string; resourceTypes?: string[] };
- };
-
- expect(url.origin + url.pathname).toBe(
- "https://linear.app/settings/api/applications/new",
- );
- expect(manifest.distribution).toBe("private");
- expect(manifest.oauth?.redirect_uris).toEqual([
- "https://nanobot.example.com/linear/oauth/callback",
- ]);
- expect(manifest.webhook?.url).toBe(
- "https://nanobot.example.com/linear/webhook",
- );
- expect(manifest.webhook?.resourceTypes).toEqual([
- "AgentSessionEvent",
- "PermissionChange",
- "OAuthAuthorization",
- ]);
- expect(manifest.webhook?.resourceTypes).not.toContain("Comment");
- });
-});
diff --git a/webui/src/tests/settings-channels.test.tsx b/webui/src/tests/settings-channels.test.tsx
index a53d2239f..a241bd551 100644
--- a/webui/src/tests/settings-channels.test.tsx
+++ b/webui/src/tests/settings-channels.test.tsx
@@ -31,7 +31,7 @@ function channelSetupField(
}
function channelSetupContract(
- channel: "discord" | "email" | "feishu" | "linear" | "matrix" | "qq",
+ channel: "discord" | "email" | "feishu" | "matrix" | "qq",
): ChannelSetupContract {
const field = (
name: string,
@@ -108,22 +108,6 @@ function channelSetupContract(
{ alternatives: [["channels.feishu.appSecret"]] },
],
};
- case "linear":
- return {
- fields: [
- field("clientId", "string", { required: true }),
- field("clientSecret", "secret", { required: true }),
- field("webhookSigningSecret", "secret", { required: true }),
- field("publicBaseUrl", "string", { required: true }),
- field("host", "string", { defaultValue: "0.0.0.0" }),
- field("port", "int", { defaultValue: "3979" }),
- field("webhookPath", "string", { defaultValue: "/linear/webhook" }),
- field("oauthCallbackPath", "string", {
- defaultValue: "/linear/oauth/callback",
- }),
- field("allowFrom", "list"),
- ],
- };
case "matrix":
return {
official_url: "https://matrix.org/ecosystem/clients/",
@@ -875,103 +859,6 @@ describe("Settings channels", () => {
expect(await screen.findByText("Scan with Feishu")).toBeInTheDocument();
});
- it("saves a Linear public URL before OAuth credentials and reveals the app manifest", async () => {
- const linearFeature = {
- name: "linear",
- display_name: "Linear",
- webui: "webui/index.tsx",
- type: "channel",
- enabled: false,
- configured: false,
- installed: true,
- ready: false,
- status: "not_enabled",
- install_supported: true,
- requires_restart: false,
- setup: channelSetupContract("linear"),
- };
- vi.stubGlobal(
- "fetch",
- vi.fn(async (input: RequestInfo | URL) => {
- const url = String(input);
- if (url === "/api/settings") return jsonResponse(settingsPayload());
- if (url === "/api/settings/cli-apps") {
- return jsonResponse({ apps: [], installed_count: 0 });
- }
- if (url === "/api/settings/mcp-presets") {
- return jsonResponse({ presets: [], installed_count: 0 });
- }
- if (url === "/api/settings/nanobot-features") {
- return jsonResponse({ features: [linearFeature], enabled_count: 0 });
- }
- return { ok: false, status: 404, json: async () => ({}) } as Response;
- }),
- );
- requestMutationMock
- .mockResolvedValueOnce({
- name: "linear",
- status: "needs_setup",
- checks: [],
- missing_fields: [
- "channels.linear.clientId",
- "channels.linear.clientSecret",
- "channels.linear.webhookSigningSecret",
- ],
- can_enable: false,
- requires_restart: false,
- message: "Missing Linear credentials.",
- })
- .mockResolvedValueOnce({
- name: "linear",
- saved: true,
- saved_keys: ["channels.linear.publicBaseUrl"],
- nanobot_features: {
- features: [{
- ...linearFeature,
- config_values: {
- "channels.linear.publicBaseUrl": "https://nanobot.example.com",
- "channels.linear.host": "0.0.0.0",
- "channels.linear.port": "3979",
- "channels.linear.webhookPath": "/linear/webhook",
- "channels.linear.oauthCallbackPath": "/linear/oauth/callback",
- },
- configured_fields: ["channels.linear.publicBaseUrl"],
- }],
- enabled_count: 0,
- requires_restart: false,
- },
- });
-
- renderSettingsView({ initialSection: "channels" });
-
- expect(await screen.findByRole("button", { name: "View Linear settings" })).toBeInTheDocument();
- fireEvent.change(screen.getByPlaceholderText("https://nanobot.example.com"), {
- target: { value: "https://nanobot.example.com" },
- });
- fireEvent.click(screen.getByRole("button", { name: "Save" }));
-
- await waitFor(() =>
- expect(requestMutationMock).toHaveBeenCalledWith(
- "settings.channel.configure",
- expect.objectContaining({
- name: "linear",
- values: expect.objectContaining({
- "channels.linear.publicBaseUrl": "https://nanobot.example.com",
- }),
- }),
- 150_000,
- ),
- );
- expect(
- await screen.findByText(
- "Partial settings saved. Complete the required fields before connecting.",
- ),
- ).toBeInTheDocument();
- expect(
- await screen.findByRole("button", { name: "Create prefilled Linear app" }),
- ).toBeInTheDocument();
- });
-
it("enables configured Feishu assistant without starting a new connect flow", async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
diff --git a/webui/src/tests/settings-test-utils.tsx b/webui/src/tests/settings-test-utils.tsx
index 7c987b542..9075b071b 100644
--- a/webui/src/tests/settings-test-utils.tsx
+++ b/webui/src/tests/settings-test-utils.tsx
@@ -5,6 +5,8 @@ import { SettingsView } from "@/components/settings/SettingsView";
import { ClientProvider } from "@/providers/ClientProvider";
import type { SettingsPayload } from "@/lib/types";
+export { fireEvent, screen, waitFor } from "@testing-library/react";
+
export const requestMutationMock = vi.fn();
export function jsonResponse(body: unknown): Response {
diff --git a/webui/tsconfig.build.json b/webui/tsconfig.build.json
index 756703b27..ceaac3a73 100644
--- a/webui/tsconfig.build.json
+++ b/webui/tsconfig.build.json
@@ -3,5 +3,5 @@
"compilerOptions": {
"types": ["node", "vite/client"]
},
- "exclude": ["src/tests/**"]
+ "exclude": ["src/tests/**", "../nanobot/channels/*/tests/webui/**"]
}
diff --git a/webui/tsconfig.json b/webui/tsconfig.json
index 8f46ecad2..5d964a164 100644
--- a/webui/tsconfig.json
+++ b/webui/tsconfig.json
@@ -35,6 +35,8 @@
"include": [
"src",
"../nanobot/channels/*/webui/**/*.ts",
- "../nanobot/channels/*/webui/**/*.tsx"
+ "../nanobot/channels/*/webui/**/*.tsx",
+ "../nanobot/channels/*/tests/webui/**/*.ts",
+ "../nanobot/channels/*/tests/webui/**/*.tsx"
]
}
diff --git a/webui/vite.config.ts b/webui/vite.config.ts
index 5f2cd3be0..af860645c 100644
--- a/webui/vite.config.ts
+++ b/webui/vite.config.ts
@@ -169,6 +169,10 @@ export default defineConfig(({ mode }) => {
environment: "happy-dom",
globals: true,
setupFiles: ["./src/tests/setup.ts"],
+ include: [
+ "src/**/*.{test,spec}.{ts,tsx}",
+ "../nanobot/channels/*/tests/webui/**/*.{test,spec}.{ts,tsx}",
+ ],
coverage: {
provider: "v8",
include: ["src/**/*.{ts,tsx}"],