From 42ce310a5284899b2fc383fd5ff5fc14c23779f0 Mon Sep 17 00:00:00 2001 From: Ryan Parry Date: Thu, 19 Nov 2026 16:59:40 +0000 Subject: [PATCH] Invite logged-out users to log in with a new login dialog, behind an Unleash experiment (STA-574) The `vortex-sta-574-login-prompt` flag splits installs into `test` and `control`. With the flag off, as in production until it's switched on, everyone is `control` and nothing changes. `test` gets: - a startup modal for logged-out users, from the Figma, with "No, thanks", "Log in to Vortex" and a "Don't show this again" tickbox. It has no X and only closes with an answer; either answer saves the tickbox through the suppressed notifications. - a redesigned `login-dialog` on every route (header, Health Check, `ensureLoggedIn`): the Figma progress view, a token fallback, and a start view. Login buttons no longer open it first, so it goes straight to the progress view; clicks outside it don't cancel the login. `control` keeps the old dialog and flow. The cohort is fixed for the session at the first decision the user would see, so the modal and the dialog agree even if flags arrive late. Adds an `account` pictogram. Co-Authored-By: Claude Opus 5.5 --- assets/pictograms/account.svg | 25 +++ locales/en/nexus_integration.json | 26 +++ .../views/HealthCheckPage.test.tsx | 4 + .../health_check/views/HealthCheckPage.tsx | 22 +- .../components/login_dialog/CopyField.tsx | 42 ++++ .../login_dialog/LoginDialog.test.tsx | 147 ++++++++++++ .../components/login_dialog/LoginDialog.tsx | 211 ++++++++++++++++++ .../login_dialog/LoginModalHeader.tsx | 27 +++ .../login_prompt/LoginPrompt.test.tsx | 84 +++++++ .../components/login_prompt/LoginPrompt.tsx | 89 ++++++++ .../showLoginPromptOnStartup.test.ts | 81 +++++++ .../login_prompt/showLoginPromptOnStartup.ts | 40 ++++ .../experiments/LoginDialogForCohort.test.tsx | 42 ++++ .../experiments/LoginDialogForCohort.tsx | 24 ++ .../experiments/loginPromptExperiment.test.ts | 79 +++++++ .../experiments/loginPromptExperiment.ts | 35 +++ .../extensions/nexus_integration/index.tsx | 15 +- .../nexus_integration/views/LoginDialog.tsx | 2 + .../src/ui/components/pictogram/Pictogram.tsx | 1 + .../Header/premium/PremiumIndicator.test.tsx | 22 +- .../Header/premium/useNexusLogin.hook.ts | 13 +- src/shared/src/types/flags.ts | 2 + 22 files changed, 1008 insertions(+), 25 deletions(-) create mode 100644 assets/pictograms/account.svg create mode 100644 src/renderer/src/extensions/nexus_integration/components/login_dialog/CopyField.tsx create mode 100644 src/renderer/src/extensions/nexus_integration/components/login_dialog/LoginDialog.test.tsx create mode 100644 src/renderer/src/extensions/nexus_integration/components/login_dialog/LoginDialog.tsx create mode 100644 src/renderer/src/extensions/nexus_integration/components/login_dialog/LoginModalHeader.tsx create mode 100644 src/renderer/src/extensions/nexus_integration/components/login_prompt/LoginPrompt.test.tsx create mode 100644 src/renderer/src/extensions/nexus_integration/components/login_prompt/LoginPrompt.tsx create mode 100644 src/renderer/src/extensions/nexus_integration/components/login_prompt/showLoginPromptOnStartup.test.ts create mode 100644 src/renderer/src/extensions/nexus_integration/components/login_prompt/showLoginPromptOnStartup.ts create mode 100644 src/renderer/src/extensions/nexus_integration/experiments/LoginDialogForCohort.test.tsx create mode 100644 src/renderer/src/extensions/nexus_integration/experiments/LoginDialogForCohort.tsx create mode 100644 src/renderer/src/extensions/nexus_integration/experiments/loginPromptExperiment.test.ts create mode 100644 src/renderer/src/extensions/nexus_integration/experiments/loginPromptExperiment.ts diff --git a/assets/pictograms/account.svg b/assets/pictograms/account.svg new file mode 100644 index 0000000000..df9bb57f01 --- /dev/null +++ b/assets/pictograms/account.svg @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/locales/en/nexus_integration.json b/locales/en/nexus_integration.json index 7d20912226..5ef69c83cf 100644 --- a/locales/en/nexus_integration.json +++ b/locales/en/nexus_integration.json @@ -1,5 +1,31 @@ { "_comment": "Nexus Mods integration strings - to be populated during migration", + "login_prompt": { + "title": "Log in for the full experience", + "description": "The button below will open the Nexus Mods website, please click “authorise” or log in / register if required.", + "login": "Log in to Vortex", + "no_thanks": "No, thanks", + "dont_show_again": "Don’t show this again" + }, + "login_dialog": { + "address": "Login address", + "progress": { + "title": "Log in or register on the Nexus Mods website", + "description": "Look out for a browser window opening and click “authorise” or log in / register if required.", + "copy_address": "The button didn’t work? Copy the below address into your browser", + "still_not_working": "Still didn’t work?", + "login_with_token": "Login with token" + }, + "token": { + "title": "Log in with token", + "description": "Click “authorise” on the website and you’ll be given a token. Paste it below and click Save.", + "step_open": "Don’t have a token yet? Copy this address into your browser and log in / register if required.", + "step_paste": "Token", + "invalid": "Your token wasn’t recognised. Copy it again using the button on the website.", + "failed": "Logging in with this token didn’t work: {{error}}", + "save": "Save" + } + }, "premium_upsell": { "benefits_title": "With Premium you get:", "benefits": { diff --git a/src/renderer/src/extensions/health_check/views/HealthCheckPage.test.tsx b/src/renderer/src/extensions/health_check/views/HealthCheckPage.test.tsx index 52bc0191bd..5db82c180d 100644 --- a/src/renderer/src/extensions/health_check/views/HealthCheckPage.test.tsx +++ b/src/renderer/src/extensions/health_check/views/HealthCheckPage.test.tsx @@ -9,6 +9,10 @@ vi.mock("react-redux", () => ({ useSelector: () => undefined, })); +vi.mock("@/views/components/Header/premium/useNexusLogin.hook", () => ({ + useNexusLogin: () => vi.fn(), +})); + vi.mock("../hooks/healthCheckTracker", () => ({ createHealthCheckTracker: () => new Proxy({}, { get: () => vi.fn() }), })); diff --git a/src/renderer/src/extensions/health_check/views/HealthCheckPage.tsx b/src/renderer/src/extensions/health_check/views/HealthCheckPage.tsx index bce0ff7f07..108253882d 100644 --- a/src/renderer/src/extensions/health_check/views/HealthCheckPage.tsx +++ b/src/renderer/src/extensions/health_check/views/HealthCheckPage.tsx @@ -2,7 +2,7 @@ import React, { useEffect, useMemo, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { useDispatch, useSelector } from "react-redux"; -import { setDialogVisible, setOpenMainPage, setSettingsPage } from "@/actions/session"; +import { setOpenMainPage, setSettingsPage } from "@/actions/session"; import type { IExtensionApi } from "@/types/IExtensionContext"; import type { IState } from "@/types/IState"; import { PremiumBadge } from "@/ui/components/badges/premium_badge/PremiumBadge"; @@ -16,8 +16,8 @@ import { Toolbar } from "@/ui/components/toolbar/Toolbar"; import type { IToolbarAction } from "@/ui/components/toolbar/ToolbarGroup"; import { ToolbarGroup } from "@/ui/components/toolbar/ToolbarGroup"; import { Typography } from "@/ui/components/typography/Typography"; -import { UserCanceled } from "@/util/CustomErrors"; import { useRelativeTime } from "@/util/useRelativeTime"; +import { useNexusLogin } from "@/views/components/Header/premium/useNexusLogin.hook"; import { Page } from "@/views/components/Page/Page"; import { PageHeader } from "@/views/components/Page/PageHeader"; import { PageScroll } from "@/views/components/Page/PageScroll"; @@ -111,6 +111,9 @@ const collectInstallAllItems = ( const HealthCheckPage = ({ api, onRefresh, active, registerReset }: IHealthCheckPageProps) => { const { t } = useTranslation(["health_check", "common"]); const dispatch = useDispatch(); + // Logging in is a prerequisite for the Nexus-backed checks rather than a fix for an + // issue, so it goes through the same OAuth flow as the header's login button. + const requestLogin = useNexusLogin(); const [selected, setSelected] = useState(null); const [selectedTab, setSelectedTab] = useState("active"); @@ -375,21 +378,6 @@ const HealthCheckPage = ({ api, onRefresh, active, registerReset }: IHealthCheck ); - // Logging in is a prerequisite for the Nexus-backed checks rather than a fix for an - // issue, so it goes through the same OAuth flow as the header's profile button. - const requestLogin = () => { - dispatch(setDialogVisible("login-dialog")); - - api.events.emit("request-nexus-login", (err: Error) => { - if (err != null && !(err instanceof UserCanceled)) { - api.showErrorNotification?.("Login Failed", err, { - id: "failed-get-nexus-key", - allowReport: false, - }); - } - }); - }; - const loggedOutState = ( { + const { t } = useTranslation(); + const [copied, setCopied] = useState(false); + + useEffect(() => { + if (!copied) { + return undefined; + } + const timer = setTimeout(() => setCopied(false), 2000); + return () => clearTimeout(timer); + }, [copied]); + + const copy = () => { + window.api.clipboard + .writeText(value) + .then(() => setCopied(true)) + .catch((err: unknown) => log("warn", "failed to copy the login address", { error: err })); + }; + + return ( +
+ + +
+ ); +}; diff --git a/src/renderer/src/extensions/nexus_integration/components/login_dialog/LoginDialog.test.tsx b/src/renderer/src/extensions/nexus_integration/components/login_dialog/LoginDialog.test.tsx new file mode 100644 index 0000000000..d0d8a7a56c --- /dev/null +++ b/src/renderer/src/extensions/nexus_integration/components/login_dialog/LoginDialog.test.tsx @@ -0,0 +1,147 @@ +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import React from "react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + dispatch: vi.fn(), + login: vi.fn(), + oauthPending: undefined as string | undefined, +})); + +vi.mock("react-redux", () => ({ + useDispatch: () => mocks.dispatch, + useSelector: (selector: (state: unknown) => unknown) => + selector({ session: { nexus: { oauthPending: mocks.oauthPending } } }), +})); +vi.mock("@/views/components/Header/premium/useNexusLogin.hook", () => ({ + useNexusLogin: () => mocks.login, +})); + +import { setOauthPending } from "../../actions/session"; +import { LoginDialog, type ILoginDialogProps } from "./LoginDialog"; + +const URL = "https://users.nexusmods.com/oauth/authorize?x=1"; + +const renderDialog = (overrides: Partial = {}) => { + const props: ILoginDialogProps = { + visible: false, + onHide: vi.fn(), + onCancelLogin: vi.fn(), + onReceiveCode: vi.fn(() => Promise.resolve()), + ...overrides, + }; + render(); + return props; +}; + +const token = (value: object) => Buffer.from(JSON.stringify(value)).toString("base64"); + +describe("LoginDialog", () => { + beforeEach(() => { + mocks.dispatch.mockReset(); + mocks.login.mockReset(); + mocks.oauthPending = undefined; + }); + + it("stays closed when nothing asked for it", () => { + renderDialog(); + + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + }); + + it("offers to log in when opened before a login has started", async () => { + renderDialog({ visible: true }); + + await userEvent.click(screen.getByTestId("login-dialog-login")); + + expect(mocks.login).toHaveBeenCalledOnce(); + }); + + it("shows the progress and the address while a login waits on the website", async () => { + mocks.oauthPending = URL; + renderDialog(); + + expect(await screen.findByText("login_dialog::progress::title")).toBeInTheDocument(); + expect(screen.getByTestId("login-spinner")).toBeInTheDocument(); + expect(screen.getByRole("textbox", { name: "login_dialog::address" })).toHaveValue(URL); + }); + + it("cancels the login when closed", async () => { + mocks.oauthPending = URL; + const props = renderDialog(); + + await userEvent.click(screen.getByRole("button", { name: "Close" })); + + expect(mocks.dispatch).toHaveBeenCalledWith(setOauthPending(undefined)); + expect(props.onCancelLogin).toHaveBeenCalledOnce(); + expect(props.onHide).toHaveBeenCalledOnce(); + }); + + it("cancels the login on Escape", async () => { + mocks.oauthPending = URL; + const props = renderDialog(); + await screen.findByText("login_dialog::progress::title"); + + await userEvent.keyboard("{Escape}"); + + expect(props.onCancelLogin).toHaveBeenCalledOnce(); + }); + + it("keeps the login going when the user clicks outside the dialog", async () => { + mocks.oauthPending = URL; + const props = renderDialog(); + await screen.findByText("login_dialog::progress::title"); + + await userEvent.click(document.querySelector(".nxm-modal-overlay") as Element); + + expect(props.onCancelLogin).not.toHaveBeenCalled(); + expect(props.onHide).not.toHaveBeenCalled(); + }); + + it("says when logging in with a readable token fails, rather than blaming the token", async () => { + mocks.oauthPending = URL; + const props = renderDialog({ + onReceiveCode: vi.fn(() => Promise.reject(new Error("network down"))), + }); + + await userEvent.click(screen.getByTestId("login-with-token")); + await userEvent.type( + screen.getByTestId("login-token-input"), + token({ authorization_code: "code", state: "s" }), + ); + await userEvent.click(screen.getByTestId("login-token-save")); + + expect(await screen.findByText("login_dialog::token::failed")).toBeInTheDocument(); + expect(screen.queryByText("login_dialog::token::invalid")).not.toBeInTheDocument(); + expect(props.onHide).not.toHaveBeenCalled(); + }); + + it("completes the login with a pasted token", async () => { + mocks.oauthPending = URL; + const props = renderDialog(); + + await userEvent.click(screen.getByTestId("login-with-token")); + await userEvent.type( + screen.getByTestId("login-token-input"), + token({ authorization_code: "code", state: "s" }), + ); + await userEvent.click(screen.getByTestId("login-token-save")); + + expect(props.onReceiveCode).toHaveBeenCalledWith("code", "s"); + expect(props.onHide).toHaveBeenCalledOnce(); + }); + + it("says when a pasted token isn't recognised", async () => { + mocks.oauthPending = URL; + const props = renderDialog(); + + await userEvent.click(screen.getByTestId("login-with-token")); + await userEvent.type(screen.getByTestId("login-token-input"), "not-a-token"); + await userEvent.click(screen.getByTestId("login-token-save")); + + expect(screen.getByText("login_dialog::token::invalid")).toBeInTheDocument(); + expect(props.onReceiveCode).not.toHaveBeenCalled(); + expect(props.onHide).not.toHaveBeenCalled(); + }); +}); diff --git a/src/renderer/src/extensions/nexus_integration/components/login_dialog/LoginDialog.tsx b/src/renderer/src/extensions/nexus_integration/components/login_dialog/LoginDialog.tsx new file mode 100644 index 0000000000..1b81d775f6 --- /dev/null +++ b/src/renderer/src/extensions/nexus_integration/components/login_dialog/LoginDialog.tsx @@ -0,0 +1,211 @@ +import { getErrorMessageOrDefault } from "@vortex/shared"; +import React, { useEffect, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { useDispatch, useSelector } from "react-redux"; + +import type { IState } from "@/types/IState"; +import { Button } from "@/ui/components/button/Button"; +import { TextAreaField } from "@/ui/components/form/text_area_field/TextAreaField"; +import { Icon } from "@/ui/components/icon/Icon"; +import { ModalPanel, ModalWrapper } from "@/ui/components/modal/Modal"; +import { Typography } from "@/ui/components/typography/Typography"; +import { log } from "@/util/log"; +import { useNexusLogin } from "@/views/components/Header/premium/useNexusLogin.hook"; + +import { setOauthPending } from "../../actions/session"; +import { CopyField } from "./CopyField"; +import { LoginModalHeader } from "./LoginModalHeader"; + +export interface ILoginDialogProps { + visible: boolean; + onHide: () => void; + /** Ends the login that's waiting on the website, telling whoever asked for it that it was cancelled. */ + onCancelLogin: () => void; + /** Completes the login with the code from a pasted token. */ + onReceiveCode: (code: string, state?: string) => Promise; +} + +/** The token the website shows is base64 JSON holding the code and state the redirect would carry. */ +const decodeToken = (token: string): { authorization_code: string; state?: string } => + JSON.parse(Buffer.from(token.replace(/\s/g, ""), "base64").toString()); + +// `session.nexus` is registered by this extension, so it isn't on the core state type. +const oauthPendingSelector = (state: IState): string | undefined => + (state.session["nexus"] as { oauthPending?: string } | undefined)?.oauthPending || undefined; + +const ignoreOutsideClick = () => undefined; + +const Spinner = () => ( + +); + +/** + * Logs the user in to Nexus Mods. While a login waits on the website it shows its progress, the + * address to open by hand and, as a last resort, a token to paste. Opened without a login under way + * (by `ensureLoggedIn`), it offers one. + */ +export const LoginDialog = ({ + visible, + onHide, + onCancelLogin, + onReceiveCode, +}: ILoginDialogProps) => { + const { t } = useTranslation(["nexus_integration"]); + const dispatch = useDispatch(); + const login = useNexusLogin(); + const oauthPending = useSelector(oauthPendingSelector); + const isOpen = visible || oauthPending !== undefined; + + const [withToken, setWithToken] = useState(false); + const [token, setToken] = useState(""); + const [tokenError, setTokenError] = useState(undefined); + + // Each opening starts on the regular view with an empty token. + useEffect(() => { + if (isOpen) { + setWithToken(false); + setToken(""); + setTokenError(undefined); + } + }, [isOpen]); + + const close = () => { + dispatch(setOauthPending(undefined)); + onCancelLogin(); + onHide(); + }; + + // Escape cancels, as in the old dialog, but a click outside doesn't: clicking Vortex to bring it + // forward mid-login would otherwise cancel the login. + useEffect(() => { + if (!isOpen) { + return undefined; + } + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === "Escape") { + close(); + } + }; + window.addEventListener("keydown", onKeyDown); + return () => window.removeEventListener("keydown", onKeyDown); + }); + + const applyToken = async () => { + let decoded: ReturnType; + try { + decoded = decodeToken(token); + } catch (err: unknown) { + log("warn", "login token could not be read", { error: err }); + setTokenError(t("login_dialog::token::invalid")); + return; + } + + try { + await onReceiveCode(decoded.authorization_code, decoded.state); + onHide(); + } catch (err: unknown) { + log("warn", "login with token failed", { error: err }); + setTokenError(t("login_dialog::token::failed", { error: getErrorMessageOrDefault(err) })); + } + }; + + const renderStart = () => ( + <> + + + + + ); + + const renderProgress = (url: string) => ( + <> + + + + +
+ + {t("login_dialog::progress::copy_address")} + + + + + + {t("login_dialog::progress::still_not_working")}{" "} + + +
+ + ); + + const renderToken = () => ( + <> + + +
+ {oauthPending !== undefined && ( +
+ + {t("login_dialog::token::step_open")} + + + +
+ )} + + { + setToken(event.target.value); + setTokenError(undefined); + }} + /> +
+ + + + ); + + const renderView = () => { + if (withToken) { + return renderToken(); + } + return oauthPending === undefined ? renderStart() : renderProgress(oauthPending); + }; + + return ( + + +
{renderView()}
+
+
+ ); +}; diff --git a/src/renderer/src/extensions/nexus_integration/components/login_dialog/LoginModalHeader.tsx b/src/renderer/src/extensions/nexus_integration/components/login_dialog/LoginModalHeader.tsx new file mode 100644 index 0000000000..b87fbfb8ef --- /dev/null +++ b/src/renderer/src/extensions/nexus_integration/components/login_dialog/LoginModalHeader.tsx @@ -0,0 +1,27 @@ +import React from "react"; + +import { Pictogram } from "@/ui/components/pictogram/Pictogram"; +import { Typography } from "@/ui/components/typography/Typography"; + +/** The account pictogram, title and description every login modal opens with. */ +export const LoginModalHeader = ({ + title, + description, +}: { + title: string; + description: string; +}) => ( +
+ + +
+ + {title} + + + + {description} + +
+
+); diff --git a/src/renderer/src/extensions/nexus_integration/components/login_prompt/LoginPrompt.test.tsx b/src/renderer/src/extensions/nexus_integration/components/login_prompt/LoginPrompt.test.tsx new file mode 100644 index 0000000000..ccc12a9719 --- /dev/null +++ b/src/renderer/src/extensions/nexus_integration/components/login_prompt/LoginPrompt.test.tsx @@ -0,0 +1,84 @@ +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import React from "react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ dispatch: vi.fn(), login: vi.fn() })); + +vi.mock("react-redux", () => ({ useDispatch: () => mocks.dispatch })); +vi.mock("@/views/components/Header/premium/useNexusLogin.hook", () => ({ + useNexusLogin: () => mocks.login, +})); + +import { suppressNotification } from "@/actions"; + +import { LOGIN_PROMPT_ID, LoginPrompt } from "./LoginPrompt"; + +const suppress = suppressNotification(LOGIN_PROMPT_ID, true); + +describe("LoginPrompt", () => { + beforeEach(() => { + mocks.dispatch.mockReset(); + mocks.login.mockReset(); + }); + + it("closes and starts the login when the button is clicked", async () => { + const onHide = vi.fn(); + render(); + + await userEvent.click(screen.getByTestId("login-prompt-login")); + + expect(onHide).toHaveBeenCalledOnce(); + expect(mocks.login).toHaveBeenCalledOnce(); + expect(mocks.dispatch).not.toHaveBeenCalled(); + }); + + it("has no X, so it only closes with an answer", async () => { + render(); + + expect(await screen.findByTestId("login-prompt-no-thanks")).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Close" })).not.toBeInTheDocument(); + }); + + it("stays open on Escape", async () => { + const onHide = vi.fn(); + render(); + + await userEvent.keyboard("{Escape}"); + + expect(onHide).not.toHaveBeenCalled(); + expect(mocks.dispatch).not.toHaveBeenCalled(); + }); + + it("remembers 'Don't show this again' when logging in", async () => { + render(); + + await userEvent.click(screen.getByRole("checkbox")); + await userEvent.click(screen.getByTestId("login-prompt-login")); + + expect(mocks.dispatch).toHaveBeenCalledWith(suppress); + expect(mocks.login).toHaveBeenCalledOnce(); + }); + + it("closes without logging in on 'No, thanks'", async () => { + const onHide = vi.fn(); + render(); + + await userEvent.click(screen.getByTestId("login-prompt-no-thanks")); + + expect(onHide).toHaveBeenCalledOnce(); + expect(mocks.login).not.toHaveBeenCalled(); + expect(mocks.dispatch).not.toHaveBeenCalled(); + }); + + it("remembers 'Don't show this again' on 'No, thanks'", async () => { + const onHide = vi.fn(); + render(); + + await userEvent.click(screen.getByRole("checkbox")); + await userEvent.click(screen.getByTestId("login-prompt-no-thanks")); + + expect(mocks.dispatch).toHaveBeenCalledWith(suppress); + expect(onHide).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/renderer/src/extensions/nexus_integration/components/login_prompt/LoginPrompt.tsx b/src/renderer/src/extensions/nexus_integration/components/login_prompt/LoginPrompt.tsx new file mode 100644 index 0000000000..2e032854f6 --- /dev/null +++ b/src/renderer/src/extensions/nexus_integration/components/login_prompt/LoginPrompt.tsx @@ -0,0 +1,89 @@ +import React, { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { useDispatch } from "react-redux"; + +import { suppressNotification } from "@/actions"; +import { Button } from "@/ui/components/button/Button"; +import { CheckboxField } from "@/ui/components/form/checkbox_field/CheckboxField"; +import { ModalPanel, ModalWrapper } from "@/ui/components/modal/Modal"; +import { useNexusLogin } from "@/views/components/Header/premium/useNexusLogin.hook"; + +import { LoginModalHeader } from "../login_dialog/LoginModalHeader"; + +/** The dialog id, and the id "Don't show this again" is remembered under. */ +export const LOGIN_PROMPT_ID = "login-prompt"; + +export interface ILoginPromptProps { + visible: boolean; + onHide: () => void; +} + +/** + * Invites a logged-out user to log in when Vortex starts. Logging in hands over to the + * `login-dialog`, which shows the progress and the fallbacks. Ticking "Don't show this again" + * and answering, with "No, thanks" or logging in, stops it appearing at future startups. + */ +const ignoreDismiss = () => undefined; + +export const LoginPrompt = ({ visible, onHide }: ILoginPromptProps) => { + const { t } = useTranslation(["nexus_integration"]); + const dispatch = useDispatch(); + const login = useNexusLogin(); + const [dontShowAgain, setDontShowAgain] = useState(false); + + const rememberChoice = () => { + if (dontShowAgain) { + dispatch(suppressNotification(LOGIN_PROMPT_ID, true)); + } + }; + + const onNoThanks = () => { + rememberChoice(); + onHide(); + }; + + // The login dialog takes over, showing the progress, once the login is waiting on the website. + const onLogin = () => { + rememberChoice(); + onHide(); + login(); + }; + + return ( + // Only closes with an answer, so "Don't show this again" is never left undecided. + + +
+ + +
+ + +
+ + + +
+
+
+
+
+ ); +}; diff --git a/src/renderer/src/extensions/nexus_integration/components/login_prompt/showLoginPromptOnStartup.test.ts b/src/renderer/src/extensions/nexus_integration/components/login_prompt/showLoginPromptOnStartup.test.ts new file mode 100644 index 0000000000..63fca4898c --- /dev/null +++ b/src/renderer/src/extensions/nexus_integration/components/login_prompt/showLoginPromptOnStartup.test.ts @@ -0,0 +1,81 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ cohort: "test" as "test" | "control" })); + +vi.mock("../../experiments/loginPromptExperiment", () => ({ + fixLoginPromptCohort: () => mocks.cohort, +})); + +import { setDialogVisible } from "@/actions"; +import type { IExtensionApi } from "@/types/IExtensionContext"; + +import { LOGIN_PROMPT_ID } from "./LoginPrompt"; +import { showLoginPromptOnStartup } from "./showLoginPromptOnStartup"; + +interface IFakeState { + loggedIn?: boolean; + suppressed?: boolean; + visibleDialog?: string; + shownDialogs?: number; +} + +const makeApi = ({ + loggedIn = false, + suppressed = false, + visibleDialog, + shownDialogs = 0, +}: IFakeState) => { + const dispatch = vi.fn(); + const state = { + confidential: { + account: { nexus: loggedIn ? { OAuthCredentials: { token: "t" } } : {} }, + }, + settings: { notifications: { suppress: suppressed ? { [LOGIN_PROMPT_ID]: true } : {} } }, + session: { + base: { visibleDialog }, + notifications: { dialogs: Array.from({ length: shownDialogs }, (_, i) => ({ id: `d${i}` })) }, + }, + }; + const api = { + getState: () => state, + awaitUI: () => Promise.resolve(), + store: { dispatch }, + } as unknown as IExtensionApi; + return { api, dispatch }; +}; + +describe("showLoginPromptOnStartup", () => { + beforeEach(() => { + mocks.cohort = "test"; + }); + + it("doesn't show it to the experiment's control cohort", async () => { + mocks.cohort = "control"; + const { api, dispatch } = makeApi({}); + + await showLoginPromptOnStartup(api); + + expect(dispatch).not.toHaveBeenCalled(); + }); + + it("shows the prompt to a logged-out user", async () => { + const { api, dispatch } = makeApi({}); + + await showLoginPromptOnStartup(api); + + expect(dispatch).toHaveBeenCalledWith(setDialogVisible(LOGIN_PROMPT_ID)); + }); + + it.each<[string, IFakeState]>([ + ["the user is logged in", { loggedIn: true }], + ["the user ticked 'Don't show this again'", { suppressed: true }], + ["another dialog is already open", { visibleDialog: "login-dialog" }], + ["a dialog from api.showDialog is open", { shownDialogs: 1 }], + ])("doesn't show it when %s", async (_, fake) => { + const { api, dispatch } = makeApi(fake); + + await showLoginPromptOnStartup(api); + + expect(dispatch).not.toHaveBeenCalled(); + }); +}); diff --git a/src/renderer/src/extensions/nexus_integration/components/login_prompt/showLoginPromptOnStartup.ts b/src/renderer/src/extensions/nexus_integration/components/login_prompt/showLoginPromptOnStartup.ts new file mode 100644 index 0000000000..095e8693dc --- /dev/null +++ b/src/renderer/src/extensions/nexus_integration/components/login_prompt/showLoginPromptOnStartup.ts @@ -0,0 +1,40 @@ +import { setDialogVisible } from "@/actions"; +import type { IExtensionApi } from "@/types/IExtensionContext"; +import type { IState } from "@/types/IState"; + +import { fixLoginPromptCohort } from "../../experiments/loginPromptExperiment"; +import { isLoggedIn } from "../../selectors"; +import { LOGIN_PROMPT_ID } from "./LoginPrompt"; + +const isSuppressed = (state: IState): boolean => + state.settings.notifications?.suppress?.[LOGIN_PROMPT_ID] === true; + +// Registered dialogs and `api.showDialog` ones are kept separately. +const isAnyDialogOpen = (state: IState): boolean => + state.session.base.visibleDialog !== undefined || + (state.session.notifications?.dialogs?.length ?? 0) > 0; + +/** + * Shows the login prompt once the UI is up, unless the user is logged in, ticked + * "Don't show this again", or another dialog is already open. + */ +export const showLoginPromptOnStartup = async (api: IExtensionApi): Promise => { + if (isLoggedIn(api.getState()) || isSuppressed(api.getState())) { + return; + } + + await api.awaitUI(); + + // Re-read: the user may have logged in, or something else opened a dialog, while the UI loaded. + const state = api.getState(); + if (isLoggedIn(state) || isAnyDialogOpen(state)) { + return; + } + + // STA-574: only the `test` cohort sees it. + if (fixLoginPromptCohort() !== "test") { + return; + } + + api.store.dispatch(setDialogVisible(LOGIN_PROMPT_ID)); +}; diff --git a/src/renderer/src/extensions/nexus_integration/experiments/LoginDialogForCohort.test.tsx b/src/renderer/src/extensions/nexus_integration/experiments/LoginDialogForCohort.test.tsx new file mode 100644 index 0000000000..fc1bea9a31 --- /dev/null +++ b/src/renderer/src/extensions/nexus_integration/experiments/LoginDialogForCohort.test.tsx @@ -0,0 +1,42 @@ +import { render, screen } from "@testing-library/react"; +import React from "react"; +import { describe, expect, it, vi } from "vitest"; + +const experiment = vi.hoisted(() => ({ cohort: "test" as "test" | "control" })); + +vi.mock("./loginPromptExperiment", () => ({ + useLoginPromptCohort: () => experiment.cohort, + fixLoginPromptCohort: () => experiment.cohort, +})); +vi.mock("react-redux", () => ({ + useSelector: (selector: (state: unknown) => unknown) => selector({ session: { nexus: {} } }), +})); +vi.mock("../components/login_dialog/LoginDialog", () => ({ + LoginDialog: () =>
new dialog
, +})); +vi.mock("../views/LoginDialog", () => ({ default: () =>
old dialog
})); + +import { LoginDialogForCohort } from "./LoginDialogForCohort"; + +const props = { + visible: true, + onHide: vi.fn(), + onCancelLogin: vi.fn(), + onReceiveCode: vi.fn(() => Promise.resolve()), +}; + +describe("LoginDialogForCohort", () => { + it("shows the new dialog to the test cohort", () => { + experiment.cohort = "test"; + render(); + + expect(screen.getByText("new dialog")).toBeInTheDocument(); + }); + + it("shows the old dialog to the control cohort", () => { + experiment.cohort = "control"; + render(); + + expect(screen.getByText("old dialog")).toBeInTheDocument(); + }); +}); diff --git a/src/renderer/src/extensions/nexus_integration/experiments/LoginDialogForCohort.tsx b/src/renderer/src/extensions/nexus_integration/experiments/LoginDialogForCohort.tsx new file mode 100644 index 0000000000..a373f5bcb3 --- /dev/null +++ b/src/renderer/src/extensions/nexus_integration/experiments/LoginDialogForCohort.tsx @@ -0,0 +1,24 @@ +import React from "react"; +import { useSelector } from "react-redux"; + +import type { IState } from "@/types/IState"; + +import { LoginDialog, type ILoginDialogProps } from "../components/login_dialog/LoginDialog"; +import LegacyLoginDialog from "../views/LoginDialog"; +import { fixLoginPromptCohort, useLoginPromptCohort } from "./loginPromptExperiment"; + +// The old dialog's props also list what `translate` injects, which it fills in itself. +const Legacy = LegacyLoginDialog as unknown as React.ComponentType; + +const isLoginPending = (state: IState): boolean => + (state.session["nexus"] as { oauthPending?: string } | undefined)?.oauthPending !== undefined; + +/** STA-574: the `login-dialog` for every route, new for `test` and old for `control`. */ +export const LoginDialogForCohort = (props: ILoginDialogProps) => { + const liveCohort = useLoginPromptCohort(); + const isOpen = useSelector(isLoginPending) || props.visible; + // Opening fixes the cohort (idempotent), so flags arriving mid-login can't swap the dialog. + const cohort = isOpen ? fixLoginPromptCohort() : liveCohort; + + return cohort === "test" ? : ; +}; diff --git a/src/renderer/src/extensions/nexus_integration/experiments/loginPromptExperiment.test.ts b/src/renderer/src/extensions/nexus_integration/experiments/loginPromptExperiment.test.ts new file mode 100644 index 0000000000..77ed70ce43 --- /dev/null +++ b/src/renderer/src/extensions/nexus_integration/experiments/loginPromptExperiment.test.ts @@ -0,0 +1,79 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + flags: new Map(), + getFlag: vi.fn(), + initialised: true, +})); + +vi.mock("@/FlagService", () => ({ + FlagService: { + get instance() { + return mocks.initialised + ? { flags: mocks.flags, getFlag: mocks.getFlag, subscribe: () => () => undefined } + : undefined; + }, + }, +})); + +const FLAG = "vortex-sta-574-login-prompt"; + +const flagOn = (on: boolean) => { + mocks.flags.clear(); + if (on) { + mocks.flags.set(FLAG, { name: FLAG }); + } +}; + +// The fixed cohort is module state, so each test gets a fresh copy of the module. +const load = async () => { + vi.resetModules(); + return import("./loginPromptExperiment.js"); +}; + +describe("login prompt cohort", () => { + beforeEach(() => { + mocks.initialised = true; + mocks.getFlag.mockReset(); + mocks.getFlag.mockImplementation((name: string) => mocks.flags.get(name)); + flagOn(false); + }); + + it("is test when the flag is on, and control when it's off", async () => { + const { loginPromptCohort } = await load(); + + expect(loginPromptCohort()).toBe("control"); + flagOn(true); + expect(loginPromptCohort()).toBe("test"); + }); + + it("is control before flags are available", async () => { + mocks.initialised = false; + const { loginPromptCohort, fixLoginPromptCohort } = await load(); + + expect(loginPromptCohort()).toBe("control"); + expect(fixLoginPromptCohort()).toBe("control"); + }); + + it("keeps the fixed cohort when flags arrive later in the session", async () => { + const { loginPromptCohort, fixLoginPromptCohort } = await load(); + + expect(fixLoginPromptCohort()).toBe("control"); + flagOn(true); + + expect(loginPromptCohort()).toBe("control"); + expect(fixLoginPromptCohort()).toBe("control"); + }); + + it("counts one flag evaluation for Unleash, however often the cohort is read", async () => { + flagOn(true); + const { loginPromptCohort, fixLoginPromptCohort } = await load(); + + loginPromptCohort(); + fixLoginPromptCohort(); + fixLoginPromptCohort(); + loginPromptCohort(); + + expect(mocks.getFlag).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/renderer/src/extensions/nexus_integration/experiments/loginPromptExperiment.ts b/src/renderer/src/extensions/nexus_integration/experiments/loginPromptExperiment.ts new file mode 100644 index 0000000000..386d61c0bb --- /dev/null +++ b/src/renderer/src/extensions/nexus_integration/experiments/loginPromptExperiment.ts @@ -0,0 +1,35 @@ +import { useSyncExternalStore } from "react"; + +import { FlagService } from "@/FlagService"; + +// STA-574 experiment. The PR and ticket cover how to read the results and how to remove it. + +const FLAG = "vortex-sta-574-login-prompt"; + +export type LoginPromptCohort = "test" | "control"; + +let fixedCohort: LoginPromptCohort | undefined; + +// Reads the flag map directly: `getFlag` counts an evaluation for Unleash on every call. +const liveCohort = (): LoginPromptCohort => + FlagService.instance?.flags.has(FLAG) ? "test" : "control"; + +/** The session's cohort once fixed; until then, whatever the flags say so far. */ +export const loginPromptCohort = (): LoginPromptCohort => fixedCohort ?? liveCohort(); + +/** + * Fixes the session's cohort the first time the user would see a difference, so the prompt, the + * dialog and the login event all agree even if flags arrive mid-session. Counts as the flag's one + * evaluation. + */ +export const fixLoginPromptCohort = (): LoginPromptCohort => { + fixedCohort ??= FlagService.instance?.getFlag(FLAG) !== undefined ? "test" : "control"; + return fixedCohort; +}; + +const subscribe = (onChange: () => void): (() => void) => + FlagService.instance?.subscribe(() => onChange()) ?? (() => undefined); + +/** `loginPromptCohort`, re-rendering when flags arrive. */ +export const useLoginPromptCohort = (): LoginPromptCohort => + useSyncExternalStore(subscribe, loginPromptCohort); diff --git a/src/renderer/src/extensions/nexus_integration/index.tsx b/src/renderer/src/extensions/nexus_integration/index.tsx index 7307d846eb..f2bda74aad 100644 --- a/src/renderer/src/extensions/nexus_integration/index.tsx +++ b/src/renderer/src/extensions/nexus_integration/index.tsx @@ -75,6 +75,8 @@ import { genGameAttribute, genModIdAttribute, } from "./attributes"; +import { LOGIN_PROMPT_ID, LoginPrompt } from "./components/login_prompt/LoginPrompt"; +import { showLoginPromptOnStartup } from "./components/login_prompt/showLoginPromptOnStartup"; import { NEXUS_API_SUBDOMAIN, NEXUS_BASE_URL, @@ -83,6 +85,7 @@ import { REVALIDATION_FREQUENCY, } from "./constants"; import * as eh from "./eventHandlers"; +import { LoginDialogForCohort } from "./experiments/LoginDialogForCohort"; import { adoptMembershipRead, ensureFreshMembership, @@ -122,7 +125,6 @@ import Tracking from "./util/tracking"; import { makeFileUID } from "./util/UIDs"; import FreeUserDLDialog from "./views/FreeUserDLDialog"; import GoPremiumDashlet from "./views/GoPremiumDashlet"; -import LoginDialog from "./views/LoginDialog"; import LoginIcon from "./views/LoginIcon"; import {} from "./views/Settings"; @@ -1088,6 +1090,13 @@ function once(api: IExtensionApi, callbacks: Array<(nexus: NexusT) => void>) { } } + // A forced logout already asks the user to log in, so don't ask twice. + if (!forcedLogout) { + showLoginPromptOnStartup(api).catch((err: unknown) => + log("warn", "failed to show login prompt", { error: getErrorMessageOrDefault(err) }), + ); + } + registerFunc(getSafe(state, ["settings", "nexus", "associateNXM"], undefined)); api.registerRepositoryLookup("nexus", true, makeRepositoryLookup(api, nexus)); @@ -1521,11 +1530,13 @@ function init(context: IExtensionContext): boolean { const onCancelLogin = () => onCancelLoginImpl(context.api); - context.registerDialog("login-dialog", LoginDialog, () => ({ + context.registerDialog("login-dialog", LoginDialogForCohort, () => ({ onCancelLogin, onReceiveCode: (code: string, state: string) => oauthCallback(context.api, code, state), })); + context.registerDialog(LOGIN_PROMPT_ID, LoginPrompt); + context.registerDialog("free-user-download", FreeUserDLDialog, () => ({ t: context.api.translate, nexus, diff --git a/src/renderer/src/extensions/nexus_integration/views/LoginDialog.tsx b/src/renderer/src/extensions/nexus_integration/views/LoginDialog.tsx index 0987011325..9162b96957 100644 --- a/src/renderer/src/extensions/nexus_integration/views/LoginDialog.tsx +++ b/src/renderer/src/extensions/nexus_integration/views/LoginDialog.tsx @@ -26,6 +26,8 @@ import { OAUTH_URL } from "../constants"; import type { IValidateKeyData } from "../types/IValidateKeyData"; import { getPageURL } from "../util/sso"; +// STA-574: the login dialog the `control` cohort still sees. + const API_ACCESS_URL = `${NEXUS_BASE_URL}/users/myaccount?tab=api+access`; export interface IBaseProps extends WithTranslation { diff --git a/src/renderer/src/ui/components/pictogram/Pictogram.tsx b/src/renderer/src/ui/components/pictogram/Pictogram.tsx index 6f209cd36c..6c87ce12a5 100644 --- a/src/renderer/src/ui/components/pictogram/Pictogram.tsx +++ b/src/renderer/src/ui/components/pictogram/Pictogram.tsx @@ -26,6 +26,7 @@ const brandMap = { } as const satisfies Record; export type IPictogramName = + | "account" | "game" | "health-check" | "mod" diff --git a/src/renderer/src/views/components/Header/premium/PremiumIndicator.test.tsx b/src/renderer/src/views/components/Header/premium/PremiumIndicator.test.tsx index 475b374f3e..b9cdfcd184 100644 --- a/src/renderer/src/views/components/Header/premium/PremiumIndicator.test.tsx +++ b/src/renderer/src/views/components/Header/premium/PremiumIndicator.test.tsx @@ -4,10 +4,15 @@ import React from "react"; import type * as ReactReduxTypes from "react-redux"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -const { dispatch, emit, openUrl } = vi.hoisted(() => ({ +const { dispatch, emit, openUrl, experiment } = vi.hoisted(() => ({ dispatch: vi.fn(), emit: vi.fn(), openUrl: vi.fn(), + experiment: { cohort: "test" as "test" | "control" }, +})); + +vi.mock("@/extensions/nexus_integration/experiments/loginPromptExperiment", () => ({ + fixLoginPromptCohort: () => experiment.cohort, })); vi.mock("@/ExtensionProvider", () => ({ @@ -36,6 +41,8 @@ vi.mock("react-redux", async () => { }; }); +import { setDialogVisible } from "@/actions"; + import { PremiumIndicator } from "./PremiumIndicator"; // --- Tests --- @@ -73,10 +80,21 @@ describe("PremiumIndicator", () => { }); it("starts the login flow when pressed", async () => { + experiment.cohort = "test"; + render(); + await userEvent.click(screen.getByRole("button", { name: "Log in" })); + + // The new login dialog opens on its own once the login is under way, so nothing opens it here. + expect(dispatch).not.toHaveBeenCalled(); + expect(emit).toHaveBeenCalledWith("request-nexus-login", expect.any(Function)); + }); + + it("opens the old login dialog first for the experiment's control cohort", async () => { + experiment.cohort = "control"; render(); await userEvent.click(screen.getByRole("button", { name: "Log in" })); - expect(dispatch).toHaveBeenCalled(); + expect(dispatch).toHaveBeenCalledWith(setDialogVisible("login-dialog")); expect(emit).toHaveBeenCalledWith("request-nexus-login", expect.any(Function)); }); }); diff --git a/src/renderer/src/views/components/Header/premium/useNexusLogin.hook.ts b/src/renderer/src/views/components/Header/premium/useNexusLogin.hook.ts index 2371209787..ad146232a4 100644 --- a/src/renderer/src/views/components/Header/premium/useNexusLogin.hook.ts +++ b/src/renderer/src/views/components/Header/premium/useNexusLogin.hook.ts @@ -3,13 +3,14 @@ import { useDispatch } from "react-redux"; import { setDialogVisible } from "@/actions"; import { useExtensionContext } from "@/ExtensionProvider"; +import { fixLoginPromptCohort } from "@/extensions/nexus_integration/experiments/loginPromptExperiment"; import { UserCanceled } from "../../../../util/CustomErrors"; /** - * Starts the Nexus Mods login flow: shows the login dialog and asks the nexus - * integration to authenticate. Cancelling is a choice rather than a fault, so only - * a real failure is reported. + * Starts the Nexus Mods login flow. The login dialog opens on its own once the login is waiting on + * the website, so it goes straight to the progress view. Cancelling is a choice rather than a + * fault, so only a real failure is reported. */ export const useNexusLogin = (): (() => void) => { const dispatch = useDispatch(); @@ -17,7 +18,11 @@ export const useNexusLogin = (): (() => void) => { const api = extensions.getApi(); return useCallback(() => { - dispatch(setDialogVisible("login-dialog")); + // STA-574: `control` keeps the old flow, which opens the old dialog first. + if (fixLoginPromptCohort() === "control") { + dispatch(setDialogVisible("login-dialog")); + } + api.events.emit("request-nexus-login", (err: Error) => { if (err != null && !(err instanceof UserCanceled)) { api.showErrorNotification?.("Login Failed", err, { diff --git a/src/shared/src/types/flags.ts b/src/shared/src/types/flags.ts index 4168ac545d..80f51cd2e7 100644 --- a/src/shared/src/types/flags.ts +++ b/src/shared/src/types/flags.ts @@ -40,6 +40,8 @@ export const flagVariantSchemas = { }), ) as z.ZodType, }, + // STA-574 experiment: on is the `test` cohort (login prompt and new login dialog). + "vortex-sta-574-login-prompt": {}, }; export interface GameFolderCheckFlagConfig {