Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"dependencies": {
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-switch": "^1.2.6",
"@radix-ui/react-tabs": "^1.1.13",
"@tailwindcss/vite": "^4.2.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
Expand Down
14 changes: 10 additions & 4 deletions apps/web/src/api/client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import type { Network } from "@/types/config";
import type { PaginationOptions } from "@/types/pagination";

type PaginationOptionsWithNetwork = PaginationOptions & {
network?: Network | null;
};

const JSON_HEADERS = { "Content-Type": "application/json" } as const;

/**
Expand Down Expand Up @@ -44,10 +49,11 @@ export const apiPaths = {
/** Dealbot app config (network this instance monitors, job rates, etc). */
config: (): string => "/api/config",
/** Simple providers list, for dropdowns/filters. */
providers: (options?: PaginationOptions): string => {
const queryString = options
? buildQueryString(options as Record<string, string | number | boolean | undefined>)
: "";
providers: (options?: PaginationOptionsWithNetwork): string | null => {
if (!options?.network) {
return null;
}
const queryString = buildQueryString(options as Record<string, string | number | boolean | undefined>);
return `/api/v1/providers${queryString}`;
},
} as const;
4 changes: 2 additions & 2 deletions apps/web/src/components/shared/Header/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ModeToggle, NetworkSwitcher, UIVersionToggle } from "@/components/shared";
import { EnvironmentSwitcher, ModeToggle, UIVersionToggle } from "@/components/shared";

