Files
t3code/apps/web/src/components/settings/ProviderSettingsPanel.environment.test.tsx
T
+36 de34391427 feat(orchestrator): introduce new orchestrator (#2829)
Co-authored-by: maria-rcks <[email protected]>
Co-authored-by: Bilal Bakr <[email protected]>
Co-authored-by: shivam <[email protected]>
Co-authored-by: Vitalii Yehorov <[email protected]>
Co-authored-by: Jake Leventhal <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Alex Southwell <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Nicholas Wasmiller <[email protected]>
Co-authored-by: PB <[email protected]>
Co-authored-by: Exotic <[email protected]>
Co-authored-by: Yash Singh <[email protected]>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Theo Browne <[email protected]>
Co-authored-by: Gabriel De Andrade <[email protected]>
Co-authored-by: Dara Adedeji <[email protected]>
Co-authored-by: scratchyone <[email protected]>
Co-authored-by: Dominic Roy <[email protected]>
Co-authored-by: chukfinley <[email protected]>
Co-authored-by: Primož Ajdišek <[email protected]>
Co-authored-by: benthecarman <[email protected]>
Co-authored-by: NaveDanan <[email protected]>
Co-authored-by: aaditagrawal <[email protected]>
Co-authored-by: Aditya Garud <[email protected]>
Co-authored-by: Nick Anisimov <[email protected]>
Co-authored-by: MacKinley Smith <[email protected]>
Co-authored-by: Yordis Prieto <[email protected]>
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: AKolenda <[email protected]>
Co-authored-by: Guillermo Casanova <[email protected]>
Co-authored-by: Otavio Salvador <[email protected]>
Co-authored-by: Shirish Pothi <[email protected]>
Co-authored-by: Ishaan Kothari <[email protected]>
Co-authored-by: Bob Fowler <[email protected]>
Co-authored-by: Anton Bezdenezhnykh <[email protected]>
Co-authored-by: ValeraZSD <[email protected]>
Co-authored-by: Ephraim <[email protected]>
Co-authored-by: Ryan Ilano <[email protected]>
Co-authored-by: Alex <[email protected]>
Co-authored-by: maco <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Tristan Knight <[email protected]>
Co-authored-by: PR Batch Tester <[email protected]>
Co-authored-by: oliver <[email protected]>
Co-authored-by: kamkm <[email protected]>
Signed-off-by: Yordis Prieto <[email protected]>
2026-10-02 12:22:22 -07:00

621 lines
21 KiB
TypeScript

import type { ReactElement } from "react";
import {
DEFAULT_UNIFIED_SETTINGS,
EnvironmentId,
ProviderDriverKind,
ProviderInstanceId,
type ServerProvider,
type UnifiedSettings,
} from "@t3tools/contracts";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { visitElements } from "../../test/reactElementTree";
import { reactHookHarness as hooks } from "../../test/reactHookHarness";
const atoms = vi.hoisted(() => ({
providers: null as ReadonlyArray<ServerProvider> | null,
providersAtom: Symbol("providers"),
refreshProviders: Symbol("refreshProviders"),
updateProvider: Symbol("updateProvider"),
uninstallAcpRegistryManagedBinary: Symbol("uninstallAcpRegistryManagedBinary"),
acceptAcpRegistryUrlAuth: Symbol("acceptAcpRegistryUrlAuth"),
}));
const commands = vi.hoisted(() => ({
refresh: vi.fn(),
updateProvider: vi.fn(),
uninstall: vi.fn(),
acceptUrlAuth: vi.fn(),
}));
const settingsState = vi.hoisted(() => ({
value: null as UnifiedSettings | null,
readEnvironmentIds: [] as EnvironmentId[],
updateEnvironmentIds: [] as EnvironmentId[],
mutationEnvironmentIds: [] as EnvironmentId[],
updateSettings: vi.fn(),
mutateProviderInstance: vi.fn(),
updateClientSettings: vi.fn(),
}));
const settingsSearchState = vi.hoisted(() => ({
targetId: null as string | null,
effects: [] as Array<() => void>,
}));
vi.mock("react", async (importOriginal) => {
const actual = await importOriginal<typeof import("react")>();
const { reactHookHarness } = await import("../../test/reactHookHarness");
return {
...actual,
useCallback: reactHookHarness.useCallback,
useEffect: (effect: () => void) => settingsSearchState.effects.push(effect),
useMemo: reactHookHarness.useMemo,
useRef: reactHookHarness.useRef,
useState: reactHookHarness.useState,
};
});
vi.mock("./settingsLayout", async (importOriginal) => {
const actual = await importOriginal<typeof import("./settingsLayout")>();
return {
...actual,
useSettingsSearchTargetId: () => settingsSearchState.targetId,
};
});
vi.mock("./SettingsScopeSentence", () => ({ SettingsScopeSentence: () => null }));
vi.mock("react/compiler-runtime", async () => {
const { reactHookHarness } = await import("../../test/reactHookHarness");
return { c: reactHookHarness.useMemoCache };
});
vi.mock("@effect/atom-react", () => ({
useAtomValue: () => atoms.providers,
}));
vi.mock("../../state/server", () => ({
EMPTY_SERVER_PROVIDERS: [],
serverEnvironment: {
providersValueAtom: () => atoms.providersAtom,
refreshProviders: atoms.refreshProviders,
updateProvider: atoms.updateProvider,
uninstallAcpRegistryManagedBinary: atoms.uninstallAcpRegistryManagedBinary,
acceptAcpRegistryUrlAuth: atoms.acceptAcpRegistryUrlAuth,
},
}));
vi.mock("../../state/use-atom-command", () => ({
useAtomCommand: (atom: symbol) =>
atom === atoms.refreshProviders
? commands.refresh
: atom === atoms.uninstallAcpRegistryManagedBinary
? commands.uninstall
: atom === atoms.acceptAcpRegistryUrlAuth
? commands.acceptUrlAuth
: commands.updateProvider,
}));
vi.mock("../../hooks/useSettings", () => ({
useUpdateClientSettings: () => settingsState.updateClientSettings,
useEnvironmentSettings: (environmentId: EnvironmentId) => {
settingsState.readEnvironmentIds.push(environmentId);
return settingsState.value;
},
useUpdateEnvironmentSettings: (environmentId: EnvironmentId) => {
settingsState.updateEnvironmentIds.push(environmentId);
return settingsState.updateSettings;
},
usePersistEnvironmentProviderInstanceMutation: (environmentId: EnvironmentId) => {
settingsState.mutationEnvironmentIds.push(environmentId);
return settingsState.mutateProviderInstance;
},
}));
vi.mock("../../environments/primary", () => ({
usePrimarySessionState: () => ({ data: null, error: null, isPending: false, refresh: vi.fn() }),
}));
vi.mock("../../state/session", () => ({
useEnvironmentSessionState: () => ({ data: null, hasError: false, isPending: true }),
}));
vi.mock("../../state/entities", () => ({
useProjects: () => [],
}));
import { EnvironmentProviderSettings } from "./ProviderSettingsPanel";
const environmentId = EnvironmentId.make("remote-device");
const codexId = ProviderInstanceId.make("codex");
const customId = ProviderInstanceId.make("codex_work");
function provider(): ServerProvider {
return {
instanceId: codexId,
driver: ProviderDriverKind.make("codex"),
enabled: true,
installed: true,
version: "1.0.0",
status: "ready",
auth: { status: "authenticated" },
checkedAt: "2026-07-24T12:00:00.000Z",
models: [],
slashCommands: [],
skills: [],
versionAdvisory: {
status: "behind_latest",
currentVersion: "1.0.0",
latestVersion: "1.1.0",
updateCommand: "pnpm add -g @openai/codex@latest",
canUpdate: true,
checkedAt: "2026-07-24T12:00:00.000Z",
message: "Update available.",
},
};
}
function renderPanel(options?: {
readonly readOnly?: boolean;
readonly targetInstanceId?: ProviderInstanceId;
}): ReactElement<Record<string, unknown>> {
hooks.beginRender();
return EnvironmentProviderSettings({
environmentId,
environmentLabel: "Remote device",
...(options?.readOnly === undefined ? {} : { readOnly: options.readOnly }),
...(options?.targetInstanceId === undefined
? {}
: { targetInstanceId: options.targetInstanceId }),
}) as ReactElement<Record<string, unknown>>;
}
function isRefreshButton(element: ReactElement<Record<string, unknown>>): boolean {
const children = element.props.children;
return (
Array.isArray(children) &&
children.some(
(child) =>
typeof child === "object" &&
child !== null &&
(child as ReactElement<Record<string, unknown>>).props?.className === "sr-only" &&
(child as ReactElement<Record<string, unknown>>).props?.children ===
"Refresh provider status",
)
);
}
function isAddProviderButton(element: ReactElement<Record<string, unknown>>): boolean {
return element.props["aria-label"] === "Add provider";
}
async function flushPromises(): Promise<void> {
await Promise.resolve();
await Promise.resolve();
}
describe("EnvironmentProviderSettings routing", () => {
beforeEach(() => {
hooks.reset();
atoms.providers = null;
settingsState.value = DEFAULT_UNIFIED_SETTINGS;
settingsState.readEnvironmentIds = [];
settingsState.updateEnvironmentIds = [];
settingsState.mutationEnvironmentIds = [];
settingsState.updateSettings.mockReset();
settingsState.updateClientSettings.mockReset();
settingsSearchState.targetId = null;
settingsSearchState.effects = [];
settingsState.mutateProviderInstance
.mockReset()
.mockResolvedValue({ _tag: "Success", value: {} });
commands.refresh.mockReset().mockResolvedValue({ _tag: "Success" });
commands.updateProvider.mockReset().mockResolvedValue({ _tag: "Success" });
commands.uninstall.mockReset().mockResolvedValue({ _tag: "Success", value: {} });
commands.acceptUrlAuth
.mockReset()
.mockResolvedValue({ _tag: "Success", value: { accepted: true } });
});
it("shows Codex and Claude while hiding untouched disabled provider slots", () => {
const panel = renderPanel();
for (const driver of ["codex", "claudeAgent"] as const) {
expect(
visitElements(
panel,
(element) => element.props.instanceId === driver && element.props.mode === "list",
),
).not.toBeNull();
}
for (const driver of ["cursor", "grok", "pi", "opencode", "antigravity"] as const) {
expect(
visitElements(
panel,
(element) => element.props.instanceId === driver && element.props.mode === "list",
),
).toBeNull();
}
});
it("keeps explicitly configured providers visible when disabled", () => {
const grokId = ProviderInstanceId.make("grok");
settingsState.value = {
...DEFAULT_UNIFIED_SETTINGS,
providerInstances: {
[grokId]: { driver: ProviderDriverKind.make("grok"), enabled: false },
},
};
const panel = renderPanel();
expect(
visitElements(
panel,
(element) => element.props.instanceId === grokId && element.props.mode === "list",
),
).not.toBeNull();
});
it("keeps legacy provider configuration visible when disabled", () => {
settingsState.value = {
...DEFAULT_UNIFIED_SETTINGS,
providers: {
...DEFAULT_UNIFIED_SETTINGS.providers,
grok: {
...DEFAULT_UNIFIED_SETTINGS.providers.grok,
enabled: false,
binaryPath: "/custom/grok",
},
},
};
const panel = renderPanel();
expect(
visitElements(
panel,
(element) => element.props.instanceId === "grok" && element.props.mode === "list",
),
).not.toBeNull();
});
it("coalesces a nullable provider snapshot before rendering array-backed UI", () => {
expect(() => renderPanel()).not.toThrow();
expect(settingsState.readEnvironmentIds).toEqual([environmentId]);
expect(settingsState.updateEnvironmentIds).toEqual([environmentId]);
expect(settingsState.mutationEnvironmentIds).toEqual([environmentId]);
});
it("routes refresh and provider update commands to the selected environment", async () => {
atoms.providers = [provider()];
const panel = renderPanel();
const refreshButton = visitElements(panel, isRefreshButton);
expect(refreshButton).not.toBeNull();
(refreshButton?.props.onClick as (() => void) | undefined)?.();
await flushPromises();
expect(commands.refresh).toHaveBeenCalledWith({
environmentId,
input: { refreshModels: true },
});
const providerCard = visitElements(
panel,
(element) =>
element.props.instanceId === codexId && typeof element.props.onRunUpdate === "function",
);
expect(providerCard).not.toBeNull();
(providerCard?.props.onRunUpdate as (() => void) | undefined)?.();
await flushPromises();
expect(commands.updateProvider).toHaveBeenCalledWith({
environmentId,
input: { provider: ProviderDriverKind.make("codex"), instanceId: codexId },
});
});
it("opens the requested provider instance instead of the first provider", () => {
settingsState.value = {
...DEFAULT_UNIFIED_SETTINGS,
providerInstances: {
[customId]: { driver: ProviderDriverKind.make("codex"), enabled: true },
},
};
atoms.providers = [provider()];
const panel = renderPanel({ targetInstanceId: customId });
const editor = visitElements(panel, (element) => element.props.mode === "editor");
expect(editor?.props.instanceId).toBe(customId);
});
it.each([
["onFavoriteModelsChange", { favorites: [{ provider: codexId, model: "chosen" }] }],
[
"onHiddenModelsChange",
{ providerModelPreferences: { [codexId]: { hiddenModels: ["chosen"], modelOrder: [] } } },
],
[
"onModelOrderChange",
{ providerModelPreferences: { [codexId]: { hiddenModels: [], modelOrder: ["chosen"] } } },
],
])("saves %s on this device without changing the selected server", (action, expected) => {
atoms.providers = [provider()];
const panel = renderPanel();
const editor = visitElements(
panel,
(element) => element.props.instanceId === codexId && element.props.mode === "editor",
);
expect(editor).not.toBeNull();
if (!editor) throw new Error("Provider editor was not rendered");
(editor.props[action] as (models: string[]) => void)(["chosen"]);
expect(settingsState.updateClientSettings).toHaveBeenCalledExactlyOnceWith(expected);
expect(settingsState.updateSettings).not.toHaveBeenCalled();
});
it("does not substitute another account when the requested instance was removed", () => {
atoms.providers = [provider()];
const panel = renderPanel({ targetInstanceId: customId });
expect(visitElements(panel, (element) => element.props.mode === "editor")).toBeNull();
expect(settingsState.updateSettings).not.toHaveBeenCalled();
});
it("keeps provider selection available while write controls are read only", () => {
settingsState.value = {
...DEFAULT_UNIFIED_SETTINGS,
providerInstances: {
[customId]: {
driver: ProviderDriverKind.make("codex"),
enabled: true,
},
},
};
atoms.providers = [provider()];
let panel = renderPanel({ readOnly: true });
const inertWrapper = visitElements(panel, (element) => element.props.inert === true);
expect(inertWrapper).not.toBeNull();
const customRow = visitElements(
panel,
(element) => element.props.instanceId === customId && element.props.mode === "list",
);
expect(customRow?.props.readOnly).toBe(true);
expect(customRow?.props.onSelect).toBeTypeOf("function");
(customRow?.props.onSelect as (() => void) | undefined)?.();
panel = renderPanel({ readOnly: true });
const customEditor = visitElements(
panel,
(element) => element.props.instanceId === customId && element.props.mode === "editor",
);
expect(customEditor).not.toBeNull();
const notice = visitElements(panel, (element) => element.props.title === "Limited permissions");
expect(notice).not.toBeNull();
expect(visitElements(panel, isRefreshButton)).toBeNull();
expect(visitElements(panel, isAddProviderButton)).toBeNull();
});
it("keeps the editable layout interactive when not read only", () => {
atoms.providers = [provider()];
const panel = renderPanel();
expect(visitElements(panel, (element) => element.props.inert === true)).toBeNull();
expect(
visitElements(panel, (element) => element.props.title === "Limited permissions"),
).toBeNull();
expect(visitElements(panel, isRefreshButton)).not.toBeNull();
expect(visitElements(panel, isAddProviderButton)).not.toBeNull();
});
it("keeps Advanced visible when search targets the provider health interval", () => {
let panel = renderPanel();
expect(visitElements(panel, (element) => element.props.title === "Advanced")).not.toBeNull();
expect(
visitElements(panel, (element) => element.props.id === "provider-health-check-interval"),
).not.toBeNull();
settingsSearchState.targetId = "provider-health-check-interval";
panel = renderPanel();
expect(visitElements(panel, (element) => element.props.title === "Advanced")).not.toBeNull();
expect(
visitElements(panel, (element) => element.props.id === "provider-health-check-interval"),
).not.toBeNull();
});
it("deletes and resets provider configuration without erasing shared preferences", async () => {
settingsState.value = {
...DEFAULT_UNIFIED_SETTINGS,
providerInstances: {
[codexId]: {
driver: ProviderDriverKind.make("codex"),
enabled: false,
},
[customId]: {
driver: ProviderDriverKind.make("codex"),
enabled: true,
},
},
providerModelPreferences: {
[customId]: { hiddenModels: ["hidden"], modelOrder: ["model"] },
},
favorites: [{ provider: customId, model: "favorite" }],
};
let panel = renderPanel();
const customRow = visitElements(
panel,
(element) => element.props.instanceId === customId && element.props.mode === "list",
);
(customRow?.props.onSelect as (() => void) | undefined)?.();
panel = renderPanel();
const customCard = visitElements(
panel,
(element) => element.props.instanceId === customId && element.props.mode === "editor",
);
expect(customCard).not.toBeNull();
(customCard?.props.onDelete as (() => void) | undefined)?.();
await flushPromises();
expect(settingsState.mutateProviderInstance).toHaveBeenLastCalledWith({
operation: "remove",
instanceId: customId,
});
settingsState.mutateProviderInstance.mockClear();
const defaultRow = visitElements(
panel,
(element) => element.props.instanceId === codexId && element.props.mode === "list",
);
(defaultRow?.props.onSelect as (() => void) | undefined)?.();
panel = renderPanel();
const defaultCard = visitElements(
panel,
(element) => element.props.instanceId === codexId && element.props.mode === "editor",
);
const resetAction = defaultCard?.props.headerAction;
const resetButton = visitElements(
resetAction,
(element) => typeof element.props.onClick === "function",
);
expect(resetButton).not.toBeNull();
(resetButton?.props.onClick as (() => void) | undefined)?.();
await flushPromises();
const [resetMutation, resetPatch] = settingsState.mutateProviderInstance.mock.lastCall ?? [];
expect(resetMutation).toEqual({ operation: "remove", instanceId: codexId });
expect(Object.keys(resetPatch ?? {}).sort()).toEqual(["providers"]);
expect(resetPatch).not.toHaveProperty("favorites");
expect(resetPatch).not.toHaveProperty("providerModelPreferences");
});
it("updates one provider instance without sending a stale whole map", async () => {
settingsState.value = {
...DEFAULT_UNIFIED_SETTINGS,
providerInstances: {
[customId]: {
driver: ProviderDriverKind.make("codex"),
enabled: true,
displayName: "Work",
},
},
};
const panel = renderPanel();
const card = visitElements(panel, (element) => element.props.instanceId === customId);
const next = {
driver: ProviderDriverKind.make("codex"),
enabled: false,
displayName: "Work",
};
(card?.props.onUpdate as ((instance: typeof next) => void) | undefined)?.(next);
await flushPromises();
expect(settingsState.mutateProviderInstance).toHaveBeenCalledWith(
{ operation: "upsert", instanceId: customId, instance: next },
{},
);
});
it("lets the server decide managed ACP cleanup after an atomic delete", async () => {
const firstId = ProviderInstanceId.make("acpRegistry_kilo_one");
const secondId = ProviderInstanceId.make("acpRegistry_kilo_two");
const registryInstance = {
driver: ProviderDriverKind.make("acpRegistry"),
enabled: true,
config: { agentId: "kilo" },
};
settingsState.value = {
...DEFAULT_UNIFIED_SETTINGS,
providerInstances: {
[firstId]: registryInstance,
[secondId]: registryInstance,
},
};
let panel = renderPanel();
const row = visitElements(
panel,
(element) => element.props.instanceId === firstId && element.props.mode === "list",
);
(row?.props.onSelect as (() => void) | undefined)?.();
panel = renderPanel();
const card = visitElements(
panel,
(element) => element.props.instanceId === firstId && element.props.mode === "editor",
);
(card?.props.onDelete as (() => void) | undefined)?.();
await flushPromises();
expect(settingsState.mutateProviderInstance).toHaveBeenCalledWith({
operation: "remove",
instanceId: firstId,
});
expect(commands.uninstall).toHaveBeenCalledWith({
environmentId,
input: { agentId: "kilo" },
});
});
it("keeps the signed-in ACP account visible when login methods are no longer advertised", () => {
const instanceId = ProviderInstanceId.make("acpRegistry_devin");
settingsState.value = {
...DEFAULT_UNIFIED_SETTINGS,
providerInstances: {
[instanceId]: {
driver: ProviderDriverKind.make("acpRegistry"),
enabled: true,
config: { agentId: "devin" },
},
},
};
atoms.providers = [
{
...provider(),
instanceId,
driver: ProviderDriverKind.make("acpRegistry"),
auth: { status: "authenticated", canLogout: false },
setup: { canAuthenticate: false, canInstall: false },
},
];
const panel = renderPanel({ targetInstanceId: instanceId });
expect(
visitElements(
panel,
(element) =>
typeof element.type === "function" &&
element.type.name === "ProviderAuthenticationSection",
),
).not.toBeNull();
});
it("routes explicit ACP browser authentication consent to the selected environment", async () => {
const instanceId = ProviderInstanceId.make("acpRegistry_antigravity");
const action = {
elicitationId: "google-login-1",
url: "https://accounts.google.com/login",
message: "Continue with Google",
};
settingsState.value = {
...DEFAULT_UNIFIED_SETTINGS,
providerInstances: {
[instanceId]: {
driver: ProviderDriverKind.make("acpRegistry"),
enabled: true,
config: { agentId: "antigravity" },
},
},
};
atoms.providers = [
{
...provider(),
instanceId,
driver: ProviderDriverKind.make("acpRegistry"),
auth: { status: "unauthenticated", action },
},
];
const panel = renderPanel();
const card = visitElements(panel, (element) => element.props.instanceId === instanceId);
(card?.props.onAcceptUrlAuth as ((candidate: typeof action) => void) | undefined)?.(action);
await flushPromises();
expect(commands.acceptUrlAuth).toHaveBeenCalledWith({
environmentId,
input: { instanceId, elicitationId: action.elicitationId },
});
});
});