Skip to content
Merged
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 changelog.d/fixes/7547-prefer-public-endpoint-url.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- **fix(dashboard):** Public and managed tunnel endpoints now take precedence over loopback URLs in dashboard setup and copyable API configuration ([#7547](https://github.com/diegosouzapw/OmniRoute/pull/7547)) — thanks @nguyenha935
56 changes: 27 additions & 29 deletions src/app/(dashboard)/dashboard/endpoint/EndpointPageClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import Link from "next/link";
import { Card, Button, Input, Modal, CardSkeleton, SegmentedControl } from "@/shared/components";
import Toggle from "@/shared/components/Toggle";
import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard";
import { useDisplayBaseUrl } from "@/shared/hooks";
import { isPublicDisplayBaseUrl, useDisplayBaseUrl } from "@/shared/hooks";
import { AI_PROVIDERS, getProviderByAlias } from "@/shared/constants/providers";
import { getProviderDisplayName } from "@/lib/display/names";
import { useTranslations } from "next-intl";
Expand All @@ -19,12 +19,7 @@ const CLOUD_ACTION_TIMEOUT_MS = 15000;

type TranslationValues = Record<string, string | number | boolean | Date>;
type CloudflaredTunnelPhase =
| "unsupported"
| "not_installed"
| "stopped"
| "starting"
| "running"
| "error";
"unsupported" | "not_installed" | "stopped" | "starting" | "running" | "error";

type CloudflaredTunnelStatus = {
supported: boolean;
Expand All @@ -43,12 +38,7 @@ type CloudflaredTunnelStatus = {
};

type TailscaleTunnelPhase =
| "unsupported"
| "not_installed"
| "needs_login"
| "stopped"
| "running"
| "error";
"unsupported" | "not_installed" | "needs_login" | "stopped" | "running" | "error";

type TailscaleTunnelStatus = {
supported: boolean;
Expand All @@ -70,13 +60,7 @@ type TailscaleTunnelStatus = {
};

type NgrokTunnelPhase =
| "unsupported"
| "not_installed"
| "stopped"
| "needs_auth"
| "starting"
| "running"
| "error";
"unsupported" | "not_installed" | "stopped" | "needs_auth" | "starting" | "running" | "error";

type NgrokTunnelStatus = {
supported: boolean;
Expand Down Expand Up @@ -187,6 +171,7 @@ export default function APIPageClient({ machineId }: Readonly<APIPageClientProps
const [ngrokToken, setNgrokToken] = useState("");
const [showNgrokTunnel, setShowNgrokTunnel] = useState(true);
const [expandedTunnel, setExpandedTunnel] = useState<string | null>(null);
const [localApiUrl, setLocalApiUrl] = useState("http://localhost:20128/v1");
const [lanUrls, setLanUrls] = useState<string[]>([]);
const [tailscaleIpUrl, setTailscaleIpUrl] = useState<string | null>(null);
const [activeEndpointTab, setActiveEndpointTab] = useState<EndpointTab>("apis");
Expand Down Expand Up @@ -335,6 +320,7 @@ export default function APIPageClient({ machineId }: Readonly<APIPageClientProps
if (res.ok) {
const data = await res.json();
if (mounted) {
if (data.localUrl) setLocalApiUrl(data.localUrl);
setLanUrls(data.lanUrls ?? []);
if (data.tailscaleIpUrl) setTailscaleIpUrl(data.tailscaleIpUrl);
}
Expand Down Expand Up @@ -1080,7 +1066,8 @@ export default function APIPageClient({ machineId }: Readonly<APIPageClientProps
}, [fetchTailscaleStatus, handleTailscaleEnable, tailscalePassword, translateOrFallback]);

const displayBaseUrl = useDisplayBaseUrl();
const baseUrl = `${displayBaseUrl}/v1`;
const displayApiUrl = `${displayBaseUrl}/v1`;
const publicDisplayApiUrl = isPublicDisplayBaseUrl(displayBaseUrl) ? displayApiUrl : null;
const normalizedCloudBaseUrl = cloudBaseUrl
? resolvedMachineId && !cloudBaseUrl.endsWith(`/${resolvedMachineId}`)
? `${cloudBaseUrl}/${resolvedMachineId}`
Expand All @@ -1097,13 +1084,9 @@ export default function APIPageClient({ machineId }: Readonly<APIPageClientProps
);
}

// Use new format endpoint (machineId embedded in key)
const currentEndpoint = cloudEnabled && cloudEndpointNew ? cloudEndpointNew : baseUrl;

const activeUrls = [
{ label: "Local", url: baseUrl, key: "active_local" },
...(cloudEnabled && cloudEndpointNew
? [{ label: "Cloud", url: cloudEndpointNew, key: "active_cloud" }]
const activeTunnelUrls = [
...(publicDisplayApiUrl
? [{ label: t("tierPublic"), url: publicDisplayApiUrl, key: "active_public" }]
: []),
...(cloudflaredStatus?.running && cloudflaredStatus.apiUrl
? [{ label: "Cloudflare", url: cloudflaredStatus.apiUrl, key: "active_cf" }]
Expand All @@ -1121,6 +1104,21 @@ export default function APIPageClient({ machineId }: Readonly<APIPageClientProps
? [{ label: "ngrok", url: ngrokStatus.apiUrl, key: "active_ngrok" }]
: []),
];
const preferredTunnelUrl = activeTunnelUrls[0]?.url ?? null;
const currentEndpoint =
preferredTunnelUrl ??
(cloudEnabled && cloudEndpointNew ? cloudEndpointNew : null) ??
displayApiUrl;
const activeUrls = [
...activeTunnelUrls,
...(cloudEnabled && cloudEndpointNew
? [{ label: "Cloud", url: cloudEndpointNew, key: "active_cloud" }]
: []),
{ label: "Local", url: localApiUrl, key: "active_local" },
].filter(
(candidate, index, candidates) =>
candidates.findIndex((other) => other.url === candidate.url) === index
);
const visibleTunnelCount = [showCloudflaredTunnel, showTailscaleFunnel, showNgrokTunnel].filter(
Boolean
).length;
Expand Down Expand Up @@ -1357,7 +1355,7 @@ export default function APIPageClient({ machineId }: Readonly<APIPageClientProps
Running
</span>
<button
onClick={() => void copy(baseUrl, "endpoint_url")}
onClick={() => void copy(localApiUrl, "endpoint_url")}
className="shrink-0 flex items-center gap-1 text-xs px-2.5 py-1.5 rounded-md border border-border/70 text-text-muted hover:text-text hover:border-border transition-colors"
>
<span className="material-symbols-outlined text-[14px]">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,14 @@ vi.mock("next-intl", () => ({
"endpoint.showInternal": "Show internal",
"endpoint.hideInternal": "Hide internal",
"endpoint.vscodeAliasTitle": "VS Code Token Alias",
"endpoint.vscodeAliasDescriptionReady": "Ready-to-paste compatibility URLs using the /api/v1/vscode/{token}/... endpoint.",
"endpoint.vscodeAliasDescriptionError": "Showing placeholder URLs because CLI keys could not be loaded in this session.",
"endpoint.vscodeAliasDescriptionLoading": "Loading CLI keys. Placeholder URLs are shown until a key is available.",
"endpoint.vscodeAliasDescriptionPlaceholder": "Showing placeholder URLs. Create or activate an API key in CLI Tools to replace {token}.",
"endpoint.vscodeAliasDescriptionReady":
"Ready-to-paste compatibility URLs using the /api/v1/vscode/{token}/... endpoint.",
"endpoint.vscodeAliasDescriptionError":
"Showing placeholder URLs because CLI keys could not be loaded in this session.",
"endpoint.vscodeAliasDescriptionLoading":
"Loading CLI keys. Placeholder URLs are shown until a key is available.",
"endpoint.vscodeAliasDescriptionPlaceholder":
"Showing placeholder URLs. Create or activate an API key in CLI Tools to replace {token}.",
"endpoint.vscodeAliasManage": "CLI Tools",
"endpoint.vscodeAliasBaseLabel": "VS Code base",
"endpoint.vscodeAliasModelsLabel": "VS Code models",
Expand Down Expand Up @@ -114,6 +118,7 @@ describe("ApiEndpointsTab", () => {
cleanupCallbacks.pop()?.();
}
document.body.innerHTML = "";
vi.unstubAllEnvs();
vi.unstubAllGlobals();
});

Expand Down Expand Up @@ -174,6 +179,7 @@ describe("ApiEndpointsTab", () => {
});

it("renders curl example using window.location.origin when NEXT_PUBLIC_BASE_URL is unset", async () => {
vi.stubEnv("NEXT_PUBLIC_BASE_URL", "");
fetchMock.mockImplementation(async (input) => {
if (input === "/api/cli-tools/keys") {
return jsonResponse({ keys: [] });
Expand Down Expand Up @@ -221,7 +227,7 @@ describe("ApiEndpointsTab", () => {

expect(
expectedOrigins.some((origin) =>
renderedText.includes(`curl -X POST ${origin}/v1/chat/completions`)
renderedText.includes(`curl -X POST ${origin}/api/v1/chat/completions`)
)
).toBe(true);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,9 +186,61 @@ describe("EndpointPageClient", () => {
cleanupCallbacks.pop()?.();
}
document.body.innerHTML = "";
vi.unstubAllEnvs();
vi.unstubAllGlobals();
});

it("shows the public browser endpoint before the runtime local endpoint", async () => {
vi.stubEnv("NEXT_PUBLIC_BASE_URL", "http://localhost:20128");
vi.stubGlobal("location", { origin: "https://api.example.com" });

fetchMock.mockImplementation((input: RequestInfo | URL) => {
const path = getRequestPath(input);
if (path === "/api/settings") {
return Promise.resolve(
jsonResponse({
cloudEnabled: false,
cloudConfigured: false,
hideEndpointCloudflaredTunnel: true,
hideEndpointTailscaleFunnel: true,
hideEndpointNgrokTunnel: true,
})
);
}
if (path === "/api/network/info") {
return Promise.resolve(
jsonResponse({
localUrl: "http://localhost:20131/v1",
lanUrls: [],
tailscaleIpUrl: null,
})
);
}
if (path === "/v1/models") return Promise.resolve(jsonResponse({ data: [] }));
if (path === "/api/mcp/status") return Promise.resolve(jsonResponse({ online: false }));
if (path === "/api/a2a/status") {
return Promise.resolve(jsonResponse({ status: "ok", tasks: { activeStreams: 0 } }));
}
if (path === "/api/search/providers") {
return Promise.resolve(jsonResponse({ providers: [] }));
}
if (path === "/api/cli-tools/keys") return Promise.resolve(jsonResponse({ keys: [] }));
throw new Error(`Unexpected request: ${path}`);
});

renderEndpointPage();

await waitForText("https://api.example.com/v1");
await waitForText("http://localhost:20131/v1");

const displayedUrls = Array.from(document.body.querySelectorAll("code")).map(
(element) => element.textContent
);
expect(displayedUrls.indexOf("https://api.example.com/v1")).toBeLessThan(
displayedUrls.indexOf("http://localhost:20131/v1")
);
});

it("renders the endpoint shell before models finish and skips hidden tunnel probes", async () => {
const modelsDeferred = createDeferred<Response>();

Expand Down
11 changes: 1 addition & 10 deletions src/app/(dashboard)/dashboard/onboarding/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export default function OnboardingWizard() {
const baseUrl = useDisplayBaseUrl();
const [step, setStep] = useState(0);
const [loading, setLoading] = useState(true);
const [apiEndpoint, setApiEndpoint] = useState(`${baseUrl}/api/v1`);
const apiEndpoint = `${baseUrl}/api/v1`;

// Security step state
const [password, setPassword] = useState("");
Expand All @@ -45,20 +45,11 @@ export default function OnboardingWizard() {

// Check if setup is already complete
useEffect(() => {
const resolveApiEndpoint = (apiPort) => {
if (typeof window === "undefined") return;
const protocol = window.location.protocol;
const hostname = window.location.hostname;
const effectiveApiPort = apiPort || 20128;
setApiEndpoint(`${protocol}//${hostname}:${effectiveApiPort}/api/v1`);
};

const checkSetup = async () => {
try {
const res = await fetch("/api/settings");
if (res.ok) {
const settings = await res.json();
resolveApiEndpoint(settings?.apiPort);
if (settings.setupComplete) {
router.replace("/dashboard");
return;
Expand Down
3 changes: 2 additions & 1 deletion src/app/api/network/info/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export async function GET(request: Request) {

const { apiPort } = getRuntimePorts();
const interfaces = os.networkInterfaces();
const localUrl = `http://localhost:${apiPort}/v1`;
const lanUrls: string[] = [];
let tailscaleIpUrl: string | null = null;

Expand All @@ -28,5 +29,5 @@ export async function GET(request: Request) {
}
}

return NextResponse.json({ lanUrls, tailscaleIpUrl });
return NextResponse.json({ localUrl, lanUrls, tailscaleIpUrl });
}
Loading