A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io
Rust ai-toolsclaude-codecodexdeepseek-harnessdesktop-appgrokgrokbuildhermeskimi-codemcpopen-sourceopencodepiprovider-managementrustskillsskills-managementtauriwsl-support
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { act, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { AuthCenterPanel } from "@/components/settings/AuthCenterPanel";
import { APP_IDS } from "@/config/appSpecs";
import type { QoderEdition } from "@/config/qoder";
import type { QoderAuthStatus, QoderLoginProgress } from "@/lib/api/qoder";
import { writeAuthOpenBrowser } from "@/lib/authLoginLink";
const mocks = vi.hoisted(() => ({ invoke: vi.fn(), copy: vi.fn() }));
vi.mock("@tauri-apps/api/core", () => ({ invoke: mocks.invoke }));
vi.mock("@/lib/clipboard", () => ({ copyText: mocks.copy }));
// The backend serves whichever edition settings select; each edition keeps its
// own saved accounts, so the fixtures hold one auth state per edition.
let active: QoderEdition = "cn";
let authState: Record<QoderEdition, QoderAuthStatus>;
let loginProgress: Record<QoderEdition, QoderLoginProgress>;
const editions = ["global", "cn"] as const;
const otherEdition = (edition: QoderEdition): QoderEdition =>
edition === "global" ? "cn" : "global";
/**
* Mount the Authorization Center with only Qoder visible in the sidebar, so the
* other services' cards stay out of the way.
*/
function mount(edition: QoderEdition = "cn") {
active = edition;
const client = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
});
const invalidate = vi.spyOn(client, "invalidateQueries");
const view = render(
<QueryClientProvider client={client}>
<AuthCenterPanel />
</QueryClientProvider>,
);
return { ...view, client, invalidate };
}
const invalidatedProviderCards = (invalidate: {
mock: { calls: readonly unknown[][] };
}) =>
invalidate.mock.calls.some(
([filters]) =>
JSON.stringify((filters as { queryKey?: unknown })?.queryKey) ===
JSON.stringify(["providers", "qoder"]),
);
function savedAccounts(edition: QoderEdition) {
authState[edition] = {
installed: true,
loggedIn: true,
username: "Existing account",
currentAccountId: "existing",
accounts: [
{
id: "existing",
username: "Existing account",
plan: "Pro",
isCurrent: true,
},
{
id: "saved",
username: "Saved account",
plan: "Free",
isCurrent: false,
},
],
};
}
const accountRow = (name: string) =>
within(screen.getByRole("list"))
.getAllByRole("listitem")
.find((row) => within(row).queryByText(name))!;
beforeAll(() => {
Element.prototype.scrollIntoView ??= vi.fn();
window.matchMedia ??= vi.fn().mockReturnValue({
matches: false,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
});
});
beforeEach(() => {
authState = {
global: { installed: true, loggedIn: false },
cn: { installed: true, loggedIn: false },
};
loginProgress = {
global: { complete: false },
cn: { complete: false },
};
mocks.invoke
.mockReset()
.mockImplementation(
async (command: string, args: Record<string, unknown> = {}) => {
// Qoder is one app: the backend picks the edition, the UI never sends it.
if (command.includes("qoder")) {
expect(args).not.toHaveProperty("app");
expect(args).not.toHaveProperty("edition");
}
const edition = active;
if (command === "get_settings")
return {
qoderEdition: edition,
visibleApps: Object.fromEntries(
APP_IDS.map((app) => [app, app === "qoder"]),
),
};
// Every card mounts once before settings arrive and hide the other
// services; their provider queries just need an empty answer.
if (command === "get_providers") return {};
if (command === "get_current_provider") return "";
if (command === "get_qoder_auth_status")
return structuredClone(authState[edition]);
if (command === "use_qoder_account") {
const account = authState[edition].accounts!.find(
(item) => item.id === args.accountId,
)!;
authState[edition] = {
...authState[edition],
loggedIn: true,
username: account.username,
email: account.email,
plan: account.plan,
currentAccountId: account.id,
accounts: authState[edition].accounts!.map((item) => ({
...item,
isCurrent: item.id === account.id,
})),
};
return structuredClone(authState[edition]);
}
if (command === "delete_qoder_account") {
const account = authState[edition].accounts!.find(
(item) => item.id === args.accountId,
)!;
authState[edition].accounts = authState[edition].accounts!.filter(
(item) => item.id !== account.id,
);
if (account.isCurrent)
Object.assign(authState[edition], {
loggedIn: false,
currentAccountId: null,
username: null,
email: null,
plan: null,
});
return structuredClone(authState[edition]);
}
if (command === "import_current_qoder_account") {
const name = authState[edition].uncollectedLogin!;
const account = {
id: "collected",
username: name,
email: null,
plan: null,
isCurrent: true,
};
authState[edition] = {
...authState[edition],
uncollectedLogin: null,
loggedIn: true,
username: name,
currentAccountId: account.id,
accounts: [...(authState[edition].accounts ?? []), account],
};
return structuredClone(authState[edition]);
}
if (command === "start_qoder_login") return `${edition}-login`;
if (command === "poll_qoder_login")
return structuredClone(loginProgress[edition]);
if (command === "cancel_qoder_login" || command === "open_external")
return;
throw new Error(
`Unexpected command: ${command} ${JSON.stringify(args)}`,
);
},
);
});
describe("Qoder accounts in the Authorization Center", () => {
it.each(editions)(
"signs in a new %s account in the browser and refreshes the provider cards",
async (edition) => {
const url =
edition === "global"
? "https://qoder.com/login?code=fixture"
: "https://qoder.com.cn/login?code=fixture";
loginProgress[edition] = { complete: false, authUrl: url };
const user = userEvent.setup();
const { invalidate } = mount(edition);
expect(await screen.findByText("qoder.signedOut")).toBeInTheDocument();
await user.click(
screen.getByRole("button", { name: "qoder.loginWithBrowser" }),
);
await waitFor(() =>
expect(mocks.invoke).toHaveBeenCalledWith("start_qoder_login", {
accountId: null,
}),
);
await waitFor(() =>
expect(mocks.invoke).toHaveBeenCalledWith("open_external", { url }),
);
expect(screen.getByText("qoder.loginWaiting")).toBeInTheDocument();
authState[edition] = {
installed: true,
loggedIn: false,
accounts: [
{
id: "new-account",
username: "Fixture Account",
plan: "Pro",
isCurrent: false,
},
],
};
loginProgress[edition] = { complete: true, accountId: "new-account" };
await screen.findByText("Fixture Account", {}, { timeout: 4000 });
await waitFor(() =>
expect(
screen.queryByText("qoder.loginWaiting"),
).not.toBeInTheDocument(),
);
expect(mocks.invoke).toHaveBeenCalledWith("cancel_qoder_login", {
flowId: `${edition}-login`,
});
expect(invalidatedProviderCards(invalidate)).toBe(true);
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
// A new login never switches Qoder over by itself.
expect(mocks.invoke).not.toHaveBeenCalledWith(
"use_qoder_account",
expect.anything(),
);
invalidate.mockClear();
await user.click(
screen.getByRole("button", { name: "qoder.useAccount" }),
);
await waitFor(() =>
expect(mocks.invoke).toHaveBeenCalledWith("use_qoder_account", {
accountId: "new-account",
}),
);
await screen.findByText("qoder.currentAccount");
expect(invalidatedProviderCards(invalidate)).toBe(true);
expect(authState[otherEdition(edition)].loggedIn).toBe(false);
expect(
mocks.invoke.mock.calls.filter(
([command]) => command === "open_external",
),
).toHaveLength(1);
},
);
it("only copies the login link when the Authorization Center keeps the browser closed", async () => {
const url = "https://qoder.com.cn/login?code=fixture";
loginProgress.cn = { complete: false, authUrl: url };
writeAuthOpenBrowser(false);
try {
const user = userEvent.setup();
mount("cn");
await user.click(
await screen.findByRole("button", { name: "qoder.loginWithBrowser" }),
);
await waitFor(() => expect(mocks.copy).toHaveBeenCalledWith(url));
expect(mocks.invoke).not.toHaveBeenCalledWith(
"open_external",
expect.anything(),
);
// 用户自己点「打开登录页面」时照样打开浏览器
await user.click(
await screen.findByRole("button", { name: "qoder.loginOpenBrowser" }),
);
await waitFor(() =>
expect(mocks.invoke).toHaveBeenCalledWith("open_external", { url }),
);
} finally {
writeAuthOpenBrowser(true);
}
});
it("reports a completed login whose account did not show up", async () => {
const user = userEvent.setup();
mount("cn");
await user.click(
await screen.findByRole("button", { name: "qoder.loginWithBrowser" }),
);
await waitFor(() =>
expect(mocks.invoke).toHaveBeenCalledWith("poll_qoder_login", {
flowId: "cn-login",
}),
);
loginProgress.cn = { complete: true, accountId: "missing" };
expect(
await screen.findByRole("alert", {}, { timeout: 4000 }),
).toHaveTextContent("qoder.loginNotConfirmed");
expect(
screen.getByRole("button", { name: "qoder.loginWithBrowser" }),
).toBeEnabled();
});
it.each(editions)(
"shows only the %s edition selected in settings",
async (edition) => {
const other = otherEdition(edition);
authState[edition].accounts = [
{ id: "mine", username: "Selected account", isCurrent: false },
];
authState[other].accounts = [
{ id: "theirs", username: "Other edition account", isCurrent: false },
];
const user = userEvent.setup();
mount(edition);
await screen.findByText("Selected account");
expect(
screen.queryByText("Other edition account"),
).not.toBeInTheDocument();
// No in-page switcher: the edition is chosen on the Apps page.
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
expect(screen.getByText("qoder.editionHint")).toBeInTheDocument();
expect(screen.getByText("qoder.accountCount")).toBeInTheDocument();
await user.click(
within(accountRow("Selected account")).getByRole("button", {
name: "qoder.useAccount",
}),
);
await waitFor(() =>
expect(mocks.invoke).toHaveBeenCalledWith("use_qoder_account", {
accountId: "mine",
}),
);
expect(authState[other].currentAccountId).toBeUndefined();
},
);
it("offers to collect a Qoder sign-in that CC Switch has not saved yet", async () => {
authState.cn = {
installed: true,
loggedIn: true,
username: "Native login",
uncollectedLogin: "Native login",
accounts: [{ id: "saved", username: "Saved account", isCurrent: false }],
};
const user = userEvent.setup();
const { invalidate } = mount("cn");
expect(
await screen.findByText("qoder.uncollectedLogin"),
).toBeInTheDocument();
// Switching now would overwrite the uncollected login: collect it first.
const use = within(accountRow("Saved account")).getByRole("button", {
name: "qoder.useAccount",
});
expect(use).toBeDisabled();
expect(use).toHaveAttribute("title", "qoder.uncollectedLoginHint");
expect(
mocks.invoke.mock.calls.some(
([command]) => command === "import_current_qoder_account",
),
).toBe(false);
await user.click(
screen.getByRole("button", { name: "qoder.collectAccount" }),
);
await waitFor(() =>
expect(mocks.invoke).toHaveBeenCalledWith("import_current_qoder_account"),
);
expect(await screen.findByText("Native login")).toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "qoder.collectAccount" }),
).not.toBeInTheDocument();
expect(invalidatedProviderCards(invalidate)).toBe(true);
expect(
within(accountRow("Saved account")).getByRole("button", {
name: "qoder.useAccount",
}),
).toBeEnabled();
});
it("shows a Qoder login that matches no saved account without a switch action", async () => {
authState.cn = {
installed: true,
loggedIn: true,
email: "[email protected]",
plan: "Pro",
accounts: [],
};
mount("cn");
expect(await screen.findByText("qoder.loggedInAs")).toBeInTheDocument();
expect(screen.getByText("qoder.signedIn")).toBeInTheDocument();
expect(screen.getByText("Pro")).toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "qoder.useAccount" }),
).not.toBeInTheDocument();
expect(
screen.getByRole("button", { name: "qoder.loginWithBrowser" }),
).toBeEnabled();
});
it.each(editions)(
"reauthenticates the saved %s account without switching or creating another row",
async (edition) => {
savedAccounts(edition);
const user = userEvent.setup();
mount(edition);
await screen.findByText("Saved account");
await user.click(
within(accountRow("Saved account")).getByRole("button", {
name: "qoder.signInAgain",
}),
);
await waitFor(() =>
expect(mocks.invoke).toHaveBeenCalledWith("start_qoder_login", {
accountId: "saved",
}),
);
authState[edition].accounts![1].plan = "Pro";
loginProgress[edition] = { complete: true, accountId: "saved" };
await waitFor(
() =>
expect(
within(accountRow("Saved account")).getByText("Pro"),
).toBeInTheDocument(),
{ timeout: 4000 },
);
expect(authState[edition].accounts).toHaveLength(2);
expect(authState[edition].currentAccountId).toBe("existing");
expect(mocks.invoke).not.toHaveBeenCalledWith(
"use_qoder_account",
expect.anything(),
);
},
);
it("switches the Qoder login to a saved account and refreshes the provider cards", async () => {
savedAccounts("global");
const user = userEvent.setup();
const { invalidate } = mount("global");
await screen.findByText("Saved account");
expect(
within(accountRow("Existing account")).getByText("qoder.currentAccount"),
).toBeInTheDocument();
await user.click(
within(accountRow("Saved account")).getByRole("button", {
name: "qoder.useAccount",
}),
);
await waitFor(() =>
expect(authState.global.currentAccountId).toBe("saved"),
);
await waitFor(() =>
expect(
within(accountRow("Saved account")).getByText("qoder.currentAccount"),
).toBeInTheDocument(),
);
expect(
within(accountRow("Existing account")).queryByText(
"qoder.currentAccount",
),
).not.toBeInTheDocument();
expect(invalidatedProviderCards(invalidate)).toBe(true);
});
it("shows a failed switch without changing the current account", async () => {
savedAccounts("cn");
const invoke = mocks.invoke.getMockImplementation()!;
mocks.invoke.mockImplementation((command, args) =>
command === "use_qoder_account"
? Promise.reject(new Error("Qoder is running a task"))
: invoke(command, args),
);
const user = userEvent.setup();
mount("cn");
await screen.findByText("Saved account");
await user.click(
within(accountRow("Saved account")).getByRole("button", {
name: "qoder.useAccount",
}),
);
expect(await screen.findByRole("alert")).toHaveTextContent(
"Qoder is running a task",
);
expect(
within(accountRow("Existing account")).getByText("qoder.currentAccount"),
).toBeInTheDocument();
expect(authState.cn.currentAccountId).toBe("existing");
});
it.each(editions)(
"adds another %s account without changing the current login",
async (edition) => {
savedAccounts(edition);
const user = userEvent.setup();
mount(edition);
await user.click(
await screen.findByRole("button", { name: "qoder.addAccount" }),
);
await waitFor(() =>
expect(mocks.invoke).toHaveBeenCalledWith("start_qoder_login", {
accountId: null,
}),
);
authState[edition].accounts!.push({
id: "added",
username: "Added account",
isCurrent: false,
});
loginProgress[edition] = { complete: true, accountId: "added" };
await screen.findByText("Added account", {}, { timeout: 4000 });
expect(authState[edition].currentAccountId).toBe("existing");
expect(authState[edition].accounts).toHaveLength(3);
expect(mocks.invoke).not.toHaveBeenCalledWith(
"use_qoder_account",
expect.anything(),
);
},
);
it.each(editions)(
"confirms removal of a saved %s account and preserves the current login and other edition",
async (edition) => {
savedAccounts(edition);
const other = otherEdition(edition);
savedAccounts(other);
const untouched = structuredClone(authState[other]);
const user = userEvent.setup();
const { invalidate } = mount(edition);
await screen.findByText("Saved account");
const trash = () =>
within(accountRow("Saved account")).getByRole("button", {
name: "qoder.deleteAccount",
});
await user.click(trash());
expect(await screen.findByRole("dialog")).toHaveTextContent(
"qoder.deleteAccountConfirm",
);
expect(mocks.invoke).not.toHaveBeenCalledWith(
"delete_qoder_account",
expect.anything(),
);
await user.click(
within(screen.getByRole("dialog")).getByRole("button", {
name: "common.cancel",
}),
);
expect(authState[edition].accounts).toHaveLength(2);
await user.click(trash());
await user.click(
within(screen.getByRole("dialog")).getByRole("button", {
name: "common.delete",
}),
);
await waitFor(() =>
expect(mocks.invoke).toHaveBeenCalledWith("delete_qoder_account", {
accountId: "saved",
}),
);
await waitFor(() =>
expect(screen.queryByText("Saved account")).not.toBeInTheDocument(),
);
expect(authState[edition].currentAccountId).toBe("existing");
expect(authState[other]).toEqual(untouched);
expect(invalidatedProviderCards(invalidate)).toBe(true);
},
);
it("warns before deleting the current account and keeps the account list usable afterwards", async () => {
savedAccounts("cn");
const user = userEvent.setup();
mount("cn");
await screen.findByText("Existing account");
await user.click(
within(accountRow("Existing account")).getByRole("button", {
name: "qoder.deleteAccount",
}),
);
expect(await screen.findByRole("dialog")).toHaveTextContent(
"qoder.deleteCurrentAccountConfirm",
);
await user.click(
within(screen.getByRole("dialog")).getByRole("button", {
name: "common.delete",
}),
);
await waitFor(() => expect(authState.cn.loggedIn).toBe(false));
await waitFor(() =>
expect(screen.queryByText("Existing account")).not.toBeInTheDocument(),
);
expect(screen.getByText("Saved account")).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "qoder.addAccount" }),
).toBeEnabled();
});
it("keeps a failed deletion in its confirmation dialog for retry", async () => {
savedAccounts("cn");
const invoke = mocks.invoke.getMockImplementation()!;
let failing = true;
mocks.invoke.mockImplementation((command, args) =>
command === "delete_qoder_account" && failing
? Promise.reject(new Error("Native credential is busy"))
: invoke(command, args),
);
const user = userEvent.setup();
mount("cn");
await screen.findByText("Saved account");
await user.click(
within(accountRow("Saved account")).getByRole("button", {
name: "qoder.deleteAccount",
}),
);
await user.click(
within(screen.getByRole("dialog")).getByRole("button", {
name: "common.delete",
}),
);
await waitFor(() =>
expect(screen.getByRole("dialog")).toHaveTextContent(
"Native credential is busy",
),
);
expect(authState.cn.accounts).toHaveLength(2);
expect(authState.cn.currentAccountId).toBe("existing");
failing = false;
await user.click(
within(screen.getByRole("dialog")).getByRole("button", {
name: "common.delete",
}),
);
await waitFor(() =>
expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),
);
expect(authState.cn.accounts).toHaveLength(1);
});
it("cancels the pending login when the user cancels it", async () => {
const user = userEvent.setup();
mount("global");
await user.click(
await screen.findByRole("button", { name: "qoder.loginWithBrowser" }),
);
await waitFor(() =>
expect(mocks.invoke).toHaveBeenCalledWith("poll_qoder_login", {
flowId: "global-login",
}),
);
await user.click(screen.getByRole("button", { name: "common.cancel" }));
await waitFor(() =>
expect(mocks.invoke).toHaveBeenCalledWith("cancel_qoder_login", {
flowId: "global-login",
}),
);
expect(screen.queryByText("qoder.loginWaiting")).not.toBeInTheDocument();
expect(
screen.getByRole("button", { name: "qoder.loginWithBrowser" }),
).toBeEnabled();
});
it("cancels the selected edition's pending login when leaving the Authorization Center", async () => {
const user = userEvent.setup();
const { unmount } = mount("cn");
await user.click(
await screen.findByRole("button", { name: "qoder.loginWithBrowser" }),
);
await waitFor(() =>
expect(mocks.invoke).toHaveBeenCalledWith("poll_qoder_login", {
flowId: "cn-login",
}),
);
unmount();
await waitFor(() =>
expect(mocks.invoke).toHaveBeenCalledWith("cancel_qoder_login", {
flowId: "cn-login",
}),
);
});
it("cancels a late start response after leaving the account screen", async () => {
let resolveStart!: (id: string) => void;
const delayed = new Promise<string>((resolve) => {
resolveStart = resolve;
});
const invoke = mocks.invoke.getMockImplementation()!;
mocks.invoke.mockImplementation((command, args) =>
command === "start_qoder_login" ? delayed : invoke(command, args),
);
const user = userEvent.setup();
const { unmount } = mount("global");
await user.click(
await screen.findByRole("button", { name: "qoder.loginWithBrowser" }),
);
unmount();
await act(async () => resolveStart("late-login"));
await waitFor(() =>
expect(mocks.invoke).toHaveBeenCalledWith("cancel_qoder_login", {
flowId: "late-login",
}),
);
expect(mocks.invoke).not.toHaveBeenCalledWith(
"poll_qoder_login",
expect.anything(),
);
expect(mocks.invoke).not.toHaveBeenCalledWith(
"open_external",
expect.anything(),
);
});
it("shows native login failures and cancels the failed flow", async () => {
savedAccounts("cn");
loginProgress.cn = {
complete: false,
error: "Native browser login denied",
};
const user = userEvent.setup();
mount("cn");
await user.click(
await screen.findByRole("button", { name: "qoder.addAccount" }),
);
expect(await screen.findByRole("alert")).toHaveTextContent(
"Native browser login denied",
);
await waitFor(() =>
expect(mocks.invoke).toHaveBeenCalledWith("cancel_qoder_login", {
flowId: "cn-login",
}),
);
expect(authState.cn.currentAccountId).toBe("existing");
expect(mocks.invoke).not.toHaveBeenCalledWith(
"open_external",
expect.anything(),
);
expect(
screen.getByRole("button", { name: "qoder.addAccount" }),
).toBeEnabled();
});
it("requires the selected edition to be installed before starting browser login", async () => {
authState.cn.installed = false;
mount("cn");
expect(
await screen.findByText("qoder.loginInstallRequired"),
).toBeInTheDocument();
expect(screen.getByText("common.notInstalled")).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "qoder.loginWithBrowser" }),
).toBeDisabled();
expect(mocks.invoke).not.toHaveBeenCalledWith(
"start_qoder_login",
expect.anything(),
);
});
it("shows a status error with a retry", async () => {
const invoke = mocks.invoke.getMockImplementation()!;
let failing = true;
mocks.invoke.mockImplementation((command, args) =>
command === "get_qoder_auth_status" && failing
? Promise.reject(new Error("settings.json is unreadable"))
: invoke(command, args),
);
const user = userEvent.setup();
mount("cn");
expect(
await screen.findByText("settings.json is unreadable"),
).toBeInTheDocument();
expect(screen.getByText("qoder.statusFailed")).toBeInTheDocument();
failing = false;
await user.click(screen.getByRole("button", { name: "common.retry" }));
expect(await screen.findByText("qoder.signedOut")).toBeInTheDocument();
});
});