feat(linear): refine browser authorization and workspace lifecycle

This commit is contained in:
Xubin Ren committed 2026-09-26 19:19:21 +08:00
1 parent 2bacff148d
commit 5375289ecd
32 files changed
+1856 -257

No files matched your search

+54 -1
View File
@@ -1,5 +1,6 @@
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import QRCode from "qrcode";
import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";
import { FeishuConnectFlow } from "../../../nanobot/channels/feishu/webui/FeishuConnectFlow";
@@ -30,9 +31,61 @@ beforeEach(() => {
});
});
afterEach(cleanup);
afterEach(() => { cleanup(); vi.restoreAllMocks(); });
describe("channel QR connect parameters", () => {
it.each([false, true])("keeps QR generation enabled by default (minimal=%s)", async (minimalPending) => {
const generateQr = vi.spyOn(QRCode, "toDataURL").mockResolvedValue("data:image/png;base64,preview");
requestMutation.mockResolvedValueOnce({
session_id: "qr-session", status: "pending", qr_url: "https://example.com/connect",
});
render(<ChannelQrConnectFlow token="tok" channelName="plugin-chat" labels={labels}
minimalPending={minimalPending} onFeaturesUpdate={vi.fn()} />);
fireEvent.click(screen.getByRole("button", { name: "Connect", exact: true }));
expect(await screen.findByRole("img", { name: "Connection QR code" })).toHaveAttribute("src", "data:image/png;base64,preview");
expect(generateQr).toHaveBeenCalledOnce();
});
it("does not generate or reserve space for QR when disabled, and still allows cancellation", async () => {
const generateQr = vi.spyOn(QRCode, "toDataURL").mockRejectedValue(new Error("QR must not run"));
requestMutation
.mockResolvedValueOnce({ session_id: "browser-session", status: "pending", qr_url: "https://example.com/authorize" })
.mockResolvedValueOnce({ session_id: "browser-session", status: "cancelled" });
render(<ChannelQrConnectFlow token="tok" channelName="plugin-chat" showQrCode={false}
labels={{ ...labels, scanTitle: "Authorize in browser", scanDescription: "Continue in the browser." }}
onFeaturesUpdate={vi.fn()} />);
fireEvent.click(screen.getByRole("button", { name: "Connect", exact: true }));
expect(await screen.findByText("Continue in the browser.")).toBeVisible();
expect(screen.getByText("Waiting")).toBeVisible();
expect(generateQr).not.toHaveBeenCalled();
expect(screen.queryByRole("img")).not.toBeInTheDocument();
expect(screen.getByText("Authorize in browser").parentElement?.parentElement)
.not.toHaveClass("sm:grid-cols-[auto_minmax(0,1fr)]");
fireEvent.click(screen.getByRole("button", { name: "Cancel", exact: true }));
expect(await screen.findByText("Stopped")).toBeVisible();
expect(requestMutation).toHaveBeenLastCalledWith("settings.channel.connect.cancel", {
channel: "plugin-chat", session_id: "browser-session",
}, 20_000);
});
it("polls browser-only authorization to completion without generating QR", async () => {
const generateQr = vi.spyOn(QRCode, "toDataURL").mockResolvedValue("data:image/png;base64,unused");
const onFeaturesUpdate = vi.fn();
const features = { features: [], enabled_count: 0 };
requestMutation
.mockResolvedValueOnce({ session_id: "browser-session", status: "pending", qr_url: "https://example.com/authorize" })
.mockResolvedValueOnce({ session_id: "browser-session", status: "succeeded", nanobot_features: features });
render(<ChannelQrConnectFlow token="tok" channelName="plugin-chat" showQrCode={false}
labels={labels} onFeaturesUpdate={onFeaturesUpdate} />);
fireEvent.click(screen.getByRole("button", { name: "Connect", exact: true }));
expect(await screen.findByText("Connected", {}, { timeout: 2000 })).toBeVisible();
expect(onFeaturesUpdate).toHaveBeenCalledWith(features);
expect(requestMutation).toHaveBeenLastCalledWith("settings.channel.connect.poll", {
channel: "plugin-chat", session_id: "browser-session",
}, 150_000);
expect(generateQr).not.toHaveBeenCalled();
});
it("forwards current channel parameters without restarting on rerender and preserves forced retries", async () => {
const props = {
token: "tok",
+7 -4
View File
@@ -5,13 +5,16 @@ import { LinearAvatar } from "../../../nanobot/channels/linear/webui/LinearAvata
afterEach(cleanup);
describe("Linear workspace logo", () => {
it("loads a real CDN logo in a fixed-size square and recovers to the workspace icon", () => {
it("keeps workspace artwork uncropped without a background plate and recovers to an icon", () => {
const view = render(<LinearAvatar workspace name="nanobot" url="https://public.linear.app/org/logo" />);
const image = view.container.querySelector("img")!;
expect(image).toHaveAttribute("width", "36");
expect(image).toHaveAttribute("height", "36");
expect(image).toHaveAttribute("width", "28");
expect(image).toHaveAttribute("height", "28");
expect(image).toHaveAttribute("referrerpolicy", "no-referrer");
expect(image.parentElement).toHaveClass("h-9", "w-9", "rounded-control");
expect(image.parentElement).toHaveClass("h-7", "w-7");
expect(image.parentElement).not.toHaveClass("overflow-hidden", "bg-muted");
expect(image).toHaveClass("object-contain");
expect(view.container.querySelector("svg")).toBeNull();
fireEvent.error(image);
expect(view.container.querySelector("img")).toBeNull();
expect(view.container.querySelector("svg")).not.toBeNull();
+58 -2
View File
@@ -2,6 +2,7 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-libra
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { LinearMemberAccess } from "../../../nanobot/channels/linear/webui/LinearMemberAccess";
import { linearMemberAccessStore } from "../../../nanobot/channels/linear/webui/member-access-store";
import type { LinearMembersPayload } from "../../../nanobot/channels/linear/webui/types";
const { requestMutation, context } = vi.hoisted(() => {
@@ -49,6 +50,61 @@ async function openMembers() {
}
describe("Linear member access", () => {
it("forgets a removed workspace's cached permissions and ignores its old in-flight save", async () => {
const store = linearMemberAccessStore(context.client, context.token, "", "org-1");
await store.load();
const deferred = deferNextRequest();
const saving = store.setAllowed("u2", true, "not confirmed");
store.invalidate();
deferred.resolve({ ...roster, members: roster.members.map(member => ({ ...member, allowed: true })) });
await saving;
expect(store.getSnapshot()).toMatchObject({ payload: null, saves: {}, loading: false });
requestMutation.mockResolvedValue({ ...roster, members: roster.members.map(member => ({ ...member, allowed: false })) });
await store.load();
expect(store.getSnapshot().payload?.members.every(member => !member.allowed)).toBe(true);
});
it("shows members without team subtitles or a team filter", async () => {
await openMembers();
expect(screen.queryByRole("combobox", { name: "Filter by team" })).not.toBeInTheDocument();
expect(screen.queryByText("nanobot", { exact: true })).not.toBeInTheDocument();
});
it("keeps one workspace-level switch per member regardless of team membership", async () => {
requestMutation.mockResolvedValue({ ...roster, members: [
{ ...roster.members[0], teams: ["Core", "Desktop"] },
{ ...roster.members[1], teams: ["Core"] },
] });
await openMembers();
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
expect(screen.queryByText(/Core|Desktop/)).not.toBeInTheDocument();
expect(requestMutation).toHaveBeenCalledTimes(1);
expect(xubin()).toBeChecked();
expect(yongru()).not.toBeChecked();
expect(screen.getAllByRole("switch")).toHaveLength(2);
});
it("searches names and user IDs, not hidden team metadata", async () => {
requestMutation.mockResolvedValue({ ...roster, members: [
{ ...roster.members[0], teams: ["Core", "Desktop"] },
{ ...roster.members[1], teams: ["Core"] },
] });
await openMembers();
const search = screen.getByRole("textbox", { name: "Search members" });
fireEvent.change(search, { target: { value: " xubin " } });
expect(xubin()).toBeVisible();
expect(screen.getAllByRole("switch")).toHaveLength(1);
fireEvent.change(search, { target: { value: "u2" } });
expect(yongru()).toBeVisible();
expect(screen.getAllByRole("switch")).toHaveLength(1);
fireEvent.change(search, { target: { value: "Desktop" } });
expect(screen.queryByRole("switch")).not.toBeInTheDocument();
expect(screen.getByText("No matching active members.")).toBeVisible();
fireEvent.change(search, { target: { value: "" } });
expect(screen.getAllByRole("switch")).toHaveLength(2);
expect(requestMutation).toHaveBeenCalledTimes(1);
});
it("renders Linear avatars without referrers and falls back when an image fails", async () => {
const avatar = "https://public.linear.app/u2/avatar";
requestMutation.mockResolvedValue({ ...roster, members: roster.members.map(member => ({
@@ -112,7 +168,7 @@ describe("Linear member access", () => {
expect(requestMutation).toHaveBeenCalledTimes(1);
fireEvent.click(header());
expect(requestMutation).toHaveBeenCalledTimes(1);
expect(screen.getByText("Finding your teammates…")).toBeVisible();
expect(screen.getByText("Finding members…")).toBeVisible();
expect(screen.getByRole("textbox", { name: "Search members" })).toBeEnabled();
expect(header()).toBeEnabled();
expect(document.querySelector(".animate-spin")).toBeNull();
@@ -139,7 +195,7 @@ describe("Linear member access", () => {
fireEvent.click(header());
expect(yongru()).toBeVisible();
expect(requestMutation).toHaveBeenCalledTimes(1);
expect(screen.queryByText("Finding your teammates…")).not.toBeInTheDocument();
expect(screen.queryByText("Finding members…")).not.toBeInTheDocument();
});
it("shows a stale list immediately while revalidating, without disabling the list", async () => {
@@ -0,0 +1,167 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { LinearResetConnection } from "../../../nanobot/channels/linear/webui/LinearResetConnection";
import type { ChannelConfigField } from "@/components/settings/channels/catalog";
const { requestMutation } = vi.hoisted(() => ({ requestMutation: vi.fn() }));
vi.mock("@/providers/ClientProvider", () => ({
useClient: () => ({ client: { requestMutation }, token: "preview-only" }),
}));
const fields: ChannelConfigField[] = [
{ key: "channels.linear.clientId", label: "Client ID" },
{ key: "channels.linear.publicBaseUrl", label: "URL" },
{ key: "channels.linear.clientSecret", label: "Secret", secret: true },
{ key: "channels.linear.webhookSigningSecret", label: "Webhook secret", secret: true },
{ key: "channels.linear.port", label: "Port", defaultValue: "3979" },
];
const orgs = [
{ organization_id: "one", organization_name: "One" },
{ organization_id: "two", organization_name: "Two" },
];
let remaining = [...orgs];
let failWorkspace: string | null = null;
let failStop = false;
let failSave = false;
beforeEach(() => {
remaining = [...orgs];
failWorkspace = null;
failStop = false;
failSave = false;
requestMutation.mockReset().mockImplementation(async (method, params) => {
if (params.operation === "inspect") return { installations: [...remaining] };
if (params.operation === "disconnect") {
if (params.organization_id === failWorkspace) throw new Error("Linear unavailable");
remaining = remaining.filter(item => item.organization_id !== params.organization_id);
return { installations: [...remaining] };
}
if (method === "settings.feature.disable") return {
features: [{ name: "linear", enabled: false, runtime_status: failStop ? "running" : "stopped" }],
enabled_count: 0,
};
if (method === "settings.channel.configure") {
if (failSave) throw new Error("Save failed");
return { saved: true };
}
throw new Error(`Unexpected mutation: ${method}`);
});
});
afterEach(cleanup);
async function openReset() {
const onWorkspaceRemoved = vi.fn();
const onWorkspacesChange = vi.fn();
render(<LinearResetConnection fields={fields} disabled={false} onBusyChange={vi.fn()}
onFeaturesUpdate={vi.fn()} onWorkspaceRemoved={onWorkspaceRemoved}
onWorkspacesChange={onWorkspacesChange} />);
fireEvent.click(screen.getByRole("button", { name: "Reset Linear connection" }));
const dialog = await screen.findByRole("alertdialog");
return { dialog, onWorkspaceRemoved, onWorkspacesChange,
confirm: () => fireEvent.click(within(dialog).getByRole("button", { name: "Reset", exact: true })) };
}
describe("reset Linear connection", () => {
it("does nothing before confirmation, and cancellation preserves everything", async () => {
const { dialog } = await openReset();
expect(requestMutation).not.toHaveBeenCalled();
expect(dialog).toHaveTextContent("Linear app, issues, comments, chat history and pairing approvals.");
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
expect(requestMutation).not.toHaveBeenCalled();
});
it("separates what is cleared from what is kept and focuses the safe action", async () => {
const { dialog } = await openReset();
expect(dialog).toHaveAccessibleName("Reset Linear?");
expect(dialog).toHaveAccessibleDescription(/Disconnect all workspaces linked through this app and stop the channel/);
expect(within(dialog).getByText("Clears").tagName).toBe("DT");
expect(within(dialog).getByText("Keeps").tagName).toBe("DT");
expect(within(dialog).getByText("Member access settings and this instance’s app configuration, including saved credentials.").tagName).toBe("DD");
expect(within(dialog).getByRole("button", { name: "Cancel" })).toHaveFocus();
expect(within(dialog).getByRole("button", { name: "Reset", exact: true })).toBeEnabled();
});
it("inspects fresh installations, revokes each, stops the channel, then clears settings", async () => {
const { confirm, onWorkspaceRemoved } = await openReset();
confirm();
await waitFor(() => expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument());
expect(onWorkspaceRemoved.mock.calls).toEqual([["one"], ["two"]]);
expect(requestMutation.mock.calls.map(([method, params]) => params.operation ?? method)).toEqual([
"inspect", "disconnect", "disconnect", "inspect", "settings.feature.disable", "settings.channel.configure",
]);
expect(requestMutation).toHaveBeenLastCalledWith("settings.channel.configure", {
name: "linear", values: {
"channels.linear.clientId": "", "channels.linear.publicBaseUrl": "",
"channels.linear.clientSecret": null, "channels.linear.webhookSigningSecret": null,
"channels.linear.port": "3979",
},
}, 150_000);
});
it("preserves credentials and the remaining workspace on partial failure, then resumes", async () => {
failWorkspace = "two";
const { confirm, dialog, onWorkspacesChange } = await openReset();
confirm();
expect(await within(dialog).findByRole("alert")).toHaveTextContent("Reset is incomplete");
expect(remaining).toEqual([orgs[1]]);
expect(onWorkspacesChange).toHaveBeenLastCalledWith([orgs[1]]);
expect(requestMutation.mock.calls.some(([method]) => method === "settings.channel.configure")).toBe(false);
failWorkspace = null;
confirm();
await waitFor(() => expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument());
expect(requestMutation.mock.calls.filter(([, params]) => params.operation === "disconnect" && params.organization_id === "one")).toHaveLength(1);
});
it("does not interpret a missing installation list as an empty one", async () => {
requestMutation.mockResolvedValueOnce({});
const { confirm, dialog } = await openReset();
confirm();
expect(await within(dialog).findByRole("alert")).toHaveTextContent("Could not verify");
expect(requestMutation).toHaveBeenCalledTimes(1);
});
it("does not clear settings while the channel is still running", async () => {
failStop = true;
const { confirm, dialog } = await openReset();
confirm();
expect(await within(dialog).findByRole("alert")).toHaveTextContent("could not be stopped");
expect(requestMutation.mock.calls.some(([method]) => method === "settings.channel.configure")).toBe(false);
});
it("keeps settings when a new workspace appears during reset", async () => {
requestMutation.mockImplementationOnce(async () => {
remaining = [orgs[1]];
return { installations: [] };
});
const { confirm, dialog } = await openReset();
confirm();
expect(await within(dialog).findByRole("alert")).toHaveTextContent("Another workspace was connected");
expect(requestMutation.mock.calls.some(([method]) => method === "settings.channel.configure")).toBe(false);
expect(remaining).toEqual([orgs[1]]);
});
it("can retry a failed config save without revoking removed workspaces again", async () => {
failSave = true;
const { confirm, dialog } = await openReset();
confirm();
expect(await within(dialog).findByRole("alert")).toHaveTextContent("Save failed");
failSave = false;
confirm();
await waitFor(() => expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument());
expect(requestMutation.mock.calls.filter(([, params]) => params.operation === "disconnect")).toHaveLength(2);
});
it("prevents repeat submissions or dismissal while resetting", async () => {
let finish!: (value: unknown) => void;
requestMutation.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
const { confirm, dialog } = await openReset();
confirm();
expect(within(dialog).getByRole("button", { name: "Resetting…" })).toBeDisabled();
expect(within(dialog).getByRole("button", { name: "Cancel" })).toBeDisabled();
fireEvent.keyDown(dialog, { key: "Escape" });
expect(dialog).toBeVisible();
finish({});
await within(dialog).findByRole("alert");
});
});
@@ -0,0 +1,91 @@
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { LinearSecretField } from "../../../nanobot/channels/linear/webui/LinearSecretField";
const field = { key: "channels.linear.clientSecret", label: "OAuth client secret", secret: true };
afterEach(cleanup);
function setup(onSave = vi.fn(async () => {}), configured = true) {
const rendered = render(<LinearSecretField field={field} configured={configured} disabled={false} onSave={onSave} />);
return { ...rendered, onSave };
}
function edit() {
fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));
return screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" });
}
describe("Linear saved secret", () => {
it("shows a saved status rather than an empty editable field", () => {
setup();
expect(screen.getByRole("status")).toHaveTextContent("Saved");
expect(screen.getByRole("group", { name: field.label }).querySelector("input")).toBeNull();
expect(screen.queryByRole("button", { name: "Show secret" })).not.toBeInTheDocument();
});
it("starts with an ordinary blank input when not configured", () => {
const { onSave } = setup(undefined, false);
const input = screen.getByLabelText(field.label, { exact: true, selector: "input" });
expect(input).toHaveValue("");
expect(input).toHaveAttribute("placeholder", "Enter secret");
expect(screen.queryByText("Saved")).not.toBeInTheDocument();
fireEvent.change(input, { target: { value: " " } });
expect(screen.getByRole("button", { name: "Save", exact: true })).toBeDisabled();
fireEvent.keyDown(input, { key: "Enter" });
expect(onSave).not.toHaveBeenCalled();
});
it("does not save on blur or revealing the new draft; Escape restores saved state", () => {
const { onSave } = setup();
const input = edit();
expect(input).toHaveFocus();
fireEvent.change(input, { target: { value: "new-draft" } });
fireEvent.blur(input);
fireEvent.click(screen.getByRole("button", { name: "Show secret" }));
expect(input).toHaveAttribute("type", "text");
expect(onSave).not.toHaveBeenCalled();
fireEvent.keyDown(input, { key: "Escape" });
expect(screen.getByRole("status")).toHaveTextContent("Saved");
expect(screen.getByRole("button", { name: "Replace OAuth client secret" })).toHaveFocus();
expect(edit()).toHaveValue("");
expect(screen.getByLabelText(field.label, { exact: true, selector: "input" })).toHaveAttribute("type", "password");
});
it("keeps the editor stable during a slow save and prevents duplicate commits", async () => {
let finish!: () => void;
const onSave = vi.fn(() => new Promise<void>(resolve => { finish = resolve; }));
setup(onSave);
const input = edit();
fireEvent.change(input, { target: { value: "new-draft" } });
fireEvent.keyDown(input, { key: "Enter" });
fireEvent.keyDown(input, { key: "Enter" });
expect(onSave).toHaveBeenCalledTimes(1);
expect(onSave).toHaveBeenCalledWith(field.key, "new-draft");
expect(input).toBeInTheDocument();
expect(input).toHaveValue("new-draft");
expect(screen.getByRole("group", { name: field.label })).toHaveAttribute("aria-busy", "true");
expect(screen.getByRole("button", { name: "Cancel" })).toBeDisabled();
expect(screen.queryByText("Saved")).not.toBeInTheDocument();
fireEvent.keyDown(input, { key: "Escape" });
expect(input).toHaveValue("new-draft");
await act(async () => finish());
expect(screen.getByRole("status")).toHaveTextContent("Saved");
expect(screen.queryByDisplayValue("new-draft")).not.toBeInTheDocument();
});
it("retains a failed draft for retry without exposing raw server errors", async () => {
const onSave = vi.fn().mockRejectedValueOnce(new Error("transport: new-draft"))
.mockResolvedValueOnce(undefined);
setup(onSave);
const input = edit();
fireEvent.change(input, { target: { value: "new-draft" } });
fireEvent.click(screen.getByRole("button", { name: "Save", exact: true }));
expect(await screen.findByRole("alert")).toHaveTextContent("Could not confirm the save");
expect(screen.getByRole("alert")).not.toHaveTextContent("new-draft");
expect(input).toHaveAccessibleDescription(/Could not confirm/);
expect(input).toHaveValue("new-draft");
fireEvent.click(screen.getByRole("button", { name: "Save", exact: true }));
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Saved"));
expect(onSave).toHaveBeenCalledTimes(2);
});
});
+11 -2
View File
@@ -4,8 +4,9 @@ import { afterEach, beforeEach, vi } from "vitest";
import { SettingsView } from "@/components/settings/SettingsView";
import { ClientProvider } from "@/providers/ClientProvider";
import type { SettingsPayload } from "@/lib/types";
import type { NanobotClient } from "@/lib/nanobot-client";
export { fireEvent, screen, waitFor, within } from "@testing-library/react";
export { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
export const requestMutationMock = vi.fn();
@@ -126,6 +127,7 @@ export function settingsPayload(): SettingsPayload {
export function renderSettingsView(
options: {
client?: NanobotClient;
initialSection?:
| "overview"
| "appearance"
@@ -149,7 +151,14 @@ export function renderSettingsView(
} = {},
) {
render(
<ClientProvider client={{ requestMutation: requestMutationMock } as never} token="tok">
<ClientProvider client={options.client ?? {
requestMutation: requestMutationMock,
status: "open",
onStatus: (handler: (status: "open") => void) => {
handler("open");
return () => {};
},
} as never} token="tok">
<SettingsView
theme="light"
initialSection={options.initialSection ?? "apps"}