Skip to content

Your lightweight open-source personal agent.

fix(linear): autosave setup and restore connection status

chengyongru4f85b78c671e
diff --git a/docs/chat-apps.md b/docs/chat-apps.md
index e87dcac8a..9de693f02 100644
--- a/docs/chat-apps.md
+++ b/docs/chat-apps.md
@@ -106,7 +106,7 @@ If `nanobot channels status` does not show the channel as enabled, the config sn
| **Microsoft Teams** | App ID + App Password + public HTTPS endpoint |
| **Mochat** | Claw token (auto-setup available) |
| **Signal** | signal-cli daemon + phone number |
-| **Linear** | Private OAuth app + public HTTPS callback URL |
+| **Linear** | Private OAuth app + public HTTPS callback and webhook URLs |
<details id="linear">
<summary><b>Linear</b></summary>
@@ -116,15 +116,17 @@ by explicitly mentioning the installed nanobot app in an issue. Follow-up prompt
inside that Agent Session continue the same nanobot session without another
mention. Ordinary issue comments do not invoke nanobot.
-The native Agent API is webhook-based. Linear must reach a stable HTTPS URL, but
-the machine running nanobot does not need its own public IP address: a reverse
-proxy, Cloudflare Tunnel, Tailscale Funnel, or another HTTPS tunnel can forward
-the public URL to nanobot's local listener.
-
-The recommended setup is **Settings → Channels → Linear**. Save the public URL
-first to reveal a prefilled private OAuth app link, create the app, copy its Client
-ID, Client Secret, and Webhook Signing Secret back into nanobot, save again, then
-choose **Connect Linear**. OAuth requests only `read`, `write`, and
+The native Agent API is webhook-based. Linear must reach a public HTTPS URL.
+An HTTPS tunnel can forward requests to nanobot's local listener without a public
+IP; a publicly reachable server can use a reverse proxy. Use a fixed hostname for
+ongoing use. Temporary tunnels also work for testing, but a hostname change
+requires updating nanobot's public URL and the app's callback and webhook URLs.
+
+The recommended setup is **Settings → Channels → Linear**. Enter the public URL
+and wait for automatic saving, select **Create prefilled Linear app**, create the
+app, then copy its Client ID, Client Secret, and Webhook Signing Secret back into
+nanobot. Leave each secret field to save it. Once the settings are saved, choose
+**Connect Linear**. OAuth requests only `read`, `write`, and
`app:mentionable`; it deliberately does not request `app:assignable` so a new task
must begin with an @mention.
diff --git a/docs/guides/linear-agent.md b/docs/guides/linear-agent.md
index 00aeaa00f..3121b0492 100644
--- a/docs/guides/linear-agent.md
+++ b/docs/guides/linear-agent.md
@@ -35,7 +35,7 @@ Prepare these four things:
|---|---|
| Working nanobot | `nanobot agent -m "Hello"` returns a response |
| Linear access | Permission to create a private OAuth app; a workspace admin must approve its installation |
-| Public HTTPS origin | A stable address such as `https://nanobot.example.com` |
+| Public HTTPS origin | A reachable address such as `https://nanobot.example.com`; use a fixed hostname for ongoing use |
| Local route | The public address forwards to nanobot's Linear listener, which defaults to port `3979` |
The public address is an **origin**, not a complete endpoint. Enter
@@ -56,11 +56,11 @@ The four network fields have different jobs:
The native Linear Agent transport requires a webhook; there is no polling mode.
The OAuth callback also needs to reach the same nanobot instance.
-You do **not** need a public IP address. A reverse proxy or HTTPS tunnel can
-forward a public hostname to `127.0.0.1:3979`. Cloudflare Tunnel, Tailscale
-Funnel, Caddy, nginx, and similar tools can all provide this route. Use a stable
-hostname for normal use: if the hostname changes, you must update both URLs in
-the Linear app.
+You do **not** need a public IP address when using an HTTPS tunnel such as
+Cloudflare Tunnel or Tailscale Funnel. On a publicly reachable server, Caddy,
+nginx, or another reverse proxy can provide HTTPS and forward requests to
+`127.0.0.1:3979`. Use a stable hostname for normal use: if the hostname changes,
+update **Public HTTPS URL** in nanobot and both registered URLs in the Linear app.
Choose the simplest option that matches your deployment:
@@ -69,7 +69,7 @@ Choose the simplest option that matches your deployment:
| Home server, laptop, or a network behind NAT | A named HTTPS tunnel with a fixed hostname |
| VPS with a domain and existing HTTPS proxy | Add a reverse-proxy route to `127.0.0.1:3979` |
| Docker or Kubernetes | Route the ingress or proxy to the container's port `3979`; keep the public URL on the ingress |
-| Short local test | A temporary HTTPS tunnel works, but you must recreate or edit the Linear app when its hostname changes |
+| Short local test | A temporary HTTPS tunnel works; update nanobot's public URL and the app's callback and webhook URLs whenever its hostname changes |
With the default paths, the route must preserve these two requests:
@@ -84,18 +84,37 @@ network. Containers and separate reverse-proxy hosts may require `0.0.0.0`.
The Linear listener serves plain HTTP locally; terminate HTTPS at the proxy or
tunnel instead of exposing port `3979` directly to the internet.
+### Temporary HTTPS for a local test
+
+Install [cloudflared](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/),
+then run it in a separate terminal:
+
+```bash
+cloudflared tunnel --url http://127.0.0.1:3979
+```
+
+Use the printed `https://<random-name>.trycloudflare.com` origin as **Public
+HTTPS URL** in the setup below. Keep the tunnel running throughout authorization
+and testing. The listener starts when you select **Connect Linear**, so a 502
+before that step can mean the local listener has not started yet.
+
+[Quick Tunnels](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/trycloudflare/)
+are intended for testing and generate a new hostname on restart. Update the
+nanobot public URL and the Linear app's Redirect URI and Webhook URL before
+continuing with a new hostname.
+
## Recommended setup in the WebUI
Keep `nanobot webui` running throughout the setup.
-### 1. Save the public address
+### 1. Enter the public address
1. Open **Settings → Channels → Linear**.
-2. Enter your stable origin in **Public HTTPS URL**, for example
+2. Enter your public origin in **Public HTTPS URL**, for example
`https://nanobot.example.com`.
-3. Leave the three OAuth credential fields empty for now.
-4. Select **Save settings**. nanobot saves the partial configuration and shows
- **Create prefilled Linear app**.
+3. Leave the three credential fields empty for now.
+4. Wait for **Settings saved.** The **Create prefilled Linear app** button
+ becomes available after the partial configuration is saved automatically.
Saving a partial configuration at this point is expected. You will create the
credentials in the next step.
@@ -130,10 +149,17 @@ In the new Linear app's settings, copy these values:
| Client Secret | **OAuth client secret** |
| Webhook signing secret | **Webhook signing secret** |
-Return to **Settings → Channels → Linear**, paste all three values, and select
-**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.
+Return to **Settings → Channels → Linear** and paste all three values. Ordinary
+fields save automatically after a short pause; secret fields save when you leave
+the field. Wait for **Settings saved.** before entering the next credential.
+**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.
+
+Closing the dialog waits for pending edits to save. If saving fails, the dialog
+keeps your input and offers **Retry**. **Remove saved credentials** clears both
+the client secret and webhook signing secret while keeping the client ID and
+public URL.
Treat the Client Secret and Webhook signing secret like passwords. They belong
only in the nanobot configuration and the Linear application settings.
@@ -143,11 +169,13 @@ only in the nanobot configuration and the Linear application settings.
1. Select **Connect Linear**.
2. Open the displayed authorization link, or scan the QR code.
3. Choose the workspace and approve the installation as a workspace admin.
-4. Return to nanobot and wait for **Linear is connected**.
+4. Return to nanobot and wait for the **Connected** badge.
nanobot enables the channel automatically after authorization. The gateway must
-remain running so Linear can deliver webhooks. To replace an authorization, use
-the reconnect action and approve it again.
+remain running so Linear can deliver webhooks. Reopening the panel shows the
+running connection immediately, without another authorization attempt.
+To replace an authorization, select
+**Connect another workspace** and authorize the same workspace again.
The pre-filled manifest creates a private app for the current workspace. A
distributable OAuth app can authorize additional workspaces; nanobot stores and
@@ -181,6 +209,9 @@ The setup is complete when all of these checks pass:
- While the channel is running, opening
`http://127.0.0.1:3979/linear/health` on the nanobot machine returns
`{"ok":true}`. Use your configured host and port if you changed them.
+- Opening `https://nanobot.example.com/linear/health` through the public route
+ also returns `{"ok":true}`. Substitute your actual public origin. This checks
+ tunnel or proxy reachability; the task checks below verify the Linear connection.
- A new comment with an explicit @mention creates an Agent Session and receives
a response.
- A normal issue comment without an @mention does nothing.
@@ -235,7 +266,9 @@ workspace-scoped access and refresh tokens.
OAuth Client ID.
- `Linear-Delivery` IDs are deduplicated.
- Verified events are committed to a local SQLite queue before nanobot returns
- HTTP 200. Pending work resumes after a restart.
+ HTTP 200. Queued webhook deliveries that have not yet been dispatched are
+ retried after a restart. This does not guarantee resumption of an interrupted
+ agent turn.
- Access and rotating refresh tokens are stored in the Linear channel state
database, not in `config.json` or the browser.
- OAuth revocation removes the affected workspace installation locally.
@@ -248,10 +281,12 @@ secret.
| Symptom | What to check |
|---|---|
-| **Create prefilled Linear app** is missing | Enter only the public HTTPS origin in **Public HTTPS URL**, then select **Save settings**. |
-| Linear rejects the callback or webhook URL | Use a stable public `https://` hostname. Do not use HTTP, localhost, a private IP, or a path in **Public HTTPS URL**. |
+| **Create prefilled Linear app** is disabled | Enter only the public HTTPS origin in **Public HTTPS URL** and wait for automatic saving to finish. If saving fails, correct the address or select **Retry**. |
+| Linear rejects the callback or webhook URL | Use a public `https://` hostname. Do not use HTTP, localhost, a private IP, or a path in **Public HTTPS URL**. |
+| The tunnel URL changed | Update **Public HTTPS URL** in nanobot and the Redirect URI and Webhook URL in the Linear app, then start **Connect Linear** again. |
+| Public health returns 502 | Start **Connect Linear** or enable the connected channel. Check local health first, then confirm the tunnel or proxy targets the same listener port. |
| OAuth opens but cannot finish | Keep `nanobot webui` running. Confirm the proxy forwards `/linear/oauth/callback` to the configured listen host and port. Then start **Connect Linear** again. |
-| OAuth finishes in Linear but nanobot keeps waiting | The callback reached a different nanobot process or URL. Compare the app's Redirect URI with the callback URL shown by nanobot. |
+| OAuth finishes in Linear but nanobot keeps waiting | Keep the nanobot connection dialog open. Confirm the Redirect URI reaches the same nanobot process, and inspect gateway logs for callback or token exchange errors. |
| The local health URL does not load | Start **Connect Linear** or enable the connected channel, then check the configured listen host and port. |
| An @mention gets no response | Confirm `AgentSessionEvent` is subscribed, the Client ID and signing secret match the same app, and the workspace authorization has not been revoked. Run `nanobot gateway logs` for the exact error. |
| The first @mention returns a pairing code | Approve it in the WebUI pairing dialog, then repeat the prompt in the same Agent Session. Alternatively, configure a narrow **Allowed Linear users** list. |
diff --git a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx
index e869b52b3..2e6dae199 100644
--- a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx
+++ b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx
@@ -9,6 +9,7 @@ import {
screen,
settingsPayload,
waitFor,
+ within,
} from "@/tests/settings-test-utils";
import { linearManifestUrl } from "../../webui/manifest";
@@ -84,7 +85,7 @@ describe("Linear channel UI", () => {
expect(manifest.webhook?.resourceTypes).not.toContain("Comment");
});
- it("saves a public URL before OAuth credentials and reveals the app manifest", async () => {
+ it("automatically saves a public URL before OAuth credentials and reveals the app button", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL) => {
@@ -130,7 +131,7 @@ describe("Linear channel UI", () => {
fireEvent.change(await screen.findByPlaceholderText("https://nanobot.example.com"), {
target: { value: "https://nanobot.example.com" },
});
- fireEvent.click(screen.getByRole("button", { name: /^Save/ }));
+ expect(screen.queryByRole("button", { name: /^Save/ })).not.toBeInTheDocument();
await waitFor(() =>
expect(requestMutationMock).toHaveBeenCalledWith(
@@ -174,7 +175,6 @@ describe("Linear channel UI", () => {
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");
@@ -190,14 +190,106 @@ describe("Linear channel UI", () => {
fireEvent.change(await screen.findByRole("textbox", { name: "OAuth client ID" }), {
target: { value: "replacement-client" },
});
- fireEvent.click(screen.getByRole("button", { name: /^Save/ }));
+ fireEvent.blur(screen.getByRole("textbox", { name: "OAuth client ID" }));
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();
+ await new Promise((resolve) => setTimeout(resolve, 750));
expect(requestMutationMock).toHaveBeenCalledTimes(1);
expect(requestMutationMock.mock.calls[0][1]).not.toHaveProperty("enable");
});
+ it("waits for a secret field to blur before saving its replacement", async () => {
+ const feature = savedFeature();
+ mockFeature(feature);
+ requestMutationMock.mockResolvedValueOnce({
+ saved: true, nanobot_features: { features: [feature], enabled_count: 0 },
+ });
+ renderSettingsView({ initialSection: "channels" });
+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
+ const input = screen.getByLabelText("OAuth client secret", { exact: true });
+ fireEvent.change(input, { target: { value: "replacement-secret" } });
+ await new Promise((resolve) => setTimeout(resolve, 750));
+ expect(requestMutationMock).not.toHaveBeenCalled();
+ fireEvent.blur(input);
+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledTimes(1));
+ const params = requestMutationMock.mock.calls[0][1] as { values: Record<string, unknown> };
+ expect(params.values["channels.linear.clientSecret"]).toBe("replacement-secret");
+ expect(params.values).not.toHaveProperty("channels.linear.webhookSigningSecret");
+ await waitFor(() => expect(input).toHaveValue(""));
+ expect(input).toHaveAttribute("placeholder", "Saved secret");
+ });
+
+ it("removes both saved secrets with one action while keeping the public URL and client ID", async () => {
+ const feature = savedFeature();
+ mockFeature(feature);
+ const secretKeys = ["channels.linear.clientSecret", "channels.linear.webhookSigningSecret"];
+ requestMutationMock.mockResolvedValueOnce({
+ saved: true, nanobot_features: {
+ features: [{ ...feature, configured_fields: feature.configured_fields?.filter(
+ (key) => !secretKeys.includes(key),
+ ) }], enabled_count: 0,
+ },
+ });
+ renderSettingsView({ initialSection: "channels" });
+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
+ expect(screen.getAllByRole("button", { name: "Remove saved credentials" })).toHaveLength(1);
+ fireEvent.click(screen.getByRole("button", { name: "Remove saved credentials" }));
+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledTimes(1));
+ const params = requestMutationMock.mock.calls[0][1] as { values: Record<string, unknown> };
+ for (const key of secretKeys) expect(params.values[key]).toBeNull();
+ expect(params.values["channels.linear.clientId"]).toBe("client-id");
+ expect(params.values["channels.linear.publicBaseUrl"]).toBe("https://nanobot.example.com");
+ await waitFor(() => expect(screen.queryByRole("button", {
+ name: "Remove saved credentials",
+ })).not.toBeInTheDocument());
+ expect(screen.getByRole("button", { name: "Connect Linear" })).toBeDisabled();
+ });
+
+ it("flushes the draft on close and waits for one in-flight save", async () => {
+ const feature = savedFeature();
+ mockFeature(feature);
+ let finishSave: ((value: unknown) => void) | undefined;
+ requestMutationMock.mockImplementationOnce(() => new Promise((resolve) => { finishSave = resolve; }));
+ renderSettingsView({ initialSection: "channels" });
+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
+ fireEvent.change(screen.getByRole("textbox", { name: "OAuth client ID" }), {
+ target: { value: "replacement-client" },
+ });
+ const dialog = screen.getByRole("dialog");
+ fireEvent.click(within(dialog).getByRole("button", { name: "Close", exact: true }));
+ expect(requestMutationMock).toHaveBeenCalledTimes(1);
+ expect(dialog).toBeVisible();
+ fireEvent.click(within(dialog).getByRole("button", { name: "Close", exact: true }));
+ expect(requestMutationMock).toHaveBeenCalledTimes(1);
+ finishSave?.({ saved: true, nanobot_features: { features: [{
+ ...feature, config_values: { ...feature.config_values, "channels.linear.clientId": "replacement-client" },
+ }], enabled_count: 0 } });
+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
+ });
+
+ it("keeps the dialog and draft after a failed close save and allows retry", async () => {
+ const feature = savedFeature();
+ mockFeature(feature);
+ requestMutationMock.mockRejectedValueOnce(new Error("Connection lost"));
+ renderSettingsView({ initialSection: "channels" });
+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
+ fireEvent.change(screen.getByRole("textbox", { name: "OAuth client ID" }), {
+ target: { value: "replacement-client" },
+ });
+ fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Close", exact: true }));
+ expect(await screen.findByRole("alert")).toHaveTextContent("Connection lost");
+ expect(screen.getByRole("dialog")).toBeVisible();
+ expect(screen.getByRole("textbox", { name: "OAuth client ID" })).toHaveValue("replacement-client");
+ requestMutationMock.mockResolvedValueOnce({ saved: true, nanobot_features: { features: [{
+ ...feature, config_values: { ...feature.config_values, "channels.linear.clientId": "replacement-client" },
+ }], enabled_count: 0 } });
+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));
+ await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled());
+ expect(requestMutationMock).toHaveBeenCalledTimes(2);
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ });
+
it("shows the OAuth handoff and cancels a pending authorization", async () => {
mockFeature(savedFeature());
requestMutationMock
@@ -211,7 +303,7 @@ describe("Linear channel UI", () => {
"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.queryByRole("button", { name: "Remove saved credentials" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Cancel" })).toBeEnabled();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(await screen.findByText("Authorization stopped.")).toBeVisible();
@@ -220,6 +312,51 @@ describe("Linear channel UI", () => {
"settings.channel.connect.cancel", { channel: "linear", session_id: "linear-oauth" }, 20_000,
);
});
+
+ it("restores a running connection on reopen without starting OAuth", async () => {
+ mockFeature({ ...savedFeature(), enabled: true, running: true, runtime_status: "running" });
+ renderSettingsView({ initialSection: "channels" });
+ const open = await screen.findByRole("button", { name: "View Linear settings" });
+ fireEvent.click(open);
+ expect(within(screen.getByRole("dialog")).getByText("Connected", { exact: true })).toBeVisible();
+ expect(screen.getByRole("button", { name: "Connect another workspace" })).toBeEnabled();
+ expect(screen.queryByRole("button", { name: "Connect Linear" })).not.toBeInTheDocument();
+ fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Close", exact: true }));
+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
+ fireEvent.click(open);
+ expect(within(screen.getByRole("dialog")).getByText("Connected", { exact: true })).toBeVisible();
+ expect(screen.getByRole("button", { name: "Connect another workspace" })).toBeEnabled();
+ expect(requestMutationMock).not.toHaveBeenCalled();
+ });
+
+ it("starts another workspace authorization directly and preserves the connection on cancel", async () => {
+ mockFeature({ ...savedFeature(), enabled: true, running: true, runtime_status: "running" });
+ requestMutationMock
+ .mockResolvedValueOnce({ session_id: "another-workspace", status: "pending",
+ qr_url: "https://linear.app/oauth/authorize?client_id=test" })
+ .mockResolvedValueOnce({ session_id: "another-workspace", status: "cancelled" });
+ renderSettingsView({ initialSection: "channels" });
+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
+ fireEvent.click(screen.getByRole("button", { name: "Connect another workspace" }));
+ expect(requestMutationMock).toHaveBeenCalledWith(
+ "settings.channel.connect.start", { channel: "linear", force: true }, 150_000,
+ );
+ expect(await screen.findByRole("link", { name: "Continue in Linear" })).toBeVisible();
+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
+ expect(await screen.findByRole("button", { name: "Connect another workspace" })).toBeEnabled();
+ expect(within(screen.getByRole("dialog")).getByText("Connected", { exact: true })).toBeVisible();
+ expect(screen.queryByText("Authorization stopped.")).not.toBeInTheDocument();
+ });
+
+ it("does not mark saved credentials or a failed runtime as connected", async () => {
+ mockFeature({ ...savedFeature(), enabled: true, configured: true, runtime_status: "failed",
+ runtime_error: "Linear channel failed to start" });
+ renderSettingsView({ initialSection: "channels" });
+ fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
+ expect(within(screen.getByRole("dialog")).queryByText("Connected", { exact: true })).not.toBeInTheDocument();
+ expect(screen.getByText("Linear channel failed to start")).toBeVisible();
+ expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled();
+ });
});
function savedFeature(): NanobotFeatureInfo {
diff --git a/nanobot/channels/linear/webui/LinearConnectFlow.tsx b/nanobot/channels/linear/webui/LinearConnectFlow.tsx
index 188cc944a..26b8d47b8 100644
--- a/nanobot/channels/linear/webui/LinearConnectFlow.tsx
+++ b/nanobot/channels/linear/webui/LinearConnectFlow.tsx
@@ -1,3 +1,4 @@
+import type { ReactNode } from "react";
import { ExternalLink } from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -8,11 +9,16 @@ import type { ChannelPluginConnectFlowProps } from "@/channel-plugins/types";
export function LinearConnectFlow({
token,
+ feature,
idleLabel,
connectRequestId,
onFeaturesUpdate,
onActiveChange,
-}: ChannelPluginConnectFlowProps & { onActiveChange?: (active: boolean) => void }) {
+ renderActions,
+}: ChannelPluginConnectFlowProps & {
+ onActiveChange?: (active: boolean) => void;
+ renderActions?: (connectButton: ReactNode) => ReactNode;
+}) {
const { t } = useTranslation();
const tx = channelTranslator(t, "linear");
@@ -24,8 +30,11 @@ export function LinearConnectFlow({
idleLabel={idleLabel}
connectRequestId={connectRequestId}
forceOnRepeat
+ connected={feature.runtime_status === "running"}
+ suppressSucceeded={feature.runtime_status === "running"}
onFeaturesUpdate={onFeaturesUpdate}
onActiveChange={onActiveChange}
+ renderActions={renderActions}
labels={{
qrAlt: tx("custom.qrAlt", "Linear authorization QR code"),
scanTitle: tx("custom.authorizeTitle", "Authorize in Linear"),
diff --git a/nanobot/channels/linear/webui/LinearPanel.tsx b/nanobot/channels/linear/webui/LinearPanel.tsx
index 2467ff06b..11399c184 100644
--- a/nanobot/channels/linear/webui/LinearPanel.tsx
+++ b/nanobot/channels/linear/webui/LinearPanel.tsx
@@ -1,5 +1,5 @@
-import { useEffect, useId, useMemo, useState } from "react";
-import { ChevronDown, ExternalLink, Loader2 } from "lucide-react";
+import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
+import { Check, ChevronDown, ExternalLink, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { channelTranslator } from "@/channel-plugins/i18n";
@@ -17,6 +17,8 @@ import {
localizedChannelDisplayName,
} from "@/components/settings/channels/ChannelIdentity";
import { Button } from "@/components/ui/button";
+import { channelValidationStatusClass } from "@/components/settings/channels/ChannelValidationProgress";
+import { useAutoSave } from "@/components/settings/shared/useAutoSave";
import { configureChannel } from "@/lib/api";
import { cn } from "@/lib/utils";
import { useClient } from "@/providers/ClientProvider";
@@ -34,6 +36,7 @@ export function LinearPanel({
actionKey,
showBrandLogos,
onFeaturesUpdate,
+ onBeforeCloseChange,
}: ChannelPluginPanelProps) {
const { client } = useClient();
const { t, i18n } = useTranslation();
@@ -58,6 +61,8 @@ export function LinearPanel({
const [saving, setSaving] = useState(false);
const [connecting, setConnecting] = useState(false);
const [notice, setNotice] = useState<string | null>(null);
+ const [saved, setSaved] = useState(false);
+ const savePromiseRef = useRef<Promise<boolean> | null>(null);
const advancedPanelId = useId();
useEffect(() => {
@@ -72,6 +77,11 @@ export function LinearPanel({
const dirty = clearedSecrets.size > 0 || editableFields.some(
(field) => fieldValues[field.key] !== savedValues[field.key],
);
+ const secretFields = editableFields.filter((field) => field.secret);
+ const touchedSecret = secretFields.some((field) =>
+ touchedFields.has(field.key) && Boolean(fieldValues[field.key]?.trim()),
+ );
+ const hasSavedSecrets = secretFields.some((field) => configuredFields.has(field.key));
const manifestDirty = [PUBLIC_BASE_URL_KEY, WEBHOOK_PATH_KEY, CALLBACK_PATH_KEY].some(
(key) => fieldValues[key] !== savedValues[key],
);
@@ -90,32 +100,74 @@ export function LinearPanel({
const setFieldValue = (key: string, value: string) => {
setFieldValues((current) => ({ ...current, [key]: value }));
setTouchedFields((current) => new Set(current).add(key));
+ setClearedSecrets((current) => {
+ if (!current.has(key)) return current;
+ const next = new Set(current);
+ next.delete(key);
+ return next;
+ });
setNotice(null);
+ setSaved(false);
};
- const saveSettings = async () => {
- if (busy || connecting) return;
- setSaving(true);
+ const saveSettings = useCallback(async (): Promise<boolean> => {
+ if (savePromiseRef.current) return savePromiseRef.current;
+ if (!dirty) return true;
+ if (busy || connecting) return false;
+ const save = (async () => {
+ setSaving(true);
+ setSaved(false);
+ setNotice(null);
+ try {
+ const payload = await configureChannel(
+ client,
+ feature.name,
+ channelValuesForSubmit(editableFields, fieldValues, touchedFields, clearedSecrets),
+ );
+ setTouchedFields(new Set());
+ setClearedSecrets(new Set());
+ setVisibleSecrets({});
+ setFieldValues((current) => Object.fromEntries(
+ editableFields.map((field) => [field.key, field.secret ? "" : current[field.key] ?? ""]),
+ ));
+ if (payload.nanobot_features) onFeaturesUpdate(payload.nanobot_features);
+ setSaved(true);
+ return true;
+ } catch (err) {
+ setNotice((err as Error).message);
+ return false;
+ } finally {
+ setSaving(false);
+ }
+ })();
+ savePromiseRef.current = save;
+ const result = await save;
+ if (savePromiseRef.current === save) savePromiseRef.current = null;
+ return result;
+ }, [busy, connecting, dirty, client, feature.name, editableFields, fieldValues,
+ touchedFields, clearedSecrets, onFeaturesUpdate]);
+
+ useAutoSave(
+ { fieldValues, clearedSecrets: [...clearedSecrets] },
+ dirty,
+ busy || connecting,
+ () => void saveSettings(),
+ !touchedSecret && !notice,
+ );
+
+ useEffect(() => {
+ onBeforeCloseChange?.(dirty ? saveSettings : null);
+ return () => onBeforeCloseChange?.(null);
+ }, [dirty, saveSettings, onBeforeCloseChange]);
+
+ const removeSavedCredentials = () => {
+ setClearedSecrets(new Set(secretFields.map((field) => field.key)));
+ setFieldValues((current) => ({
+ ...current,
+ ...Object.fromEntries(secretFields.map((field) => [field.key, ""])),
+ }));
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);
- }
+ setSaved(false);
};
const formProps = {
@@ -124,18 +176,10 @@ export function LinearPanel({
visibleSecrets,
clearedSecrets,
onChange: setFieldValue,
+ onFieldBlur: () => { void saveSettings(); },
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,
};
@@ -149,6 +193,24 @@ export function LinearPanel({
<div className="flex flex-wrap items-center justify-between gap-3 pe-20">
<ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
<h3 className="sr-only">{displayName}</h3>
+ {feature.runtime_status === "running" ? (
+ <span role="status" className={cn(
+ "ms-auto inline-flex shrink-0 items-center gap-1.5 rounded-full px-2.5 py-1 text-[11.5px] font-medium",
+ channelValidationStatusClass("connected"),
+ )}>
+ <Check className="h-3.5 w-3.5" aria-hidden />
+ {t("settings.channels.validation.connected", { defaultValue: "Connected" })}
+ </span>
+ ) : null}
+ <span role="status" aria-live="polite" aria-atomic="true" className={cn(
+ "ms-auto inline-flex items-center gap-1.5 text-[11px] text-muted-foreground",
+ !saving && !saved && "sr-only",
+ )}>
+ {saving ? <><Loader2 className="h-3 w-3 animate-spin motion-reduce:animate-none" aria-hidden />
+ {t("settings.actions.saving", { defaultValue: "Saving" })}</> : saved ? <>
+ <Check className="h-3 w-3" aria-hidden />
+ {t("settings.channels.savedSettings", { defaultValue: "Settings saved." })}</> : null}
+ </span>
<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}
@@ -162,40 +224,62 @@ export function LinearPanel({
</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>
+ {!manifestUrl || manifestDirty ? (
+ <p className="text-[12px] leading-5 text-muted-foreground">
+ {tx("custom.savePublicUrl", "Enter a public HTTPS URL to create a prefilled Linear app.")}
+ </p>
+ ) : null}
<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>
+ {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">
+ <p role="alert">{notice}</p>
+ <Button type="submit" variant="secondary" size="sm" disabled={busy || connecting}
+ className="min-h-10 rounded-full text-[12px]">
+ {tx("custom.retrySave", "Retry")}
+ </Button>
+ </div>
+ ) : null}
</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>
+ <LinearConnectFlow token={token} feature={feature}
+ idleLabel={tx("custom.connect", "Connect Linear")} onFeaturesUpdate={onFeaturesUpdate}
+ 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]">
+ <div className="me-auto min-w-0 max-w-full">
+ {manifestUrl && !manifestDirty ? (
+ <Button asChild variant="secondary" size="sm"
+ className="h-auto min-h-10 max-w-full gap-2 whitespace-normal rounded-full px-4 py-2 text-[12px]">
+ <a href={manifestUrl} target="_blank" rel="noreferrer">
+ {tx("custom.createApp", "Create prefilled Linear app")}
+ <ExternalLink className="h-3.5 w-3.5 shrink-0" aria-hidden />
+ </a>
+ </Button>
+ ) : (
+ <Button variant="secondary" size="sm" disabled
+ className="h-auto min-h-10 max-w-full whitespace-normal rounded-full px-4 py-2 text-[12px]">
+ {tx("custom.createApp", "Create prefilled Linear app")}
+ </Button>
+ )}
+ </div>
+ {hasSavedSecrets ? (
+ <Button type="button" variant="ghost" size="sm" disabled={busy || connecting}
+ className="h-auto min-h-10 whitespace-normal rounded-full text-[12px] text-muted-foreground"
+ onClick={removeSavedCredentials}>
+ {tx("custom.removeCredentials", "Remove saved credentials")}
+ </Button>
+ ) : null}
+ <fieldset disabled={busy || dirty || !credentialsSaved} className="min-w-0 sm:col-start-3">
+ <legend className="sr-only">{tx("custom.authorizeTitle", "Authorize in Linear")}</legend>
+ {connectButton}
+ </fieldset>
+ </div>
+ )} />
{dirty || !credentialsSaved ? (
<p className="mt-2 text-[12px] leading-5 text-muted-foreground">
- {tx("custom.saveBeforeConnect", "Save the app credentials before authorizing a workspace.")}
+ {tx("custom.saveBeforeConnect", "Enter the app credentials and wait for them to save before connecting.")}
</p>
) : null}
</aside>
diff --git a/nanobot/channels/linear/webui/locales/en.json b/nanobot/channels/linear/webui/locales/en.json
index 04bcb04b8..b28c8127f 100644
--- a/nanobot/channels/linear/webui/locales/en.json
+++ b/nanobot/channels/linear/webui/locales/en.json
@@ -10,7 +10,7 @@
"Expose this nanobot instance through a stable HTTPS URL (a tunnel is fine).",
"Create a private OAuth app in Linear with read, write, and app:mentionable scopes. Do not add app:assignable.",
"Subscribe the app webhook to AgentSessionEvent, PermissionChange, and OAuthAuthorization using the generated webhook URL.",
- "Save settings, connect the workspace with OAuth, then @mention the app on an issue."
+ "Enter the app credentials, wait for them to save automatically, connect the workspace with OAuth, then @mention the app on an issue."
],
"fields": {
"clientId": {
@@ -68,7 +68,9 @@
"connect": "Connect 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."
+ "savePublicUrl": "Enter a public HTTPS URL to create a prefilled Linear app.",
+ "saveBeforeConnect": "Enter the app credentials and wait for them to save before connecting.",
+ "removeCredentials": "Remove saved credentials",
+ "retrySave": "Retry"
}
}
diff --git a/nanobot/channels/linear/webui/locales/es.json b/nanobot/channels/linear/webui/locales/es.json
index 0a4b2d4ec..72bc4454e 100644
--- a/nanobot/channels/linear/webui/locales/es.json
+++ b/nanobot/channels/linear/webui/locales/es.json
@@ -10,7 +10,7 @@
"Expón esta instancia de nanobot mediante una URL HTTPS estable (puedes usar un túnel).",
"Crea una aplicación OAuth privada en Linear con los permisos read, write y app:mentionable. No añadas app:assignable.",
"Suscribe el webhook de la aplicación a AgentSessionEvent, PermissionChange y OAuthAuthorization con la URL generada.",
- "Guarda la configuración, conecta el espacio de trabajo mediante OAuth y @menciona la aplicación en una incidencia."
+ "Introduce las credenciales de la aplicación, espera a que se guarden automáticamente, conecta el espacio de trabajo con OAuth y menciona la aplicación con @ en una incidencia."
],
"fields": {
"clientId": {
@@ -68,7 +68,9 @@
"connect": "Conectar 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."
+ "savePublicUrl": "Introduce una URL HTTPS pública para crear una aplicación de Linear preconfigurada.",
+ "saveBeforeConnect": "Introduce las credenciales de la aplicación y espera a que se guarden antes de conectar.",
+ "removeCredentials": "Eliminar credenciales guardadas",
+ "retrySave": "Reintentar"
}
}
diff --git a/nanobot/channels/linear/webui/locales/fr.json b/nanobot/channels/linear/webui/locales/fr.json
index ed2ec43b1..9150a735f 100644
--- a/nanobot/channels/linear/webui/locales/fr.json
+++ b/nanobot/channels/linear/webui/locales/fr.json
@@ -10,7 +10,7 @@
"Exposez cette instance nanobot avec une URL HTTPS stable (un tunnel convient).",
"Créez une application OAuth privée dans Linear avec les autorisations read, write et app:mentionable. N’ajoutez pas app:assignable.",
"Abonnez le webhook de l’application à AgentSessionEvent, PermissionChange et OAuthAuthorization avec l’URL générée.",
- "Enregistrez les paramètres, connectez l’espace de travail avec OAuth, puis @mentionnez l’application dans un ticket."
+ "Saisissez les identifiants de l’application, attendez leur enregistrement automatique, connectez l’espace de travail avec OAuth, puis mentionnez l’application avec @ dans une issue."
],
"fields": {
"clientId": {
@@ -68,7 +68,9 @@
"connect": "Connecter 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."
+ "savePublicUrl": "Saisissez une URL HTTPS publique pour créer une application Linear préremplie.",
+ "saveBeforeConnect": "Saisissez les identifiants de l’application et attendez leur enregistrement avant de vous connecter.",
+ "removeCredentials": "Supprimer les identifiants enregistrés",
+ "retrySave": "Réessayer"
}
}
diff --git a/nanobot/channels/linear/webui/locales/id.json b/nanobot/channels/linear/webui/locales/id.json
index 6a51bc160..fd94b52cb 100644
--- a/nanobot/channels/linear/webui/locales/id.json
+++ b/nanobot/channels/linear/webui/locales/id.json
@@ -10,7 +10,7 @@
"Ekspos instans nanobot ini melalui URL HTTPS yang stabil (tunnel dapat digunakan).",
"Buat aplikasi OAuth privat di Linear dengan scope read, write, dan app:mentionable. Jangan tambahkan app:assignable.",
"Daftarkan webhook aplikasi untuk AgentSessionEvent, PermissionChange, dan OAuthAuthorization menggunakan URL yang dibuat.",
- "Simpan pengaturan, hubungkan workspace melalui OAuth, lalu @mention aplikasi pada issue."
+ "Masukkan kredensial aplikasi, tunggu hingga tersimpan otomatis, hubungkan ruang kerja dengan OAuth, lalu sebut aplikasi dengan @ dalam issue."
],
"fields": {
"clientId": {
@@ -68,7 +68,9 @@
"connect": "Hubungkan 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."
+ "savePublicUrl": "Masukkan URL HTTPS publik untuk membuat aplikasi Linear yang sudah terisi.",
+ "saveBeforeConnect": "Masukkan kredensial aplikasi dan tunggu hingga tersimpan sebelum menghubungkan.",
+ "removeCredentials": "Hapus kredensial tersimpan",
+ "retrySave": "Coba lagi"
}
}
diff --git a/nanobot/channels/linear/webui/locales/ja.json b/nanobot/channels/linear/webui/locales/ja.json
index dc154eff4..c386da1d3 100644
--- a/nanobot/channels/linear/webui/locales/ja.json
+++ b/nanobot/channels/linear/webui/locales/ja.json
@@ -10,7 +10,7 @@
"この nanobot インスタンスを安定した HTTPS URL で公開します(トンネルも利用できます)。",
"Linear で read、write、app:mentionable スコープを持つ非公開 OAuth アプリを作成します。app:assignable は追加しないでください。",
"生成された URL を使い、アプリの webhook を AgentSessionEvent、PermissionChange、OAuthAuthorization に登録します。",
- "設定を保存し、OAuth でワークスペースを接続してから、issue でアプリを @メンションします。"
+ "アプリの認証情報を入力し、自動保存の完了後に OAuth でワークスペースを接続して、issue でアプリを @メンションします。"
],
"fields": {
"clientId": {
@@ -68,7 +68,9 @@
"connect": "Linear に接続",
"openLinear": "Linear で続行",
"createApp": "入力済みの Linear アプリを作成",
- "savePublicUrl": "公開 URL を保存すると、入力済みの Linear アプリを作成できます。",
- "saveBeforeConnect": "ワークスペースを認証する前にアプリの認証情報を保存してください。"
+ "savePublicUrl": "公開 HTTPS URL を入力すると、入力済みの Linear アプリを作成できます。",
+ "saveBeforeConnect": "アプリの認証情報を入力し、自動保存が完了してから接続してください。",
+ "removeCredentials": "保存済みの認証情報を削除",
+ "retrySave": "再試行"
}
}
diff --git a/nanobot/channels/linear/webui/locales/ko.json b/nanobot/channels/linear/webui/locales/ko.json
index 265c28665..cd7f654fa 100644
--- a/nanobot/channels/linear/webui/locales/ko.json
+++ b/nanobot/channels/linear/webui/locales/ko.json
@@ -10,7 +10,7 @@
"이 nanobot 인스턴스를 안정적인 HTTPS URL로 공개하세요(터널을 사용할 수 있습니다).",
"Linear에서 read, write, app:mentionable 범위가 있는 비공개 OAuth 앱을 만드세요. app:assignable은 추가하지 마세요.",
"생성된 URL로 앱 webhook을 AgentSessionEvent, PermissionChange, OAuthAuthorization에 구독하세요.",
- "설정을 저장하고 OAuth로 워크스페이스를 연결한 다음 이슈에서 앱을 @멘션하세요."
+ "앱 인증 정보를 입력하고 자동 저장이 완료되면 OAuth로 워크스페이스를 연결한 후 이슈에서 앱을 @멘션하세요."
],
"fields": {
"clientId": {
@@ -68,7 +68,9 @@
"connect": "Linear 연결",
"openLinear": "Linear에서 계속",
"createApp": "미리 입력된 Linear 앱 만들기",
- "savePublicUrl": "공개 URL을 저장하면 미리 입력된 Linear 앱을 만들 수 있습니다.",
- "saveBeforeConnect": "워크스페이스를 승인하기 전에 앱 자격 증명을 저장하세요."
+ "savePublicUrl": "공개 HTTPS URL을 입력하면 미리 채워진 Linear 앱을 만들 수 있습니다.",
+ "saveBeforeConnect": "앱 인증 정보를 입력하고 자동 저장이 완료된 후 연결하세요.",
+ "removeCredentials": "저장된 인증 정보 삭제",
+ "retrySave": "다시 시도"
}
}
diff --git a/nanobot/channels/linear/webui/locales/pt-BR.json b/nanobot/channels/linear/webui/locales/pt-BR.json
index bb77f2d35..1a9c35a4d 100644
--- a/nanobot/channels/linear/webui/locales/pt-BR.json
+++ b/nanobot/channels/linear/webui/locales/pt-BR.json
@@ -10,7 +10,7 @@
"Exponha esta instância do nanobot por uma URL HTTPS estável (um túnel pode ser usado).",
"Crie um aplicativo OAuth privado no Linear com os escopos read, write e app:mentionable. Não adicione app:assignable.",
"Inscreva o webhook do aplicativo em AgentSessionEvent, PermissionChange e OAuthAuthorization usando a URL gerada.",
- "Salve as configurações, conecte o workspace com OAuth e @mencione o aplicativo em uma issue."
+ "Insira as credenciais do aplicativo, aguarde o salvamento automático, conecte o espaço de trabalho com OAuth e mencione o aplicativo com @ em uma issue."
],
"fields": {
"clientId": {
@@ -68,7 +68,9 @@
"connect": "Conectar 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."
+ "savePublicUrl": "Insira uma URL HTTPS pública para criar um aplicativo Linear pré-preenchido.",
+ "saveBeforeConnect": "Insira as credenciais do aplicativo e aguarde o salvamento antes de conectar.",
+ "removeCredentials": "Remover credenciais salvas",
+ "retrySave": "Tentar novamente"
}
}
diff --git a/nanobot/channels/linear/webui/locales/vi.json b/nanobot/channels/linear/webui/locales/vi.json
index 1e3128476..854e4732d 100644
--- a/nanobot/channels/linear/webui/locales/vi.json
+++ b/nanobot/channels/linear/webui/locales/vi.json
@@ -10,7 +10,7 @@
"Công khai phiên bản nanobot này qua URL HTTPS ổn định (có thể dùng tunnel).",
"Tạo ứng dụng OAuth riêng tư trong Linear với các scope read, write và app:mentionable. Không thêm app:assignable.",
"Đăng ký webhook của ứng dụng cho AgentSessionEvent, PermissionChange và OAuthAuthorization bằng URL được tạo.",
- "Lưu cài đặt, kết nối workspace qua OAuth, rồi @mention ứng dụng trong một issue."
+ "Nhập thông tin xác thực của ứng dụng, chờ lưu tự động, kết nối không gian làm việc bằng OAuth, rồi nhắc đến ứng dụng bằng @ trong issue."
],
"fields": {
"clientId": {
@@ -68,7 +68,9 @@
"connect": "Kết nối 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."
+ "savePublicUrl": "Nhập URL HTTPS công khai để tạo ứng dụng Linear được điền sẵn.",
+ "saveBeforeConnect": "Nhập thông tin xác thực của ứng dụng và chờ lưu xong trước khi kết nối.",
+ "removeCredentials": "Xóa thông tin xác thực đã lưu",
+ "retrySave": "Thử lại"
}
}
diff --git a/nanobot/channels/linear/webui/locales/zh-CN.json b/nanobot/channels/linear/webui/locales/zh-CN.json
index c79ff8151..917759ed9 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","createApp":"创建预填的 Linear 应用","savePublicUrl":"保存公网地址后,即可创建预填的 Linear 应用。","saveBeforeConnect":"请先保存应用凭据,再授权工作区。"}}
+{"description":"通过 Linear 原生 Agent Session 在 issue 中使用 nanobot。","requirements":"一个私有 Linear OAuth 应用和稳定的公网 HTTPS 回调地址","setup":{"docsLabel":"打开 Linear 配置指南","officialLabel":"创建 Linear OAuth 应用","tryIt":"在 issue 评论中 @ 应用;进入 Agent Session 后,后续对话无需重复 @。","summary":"创建私有 Linear OAuth 应用,保存凭据和公网地址,再授权工作区。新会话必须显式 @ 应用,普通评论会被忽略。","steps":["用稳定的 HTTPS 地址暴露此 nanobot 实例(可以使用隧道)。","在 Linear 创建私有 OAuth 应用,启用 read、write 和 app:mentionable;不要启用 app:assignable。","将应用 webhook 订阅 AgentSessionEvent、PermissionChange 和 OAuthAuthorization,并填写生成的 webhook 地址。","填写应用凭据,等待自动保存完成,通过 OAuth 连接工作区,然后在 issue 中 @ 应用。"],"fields":{"clientId":{"label":"OAuth Client ID","placeholder":"Linear OAuth Client ID","help":"从 Linear 私有 OAuth 应用中复制。"},"clientSecret":{"label":"OAuth Client Secret","placeholder":"••••••","help":"只保存在此 nanobot 实例中。"},"webhookSigningSecret":{"label":"Webhook 签名密钥","placeholder":"••••••","help":"在解析 webhook 内容前验证 Linear-Signature。"},"publicBaseUrl":{"label":"公网 HTTPS 地址","placeholder":"https://nanobot.example.com","help":"稳定且能转发到下方监听端口的 HTTPS 源地址,不要包含路径。"},"host":{"label":"监听地址","placeholder":"0.0.0.0"},"port":{"label":"监听端口","placeholder":"3979"},"webhookPath":{"label":"Webhook 路径","placeholder":"/linear/webhook"},"oauthCallbackPath":{"label":"OAuth 回调路径","placeholder":"/linear/oauth/callback"},"allowFrom":{"label":"允许的 Linear 用户","placeholder":"用逗号分隔 Linear 用户 ID","help":"留空使用 nanobot 配对;填写 * 允许已连接工作区内的所有用户。"}}},"custom":{"qrAlt":"Linear 授权二维码","authorizeTitle":"在 Linear 中授权","authorizeDescription":"在当前浏览器打开 Linear 或扫描二维码;授权后 nanobot 会自动启用 channel。","waiting":"正在等待 Linear 授权……","connected":"Linear 已连接。","stopped":"授权已停止。","connecting":"正在连接……","reconnect":"连接另一个工作区","connect":"连接 Linear","openLinear":"前往 Linear","createApp":"创建预填的 Linear 应用","savePublicUrl":"填写公网 HTTPS 地址后,即可创建预填的 Linear 应用。","saveBeforeConnect":"填写应用凭据,等待自动保存完成后再连接。","removeCredentials":"删除已保存的凭据","retrySave":"重试"}}
diff --git a/nanobot/channels/linear/webui/locales/zh-TW.json b/nanobot/channels/linear/webui/locales/zh-TW.json
index 477ffb1b7..ecf1a3319 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","createApp":"建立預填的 Linear 應用程式","savePublicUrl":"儲存公開網址後,即可建立預填的 Linear 應用程式。","saveBeforeConnect":"請先儲存應用程式憑證,再授權工作區。"}}
+{"description":"透過 Linear 原生 Agent Session 在 issue 中使用 nanobot。","requirements":"一個私有 Linear OAuth 應用程式和穩定的公網 HTTPS 回呼網址","setup":{"docsLabel":"開啟 Linear 設定指南","officialLabel":"建立 Linear OAuth 應用程式","tryIt":"在 issue 評論中 @ 應用程式;進入 Agent Session 後,後續對話無需重複 @。","summary":"建立私有 Linear OAuth 應用程式,儲存憑證和公網網址,再授權工作區。新會話必須明確 @ 應用程式,普通評論會被忽略。","steps":["用穩定的 HTTPS 網址公開此 nanobot 實例(可以使用隧道)。","在 Linear 建立私有 OAuth 應用程式,啟用 read、write 和 app:mentionable;不要啟用 app:assignable。","將應用程式 webhook 訂閱 AgentSessionEvent、PermissionChange 和 OAuthAuthorization,並填入產生的 webhook 網址。","填寫應用程式憑證,等待自動儲存完成,透過 OAuth 連接工作區,然後在 issue 中 @ 應用程式。"],"fields":{"clientId":{"label":"OAuth Client ID","placeholder":"Linear OAuth Client ID","help":"從 Linear 私有 OAuth 應用程式中複製。"},"clientSecret":{"label":"OAuth Client Secret","placeholder":"••••••","help":"只儲存在此 nanobot 實例中。"},"webhookSigningSecret":{"label":"Webhook 簽署密鑰","placeholder":"••••••","help":"在解析 webhook 內容前驗證 Linear-Signature。"},"publicBaseUrl":{"label":"公網 HTTPS 網址","placeholder":"https://nanobot.example.com","help":"穩定且能轉送到下方監聽連接埠的 HTTPS 來源網址,不要包含路徑。"},"host":{"label":"監聽位址","placeholder":"0.0.0.0"},"port":{"label":"監聽連接埠","placeholder":"3979"},"webhookPath":{"label":"Webhook 路徑","placeholder":"/linear/webhook"},"oauthCallbackPath":{"label":"OAuth 回呼路徑","placeholder":"/linear/oauth/callback"},"allowFrom":{"label":"允許的 Linear 使用者","placeholder":"以逗號分隔 Linear 使用者 ID","help":"留空使用 nanobot 配對;填寫 * 允許已連接工作區內的所有使用者。"}}},"custom":{"qrAlt":"Linear 授權 QR code","authorizeTitle":"在 Linear 中授權","authorizeDescription":"在目前瀏覽器開啟 Linear 或掃描 QR code;授權後 nanobot 會自動啟用 channel。","waiting":"正在等待 Linear 授權……","connected":"Linear 已連接。","stopped":"授權已停止。","connecting":"正在連接……","reconnect":"連接另一個工作區","connect":"連接 Linear","openLinear":"前往 Linear","createApp":"建立預填的 Linear 應用程式","savePublicUrl":"填寫公開 HTTPS 網址後,即可建立預填的 Linear 應用程式。","saveBeforeConnect":"填寫應用程式憑證,等待自動儲存完成後再連線。","removeCredentials":"刪除已儲存的憑證","retrySave":"重試"}}
diff --git a/webui/src/channel-plugins/types.ts b/webui/src/channel-plugins/types.ts
index e97fe7281..d9d708469 100644
--- a/webui/src/channel-plugins/types.ts
+++ b/webui/src/channel-plugins/types.ts
@@ -25,6 +25,7 @@ export type ChannelPluginPanelProps = {
showBrandLogos: boolean;
onAction: ChannelFeatureAction;
onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;
+ onBeforeCloseChange?: (handler: (() => Promise<boolean>) | null) => void;
};
export type ChannelPluginConnectFlowProps = {
diff --git a/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx b/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx
index a14e35400..721381c4b 100644
--- a/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx
+++ b/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx
@@ -43,6 +43,7 @@ export function ChannelQrConnectFlow({
idleLabel,
connectRequestId,
forceOnRepeat = false,
+ connected = false,
autoStart = false,
minimalPending = false,
labels,
@@ -52,6 +53,7 @@ export function ChannelQrConnectFlow({
resolveMessage,
suppressSucceeded = false,
onActiveChange,
+ renderActions,
}: {
token: string;
channelName: string;
@@ -59,6 +61,7 @@ export function ChannelQrConnectFlow({
idleLabel?: string;
connectRequestId?: number;
forceOnRepeat?: boolean;
+ connected?: boolean;
autoStart?: boolean;
minimalPending?: boolean;
labels: ChannelQrConnectLabels;
@@ -68,6 +71,7 @@ export function ChannelQrConnectFlow({
resolveMessage?: (payload: ChannelConnectPayload) => string | undefined;
suppressSucceeded?: boolean;
onActiveChange?: (active: boolean) => void;
+ renderActions?: (connectButton: ReactNode) => ReactNode;
}) {
const { client } = useClient();
const pageVisible = usePageVisibility();
@@ -82,7 +86,7 @@ export function ChannelQrConnectFlow({
const pollInFlight = useRef(false);
const pending = connect?.status === "pending";
- const succeeded = connect?.status === "succeeded";
+ const succeeded = !pending && (connected || connect?.status === "succeeded");
const canStart = !pending && !busy;
useEffect(() => {
onActiveChange?.(pending || busy);
@@ -248,6 +252,10 @@ export function ChannelQrConnectFlow({
}
};
+ const renderActionRow = renderActions ?? ((connectButton: ReactNode) => (
+ <div className="flex flex-wrap justify-end gap-2">{connectButton}</div>
+ ));
+
return (
<div className="mt-3 space-y-3">
{autoStart && busy && !connect ? (
@@ -320,7 +328,8 @@ export function ChannelQrConnectFlow({
</div>
) : null}
- {connect && ["expired", "failed", "cancelled"].includes(connect.status) ? (
+ {connect && ["expired", "failed", "cancelled"].includes(connect.status)
+ && !(connected && connect.status === "cancelled") ? (
<div className="rounded-control border border-border/60 px-3 py-2 text-[12px] leading-5 text-muted-foreground">
{displayMessage || labels.stopped}
</div>
@@ -332,7 +341,7 @@ export function ChannelQrConnectFlow({
</div>
) : null}
- {!pending && !(autoStart && busy && !connect) ? <div className="flex flex-wrap justify-end gap-2">
+ {!pending && !(autoStart && busy && !connect) ? renderActionRow(
<Button
type="button"
size="sm"
@@ -352,7 +361,7 @@ export function ChannelQrConnectFlow({
? labels.scanAgain
: idleLabel ?? labels.connect}
</Button>
- </div> : null}
+ ) : null}
</div>
);
}
diff --git a/webui/src/components/settings/channels/ChannelSetupPanel.tsx b/webui/src/components/settings/channels/ChannelSetupPanel.tsx
index 3df4af53e..b35d66c3e 100644
--- a/webui/src/components/settings/channels/ChannelSetupPanel.tsx
+++ b/webui/src/components/settings/channels/ChannelSetupPanel.tsx
@@ -107,6 +107,7 @@ export function ChannelSetupPanel({
showBrandLogos={showBrandLogos}
onAction={onAction}
onFeaturesUpdate={onFeaturesUpdate}
+ onBeforeCloseChange={onBeforeCloseChange}
/>
</Suspense>
);
diff --git a/webui/src/tests/settings-test-utils.tsx b/webui/src/tests/settings-test-utils.tsx
index 9075b071b..5fcdce550 100644
--- a/webui/src/tests/settings-test-utils.tsx
+++ b/webui/src/tests/settings-test-utils.tsx
@@ -5,7 +5,7 @@ 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 { fireEvent, screen, waitFor, within } from "@testing-library/react";
export const requestMutationMock = vi.fn();