Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

32.5 KB
Raw Blame
import { useEffect, useState } from "react";
import { Rocket, Star } from "lucide-react";
import type { CloudAccountState } from "../../electron/cloud-account.mjs";
import type { CloudOffer } from "../../electron/cloud-home.mjs";
import type { ConfigStatus } from "@/state/config-status";
import { api, useStore } from "@/state/store";
import { APP_REPOSITORY, appVersion } from "@/lib/app-links";
import { track } from "@/lib/analytics";
import { announcementConditions, announcementPlan, announcementPlatform, announcementSurface, markLaunchAnnouncement, pickAnnouncement, providersRestricted, rememberCardSeen, rememberSponsorDay,
  reportAnnouncement, SPONSOR_CARDS_FOR_TEAM_MEMBERS, useAnnouncementCards, type SeenRecord } from "@/lib/announcements";
import { brandStatus } from "@/lib/brand";
import { modelgoOfferable, reportModelgoOffer } from "@/lib/modelgo-offer";
import { buyOfferAllowed, cloudNoticeKind, cloudPlanView, cloudTrialNotice, cloudTrialView, offerTrialDays } from "@/lib/cloud-plan";
import { jobRoutine, useCloudIntent } from "@/lib/cloud-intent";
import { CLOUD_INTENT_GIVEN, cloudSetupStage } from "@/lib/cloud-setup";
import { cornerPopupWaits, firstChatQuiet, firstReplyPending } from "@/lib/corner-popup";
import { ANNOUNCEMENT_NOTICE, CLOUD_INTRO, CLOUD_NOTICE, CLOUD_TRIAL_NOTICE, dismissNotice, dismissNotices, EARLIER_WHATS_NEW_NOTICE, GROK_MOVE_NOTICE, introShown, introStage, launchNotice, markLaunchNotice, MODELGO_CARD_CAMPAIGN, MODELGO_CARD_NOTICE, MODELGO_OFFER_NOTICE, nextNotice, noticeSeen, PHONE_UPDATE_NOTICE, phoneUpdateHint, PREVIOUS_WHATS_NEW_NOTICE, PRODUCT_HUNT_NOTICE, TOGETHER_NOTICE, PRODUCT_HUNT_UNTIL, PRODUCT_HUNT_URL, SIMPLE_MODE_NOTICE, STAR_NOTICE, TEAMS_NOTICE, TWO_PLACES_NOTICE, UPDATES_CONSENT_NOTICE, usedBefore, WHATS_NEW_NOTICE } from "@/lib/notices";
import { rememberNoticeSeen } from "@/lib/announcement-history";
import { reportTeams, teamsAction } from "@/lib/teams-whats-new";
import { useTwoPlaces } from "@/lib/two-places";
import { togetherSlideShown, useTogetherNoticeDrawn, useTogetherNoticeDue } from "@/lib/places-together";
import { SIMPLE_ONLY } from "@/lib/simple-only";
import { useAdvancedBackDue, useNewLookDue } from "@/lib/new-look";
import { useAdvancedMode } from "@/lib/interface-mode";
import { promotionsEnabled } from "@/lib/feature-flags";
import { useSimpleModePromptSeen } from "@/lib/simple-mode-prompt";
import { reportWhatsNew, togetherSlideDue, WHATS_NEW_SOURCES, whatsNewAudience, whatsNewCarousel, whatsNewView, type WhatsNewAction, type WhatsNewSlide } from "@/lib/whats-new";
import { cloudSignInDue, onboardingCloudOffered, welcomeFinishedThisLaunch, type WelcomeViewer } from "@/lib/onboarding";
import { launchDialogShown, markLaunchDialog } from "@/lib/launch-dialogs";
import { useUpdaterState } from "@/lib/updater";
import { phonePairingSettingsAction } from "@/lib/phone-pairing";
import { activeLocale, t } from "@/lib/i18n";
import { AnnouncementCard, announcementPlaceAction } from "./AnnouncementCard";
import { engineReady } from "./EngineLibrary";
import { CLOUD_NOTICE_CARD, cloudNoticeStep, CloudNoticeCard } from "./CloudNotice";
import { CloudTrialIntroCard } from "./CloudTrialIntro";
import { hasBotsHere } from "@/lib/move-changes";
import { useMoveQuiet } from "./CloudSendStrip";
import { CloudTrialNoticeCard, useCloudPlanSnapshot } from "./CloudTrialNotice";
import { GrokMovePopup, reportGrokMovePopup, type GrokMovePopupAction } from "./GrokMovePopup";
import { GrokMoveDialog } from "./lazy-screens";
import { openKeySettings } from "./keys/key-focus";
import { ModelgoOfferCard, type ModelgoCardAction } from "./ModelgoOffer";
import { LinkButton, NoticeCard, NoticeToast, NotNowButton } from "./NoticeCard";
import { useDesktopNotices, useOtherDialogOpen } from "./notice-dialogs";
import { localDesktopPage } from "./onboarding/welcome-viewer";
import { UpdatesConsentDialog, updatesConsentBridge, useUpdatesConsent } from "./UpdatesConsent";
import { useMausBotWelcomeDue } from "./MausBotWelcome";
import { NewLookNotice, reportNewLook } from "./NewLookNotice";
import { PhoneUpdateCard, phonesToTell, useRetiredLinkPhones } from "./PhoneUpdateNotice";
import { reportSimpleModePrompt, SimpleModePrompt } from "./SimpleModePrompt";
import { TwoPlacesCard } from "./TwoPlacesCard";
import { TogetherNotice } from "./TogetherNotice";
import { TeamsPopup } from "./whats-new/TeamsPopup";
import { WhatsNewPopup } from "./whats-new/WhatsNewPopup";