const Header = () => (
<header className="sticky top-0 z-50 border-b bg-background/80 backdrop-blur supports-[backdrop-filter]:bg-background/60">
Expand All @@ -14,7 +14,7 @@ const Header = () => (
</div>
</div>
<div className="flex items-center gap-2 sm:gap-4">
<NetworkSwitcher />
<EnvironmentSwitcher />
<UIVersionToggle />
<ModeToggle />
</div>
Expand Down
102 changes: 102 additions & 0 deletions apps/web/src/components/shared/Network/EnvironmentSwitcher.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { server } from "@test/mocks/server";
import { render, screen, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { MemoryRouter } from "react-router-dom";
import { SWRConfig } from "swr";
import { describe, expect, it } from "vitest";
import EnvironmentSwitcher from "./EnvironmentSwitcher";

const configUrl = "/api/config";

function makeConfig(network: "mainnet" | "calibration") {
return {
networks: [
{
network,
dealsPerSpPerHour: 4,
retrievalsPerSpPerHour: 4,
dataSetCreationsPerSpPerHour: 0,
pullChecksPerSpPerHour: 0,
dataRetentionPollIntervalSeconds: 3600,
providersRefreshIntervalSeconds: 3600,
},
],
};
}

// Each render gets a fresh SWR cache so cases setting different /api/config
// responses don't reuse a value cached by a previous case.
function renderSwitcher() {
return render(
<SWRConfig value={{ provider: () => new Map() }}>
<MemoryRouter>
<EnvironmentSwitcher />
</MemoryRouter>
</SWRConfig>,
);
}

describe("EnvironmentSwitcher", () => {
it("links to Staging when current deployment monitors mainnet (Production)", async () => {
server.use(http.get(configUrl, () => HttpResponse.json(makeConfig("mainnet"))));

renderSwitcher();

const link = await screen.findByRole("link", { name: /Switch to Staging/i });
expect(link).toHaveAttribute("href", "https://staging.dealbot.filoz.org");
});

it("links to Production when current deployment monitors calibration (Staging)", async () => {
server.use(http.get(configUrl, () => HttpResponse.json(makeConfig("calibration"))));

renderSwitcher();

const link = await screen.findByRole("link", { name: /Switch to Production/i });
expect(link).toHaveAttribute("href", "https://dealbot.filoz.org");
});

it("shows loading skeleton initially", () => {
server.use(http.get(configUrl, () => new Promise(() => {})));

const { container } = renderSwitcher();

expect(container.querySelector(".animate-pulse")).toBeInTheDocument();
});

it("hides component when config fails to load", async () => {
server.use(http.get(configUrl, () => new HttpResponse(null, { status: 500 })));

const { container } = renderSwitcher();

await waitFor(() => {
expect(container.firstChild).toBeNull();
});
});

it("opens link with rel=noreferrer", async () => {
server.use(http.get(configUrl, () => HttpResponse.json(makeConfig("mainnet"))));

renderSwitcher();

const link = await screen.findByRole("link", { name: /Switch to Staging/i });
expect(link).toHaveAttribute("rel", "noreferrer");
});

it("shows amber dot when linking to Staging (calibration)", async () => {
server.use(http.get(configUrl, () => HttpResponse.json(makeConfig("mainnet"))));

const { container } = renderSwitcher();

await screen.findByRole("link", { name: /Switch to Staging/i });
expect(container.querySelector(".bg-amber-500")).toBeInTheDocument();
});

it("shows emerald dot when linking to Production (mainnet)", async () => {
server.use(http.get(configUrl, () => HttpResponse.json(makeConfig("calibration"))));

const { container } = renderSwitcher();

await screen.findByRole("link", { name: /Switch to Production/i });
expect(container.querySelector(".bg-emerald-500")).toBeInTheDocument();
});
});
35 changes: 35 additions & 0 deletions apps/web/src/components/shared/Network/EnvironmentSwitcher.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { ArrowLeftRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useActiveNetworks } from "@/hooks/useActiveNetworks";
import { ENVIRONMENT_LABEL, NETWORK_DEPLOYMENT_URL, NETWORK_DOT_CLASS } from "./constants";

/**
* Header control that links to the sibling deployment for the other environment.
*
* Environment is determined by which networks the current deployment monitors:
* - Active networks include mainnet → Production deployment → link to Staging
* - Active networks are calibration-only → Staging deployment → link to Production
*/
export default function EnvironmentSwitcher() {
const { activeNetworks, loading, error } = useActiveNetworks();

if (loading) {
return <div className="h-8 w-8 sm:w-40 animate-pulse rounded-md bg-muted" aria-hidden />;
}

if (error || activeNetworks.length === 0) return null;

const isProduction = activeNetworks.includes("mainnet");
const targetEnv = isProduction ? "calibration" : "mainnet";
const label = `Switch to ${ENVIRONMENT_LABEL[targetEnv]}`;

return (
<Button asChild variant="outline" size="sm" title={label} aria-label={label}>
<a href={NETWORK_DEPLOYMENT_URL[targetEnv]} rel="noreferrer">
<span className={`h-2 w-2 rounded-full ${NETWORK_DOT_CLASS[targetEnv]}`} aria-hidden />
<ArrowLeftRight className="h-3.5 w-3.5" />
<span className="hidden sm:inline">{ENVIRONMENT_LABEL[targetEnv]}</span>
</a>
</Button>
);
}
12 changes: 8 additions & 4 deletions apps/web/src/components/shared/Network/NetworkBadge.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
import { useNetworkConfig } from "@/hooks/useNetworkConfig";
import type { Network } from "@/types/config";
import { NETWORK_DOT_CLASS, NETWORK_LABEL } from "./constants";

function NetworkBadge({ className }: { className?: string }) {
const { network, loading, error } = useNetworkConfig();
interface NetworkBadgeProps {
network: Network | null;
loading?: boolean;
className?: string;
}

function NetworkBadge({ network, loading = false, className }: NetworkBadgeProps) {
if (loading) {
return (
<span className={`inline-block h-6 w-40 animate-pulse rounded-full bg-muted ${className ?? ""}`} aria-hidden />
);
}

if (error || network === null) return null;
if (network === null) return null;

return (
<span
Expand Down
142 changes: 31 additions & 111 deletions apps/web/src/components/shared/Network/NetworkSwitcher.test.tsx
Original file line number Diff line number Diff line change
@@ -1,131 +1,51 @@
import { server } from "@test/mocks/server";
import { render, screen, waitFor } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { MemoryRouter } from "react-router-dom";
import { SWRConfig } from "swr";
import { describe, expect, it } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import NetworkSwitcher from "./NetworkSwitcher";

const configUrl = "/api/config";

// Each render gets a fresh SWR cache so cases setting different /api/config
// responses don't reuse a value cached by a previous case.
function renderSwitcher() {
return render(
<SWRConfig value={{ provider: () => new Map() }}>
<MemoryRouter>
<NetworkSwitcher />
</MemoryRouter>
</SWRConfig>,
);
}

describe("NetworkSwitcher", () => {
it("shows current network and a link to switch to the other deployment (mainnet → calibration)", async () => {
server.use(
http.get(configUrl, () =>
HttpResponse.json({
network: "mainnet",
jobs: {},
}),
),
);

renderSwitcher();

const switchLink = await screen.findByRole("link", { name: /Switch to Calibration/i });
expect(switchLink).toHaveAttribute("href", "https://staging.dealbot.filoz.org");
it("renders nothing when only one network is active", () => {
const { container } = render(<NetworkSwitcher networks={["mainnet"]} selected="mainnet" onChange={vi.fn()} />);
expect(container.firstChild).toBeNull();
});

it("offers switching to mainnet when current instance monitors calibration", async () => {
server.use(
http.get(configUrl, () =>
HttpResponse.json({
network: "calibration",
jobs: {},
}),
),
);

renderSwitcher();

const switchLink = await screen.findByRole("link", { name: /Switch to Mainnet/i });
expect(switchLink).toHaveAttribute("href", "https://dealbot.filoz.org");
it("renders a tab for each network when multiple are active", () => {
render(<NetworkSwitcher networks={["mainnet", "calibration"]} selected="mainnet" onChange={vi.fn()} />);
expect(screen.getByRole("tab", { name: /mainnet/i })).toBeInTheDocument();
expect(screen.getByRole("tab", { name: /calibration/i })).toBeInTheDocument();
});

it("shows loading state initially", () => {
server.use(http.get(configUrl, () => new Promise(() => {})));

const { container } = renderSwitcher();

const loadingElement = container.querySelector(".animate-pulse");
expect(loadingElement).toBeInTheDocument();
expect(loadingElement).toHaveClass("bg-muted");
it("marks the selected network tab as aria-selected", () => {
render(<NetworkSwitcher networks={["mainnet", "calibration"]} selected="calibration" onChange={vi.fn()} />);
expect(screen.getByRole("tab", { name: /calibration/i })).toHaveAttribute("aria-selected", "true");
expect(screen.getByRole("tab", { name: /mainnet/i })).toHaveAttribute("aria-selected", "false");
});

it("hides component when network config fails to load", async () => {
server.use(
http.get(configUrl, () => {
return new HttpResponse(null, { status: 500 });
}),
);
it("calls onChange with the clicked network", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(<NetworkSwitcher networks={["mainnet", "calibration"]} selected="mainnet" onChange={onChange} />);

const { container } = renderSwitcher();

await waitFor(() => {
expect(container.firstChild).toBeNull();
});
await user.click(screen.getByRole("tab", { name: /calibration/i }));
expect(onChange).toHaveBeenCalledWith("calibration");
Comment thread
silent-cipher marked this conversation as resolved.
});

it("opens link in new tab with proper security attributes", async () => {
server.use(
http.get(configUrl, () =>
HttpResponse.json({
network: "mainnet",
jobs: {},
}),
),
it("shows emerald dot for mainnet tab", () => {
const { container } = render(
<NetworkSwitcher networks={["mainnet", "calibration"]} selected="mainnet" onChange={vi.fn()} />,
);

renderSwitcher();

const switchLink = await screen.findByRole("link", { name: /Switch to Calibration/i });
expect(switchLink).toHaveAttribute("rel", "noreferrer");
expect(container.querySelector(".bg-emerald-500")).toBeInTheDocument();
});

it("displays correct network indicator color for calibration", async () => {
server.use(
http.get(configUrl, () =>
HttpResponse.json({
network: "calibration",
jobs: {},
}),
),
it("shows amber dot for calibration tab", () => {
const { container } = render(
<NetworkSwitcher networks={["mainnet", "calibration"]} selected="mainnet" onChange={vi.fn()} />,
);

const { container } = renderSwitcher();

await screen.findByRole("link", { name: /Switch to Mainnet/i });

const networkDot = container.querySelector(".bg-emerald-500");
expect(networkDot).toBeInTheDocument();
expect(container.querySelector(".bg-amber-500")).toBeInTheDocument();
});

it("displays correct network indicator color for mainnet", async () => {
server.use(
http.get(configUrl, () =>
HttpResponse.json({
network: "mainnet",
jobs: {},
}),
),
);

const { container } = renderSwitcher();

await screen.findByRole("link", { name: /Switch to Calibration/i });

const networkDot = container.querySelector(".bg-amber-500");
expect(networkDot).toBeInTheDocument();
it("has role=tablist on the container", () => {
render(<NetworkSwitcher networks={["mainnet", "calibration"]} selected="mainnet" onChange={vi.fn()} />);
expect(screen.getByRole("tablist")).toBeInTheDocument();
});
});
Loading