Files
netbird/client/ui/frontend/src/contexts/ProfileContext.tsx
Zoltan Papp 9620890b65 [client] Always connect on profile selection except in manage profiles (#6838)
Selecting a profile from the header dropdown or the tray submenu now
always brings the connection up after the switch, regardless of the
previous daemon state. Switching from the manage-profiles screen
(including profile creation) never connects, leaving a chance to adjust
the management URL first.

## Describe your changes

## Issue ticket number and link

## Stack

<!-- branch-stack -->

### Checklist
- [ ] Is it a bug fix
- [ ] Is a typo/documentation fix
- [x] Is a feature enhancement
- [ ] It is a refactor
- [ ] Created tests that fail without the change (if possible)
- [ ] This change does **not** modify the public API, gRPC protocols,
functionality behavior, CLI / service flags, or introduce a new feature
— **OR** I have discussed it with the NetBird team beforehand (link the
issue / Slack thread in the description). See
[CONTRIBUTING.md](https://github.com/netbirdio/netbird/blob/main/CONTRIBUTING.md#discuss-changes-with-the-netbird-team-first).

> By submitting this pull request, you confirm that you have read and
agree to the terms of the [Contributor License
Agreement](https://github.com/netbirdio/netbird/blob/main/CONTRIBUTOR_LICENSE_AGREEMENT.md).

## Documentation
Select exactly one:

- [ ] I added/updated documentation for this change
- [x] Documentation is **not needed** for this change (explain why)

### Docs PR URL (required if "docs added" is checked)
Paste the PR link from https://github.com/netbirdio/docs here:

https://github.com/netbirdio/docs/pull/__

<!-- codesmith:footer -->
---
<a
href="https://app.blacksmith.sh/netbirdio/codesmith/netbird/pr/6838"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-dark-v2.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-light-v2.svg"><img
alt="View with Codesmith"
src="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-dark-v2.svg"></picture></a>
<a
href="https://backend.blacksmith.sh/track/enable-autofix?expires=1787157550&installation_model_id=427504&pr_number=6838&repository=netbirdio%2Fnetbird&return_to=https%3A%2F%2Fgithub.com%2Fnetbirdio%2Fnetbird%2Fpull%2F6838&signature=8fe9c5f0779df46c76b4135a373591762eb1498d890ff6996626fb75d6433e0a"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-light.svg"><img
alt="Autofix with Codesmith"
src="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-dark.svg"></picture></a>
<sup>Need help on this PR? Tag <code>/codesmith</code> with what you
need. Autofix is disabled.</sup>

<!-- codesmith:autofix:disabled -->
<!-- /codesmith:footer -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Added the ability to switch profiles without automatically
establishing a connection.
* Existing profile switching continues to connect when appropriate,
while safely handling active or pending connections during the switch.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-07-21 15:28:11 +02:00

196 lines
6.3 KiB
TypeScript

import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import { Events } from "@wailsio/runtime";
import { Connection, ProfileSwitcher, Profiles as ProfilesSvc } from "@bindings/services";
import type { Profile } from "@bindings/services/models.js";
import i18next from "@/lib/i18n";
import { errorDialog, formatErrorMessage } from "@/lib/errors";
const EVENT_PROFILE_CHANGED = "netbird:profile:changed";
type ProfileContextValue = {
username: string;
// activeProfile is the display NAME of the active profile (for rendering
// and the "default" check). activeProfileId is its stable on-disk ID, used
// as the handle for daemon requests and for active-profile comparisons,
// since display names can collide.
activeProfile: string;
activeProfileId: string;
profiles: Profile[];
loaded: boolean;
refresh: () => Promise<void>;
switchProfile: (id: string) => Promise<void>;
switchProfileNoConnect: (id: string) => Promise<void>;
addProfile: (name: string) => Promise<string>;
removeProfile: (id: string) => Promise<void>;
renameProfile: (id: string, newName: string) => Promise<void>;
logoutProfile: (id: string) => Promise<void>;
};
const ProfileContext = createContext<ProfileContextValue | null>(null);
export const useProfile = () => {
const ctx = useContext(ProfileContext);
if (!ctx) {
throw new Error("useProfile must be used inside ProfileProvider");
}
return ctx;
};
export const ProfileProvider = ({ children }: { children: ReactNode }) => {
const [username, setUsername] = useState("");
const [activeProfile, setActiveProfile] = useState("");
const [activeProfileId, setActiveProfileId] = useState("");
const [profiles, setProfiles] = useState<Profile[]>([]);
const [loaded, setLoaded] = useState(false);
const retryRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const refresh = useCallback(async () => {
if (retryRef.current) {
clearTimeout(retryRef.current);
retryRef.current = null;
}
try {
const u = await ProfilesSvc.Username();
const [active, list] = await Promise.all([
ProfilesSvc.GetActive(),
ProfilesSvc.List(u),
]);
setUsername(u);
setActiveProfile(active.profileName || "default");
setActiveProfileId(active.id || "default");
setProfiles(list);
setLoaded(true);
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
if (msg.includes("code = Unavailable")) {
retryRef.current = setTimeout(() => {
void refresh();
}, 1000);
return;
}
setLoaded(true);
await errorDialog({
Title: i18next.t("profile.error.loadTitle"),
Message: formatErrorMessage(e),
});
}
}, []);
useEffect(() => {
refresh().catch((err: unknown) => console.error("[ProfileContext] refresh failed", err));
return () => {
if (retryRef.current) clearTimeout(retryRef.current);
};
}, [refresh]);
useEffect(() => {
const off = Events.On(EVENT_PROFILE_CHANGED, () => {
refresh().catch((err: unknown) =>
console.error("[ProfileContext] refresh failed", err),
);
});
return () => {
off();
};
}, [refresh]);
// id is a handle: the daemon resolves an exact ID, ID prefix, or unique
// display name. The UI passes the profile's ID for precision.
const switchProfile = useCallback(
async (id: string) => {
await ProfileSwitcher.SwitchActive({ profileName: id, username });
await refresh();
},
[username, refresh],
);
// Manage-profiles variant: switches without connecting, so the user can
// still adjust the management URL before bringing the connection up.
const switchProfileNoConnect = useCallback(
async (id: string) => {
await ProfileSwitcher.SwitchActiveNoConnect({ profileName: id, username });
await refresh();
},
[username, refresh],
);
// addProfile creates a profile by display name and returns the
// daemon-generated ID, so the caller can immediately address it by ID.
const addProfile = useCallback(
async (name: string) => {
const id = await ProfilesSvc.Add({ profileName: name, username });
await refresh();
return id;
},
[username, refresh],
);
const removeProfile = useCallback(
async (id: string) => {
await ProfilesSvc.Remove({ profileName: id, username });
await refresh();
},
[username, refresh],
);
// The daemon resolves the handle (exact ID, ID prefix, or unique display
// name) — passing the ID is precise and avoids collisions on rename.
const renameProfile = useCallback(
async (id: string, newName: string) => {
await ProfilesSvc.Rename({ handle: id, newName, username });
await refresh();
},
[username, refresh],
);
const logoutProfile = useCallback(
async (id: string) => {
await Connection.Logout({ profileName: id, username });
await refresh();
},
[username, refresh],
);
const value = useMemo<ProfileContextValue>(
() => ({
username,
activeProfile,
activeProfileId,
profiles,
loaded,
refresh,
switchProfile,
switchProfileNoConnect,
addProfile,
removeProfile,
renameProfile,
logoutProfile,
}),
[
username,
activeProfile,
activeProfileId,
profiles,
loaded,
refresh,
switchProfile,
switchProfileNoConnect,
addProfile,
removeProfile,
renameProfile,
logoutProfile,
],
);
return <ProfileContext.Provider value={value}>{children}</ProfileContext.Provider>;
};