function StarCard({ onDismiss }: { onDismiss: () => void }) {
  return <NoticeCard titleId="github-star-title" notice="github-star" icon={Star} title={t("star.title")} onDismiss={onDismiss}>
    <p className="mb-3 mt-1 text-[13px] text-ink-secondary">{t("star.body")}</p>
    <div className="flex flex-wrap items-center gap-3">
      <LinkButton url={APP_REPOSITORY} label={t("star.button")} onOpened={onDismiss} />
      <NotNowButton onClick={onDismiss} />
    </div>
  </NoticeCard>;
}

function ProductHuntCard({ onDone }: { onDone: (action: "upvote" | "not_now" | "close") => void }) {
  return <NoticeCard titleId="product-hunt-title" notice="product-hunt" icon={Rocket} title={t("productHunt.title")} onDismiss={() => onDone("close")}>
    <p className="mb-3 mt-1 text-[13px] text-ink-secondary">{t("productHunt.body")}</p>
    <div className="flex flex-wrap items-center gap-3">
      <LinkButton url={PRODUCT_HUNT_URL} label={t("productHunt.button")} onOpened={() => onDone("upvote")} />
      <NotNowButton onClick={() => onDone("not_now")} />
    </div>
  </NoticeCard>;
}

const trialKey = (trial: { state: string; endsAt: number }) => `${trial.state}:${trial.endsAt}`;
/** A first run lands in its Chief's chat, whose first messages arrive one at a time; the Grok Bot popup follows them. */
const FIRST_MESSAGES_MS = 6_000;

export function AppNotices({ quiet = false, viewer = null, now = Date.now }: { quiet?: boolean; viewer?: WelcomeViewer | null; now?: () => number }) {
  const { state, dispatch } = useStore();
  const promotions = promotionsEnabled(state.config);
  const remote = window.ogb?.remoteClient?.active === true;
  const local = localDesktopPage();
  const bridge = !remote && local ? window.ogb?.cloudAccount : undefined;
  const desktop = remote ? undefined : window.ogb?.desktopNotices;
  const desktopState = useDesktopNotices(desktop);
  // Asked once main has restored the Cloud sign-in, which it waits for before answering desktopState.
  const planBridge = !remote && (bridge || (viewer?.cloudHome && (desktopState || !desktop))) ? window.ogb?.cloudPlan : undefined;
  const [account, setAccount] = useState<CloudAccountState | null>(null);
  const plan = useCloudPlanSnapshot(planBridge);
  const [offer, setOffer] = useState<CloudOffer | null | undefined>(undefined);
  const [offerFor, setOfferFor] = useState<string | null>(null);
  const [organization, setOrganization] = useState<boolean | null>(window.ogb?.organization ? null : false);
  const [closed, setClosed] = useState(false);
  const [introOpen, setIntroOpen] = useState(false);
  const [trialOpen, setTrialOpen] = useState<string | null>(null);
  const [toast, setToast] = useState<string | null>(null);
  const [failed, setFailed] = useState(false);
  const [busy, setBusy] = useState(false);
  const [simpleShown, setSimpleShown] = useState(false);
  const [announcementShown, setAnnouncementShown] = useState<string | null>(null);
  const [grokShown, setGrokShown] = useState(false);
  const [grokOpen, setGrokOpen] = useState(false);
  const [grokLanded, setGrokLanded] = useState(false);
  const [modelgoShown, setModelgoShown] = useState(false);
  const consentHere = (local || viewer?.cloudHome === true) && brandStatus().source !== "file";
  const consent = useUpdatesConsent(consentHere ? updatesConsentBridge() : undefined);
  const [consentDone, setConsentDone] = useState(false);
  const updater = useUpdaterState();
  const intent = useCloudIntent();
  const moving = useMoveQuiet(now);
  const mausBot = useMausBotWelcomeDue(viewer);
  // Bots in two places: this computer's page only, where main knows what lives here.
  const two = useTwoPlaces();
  // Together by default: this computer's page only, where the one list is; never during a live call.
  const togetherDue = useTogetherNoticeDue();
  // While the notice of the default is due, or main has not said yet whether it is, the bots of this computer and My
  // Cloud are about to work together: no suggestion to move them to My Cloud goes ahead of it.
  const cloudHeld = two.suggest?.kind === "cloud" && togetherDue !== false;
  const twoFact = !local || two.suggest === null || (cloudHeld && togetherDue === true) ? false : two.suggest === undefined || cloudHeld ? null : true;
  // Once drawn it stays until closed, though main stops calling it due as soon as one of its switches is used.
  const [togetherOpen, setTogetherOpen] = useState(false);
  // The notice's slide in What's new, kept in this page's carousel once shown there (main stops calling it due then).
  const togetherDrawn = useTogetherNoticeDrawn();
  const [togetherSlideKept, setTogetherSlideKept] = useState(false);
  const togetherFact = togetherOpen ? true : remote || !local || togetherDue === false ? false : togetherDue === null || (state.liveCall && state.liveCall.status !== "ended") ? null : true;
  // Phones whose older app lost its way in: this computer's own page only, never a Cloud, a server's page or client mode.
  const linkPhones = useRetiredLinkPhones(!remote && local);
  useEffect(() => {
    if (!bridge) return;
    let active = true, updated = false;
    const unsubscribe = bridge.onState(next => { updated = true; if (active) setAccount(next); });
    void bridge.state().then(next => { if (active && !updated) setAccount(next); }).catch(() => {});
    return () => { active = false; unsubscribe(); };
  }, [bridge]);
  useEffect(() => {
    const org = window.ogb?.organization;
    if (!org) return;
    let active = true;
    const read = (next: { status: string; organization?: unknown }) => { if (active) setOrganization(next.status !== "signed-out" && Boolean(next.organization)); };
    const unsubscribe = org.onState(read);
    void org.state().then(read, () => { if (active) setOrganization(false); });
    return () => { active = false; unsubscribe(); };
  }, []);
  const view = bridge ? cloudPlanView(account) : null;
  const record = state.config?.onboarding;
  const introAllowed = promotions && Boolean(bridge) && brandStatus().source !== "file" && organization !== true && !onboardingCloudOffered(record);
  const stage = introStage(record, now());
  const trialDue = cloudTrialNotice(plan);
  const branded = brandStatus().source === "file", team = Boolean(state.config?.team);
  const liveCall = Boolean(state.liveCall && state.liveCall.status !== "ended");
  // What's new, once per person on every page but a branded build's. Its plan slides: This computer's page of a desktop that
  // sells MausBot Cloud, never one an organization runs. Its last slide is the notice of the bots together, for whom that
  // notice is due and was never drawn; closed before that slide, the corner notice shows it on a later launch.
  const whatsNewSeen = noticeSeen(record, WHATS_NEW_NOTICE) || Boolean(desktopState?.seen.includes(WHATS_NEW_NOTICE));
  const togetherSlide = togetherSlideDue({ here: local && !remote && !branded, due: togetherDue, drawn: togetherDrawn, kept: togetherSlideKept });
  const whatsNewHere = !branded && !whatsNewSeen;
  const plansDue = !whatsNewHere || !bridge || !desktop || organization === true ? false : !desktopState || organization === null ? null : desktopState.cloud;
  const whatsNewFor = plansDue === false ? null : whatsNewAudience(account);
  const wantOffer = promotions && Boolean(bridge?.offer) && ((introAllowed && view !== null && buyOfferAllowed(view) && stage !== "done")
    || whatsNewFor === "none" || whatsNewFor === "own");
  const offerKey = wantOffer ? `${view?.kind}:${JSON.stringify(account?.offer ?? null)}` : null;
  useEffect(() => {
    if (!offerKey || !bridge?.offer) return;
    let active = true;
    const answer = (next: CloudOffer | null) => { if (active) { setOffer(next); setOfferFor(offerKey); } };
    void bridge.offer().then(answer, () => answer(null));
    return () => { active = false; };
  }, [offerKey, bridge]);
  useEffect(() => {
    if (whatsNewSeen && desktopState && !desktopState.seen.includes(WHATS_NEW_NOTICE)) void desktop?.seen(WHATS_NEW_NOTICE).catch(() => {});
  }, [whatsNewSeen, desktopState]);
  const offerRead = !bridge?.offer ? null : offerFor === offerKey ? offer : undefined;
  const plans = !promotions || plansDue === false ? "none" : plansDue === null ? "loading" : whatsNewView(account, offerRead);
  const teamSold = plansDue === true && offerRead ? offerRead.plans.some(entry => entry.tier === "team") : undefined;
  const consentDue = consent.state?.available === true && consent.state.due && !consentDone;
  const consentBlocked = useOtherDialogOpen(consentDue) || liveCall;
  const consentFact = !consentHere || consentDone ? false : consent.state === undefined ? null : consentDue ? (consentBlocked ? null : true) : false;
  // Every page with the app's chrome, desktop or Cloud, new install or not: once per browser, as the mode is. With Simple
  // the only mode, its place goes to the word about the new look, only where Advanced was on; a browser put back on
  // Advanced gets the word that it is back there instead.
  const promptSeen = useSimpleModePromptSeen(), newLookDue = useNewLookDue(), backDue = useAdvancedBackDue(), advanced = useAdvancedMode();
  const advancedBack = backDue && advanced;
  const simpleDue = SIMPLE_ONLY ? newLookDue : advancedBack || !promptSeen;
  const simpleBlocked = useOtherDialogOpen(simpleDue) || liveCall;
  // A sponsor's card is for whoever chooses a team's providers: its Owner and Admins, never its members.
  const sponsorsHere = SPONSOR_CARDS_FOR_TEAM_MEMBERS || !state.config?.team || viewer?.canSave === true;
  const teams = teamsAction({ team: state.config?.team, viewer, account, canAddCloud: Boolean(bridge) });
  // Owed while it has a slide for this person (or may, while that is read): the Teams popup and the sponsor's card it took
  // in wait for it, and count as seen with it.
  // A Cloud this person has: this page is one, or this desktop's sign-in has a plan of its own or a team's.
  const hasCloud = viewer?.cloudHome === true || whatsNewFor === "own" || whatsNewFor === "team";
  const whatsNewTeam = organization === true || (!promotions && teams.kind === "start") ? null : teams;
  const whatsNewState = !whatsNewHere ? "none" : togetherSlide === null ? "loading" : whatsNewCarousel({ plans, team: whatsNewTeam, teamSold,
    cloud: hasCloud, apps: { place: state.config?.cloudHome === true ? "cloud" : "computer", install: local && !remote && Boolean(window.ogb?.appInstall) },
    staging: account?.staging === true, together: togetherSlide });
  const whatsNew = typeof whatsNewState === "object" ? whatsNewState : null;
  const whatsNewOwed = whatsNewState !== "none";
  const whatsNewBlocked = useOtherDialogOpen(whatsNewOwed, true) || liveCall;

  const trial = plan?.trial;
  const key = trial ? trialKey(trial) : null;
  const setupRecord = record && (intent.pending || intent.sent) ? { ...record, hintsSeen: [...record.hintsSeen, CLOUD_INTENT_GIVEN] } : record;
  const setupHere = cloudSignInDue(viewer, state, engineReady)
    || ["waiting", "shown"].includes(cloudSetupStage({ viewer, connected: state.connected, enginesKnown: state.instances.length > 0,
      engineReady: state.instances.some(engineReady), onboarding: setupRecord, planned: Boolean(jobRoutine(state.routines, intent.sent)) }));
  const waits = cornerPopupWaits(state, updater, { quiet, idle: true, viewer, duringFirstChat: true }) || Boolean(state.cloudAdd) || state.cloudHowTo || setupHere;
  const kind = view ? cloudNoticeKind(view, account) : null;
  const introDue = (): boolean | null => {
    if (!introAllowed || !view) return false;
    if (view.kind === "unknown" || view.kind === "connecting" || organization === null) return null;
    if (!buyOfferAllowed(view) || !usedBefore(state.bots)) return false;
    if (offer === undefined) return null;
    if (offerTrialDays(offer) === null) return false;
    return introOpen || stage === "due" ? true : null;
  };
  const cards = Boolean(bridge || planBridge);
  // Promotions never land on a new install's first chat: they wait for its first reply, and the full-screen What's new popup
  // also for a launch after the one whose welcome just finished. Account and billing notices keep their own rules.
  // Unknown (null) until the bots have loaded, so nothing lower in the queue flashes up before them.
  const firstChat = firstReplyPending(state);
  // MausBot's first-launch card goes first: the popup and the question wait while it is due. The popup skips a launch the
  // card used; the question may follow the card once it closes, as it follows the popup.
  const afterWelcome = welcomeFinishedThisLaunch() || launchDialogShown() === "mausbot" || firstChat;
  const consentWaits = welcomeFinishedThisLaunch() || firstChat;
  const mausBotFirst = mausBot.due;
  const consentNow = consentWaits === true || consentFact === false ? false : consentWaits === null || mausBotFirst ? null : consentFact;
  // The Grok Bot popup: once for everyone who can add a bot, the one thing a first chat may be interrupted by. Nothing reads
  // this computer for it: GrokMoveDialog does that, once opened.
  const grokDue = !remote && viewer?.canSave !== false && !state.config?.team && brandStatus().source !== "file" && organization !== true && moving !== true
    && launchDialogShown() !== "mausbot" && !noticeSeen(record, GROK_MOVE_NOTICE) && !desktopState?.seen.includes(GROK_MOVE_NOTICE);
  const grokBlocked = useOtherDialogOpen(grokDue) || liveCall;
  const grokLanding = welcomeFinishedThisLaunch() && !grokLanded;
  useEffect(() => {
    if (!grokDue || !grokLanding || waits) return;
    const timer = setTimeout(() => setGrokLanded(true), FIRST_MESSAGES_MS);
    return () => clearTimeout(timer);
  }, [grokDue, grokLanding, waits]);
  const grokNow = !grokDue ? false
    : !viewer || (desktop && !desktopState) || organization === null || firstChat === null || mausBotFirst || moving === null || grokLanding || grokBlocked ? null : true;
  // What's new: once some bot has answered, the launch a new install's welcome finished in included. Never in the launch
  // MausBot's card took, over a first run's own screens or another dialog, during a live call or a move.
  const whatsNewNow = !whatsNewOwed || moving || firstChat === true || launchDialogShown() === "mausbot" ? false
    : whatsNewState === "loading" || !viewer || organization === null || (desktop && !desktopState) || firstChat === null || mausBotFirst || moving === null || whatsNewBlocked ? null : true;
  // A card from the project's announcements file: never in the launch a welcome or MausBot's card took, else the built-in
  // sponsor card's exclusions, and src/lib/announcements.ts's rules for which card and for whom (once per person, one
  // sponsor card a week, none on a branded build).
  const remoteCards = useAnnouncementCards(!branded);
  const surface = announcementSurface(local, Boolean(state.config?.cloudHome || viewer?.cloudHome));
  const seenRecord: SeenRecord = { record, desktop: desktopState?.seen ?? [], team };
  const picked = remoteCards.length === 0 ? null : pickAnnouncement(remoteCards, {
    facts: { nowMs: now(), version: appVersion(), platform: announcementPlatform(globalThis.navigator?.userAgent), surface, plan: announcementPlan(surface, view, team),
      people: usedBefore(state.bots) ? "existing" : "new", locale: activeLocale(), conditions: announcementConditions(state) },
    seen: seenRecord, branded, admin: viewer?.canSave !== false,
    sponsors: promotions && !providersRestricted(state.config?.managedPolicy) && sponsorsHere,
  });
  const announcement = picked && picked !== "wait" ? picked : null;
  // Teams: once for whom What's new has nothing, ahead of every other notice, on every page but a branded build's or an
  // organization's desktop; never in the launch a welcome or MausBot's card took, before a first reply, over a first run's
  // own screens or another dialog, during a live call or a move.
  const teamsSeen = noticeSeen(record, TEAMS_NOTICE) || Boolean(desktopState?.seen.includes(TEAMS_NOTICE));
  const teamsHere = !branded && whatsNewTeam !== null && !teamsSeen && !whatsNewOwed;
  const teamsBlocked = useOtherDialogOpen(teamsHere, true) || liveCall;
  const teamsNow = !teamsHere || moving || afterWelcome === true ? false
    : organization === null || !viewer || (desktop && !desktopState) || afterWelcome === null || mausBotFirst || moving === null || teamsBlocked ? null : true;
  const announcementNow = !picked || moving || welcomeFinishedThisLaunch() || launchDialogShown() === "mausbot" ? false
    : picked === "wait" || !viewer || organization === null || moving === null || firstChat === null || mausBotFirst || liveCall || (desktop && !desktopState) ? null : true;
  const remembering = { desktop, liveIds: new Set(remoteCards.map(card => card.id)), save: (hintsSeen: string[]) => void api("/api/config", { method: "PUT", body: JSON.stringify({ onboarding: { hintsSeen } }) })
    .then(config => dispatch({ type: "configStatus", config })).catch(() => {}) };
  // The sponsor's card, once more on its own: once per person (on a Team Cloud, its Owner and Admins), where ModelGo may be
  // offered and is not set up yet, while promotional messages are on. Never in the launch a welcome or MausBot's card took,
  // before a first reply, during a live call or a move; it waits until this place's settings are read.
  const modelgoSeen = noticeSeen(record, MODELGO_CARD_NOTICE) || Boolean(desktopState?.seen.includes(MODELGO_CARD_NOTICE));
  const modelgoSetUp = Boolean(state.config?.modelgo?.configured) || state.instances.some(instance => instance.driverKind === "modelgo" && engineReady(instance));
  const modelgoHere = promotions && sponsorsHere && !modelgoSeen && !modelgoSetUp && modelgoOfferable(state.config?.managedPolicy);
  const modelgoNow = !modelgoHere || moving || afterWelcome === true ? false
    : !state.config || !viewer || organization === null || (desktop && !desktopState) || afterWelcome === null || mausBotFirst || moving === null || liveCall ? null : true;
  const retiredPhones = phonesToTell(linkPhones, record);
  const phoneNow = retiredPhones?.length === 0 ? false
    : retiredPhones === undefined || !viewer || mausBotFirst || liveCall ? null : true;
  const launch = launchNotice();
  // After a closed popup only the product-updates question and an announcement card may follow in this launch (nextNotice's
  // FOLLOWERS); nothing else does.
  const notice = waits ? null
    : firstChatQuiet(state) ? (grokNow === true && (launch === null || launch === GROK_MOVE_NOTICE) ? GROK_MOVE_NOTICE : null)
    : teamsHere || cards || whatsNewOwed || consentHere || simpleDue || announcementNow !== false || twoFact !== false || togetherFact !== false || grokNow !== false || phoneNow !== false || modelgoNow !== false ? nextNotice({
    [TEAMS_NOTICE]: teamsNow,
    [GROK_MOVE_NOTICE]: grokNow,
    [PHONE_UPDATE_NOTICE]: phoneNow,
    [WHATS_NEW_NOTICE]: whatsNewNow,
    // Never in the launch whose welcome just finished, nor over MausBot's first-launch card.
    [SIMPLE_MODE_NOTICE]: !simpleDue || afterWelcome === true ? false : afterWelcome === null || mausBotFirst || simpleBlocked ? null : true,
    [UPDATES_CONSENT_NOTICE]: consentNow,
    [TWO_PLACES_NOTICE]: twoFact,
    [PRODUCT_HUNT_NOTICE]: !promotions || !cards || moving || firstChat === true || brandStatus().source === "file" || now() >= PRODUCT_HUNT_UNTIL ? false
      : organization === null || moving === null || firstChat === null ? null : !organization,
    [CLOUD_INTRO]: !promotions || moving ? false : moving === null ? null : introDue(),
    [CLOUD_TRIAL_NOTICE]: planBridge && plan === null ? null : Boolean(key && (trialDue || trialOpen === key)),
    [CLOUD_NOTICE]: !view ? false : view.kind === "unknown" ? null
      : Boolean(kind && !noticeSeen(record, CLOUD_NOTICE_CARD[kind].dismissed)),
    [TOGETHER_NOTICE]: togetherFact,
    [MODELGO_CARD_NOTICE]: modelgoNow,
    [ANNOUNCEMENT_NOTICE]: announcementNow,
    [STAR_NOTICE]: !promotions || !bridge || moving || brandStatus().source === "file" || !usedBefore(state.bots) ? false : moving === null ? null : true,
  }, id => id === TEAMS_NOTICE ? teamsSeen : id === MODELGO_CARD_NOTICE ? modelgoSeen : id === CLOUD_INTRO ? stage === "done" && !introOpen
    : id === STAR_NOTICE || id === PRODUCT_HUNT_NOTICE ? noticeSeen(record, id) : false, launch, closed) : null;

  const shownKey = notice === CLOUD_TRIAL_NOTICE ? key : notice === ANNOUNCEMENT_NOTICE ? `${notice}:${announcement?.id}` : notice;
  useEffect(() => {
    if (!shownKey || !notice) return;
    markLaunchNotice(notice);
    // The popups and the question own this launch: MausBot's first-launch card waits for a later one.
    if (shownKey === TEAMS_NOTICE || shownKey === GROK_MOVE_NOTICE || shownKey === SIMPLE_MODE_NOTICE || shownKey === WHATS_NEW_NOTICE || shownKey === UPDATES_CONSENT_NOTICE) markLaunchDialog("notices");
    if (shownKey === CLOUD_INTRO) {
      setIntroOpen(true);
      track("cloud_card_shown", { variant: view?.kind === "signed-out" ? "signed_out" : "free" });
      const patch = introShown(record, now());
      if (patch) void api("/api/config", { method: "PUT", body: JSON.stringify(patch) }).then(config => dispatch({ type: "configStatus", config })).catch(() => {});
    } else if (notice === CLOUD_TRIAL_NOTICE && trialOpen !== shownKey) {
      setTrialOpen(shownKey);
      void planBridge?.noticeSeen?.().catch(() => {});
    } else if (shownKey === SIMPLE_MODE_NOTICE && !simpleShown) {
      setSimpleShown(true);
      if (SIMPLE_ONLY || advancedBack) reportNewLook("shown", advancedBack);
      else reportSimpleModePrompt("shown");
    } else if (notice === ANNOUNCEMENT_NOTICE && announcement && announcementShown !== announcement.id) {
      setAnnouncementShown(announcement.id);
      markLaunchAnnouncement(announcement.id);
      reportAnnouncement(announcement, "shown");
      if (announcement.kind === "sponsor") rememberSponsorDay(seenRecord, now(), remembering);
    } else if (shownKey === TOGETHER_NOTICE) {
      setTogetherOpen(true);
    } else if (shownKey === GROK_MOVE_NOTICE && !grokShown) {
      setGrokShown(true);
      reportGrokMovePopup("shown");
    } else if (shownKey === MODELGO_CARD_NOTICE && !modelgoShown) {
      setModelgoShown(true);
      reportModelgoOffer("shown", "popup", MODELGO_CARD_CAMPAIGN);
    }
  }, [shownKey]);

  const save = (id: string) => {
    const patch = dismissNotice(record, id);
    if (patch) void api("/api/config", { method: "PUT", body: JSON.stringify(patch) })
      .then(config => dispatch({ type: "configStatus", config })).catch(() => {});
  };
  const close = () => { setClosed(true); setTrialOpen(null); setFailed(false); };
  if (grokOpen) return <GrokMoveDialog onClose={() => setGrokOpen(false)} />;
  if (toast) return <NoticeToast text={toast} onDone={() => setToast(null)} />;
  if (!notice) return null;

  if (notice === GROK_MOVE_NOTICE) {
    const done = (action: GrokMovePopupAction) => {
      reportGrokMovePopup(action); close(); save(GROK_MOVE_NOTICE);
      void desktop?.seen(GROK_MOVE_NOTICE).catch(() => {});
      if (action === "start") setGrokOpen(true);
    };
    return <GrokMovePopup onDone={done} />;
  }

  const writer = { team, desktop, saved: (config: ConfigStatus) => dispatch({ type: "configStatus", config }) };
  if (notice === TEAMS_NOTICE) {
    const done = () => { close(); rememberNoticeSeen(TEAMS_NOTICE, record, writer); };
    return <TeamsPopup action={teams} onStep={step => reportTeams(step, teams)} onDone={done} onStart={() => dispatch({ type: "openCloudAdd", source: WHATS_NEW_SOURCES.team })} />;
  }

  if (notice === MODELGO_CARD_NOTICE) {
    const done = (action: ModelgoCardAction) => {
      reportModelgoOffer(action, "popup", MODELGO_CARD_CAMPAIGN); close(); rememberNoticeSeen(MODELGO_CARD_NOTICE, record, writer);
      if (action === "add_key") dispatch(openKeySettings("modelgo"));
    };
    return <ModelgoOfferCard addKey={viewer?.canSave !== false} onDone={done} />;
  }

  if (notice === PHONE_UPDATE_NOTICE && retiredPhones?.length) {
    const done = () => { close(); const patch = dismissNotices(record, retiredPhones.map(phone => phoneUpdateHint(phone.id)));
      if (patch) void api("/api/config", { method: "PUT", body: JSON.stringify(patch) }).then(config => dispatch({ type: "configStatus", config })).catch(() => {}); };
    return <PhoneUpdateCard phones={retiredPhones} onOpen={() => { done(); dispatch(phonePairingSettingsAction()); }} onDismiss={done} />;
  }

  if (notice === TOGETHER_NOTICE) return <TogetherNotice onClose={() => { setTogetherOpen(false); close(); }} />;

  if (notice === SIMPLE_MODE_NOTICE) {
    return SIMPLE_ONLY || advancedBack ? <NewLookNotice onClose={close} back={advancedBack} /> : <SimpleModePrompt onClose={close} />;
  }

  if (notice === WHATS_NEW_NOTICE && whatsNew) {
    const report = (action: WhatsNewAction, slide: WhatsNewSlide) => {
      // Shown here, the notice of the bots together is done: kept in this carousel, and never in the corner after.
      if (action === "seen" && slide === "together" && !togetherSlideKept) { setTogetherSlideKept(true); void togetherSlideShown(); }
      reportWhatsNew(action, slide, whatsNew);
    };
    const done = () => { close(); rememberNoticeSeen(WHATS_NEW_NOTICE, record, writer, [PREVIOUS_WHATS_NEW_NOTICE, EARLIER_WHATS_NEW_NOTICE, TEAMS_NOTICE, MODELGO_OFFER_NOTICE]); };
    return <WhatsNewPopup view={whatsNew} report={report} onDone={done} onBuy={slide => dispatch({ type: "openCloudAdd", source: WHATS_NEW_SOURCES[slide] })}
      onOpenApps={() => dispatch({ type: "showPublishedApps" })} />;
  }

  if (notice === UPDATES_CONSENT_NOTICE && consent.state) {
    const done = () => { setConsentDone(true); close(); };
    return <UpdatesConsentDialog signedIn={consent.state.signedIn}
      onYes={async email => { await consent.choose("opted_in", email); done(); }}
      onNo={() => { done(); void consent.choose("declined").catch(() => {}); }} />;
  }
  if (notice === CLOUD_INTRO && offer) {
    const done = (action: string) => { track("cloud_card_action", { action }); close(); save(CLOUD_INTRO); };
    return <CloudTrialIntroCard offer={offer} botsHere={hasBotsHere({ bots: state.bots, cloudHome: state.config?.cloudHome === true, desktop: Boolean(window.ogb), remote: window.ogb?.remoteClient?.active === true })}
      onStart={() => { done("start"); dispatch({ type: "openCloudAdd", source: "app_card" }); }}
      onHowTo={() => { done("howto"); dispatch({ type: "cloudHowTo", open: true }); }}
      onSignIn={view?.kind === "signed-out" ? () => { track("cloud_card_action", { action: "signin" }); close(); dispatch({ type: "openCloudAdd", source: "app_card", signIn: true }); } : undefined}
      onNotNow={() => { done("not_now"); setToast(t("cloudIntro.later")); }}
      onDismiss={() => { done("close"); setToast(t("cloudIntro.later")); }} />;
  }
  if (notice === CLOUD_TRIAL_NOTICE && trial) {
    const shown = cloudTrialView(trial, plan?.credit);
    const act = () => { setFailed(false); void planBridge?.manage().then(close, () => setFailed(true)); };
    return <CloudTrialNoticeCard view={shown} failed={failed} onAction={act} onClose={close} />;
  }
  if (notice === CLOUD_NOTICE && kind && bridge) {
    const act = () => {
      if (busy) return;
      setFailed(false); setBusy(true);
      void cloudNoticeStep(kind, bridge).then(next => setAccount(next), () => setFailed(true)).finally(() => setBusy(false));
    };
    return <CloudNoticeCard kind={kind} busy={busy} failed={failed} onAction={act} onNotNow={() => { close(); save(CLOUD_NOTICE_CARD[kind].dismissed); }} />;
  }
  if (notice === TWO_PLACES_NOTICE && two.suggest) {
    const { key, kind } = two.suggest;
    return <TwoPlacesCard key={key} suggest={two.suggest}
      onBring={() => { track("two_places_card", { action: "bring", kind }); return two.accept(key).then(close); }}
      onDismiss={() => { track("two_places_card", { action: "not_now", kind }); two.dismiss(key); close(); }} />;
  }
  if (notice === PRODUCT_HUNT_NOTICE) {
    return <ProductHuntCard onDone={action => { track("product_hunt_card", { action }); close(); save(PRODUCT_HUNT_NOTICE); }} />;
  }
  if (notice === ANNOUNCEMENT_NOTICE && announcement) {
    const done = (action: "primary" | "secondary" | "close") => {
      reportAnnouncement(announcement, action); close(); rememberCardSeen(seenRecord, announcement.id, remembering);
    };
    return <AnnouncementCard key={announcement.id} card={announcement} onDone={done} open={place => dispatch(announcementPlaceAction(place))} />;
  }
  if (notice === STAR_NOTICE) return <StarCard onDismiss={() => { close(); save(STAR_NOTICE); }} />;
  return null;
}