-
-
-
- {choice.name}
- {(found || installed) && {installedVersion ? `Версия ${installedVersion}` : "Версия не определена"} }
- {title}
- {detail && {detail} }
-
-
- {/* Extend across the card so logo color follows the download fill exactly. */}
-
-
-
- {failedMessage ? Повторить
- : paused ? Продолжить
- : downloading ? void pause()}>{pauseRequested ? "Приостанавливаем…" : "Приостановить"}
- : completed ? Готово
- : (!active || state?.status === "available") && start()}>{unsupported ? "Недоступно" : downloaded ? "Установить" : found || installed ? "Проверить обновления" : "Скачать"} }
-
-
+ return (
+
+
}
+ brand={desktop}
+ version={
+ found &&
+ !downloading &&
+ !downloaded &&
+ !installing &&
+ (!installed || !focused) &&
+ !retryInstall
+ ? (installed ? state.version : version)
+ ? `Версия ${installed ? state.version : version}`
+ : "Версия не определена"
+ : undefined
+ }
+ status={status}
+ detail={
+ downloading
+ ? `${megabytes(state.received)} / ${state.total > 0 ? megabytes(state.total) : "…"} МБ`
+ : undefined
+ }
+ notice={
+ downloading && state.reconnecting
+ ? "Восстанавливаем соединение…"
+ : undefined
+ }
+ error={!focused ? failedMessage : undefined}
+ progress={progress}
+ downloading={downloading}
+ filled={downloaded || installing || installed}
+ tone={
+ installed
+ ? "success"
+ : state?.status === "failed"
+ ? "error"
+ : "default"
+ }
+ onOpen={!focused && active ? onSelect : undefined}
+ action={
+ !focused && (active || canDownload) ? (
+
+
+ {found ? "Обновить" : "Скачать"}
+
+
+ ) : undefined
+ }
+ />
+ {focused && (
+ <>
+ {downloaded && (state.notes.length > 0 || !state.path) && (
+
+ {state.notes.map((note) => (
+ {note}
+ ))}
+ {!state.path && (
+
+ Система запросит права администратора для установки{" "}
+ {choice.name}.
+
+ )}
+
+ )}
+ {installable && running.length > 0 && (
+
+ Wizard закроет {running.join(", ")} и откроет снова. Сохраните
+ текущую работу перед установкой.
+
+ )}
+ {installable && !runningApps.checked && (
+
+ {runningApps.error ?? "Проверяем запущенные приложения…"}
+
+ )}
+ {installable && confirmation && (
+
+
+ {confirmation}
+
+ )}
+ {installing && (
+
+ Не выходите из Wizard до завершения установки.
+
+ )}
+ {installed &&
+ state.notices.map((notice) => (
+
+ {notice}
+
+ ))}
+ {failedMessage && (
+
+ {failedMessage}
+
+ )}
+
+ Назад
+
+ }
+ >
+ {(downloaded ||
+ (state?.status === "failed" &&
+ state.operation === "download")) && (
+
+ )}
+ {downloading ? (
+
+ ) : installing ? (
+
+ Устанавливаем…
+
+ ) : current ? (
+ Готово
+ ) : (
+ (installable || canDownload) && (
+
+ installable
+ ? void controls.install(
+ desktop,
+ confirmed,
+ running.length > 0,
+ )
+ : start()
+ }
+ >
+ {actionLabel}
+
+ )
+ )}
+
+ >
+ )}
- {(downloading || paused) &&
}
- {failedMessage &&
{failedMessage}
}
- {!found && state?.status === "unsupported" &&
{state.message} }
- {installed && state.notices.length > 0 &&
{state.notices.map((notice) => {notice} )}
}
- ;
+ );
}
diff --git a/crates/wizard-gui/wizard-ui/src/onboarding/Installations.tsx b/crates/wizard-gui/wizard-ui/src/onboarding/Installations.tsx
new file mode 100644
index 0000000..52d52ad
--- /dev/null
+++ b/crates/wizard-gui/wizard-ui/src/onboarding/Installations.tsx
@@ -0,0 +1,224 @@
+import { invoke } from "@tauri-apps/api/core";
+import { useEffect, useRef, useState, type ReactNode } from "react";
+import {
+ useDesktopInstall,
+ type DesktopApp,
+ type Snapshot,
+} from "../agents/desktop_install_state";
+import type { useAgentState } from "../agents/agents_state";
+import { Dialog } from "../components/catalyst/dialog";
+import { DialogHeader } from "../components/ui/DialogHeader";
+import { ViewTransition } from "../components/ui/Layout";
+import { StateNotice } from "../components/ui/StateNotice";
+import { Text } from "../components/catalyst/text";
+import { choices, isFound } from "./agents";
+import { InstallCard } from "./InstallCard";
+import {
+ InstallationsContext,
+ type Installations,
+} from "./installations_state";
+import "./SetupDialog.css";
+
+/** The provider outlives pages and dialogs. Only explicit cancellation stops a transfer. */
+export function InstallationsProvider({
+ children,
+ agents,
+ signedIn,
+}: {
+ children: ReactNode;
+ agents: ReturnType
;
+ signedIn: boolean;
+}) {
+ const claude = useDesktopInstall("claude");
+ const chatgpt = useDesktopInstall("chatgpt");
+ const observations = { claude, chatgpt };
+ // Navigation belongs to this opening of the dialog, never to the background job.
+ const [navigation, setNavigation] = useState<{ desktop: DesktopApp | null; fromPicker: boolean }>();
+ const view = navigation?.desktop;
+ const title = useRef(null);
+ useEffect(() => {
+ title.current
+ ?.querySelector("h2")
+ ?.focus({ preventScroll: true });
+ }, [view]);
+ const selectedStatus = view ? observations[view].state?.status : undefined;
+ useEffect(() => {
+ // A completed/cancelled operation may remove the focused action button.
+ if (document.activeElement === document.body)
+ title.current
+ ?.querySelector("h2")
+ ?.focus({ preventScroll: true });
+ }, [selectedStatus]);
+ const [requesting, setRequesting] = useState({});
+ const [errors, setErrors] = useState({});
+ const [acknowledged, setAcknowledged] = useState<
+ Partial>
+ >({});
+ const inFlight = useRef(new Set());
+
+ async function run(desktop: DesktopApp, action: () => Promise) {
+ if (inFlight.current.has(desktop)) return;
+ inFlight.current.add(desktop);
+ setRequesting((current) => ({ ...current, [desktop]: true }));
+ setErrors((current) => ({ ...current, [desktop]: undefined }));
+ try {
+ await action();
+ } catch (cause) {
+ setErrors((current) => ({
+ ...current,
+ [desktop]:
+ typeof cause === "string"
+ ? cause
+ : "Не удалось выполнить действие. Попробуйте ещё раз.",
+ }));
+ } finally {
+ inFlight.current.delete(desktop);
+ setRequesting((current) => ({ ...current, [desktop]: false }));
+ }
+ }
+
+ const desktopChoices = choices.filter((choice) => choice.desktop);
+ const jobs = desktopChoices
+ .filter((choice) => {
+ const state = observations[choice.desktop!].state;
+ return (
+ state?.status === "downloading" ||
+ state?.status === "ready_to_install" ||
+ state?.status === "installing" ||
+ (state?.status === "installed" &&
+ acknowledged[choice.desktop!] !== state.revision) ||
+ (state?.status === "failed" && state.operation !== "check")
+ );
+ })
+ .map((choice) => choice.desktop!);
+
+ const controls: Installations = {
+ observations,
+ requesting,
+ errors,
+ jobs,
+ open: (desktop) => setNavigation({ desktop: desktop ?? null, fromPicker: false }),
+ download: (desktop) =>
+ run(desktop, async () => {
+ if (!signedIn) return;
+ let state = observations[desktop].state;
+ if (!state || observations[desktop].busy) return;
+ if (
+ state.status !== "available" &&
+ !(state.status === "failed" && state.operation === "download")
+ ) {
+ await invoke("check_desktop_release", { desktop });
+ state = await invoke("get_desktop_install_state", {
+ desktop,
+ lastRevision: null,
+ });
+ while (state.status === "checking") {
+ state = await invoke("get_desktop_install_state", {
+ desktop,
+ lastRevision: state.revision,
+ });
+ }
+ }
+ // Checking may restore a complete archive, or find the installed version current.
+ if (
+ state.status === "available" ||
+ (state.status === "failed" && state.operation === "download")
+ ) {
+ await invoke("download_desktop_release", { desktop });
+ }
+ }),
+ cancel: (desktop) =>
+ run(desktop, () => invoke("cancel_desktop_download", { desktop })),
+ install: (desktop, confirmed, close) =>
+ run(desktop, () =>
+ invoke("install_desktop_release", {
+ desktop,
+ confirmed,
+ close,
+ openAfterInstall: false,
+ }),
+ ),
+ };
+
+ return (
+
+ {children}
+ {view !== undefined && (
+ setNavigation(undefined)}
+ size={view ? "md" : "2xl"}
+ className={`setup-dialog relative${view ? " setup-dialog-compact" : ""}`}
+ >
+
+ setNavigation(undefined)}
+ />
+
+
+ {agents.status === "ready" ? (
+
+ {desktopChoices
+ .filter((choice) => !view || choice.desktop === view)
+ .map((choice) => {
+ const desktop = choice.desktop!;
+ const detection =
+ desktop === "claude"
+ ? agents.data.claude_desktop
+ : agents.data.codex.status === "found"
+ ? agents.data.codex.data.desktop
+ : agents.data.codex;
+ return (
+ setNavigation({ desktop, fromPicker: true })}
+ onBack={navigation?.fromPicker ? () => setNavigation({ desktop: null, fromPicker: false }) : undefined}
+ onDone={() => {
+ setAcknowledged((current) => ({
+ ...current,
+ [desktop]: observations[desktop].state?.revision,
+ }));
+ setNavigation(undefined);
+ }}
+ />
+ );
+ })}
+
+ ) : (
+
+
+ {agents.status === "loading"
+ ? "Ищем установленных агентов…"
+ : "Не удалось проверить приложения. Проверка повторится автоматически."}
+
+
+ )}
+ {!signedIn && (
+
+ Войдите в CoreInfra Hub, чтобы скачать приложение.
+
+ )}
+
+
+ )}
+
+ );
+}
diff --git a/crates/wizard-gui/wizard-ui/src/onboarding/SetupDialog.css b/crates/wizard-gui/wizard-ui/src/onboarding/SetupDialog.css
index bd47f42..243b5f7 100644
--- a/crates/wizard-gui/wizard-ui/src/onboarding/SetupDialog.css
+++ b/crates/wizard-gui/wizard-ui/src/onboarding/SetupDialog.css
@@ -1,67 +1,6 @@
-.setup-dialog { font-size: 14px; line-height: 24px; transition-property: max-width, opacity, translate, scale; transition-duration: 180ms; }
-.setup-dialog-compact { padding: 24px; }
+.setup-dialog { transition: max-width var(--ui-duration) var(--ui-ease); }
.setup-dialog :where(h1, h2):focus { outline: none; }
-.setup-dialog h2 { padding-right: 32px; }
-.onboarding-stage { animation: setup-enter 180ms ease-out; }
-.onboarding-footer { margin-top: 24px; }
-.onboarding-agent-list > * { margin-block: 0; }
-.onboarding-agent-row { border: 1px solid #e4e4e7; border-radius: 10px; padding: 12px 14px; transition: background 150ms, border-color 150ms; }
-.onboarding-agent-row:hover { background: #fafafa; }
-.onboarding-agent-row[data-selected="true"] { border-color: #a1a1aa; background: #f4f4f5; }
-.onboarding-agent-avatar { display: grid; place-items: center; width: 40px; height: 40px; }
-.onboarding-configure > fieldset { margin-top: 20px; }
-
-/* The install view uses the same neutral paper and graphite as the overview. */
-.onboarding-install-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: start; gap: 12px; margin-top: 24px; }
+.onboarding-install-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: stretch; gap: var(--ui-space-4); margin-top: var(--ui-space-6); }
.onboarding-install-grid[data-focused="true"] { grid-template-columns: minmax(0, 1fr); }
-.onboarding-install-grid[data-confirming="true"] { margin-top: 0; }
-.onboarding-install-confirmation { animation: setup-enter 180ms ease-out; }
-.setup-dialog-compact .onboarding-install-grid:not([data-confirming="true"]) { margin-top: 16px; }
-.setup-dialog-compact .onboarding-install-main { --install-padding-inline: 18px; padding-block: 16px; }
-.setup-dialog-compact .onboarding-install-copy { min-height: 128px; gap: 16px; }
-.onboarding-install-card { --install-ink: var(--brand-claude); position: relative; isolation: isolate; overflow: hidden; border: 1px solid #e4e4e7; border-radius: 14px; background: #f5f5f5; }
-.onboarding-install-card[data-app="chatgpt"] { --install-ink: var(--brand-openai); }
-.onboarding-install-card[data-app] p { color: #71717a; }
-.onboarding-install-main { --install-padding-inline: 22px; position: relative; padding: 20px var(--install-padding-inline); }
-.onboarding-install-copy { position: relative; z-index: 1; display: flex; min-height: 156px; flex-direction: column; align-items: flex-start; justify-content: space-between; gap: 18px; }
-.onboarding-install-header { position: relative; display: flex; align-items: center; width: 100%; min-height: 56px; }
-.onboarding-install-details { max-width: calc(100% - 90px); }
-.onboarding-install-actions { min-height: 36px; }
-.onboarding-install-actions > button { white-space: nowrap; background: #fafafa; }
-.onboarding-install-note { position: relative; padding: 0 22px 20px; overflow-wrap: anywhere; }
-.onboarding-install-logo { position: absolute; right: var(--install-padding-inline); top: 0; bottom: 0; display: flex; align-items: center; pointer-events: none; }
-.onboarding-install-header > .onboarding-install-logo { right: 0; }
-.onboarding-install-mark { display: grid; place-items: center; width: 76px; height: 84px; rotate: -6deg; transition: rotate 220ms ease, translate 220ms ease; }
-.onboarding-install-logo svg { width: 48px; height: 48px; color: #71717a; transition: color 220ms ease; }
-.onboarding-install-card[data-app="chatgpt"] .onboarding-install-mark { rotate: 6deg; }
-@media (hover: hover) {
- .onboarding-install-card[data-app]:hover .onboarding-install-mark { rotate: 0deg; translate: 0 -3px; }
- .onboarding-install-card[data-active="false"]:hover .onboarding-install-logo svg { color: var(--install-ink); }
-}
-.onboarding-install-card[data-active="false"]:has(:focus-visible) .onboarding-install-logo svg { color: var(--install-ink); }
-.onboarding-download-fill,
-.onboarding-install-color { position: absolute; inset: 0; pointer-events: none; clip-path: inset(0 calc(100% - var(--install-progress, 0%)) 0 0); transition: clip-path 800ms linear; }
-.onboarding-download-fill { background: #dedee3; }
-.onboarding-install-header > .onboarding-install-color { inset: 0 calc(-1 * var(--install-padding-inline)); }
-.onboarding-install-card[data-active="true"] .onboarding-install-mark { rotate: 0deg; translate: none; }
-
-:root[data-theme="dark"] .onboarding-agent-row { border-color: #3f3f46; }
-:root[data-theme="dark"] .onboarding-agent-row:hover { background: #27272a; }
-:root[data-theme="dark"] .onboarding-agent-row[data-selected="true"] { background: #27272a; border-color: #71717a; }
-:root[data-theme="dark"] .onboarding-install-card { background: #242427; border-color: #3f3f46; }
-:root[data-theme="dark"] .onboarding-install-card[data-app] p { color: #a1a1aa; }
-:root[data-theme="dark"] .onboarding-install-actions > button { background: #ffffff08; }
-:root[data-theme="dark"] .onboarding-install-logo svg { color: #a1a1aa; }
-:root[data-theme="dark"] .onboarding-download-fill { background: #3f3f46; }
-.onboarding-install-card .onboarding-install-color .onboarding-install-logo svg { color: var(--install-ink); }
-@keyframes setup-enter { from { opacity: 0; translate: 0 4px; } to { opacity: 1; translate: 0; } }
-@media (max-width: 639px) {
- .setup-dialog { padding: 24px; }
- .onboarding-install-grid { grid-template-columns: minmax(0, 1fr); }
- .onboarding-install-details { max-width: calc(100% - 84px); }
- .onboarding-install-mark { width: 68px; height: 76px; }
- .onboarding-install-logo svg { width: 44px; height: 44px; }
-}
-@media (prefers-reduced-motion: reduce) {
- .onboarding-download-fill, .onboarding-install-color, .onboarding-install-mark { transition: none; }
-}
+.onboarding-install-entry { display: flex; min-width: 0; flex-direction: column; }
+@media (max-width: 639px) { .onboarding-install-grid { grid-template-columns: minmax(0, 1fr); } }
diff --git a/crates/wizard-gui/wizard-ui/src/onboarding/SetupDialog.tsx b/crates/wizard-gui/wizard-ui/src/onboarding/SetupDialog.tsx
index e6f83a5..ee38df5 100644
--- a/crates/wizard-gui/wizard-ui/src/onboarding/SetupDialog.tsx
+++ b/crates/wizard-gui/wizard-ui/src/onboarding/SetupDialog.tsx
@@ -1,25 +1,50 @@
import { invoke } from "@tauri-apps/api/core";
import { useCallback, useEffect, useRef, useState } from "react";
-import { XMarkIcon } from "@heroicons/react/20/solid";
import { Button } from "../components/catalyst/button";
-import { Dialog, DialogTitle } from "../components/catalyst/dialog";
+import { Dialog } from "../components/catalyst/dialog";
+import { DialogHeader } from "../components/ui/DialogHeader";
+import { ActionBar, ViewTransition } from "../components/ui/Layout";
+import { Identity } from "../components/ui/Identity";
import { Field, Label } from "../components/catalyst/fieldset";
-import { Heading } from "../components/catalyst/heading";
import { Select } from "../components/catalyst/select";
import { Text } from "../components/catalyst/text";
import { ErrorText } from "../components/ErrorText";
import type { HubAccountControl } from "../settings/HubAccount";
import { hubDisplayName } from "../settings/hub_account";
import { useHubTokens } from "../settings/hub_tokens";
-import { hubModes, routingModes, RoutingFieldset, type Hub } from "../agents/AgentConfiguration";
-import { type AgentChange, type PreparedAgentChange, type TokenChoice, type useAgentState, prepareAgentChange } from "../agents/agents_state";
+import {
+ hubModes,
+ routingModes,
+ RoutingFieldset,
+ type Hub,
+} from "../agents/AgentConfiguration";
+import {
+ type AgentChange,
+ type PreparedAgentChange,
+ type TokenChoice,
+ type useAgentState,
+ prepareAgentChange,
+} from "../agents/agents_state";
import { PreparedPlanDialog } from "../agents/PreparedPlanDialog";
-import { agentPaths } from "../agents/navigation";
-import { AgentSelection, type InstallView } from "./AgentSelection";
-import { AgentIcon, choices, isFound, type AgentChoice, type ChoiceId } from "./agents";
+import { AgentSelection } from "./AgentSelection";
+import {
+ AgentIcon,
+ choices,
+ isFound,
+ type AgentChoice,
+ type ChoiceId,
+} from "./agents";
import "./SetupDialog.css";
-function Configure({ choice, agents, hub, account, onBusy, onComplete, onBack }: {
+function Configure({
+ choice,
+ agents,
+ hub,
+ account,
+ onBusy,
+ onComplete,
+ onBack,
+}: {
choice: AgentChoice;
agents: ReturnType;
hub: Hub;
@@ -32,52 +57,136 @@ function Configure({ choice, agents, hub, account, onBusy, onComplete, onBack }:
const [preparing, setPreparing] = useState(false);
const [error, setError] = useState();
const inFlight = useRef(false);
- const agent = agents.status === "ready" ? agents.data[choice.agent] : undefined;
+ const agent =
+ agents.status === "ready" ? agents.data[choice.agent] : undefined;
const found = agents.status === "ready" && isFound(choice, agents.data);
const busy = preparing || Boolean(prepared);
- useEffect(() => { onBusy(busy); return () => onBusy(false); }, [busy, onBusy]);
+ useEffect(() => {
+ onBusy(busy);
+ return () => onBusy(false);
+ }, [busy, onBusy]);
async function prepare(change: AgentChange, token: TokenChoice | null) {
if (inFlight.current) return;
inFlight.current = true;
setPreparing(true);
setError(undefined);
- try { setPrepared(await prepareAgentChange(change, token)); }
- catch (cause) { setError(`Не удалось подготовить изменения: ${typeof cause === "string" ? cause : "попробуйте снова"}`); }
- finally { inFlight.current = false; setPreparing(false); }
+ try {
+ setPrepared(await prepareAgentChange(change, token));
+ } catch (cause) {
+ setError(
+ `Не удалось подготовить изменения: ${typeof cause === "string" ? cause : "попробуйте снова"}`,
+ );
+ } finally {
+ inFlight.current = false;
+ setPreparing(false);
+ }
}
- return
-
- {account.account?.profile && account.account.profile.hubs.length > 1 &&
- Хаб
- account.select(event.target.value)}>
- {account.account.profile.hubs.map((item) => {item.is_personal ? "Личный хаб" : hubDisplayName(item)} )}
-
- }
- {found && agent?.status === "found" ?
Назад} actionsClassName="justify-between"
- toChange={(mode) => {
- switch (choice.agent) {
- case "codex": return { CodexSetRouting: mode };
- case "claude": return { ClaudeSetRouting: mode };
- case "claude_desktop": return { ClaudeDesktopSetRouting: mode };
- case "opencode": return { SetOpenCodeHub: mode === "hub" ? "hub" : "disabled" };
- case "pi": return { SetPiHub: mode === "hub" ? "hub" : "disabled" };
- }
- }} onPrepare={(change, token) => void prepare(change, token)} /> :
- {agents.status === "loading" ? "Обновляем список приложений…" : "Агент не обнаружен. Дождитесь обновления списка или выберите другого агента."}
- Назад
-
}
- {prepared && setPrepared(undefined)} onApplied={() => onComplete(prepared.restarts_desktop)} />}
- ;
+ return (
+
+
}
+ title={choice.name}
+ focusable
+ />
+ {account.account?.profile && account.account.profile.hubs.length > 1 && (
+
+ Хаб
+ account.select(event.target.value)}
+ >
+ {account.account.profile.hubs.map((item) => (
+
+ {item.is_personal ? "Личный хаб" : hubDisplayName(item)}
+
+ ))}
+
+
+ )}
+ {found && agent?.status === "found" ? (
+
+ Назад
+
+ }
+ actionsClassName="justify-between"
+ toChange={(mode) => {
+ switch (choice.agent) {
+ case "codex":
+ return { CodexSetRouting: mode };
+ case "claude":
+ return { ClaudeSetRouting: mode };
+ case "claude_desktop":
+ return { ClaudeDesktopSetRouting: mode };
+ case "opencode":
+ return { SetOpenCodeHub: mode === "hub" ? "hub" : "disabled" };
+ case "pi":
+ return { SetPiHub: mode === "hub" ? "hub" : "disabled" };
+ }
+ }}
+ onPrepare={(change, token) => void prepare(change, token)}
+ />
+ ) : (
+
+
+ {agents.status === "loading"
+ ? "Обновляем список приложений…"
+ : "Агент не обнаружен. Дождитесь обновления списка или выберите другого агента."}
+
+
+ Назад
+
+
+ )}
+ {prepared && (
+ setPrepared(undefined)}
+ onApplied={() => onComplete(prepared.restarts_desktop)}
+ />
+ )}
+
+ );
}
-function Completed({ choice, restarted, onFinish, onBusy, onBack }: { choice: AgentChoice; restarted: boolean; onFinish: () => void; onBusy: (busy: boolean) => void; onBack: () => void }) {
+function Completed({
+ choice,
+ restarted,
+ onFinish,
+ onBusy,
+ onBack,
+}: {
+ choice: AgentChoice;
+ restarted: boolean;
+ onFinish: () => void;
+ onBusy: (busy: boolean) => void;
+ onBack: () => void;
+}) {
const [launching, setLaunching] = useState(false);
const [error, setError] = useState();
const inFlight = useRef(false);
@@ -91,54 +200,105 @@ function Completed({ choice, restarted, onFinish, onBusy, onBack }: { choice: Ag
await invoke("launch_agent", { agent: choice.id });
onFinish();
} catch (cause) {
- setError(typeof cause === "string" ? cause : `Не удалось запустить ${choice.name}. Попробуйте ещё раз.`);
+ setError(
+ typeof cause === "string"
+ ? cause
+ : `Не удалось запустить ${choice.name}. Попробуйте ещё раз.`,
+ );
} finally {
inFlight.current = false;
setLaunching(false);
onBusy(false);
}
}
- return
-
-
-
{choice.name} настроен
-
-
{restarted ? "Приложение открыто с новыми настройками." : choice.desktop ? "Можно открывать приложение и начинать работу." : "Агент откроется в терминале."}
-
-
Выбрать другого агента
-
restarted ? onFinish() : void launch()}>{restarted ? "Готово" : launching ? "Запускаем…" : "Запустить агента"}
+ return (
+
+
}
+ title={`${choice.name} настроен`}
+ focusable
+ />
+
+ {restarted
+ ? "Приложение открыто с новыми настройками."
+ : choice.desktop
+ ? "Можно открывать приложение и начинать работу."
+ : "Агент откроется в терминале."}
+
+
+ Выбрать другого агента
+
+ }
+ >
+ (restarted ? onFinish() : void launch())}
+ >
+ {restarted ? "Готово" : launching ? "Запускаем…" : "Запустить агента"}
+
+
+ {error && (
+
+ {error}
+
+ )}
- {error &&
{error}
}
-
;
+ );
}
-type Stage = "entry" | "install" | "select" | "configure" | "complete";
+type Stage = "entry" | "select" | "configure" | "complete";
-export function SetupDialog({ initialStage, account, agents, onClose, onFinished }: {
- initialStage: "install" | "select";
+export function SetupDialog({
+ account,
+ agents,
+ onClose,
+}: {
account: HubAccountControl;
agents: ReturnType
;
onClose: () => void;
- onFinished: () => void;
}) {
- const installed = agents.status === "ready" ? choices.filter((choice) => isFound(choice, agents.data)) : [];
+ const installed =
+ agents.status === "ready"
+ ? choices.filter((choice) => isFound(choice, agents.data))
+ : [];
const [selected, setSelected] = useState();
- const [stage, setStage] = useState(initialStage === "select" ? "entry" : initialStage);
+ const [stage, setStage] = useState("entry");
const [restarted, setRestarted] = useState(false);
// Resolve the entry screen from live detection, not the first (possibly partial) snapshot.
- const viewStage = stage === "entry" ? installed.length === 1 ? "configure" : "select" : stage;
- const [installView, setInstallView] = useState("choose");
+ const viewStage =
+ stage === "entry"
+ ? installed.length === 1
+ ? "configure"
+ : "select"
+ : stage;
const [busy, setBusy] = useState(false);
const content = useRef(null);
- const hub: Hub = { ...useHubTokens(account.account?.active_hub_id), signedIn: account.signedIn };
- const selectedChoice = stage === "entry" && installed.length === 1 ? installed[0] : choices.find((choice) => choice.id === selected);
+ const hub: Hub = {
+ ...useHubTokens(account.account?.active_hub_id),
+ signedIn: account.signedIn,
+ };
+ const selectedChoice =
+ stage === "entry" && installed.length === 1
+ ? installed[0]
+ : choices.find((choice) => choice.id === selected);
const setAgentBusy = account.setAgentBusy;
- const changeBusy = useCallback((value: boolean) => { setBusy(value); setAgentBusy(value); }, [setAgentBusy]);
+ const changeBusy = useCallback(
+ (value: boolean) => {
+ setBusy(value);
+ setAgentBusy(value);
+ },
+ [setAgentBusy],
+ );
const choose = useCallback((id: ChoiceId) => setSelected(id), []);
useEffect(() => {
- content.current?.querySelector("h2")?.focus({ preventScroll: true });
- }, [viewStage, installView]);
+ content.current
+ ?.querySelector("h2")
+ ?.focus({ preventScroll: true });
+ }, [viewStage]);
useEffect(() => () => setAgentBusy(false), [setAgentBusy]);
function configure(id: ChoiceId) {
@@ -147,19 +307,61 @@ export function SetupDialog({ initialStage, account, agents, onClose, onFinished
setStage("configure");
}
function finish() {
- onFinished();
onClose();
- if (selectedChoice) window.location.hash = agentPaths[selectedChoice.agent];
}
- const compact = viewStage === "install" && installView !== "choose";
- return { if (!busy) onClose(); }} size={compact ? "md" : "2xl"} className={`setup-dialog relative${compact ? " setup-dialog-compact" : ""}`}>
- {viewStage === "install" ? installView === "confirm" ? "Подтверждение установки" : "Установка агентов" : "Настройка агентов"}
-
-
- {(viewStage === "install" || viewStage === "select") &&
}
- {viewStage === "configure" && selectedChoice &&
{ setSelected(selectedChoice.id); setRestarted(restarted && Boolean(selectedChoice.desktop)); changeBusy(false); setStage("complete"); }} onBack={() => setStage("select")} />}
- {viewStage === "complete" && selectedChoice && setStage("select")} />}
-
- ;
+ return (
+ {
+ if (!busy) onClose();
+ }}
+ size="2xl"
+ className="setup-dialog relative"
+ >
+
+
+
+ {viewStage === "select" && (
+
+ )}
+ {viewStage === "configure" && selectedChoice && (
+ {
+ setSelected(selectedChoice.id);
+ setRestarted(restarted && Boolean(selectedChoice.desktop));
+ changeBusy(false);
+ setStage("complete");
+ }}
+ onBack={() => setStage("select")}
+ />
+ )}
+ {viewStage === "complete" && selectedChoice && (
+ setStage("select")}
+ />
+ )}
+
+
+
+ );
}
diff --git a/crates/wizard-gui/wizard-ui/src/onboarding/installations_state.ts b/crates/wizard-gui/wizard-ui/src/onboarding/installations_state.ts
new file mode 100644
index 0000000..674b3c9
--- /dev/null
+++ b/crates/wizard-gui/wizard-ui/src/onboarding/installations_state.ts
@@ -0,0 +1,27 @@
+import { createContext, useContext } from "react";
+import type { DesktopApp, Snapshot, useDesktopInstall } from "../agents/desktop_install_state";
+
+type Observation = ReturnType;
+export type Installations = {
+ observations: Record;
+ jobs: DesktopApp[];
+ requesting: Partial>;
+ errors: Partial>;
+ open: (desktop?: DesktopApp) => void;
+ download: (desktop: DesktopApp) => Promise;
+ cancel: (desktop: DesktopApp) => Promise;
+ install: (desktop: DesktopApp, confirmed: boolean, close: boolean) => Promise;
+};
+
+export const InstallationsContext = createContext(null);
+
+export function useInstallations() {
+ const value = useContext(InstallationsContext);
+ if (!value) throw new Error("InstallationsProvider is missing");
+ return value;
+}
+
+export function downloadProgress(state: Snapshot | undefined) {
+ return state?.status === "downloading" && state.total > 0
+ ? Math.min(100, Math.floor(state.received / state.total * 100)) : undefined;
+}
diff --git a/crates/wizard-gui/wizard-ui/src/overview/Overview.css b/crates/wizard-gui/wizard-ui/src/overview/Overview.css
index 4251040..6efe03d 100644
--- a/crates/wizard-gui/wizard-ui/src/overview/Overview.css
+++ b/crates/wizard-gui/wizard-ui/src/overview/Overview.css
@@ -1,20 +1,11 @@
-/* One text size; pen-written numerals are decorative artwork. Controls stay Catalyst. */
-.overview,
-.overview :where(h1, h2, h3, p, span, button, a),
-.setup-dialog :where(h1, h2, h3, p, span, button, a, label, legend, select),
-body:has(.overview) #headlessui-portal-root :where(h1, h2, h3, p, span, button, a, label, legend, select, li) {
- font-size: 14px !important;
- line-height: 24px !important;
-}
.overview {
flex: 1;
overflow-y: auto;
overscroll-behavior: contain;
- padding: 36px 32px;
+ padding: var(--ui-page-gutter);
container: overview / inline-size;
}
-.overview[data-onboarding="true"] { padding: 32px clamp(24px, 5vw, 56px); }
-.overview-content { width: 100%; max-width: 1040px; margin-inline: auto; }
+.overview-content { width: 100%; max-width: var(--ui-content-width); margin-inline: auto; }
.overview-hero {
--hero-gutter: 28px;
position: relative;
@@ -31,70 +22,84 @@ body:has(.overview) #headlessui-portal-root :where(h1, h2, h3, p, span, button,
.overview-hero-copy { flex: 1; min-width: 0; max-width: 380px; margin: 24px 12px 24px calc(var(--hero-gutter) - 5px); }
.overview-hero-copy h1 { color: #18181b; }
.overview-hero-copy p { color: #3f3f46; }
-.overview-hero-text {
- padding: 2px 5px;
- border-radius: 2px;
- background: #fffdf9f2;
- -webkit-box-decoration-break: clone;
- box-decoration-break: clone;
-}
-/* The two ink lattices form interference bands in the original high-resolution artwork. */
-.overview-backdrop {
- position: absolute;
- inset: 0;
- z-index: -1;
- overflow: hidden;
- isolation: isolate;
- background: #e4b899;
- pointer-events: none;
-}
+.overview-hero-text { padding: 2px 5px; border-radius: 2px; background: #fffdf9f2; -webkit-box-decoration-break: clone; box-decoration-break: clone; }
+.overview-backdrop { position: absolute; inset: 0; z-index: -1; overflow: hidden; isolation: isolate; background: #e4b899; pointer-events: none; }
.overview-backdrop > img { position: absolute; inset: 0; display: block; width: 100%; height: 100%; object-fit: cover; }
-.overview-skip { flex-shrink: 0; margin-right: -8px; color: #71717a !important; font-weight: 400 !important; white-space: nowrap; }
-.overview-video {
- position: relative;
- display: block;
- flex-shrink: 0;
- width: calc(100% - var(--hero-gutter) * 2);
- max-width: 330px;
- margin: 8px 8px 8px var(--hero-gutter);
- border: 0;
- border-radius: 12px;
- background: transparent;
- cursor: pointer;
- isolation: isolate;
-}
+.overview-video { position: relative; display: block; flex-shrink: 0; width: calc(100% - var(--hero-gutter) * 2); max-width: 330px; margin: 8px 8px 8px var(--hero-gutter); border: 0; border-radius: 12px; background: transparent; cursor: pointer; isolation: isolate; }
.overview-video-visual { position: relative; display: block; width: 100%; aspect-ratio: 1280 / 832; }
-.overview-video-media {
- position: absolute;
- inset: 0;
- display: block;
- overflow: hidden;
- border-radius: 8px;
-}
+.overview-video-media { position: absolute; inset: 0; display: block; overflow: hidden; border-radius: 8px; }
.overview-video-media > img { display: block; width: 100%; height: 100%; object-fit: cover; }
-.overview-video-play {
- position: absolute;
- top: 50%; left: 50%;
- display: grid;
- place-items: center;
- width: 40px; height: 40px;
- border-radius: 50%;
- background: #fff;
- color: #27272a;
- box-shadow: 0 2px 12px #0002;
- transform: translate(-50%, -50%);
- transition: scale 180ms ease;
-}
+.overview-video-play { position: absolute; top: 50%; left: 50%; display: grid; place-items: center; width: 40px; height: 40px; border-radius: 50%; background: #fff; color: #27272a; box-shadow: 0 2px 12px #0002; transform: translate(-50%, -50%); transition: scale 180ms ease; }
.overview-video-play svg { width: 20px; height: 20px; margin-left: 2px; }
.overview-video:is(:hover, :focus-visible) .overview-video-play { scale: 1.06; }
-.overview-video:focus-visible { outline: 2px solid #6366f1; outline-offset: 4px; }
+.overview-video:focus-visible { outline: 2px solid var(--ui-focus); outline-offset: 4px; }
+.overview-dashboard { display: grid; gap: var(--ui-space-6); margin-top: var(--ui-space-6); }
+.overview-account {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--ui-space-4);
+ padding: var(--ui-space-5) var(--ui-panel-gutter);
+ border: 1px solid var(--ui-border);
+ border-radius: var(--ui-radius-panel);
+ background: var(--ui-surface-muted);
+}
+.overview-account > div { flex: 1 1 220px; }
+.overview-agents-header { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--ui-space-4); margin-bottom: var(--ui-space-4); }
+.overview-agent-list { margin: 0; padding: 0; list-style: none; }
+.overview-agent-row { display: grid; grid-template-columns: minmax(200px, 1fr) minmax(0, 1.45fr); align-items: center; gap: var(--ui-space-5); padding: var(--ui-space-4) 0; }
+.overview-agent-row + .overview-agent-row { border-top: 1px solid var(--ui-border); }
+.overview-agent-identity { display: flex; align-items: center; gap: var(--ui-space-3); min-width: 0; }
+.overview-agent-name { color: var(--ui-ink); font-size: 14px; line-height: 24px; font-weight: 600; overflow-wrap: anywhere; }
+.overview-agent-name:hover { text-decoration: underline; text-underline-offset: 3px; }
+.overview-agent-name:focus-visible { outline: 2px solid var(--ui-focus); outline-offset: 4px; border-radius: 2px; }
+.overview-agent-actions { display: flex; align-items: center; flex-wrap: wrap; gap: var(--ui-space-4); min-width: 0; }
+.overview-agent-actions .ui-version-row { grid-template-columns: minmax(0, 1fr) auto; }
+.overview-agent-actions .ui-version-actions { justify-content: flex-end; }
+.overview-agent-actions > button { margin-left: auto; }
+.overview-agent-version { min-width: 120px; font-size: 14px; line-height: 24px; font-variant-numeric: tabular-nums; }
+@container overview (max-width: 640px) {
+ .overview-agent-row { grid-template-columns: minmax(0, 1fr); gap: var(--ui-space-3); padding-block: var(--ui-space-5); }
+ .overview-agent-actions { padding-left: 36px; }
+ .overview-agent-version:empty { display: none; }
+}
.overview-actions { margin-top: 16px; }
.overview-actions-header { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 4px 16px; min-height: 36px; margin-bottom: 16px; }
.overview-actions-header > h2 { flex-shrink: 0; }
-.overview-cards { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; }
+.overview-cards { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: var(--ui-space-4); }
+.overview-cards[data-dashboard="true"] { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--ui-space-5); }
+.overview-cards[data-dashboard="true"] .overview-card { display: flex; transform-origin: top left; }
+.overview-cards[data-dashboard="true"] .overview-art { height: 126px; min-height: 126px; }
+.overview-cards[data-dashboard="true"] .overview-sketch { top: 6px; right: 24px; width: 166px; height: 120px; }
+.overview-cards[data-dashboard="true"] .overview-card-copy { min-height: 158px; }
+.overview-cards[data-dashboard="true"] .overview-card-actions { justify-content: flex-end; min-height: 40px; }
+.overview-cards [data-management-target] { scroll-margin-block: 24px; }
+.overview-hub-identity { display: block; overflow-wrap: anywhere; }
+.overview-balance { display: flex; flex-direction: column; gap: 5px; margin-top: 18px; }
+.overview-balance-label { font-size: 12px; line-height: 20px; }
+.overview-balance-value { color: var(--ui-ink); font-size: 16px; line-height: 28px; font-weight: 500; font-variant-numeric: tabular-nums; }
+.overview-balance-value[data-amount="true"] { font-size: 32px; line-height: 40px; letter-spacing: -.04em; }
+.overview-connected-agents { display: flex; flex-wrap: wrap; align-items: center; gap: 12px 16px; margin: 16px 0; min-height: 24px; }
+.overview-connected-agent { display: inline-flex; align-items: center; gap: 8px; color: var(--ui-ink); font-size: 13px; line-height: 24px; white-space: nowrap; }
+.overview-connected-agent svg { width: 22px; height: 22px; }
+.overview-agents-more { font-size: 13px; line-height: 24px; white-space: nowrap; }
+.overview-manage-hint { display: block; font-size: 12px; line-height: 20px; }
+.overview-ready-notice { display: flex; align-items: center; gap: 16px; margin: 24px 0; padding: 20px 24px; border: 1px solid var(--ui-border); border-radius: var(--ui-radius-panel); background: var(--ui-surface-muted); }
+.overview-ready-notice > div { flex: 1; min-width: 0; }
+.overview-ready-notice p { margin-top: 4px; }
+.overview-ready-notice > button { flex-shrink: 0; }
+.overview-agent-manager { margin-top: 24px; container: overview / inline-size; }
+.overview-merge-ghost { position: fixed !important; z-index: 60; margin: 0; pointer-events: none; transform-origin: top left; animation: none !important; box-shadow: 0 16px 32px #0002; }
+@container overview (max-width: 640px) {
+ .overview-cards[data-dashboard="true"] { grid-template-columns: minmax(0, 1fr); }
+ .overview-ready-notice { flex-wrap: wrap; padding: 20px; align-items: flex-start; }
+ .overview-ready-notice > div { flex-basis: 100%; }
+ .overview-ready-notice > button { margin-left: auto; }
+}
.overview-card {
- --card-bg: #f5f5f5;
- --card-border: #e4e4e7;
+ --card-bg: var(--ui-surface-muted);
+ --card-border: var(--ui-border);
--sketch-ink: #71717a;
--sketch-paper: #fafafa;
--grid-ink: #71717a12;
@@ -106,7 +111,7 @@ body:has(.overview) #headlessui-portal-root :where(h1, h2, h3, p, span, button,
flex-direction: column;
overflow: hidden;
border: 1px solid var(--card-border);
- border-radius: 14px;
+ border-radius: var(--ui-radius-panel);
background: var(--card-bg);
transition: background 320ms ease, border-color 200ms ease;
animation: overview-enter 300ms ease-out both;
@@ -115,11 +120,10 @@ body:has(.overview) #headlessui-portal-root :where(h1, h2, h3, p, span, button,
.overview-card[data-kind="configure"] { animation-delay: 90ms; }
.overview-card[data-disabled="true"] { --card-bg: #f8f8f8; --card-border: #ebebed; --sketch-ink: #a1a1aa; --grid-ink: #71717a0c; }
.overview-card[data-disabled="true"] .overview-step-number { opacity: .5; }
-.overview-card[data-disabled="true"] h3 { color: #71717a; }
-.overview-card[data-disabled="true"] p { color: #7a7a82; }
-.overview-card-body { position: relative; display: flex; flex: 1; flex-direction: column; padding: 10px 20px 20px; }
-.overview-card h3 { overflow-wrap: anywhere; }
-.overview-card-copy { min-height: 104px; animation: overview-enter 220ms ease-out; }
+.overview-card[data-disabled="true"] :is(h2, h3, p) { color: var(--ui-ink-subtle); }
+.overview-card-body { position: relative; display: flex; flex: 1; flex-direction: column; padding: 12px var(--ui-panel-gutter) var(--ui-panel-gutter); }
+.overview-card :is(h2, h3) { overflow-wrap: anywhere; }
+.overview-card-copy { min-height: 104px; padding-bottom: var(--ui-space-4); overflow-wrap: anywhere; animation: overview-enter 220ms ease-out; }
.overview-card-copy p { color: #71717a; }
.overview-card-actions { display: flex; flex-wrap: wrap; align-items: center; align-content: flex-end; gap: 10px 14px; min-height: 48px; margin-top: auto; }
.overview-card-actions > button { white-space: nowrap; }
@@ -195,11 +199,9 @@ body:has(.overview) #headlessui-portal-root :where(h1, h2, h3, p, span, button,
.overview-card-copy { min-height: 84px; }
}
@container overview (max-width: 470px) {
- .overview-hero { min-height: 220px; }
.overview-video { max-width: 290px; }
.overview-actions { margin-top: 20px; }
.overview-actions-header { align-items: flex-start; flex-direction: column; gap: 0; }
- .overview-skip { margin-left: -8px; margin-right: 0; }
.overview-card { display: flex; }
.overview-art { height: 132px; min-height: 0; }
.overview-step-number { top: 20px; left: 17px; width: 52px; height: 64px; }
@@ -209,9 +211,7 @@ body:has(.overview) #headlessui-portal-root :where(h1, h2, h3, p, span, button,
}
@media (max-width: 639px) {
.overview { padding: 20px; }
- .overview[data-onboarding="true"] { padding: 36px 20px 24px; }
}
-:root[data-theme="dark"] .overview-skip { color: #a1a1aa !important; }
:root[data-theme="dark"] .overview-card {
--card-bg: #242427;
--card-border: #353539;
@@ -223,7 +223,6 @@ body:has(.overview) #headlessui-portal-root :where(h1, h2, h3, p, span, button,
:root[data-theme="dark"] .overview-card[data-kind="install"] { --hover-ink: #a1a1aa; }
:root[data-theme="dark"] .overview-card[data-disabled="true"] { --card-bg: #202023; --card-border: #2e2e32; --sketch-ink: #66666f; --sketch-paper: #242427; --grid-ink: #a1a1aa09; }
:root[data-theme="dark"] .overview-card-copy p { color: #a1a1aa; }
-:root[data-theme="dark"] .overview-card[data-disabled="true"] :is(h3,p) { color: #85858f; }
:root[data-theme="dark"] .overview-card-actions > a { color: #a1a1aa; }
/* Only the drawings gain color; paper, grid and card borders stay neutral. */
.overview-card[data-disabled="false"]:has(:focus-visible) {
@@ -248,7 +247,10 @@ body:has(.overview) #headlessui-portal-root :where(h1, h2, h3, p, span, button,
}
@media (prefers-reduced-motion: reduce) {
.overview-card-strike { display: none; }
- .overview *, .setup-dialog *, body:has(.overview) #headlessui-portal-root * { animation: none !important; transition: none !important; }
+ .overview * { animation: none !important; transition: none !important; }
.overview-sketch, .overview-sketch-app, .overview-sketch-identity, .overview-sketch-slider, .overview-sketch-download-arrow { translate: none !important; scale: none !important; rotate: none !important; }
.overview-video:is(:hover, :focus-visible) .overview-video-play { scale: 1; }
}
+
+:root[data-motion="reduce"] :is(.overview-sketch, .overview-sketch-app, .overview-sketch-identity, .overview-sketch-slider, .overview-sketch-download-arrow) { translate: none; scale: none; rotate: none; }
+:root[data-motion="reduce"] .overview-card-strike { display: none; }
diff --git a/crates/wizard-gui/wizard-ui/src/overview/Overview.tsx b/crates/wizard-gui/wizard-ui/src/overview/Overview.tsx
index 24b96aa..7b83e03 100644
--- a/crates/wizard-gui/wizard-ui/src/overview/Overview.tsx
+++ b/crates/wizard-gui/wizard-ui/src/overview/Overview.tsx
@@ -1,114 +1,340 @@
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { ArrowUpRightIcon } from "@heroicons/react/20/solid";
-import type { useAgentState } from "../agents/agents_state";
+import { hasAgentDetectionError, type useAgentState } from "../agents/agents_state";
import { Button } from "../components/catalyst/button";
import { Heading } from "../components/catalyst/heading";
import { Text, TextLink } from "../components/catalyst/text";
import { ErrorText } from "../components/ErrorText";
+import { StateNotice } from "../components/ui/StateNotice";
+import { Dialog } from "../components/catalyst/dialog";
+import { DialogHeader } from "../components/ui/DialogHeader";
import type { HubAccountControl } from "../settings/HubAccount";
import { hubDisplayName } from "../settings/hub_account";
-import { choices, isFound } from "../onboarding/agents";
+import { formatHubBalance, needsHubTopUp, useHubSummary } from "../settings/hub_summary";
+import { AgentIcon, choices, isFound } from "../onboarding/agents";
+import { useInstallations } from "../onboarding/installations_state";
import { SetupDialog } from "../onboarding/SetupDialog";
import { OverviewArtwork } from "./OverviewArtwork";
-import { OverviewCard } from "./OverviewCard";
-import { OverviewVideo } from "./OverviewVideo";
import { OverviewBackdrop } from "./OverviewBackdrop";
+import { OverviewCard, OverviewCardContent } from "./OverviewCard";
+import { OverviewVideo } from "./OverviewVideo";
+import { OverviewAgents } from "./OverviewAgents";
+import { useOverviewTransition } from "./useOverviewTransition";
import "./Overview.css";
-export function Overview({ account, agents, onboarding, onFinishOnboarding }: {
+export function Overview({
+ account,
+ agents,
+}: {
account: HubAccountControl;
agents: ReturnType;
- onboarding: boolean;
- onFinishOnboarding: () => void;
}) {
- const [setup, setSetup] = useState<"install" | "select">();
+ const [setup, setSetup] = useState<"select">();
+ const [management, setManagement] = useState(false);
+ const overviewRoot = useRef(null);
const [registrationOpened, setRegistrationOpened] = useState(false);
const connected = account.signedIn;
const pending = account.account?.pending;
const loadingAccount = !account.account;
- const installed = agents.status === "ready" ? choices.filter((choice) => isFound(choice, agents.data)) : [];
+ const installed =
+ agents.status === "ready"
+ ? choices.filter((choice) => isFound(choice, agents.data))
+ : [];
const canConfigure = connected && installed.length > 0;
- const activeHub = account.account?.profile?.hubs.find((hub) => hub.hub_id === account.account?.active_hub_id);
- const hubName = activeHub?.is_personal ? "Личный хаб" : activeHub ? hubDisplayName(activeHub) : "CoreInfra AI Hub";
+ const activeHub = account.account?.profile?.hubs.find(
+ (hub) => hub.hub_id === account.account?.active_hub_id,
+ );
+ const hubName = activeHub?.is_personal
+ ? "Личный хаб"
+ : activeHub
+ ? hubDisplayName(activeHub)
+ : "CoreInfra AI Hub";
const profile = account.account?.profile;
- const accountDisabled = account.submitting || (!connected && (loadingAccount || account.agentBusy));
+ const accountDisabled =
+ account.submitting || (!connected && (loadingAccount || account.agentBusy));
const accountAction = connected ? account.open : account.change;
- const openInstall = () => setSetup("install");
- const openConfigure = () => setSetup("select");
- const detectionError = agents.status === "error" || (agents.status === "ready" && Object.values(agents.data).some((agent) => typeof agent === "object" && agent.status === "error"));
+ const installations = useInstallations();
+ const openInstall = () => { setManagement(false); installations.open(); };
+ const openConfigure = () => { setManagement(false); setSetup("select"); };
+ const detectionError =
+ agents.status === "error" ||
+ (agents.status === "ready" &&
+ choices.some((choice) => hasAgentDetectionError(agents.data[choice.agent])));
+ const configured = agents.status === "ready" && Object.values(agents.data).some(
+ (agent) => typeof agent === "object" && agent.status === "found" && agent.data.routing_mode !== "disabled",
+ );
+ const connectedAgents = agents.status === "ready" ? installed.filter(choice => {
+ const agent = agents.data[choice.agent];
+ return agent.status === "found" && agent.data.routing_mode !== "disabled";
+ }) : [];
+ const listedAgents = connectedAgents.length ? connectedAgents : installed;
+ const { dashboard: showDashboard, merging } = useOverviewTransition(overviewRoot, {
+ ready: !loadingAccount && agents.status !== "loading",
+ connected,
+ requested: connected && (configured || detectionError),
+ suspended: !!setup,
+ });
+ const summary = useHubSummary(account.account?.active_hub_id, connected);
+ const guest = summary.data?.role_in_hub === "guest";
+ const balance = summary.data?.balance_rub;
+ const balanceLabel = summary.error ??
+ (summary.loading ? "Загружаем баланс…" : typeof balance === "number" && Number.isFinite(balance)
+ ? formatHubBalance(balance) : "Баланс недоступен");
- useEffect(() => { if (!connected) setSetup(undefined); }, [connected]);
+ useEffect(() => {
+ if (!connected) { setSetup(undefined); setManagement(false); }
+ }, [connected]);
- return
-
-
-
-
- Начало работы
- {onboarding && Пропустить быструю настройку }
-
-
-
-
-
-
- {connected ? hubName : "Подключите свой аккаунт"}
- {connected ? {profile?.verified_email ?? profile?.username ?? "CoreInfra Hub"}
- : {pending
- ? "Завершите вход в браузере. Wizard подключится автоматически."
- : registrationOpened
- ? "Создайте аккаунт в браузере, затем вернитесь и войдите в хаб."
- : "Войдите в CoreInfra Hub, чтобы подключить своих агентов."} }
-
-
- {connected ?
Открыть хаб
- :
{loadingAccount ? "Проверяем аккаунт…" : account.submitting ? "Открываем браузер…" : pending ? "Продолжить вход" : "Войти"} }
- {!connected && !pending &&
{
- event.preventDefault();
- if (!loadingAccount && !account.submitting) { setRegistrationOpened(true); account.register(); }
- }}>Создать аккаунт }
-
-
-
+ // Wait for the first snapshot before deciding between onboarding and daily use.
+ if (loadingAccount || agents.status === "loading") return (
+
+ Обзор
+
+ {account.error ? "Не удалось проверить аккаунт. Повторяем подключение автоматически." : "Проверяем аккаунт и установленные приложения…"}
+
+
+ );
-
-
-
-
-
Установите агентов
-
Wizard скачает и установит Claude или ChatGPT приложения!
+ return (
+
+
+
+ {showDashboard && configured && needsHubTopUp(summary.data) && (
+
+
+ Агент готов!
+ Чтобы начать использовать – пополните баланс хаба.
-
Установить агента
+
Пополнить
-
+ )}
+
+ {!showDashboard &&
+
+ Начало работы
+
+
}
+
+
+
+
+ {profile?.verified_email ?? profile?.username}
+ {!guest &&
+ Баланс хаба
+ {balanceLabel}
+ }
+ > : connected
+ ? (profile?.verified_email ??
+ profile?.username ??
+ "CoreInfra Hub")
+ : pending
+ ? "Завершите вход в браузере. Wizard подключится автоматически."
+ : registrationOpened
+ ? "Создайте аккаунт в браузере, затем вернитесь и войдите в хаб."
+ : "Войдите в CoreInfra Hub, чтобы подключить своих агентов."
+ }
+ actions={
+ <>
+ {connected ? (
+
+ {showDashboard ? "Перейти в хаб" : "Открыть хаб"}
+
+
+ ) : (
+
+ {loadingAccount
+ ? "Проверяем аккаунт…"
+ : account.submitting
+ ? "Открываем браузер…"
+ : pending
+ ? "Продолжить вход"
+ : "Войти"}
+
+ )}
+ {!connected && !pending && (
+ {
+ event.preventDefault();
+ if (!loadingAccount && !account.submitting) {
+ setRegistrationOpened(true);
+ account.register();
+ }
+ }}
+ >
+ Создать аккаунт
+
+ )}
+ >
+ }
+ />
+
-
-
-
-
- Настройте агентов
- {!connected ? "Доступно после подключения аккаунта." : agents.status === "loading" ? "Ищем установленных агентов…" : canConfigure ? "Подключите агента к хабу и начните работу." : detectionError ? "Дождитесь проверки установленных агентов." : "Сначала установите хотя бы одного агента."}
-
-
Настроить агента
+ {!showDashboard &&
+
+
+ Установить агента
+
+ }
+ />
+ }
+
+
+ setManagement(true) : openConfigure}
+ label={showDashboard ? "Открыть панель управления агентами" : "Выбрать агента для настройки"}
+ describedBy="overview-configure-help"
+ />
+
+ {detectionError && Не все приложения удалось проверить. }
+
+ {listedAgents.slice(0, 2).map(choice => (
+
+ {choice.name}
+
+ ))}
+ {listedAgents.length > 2 && … ещё {listedAgents.length - 2} }
+
+ Приложения, обновления и настройки подключения.
+ > : !connected
+ ? "Доступно после подключения аккаунта."
+ : canConfigure
+ ? "Подключите агента к хабу и начните работу."
+ : detectionError
+ ? "Дождитесь проверки установленных агентов."
+ : "Сначала установите хотя бы одного агента."
+ }
+ descriptionId="overview-configure-help"
+ actions={
+ showDashboard ? setManagement(true)}>Панель управления :
+ Настроить агента
+
+ }
+ />
+
-
+ {account.error && (
+
+ {account.error}
+
+ )}
+ {connected && detectionError && !showDashboard && (
+
+ Не все приложения удалось проверить. Список обновится
+ автоматически.
+
+ )}
+
- {account.error && {account.error}
}
- {connected && detectionError && Не все приложения удалось проверить. Список обновится автоматически. }
-
+ {management && connected && (
+
{ if (!account.agentBusy) setManagement(false); }}>
+ setManagement(false)} />
+
+
+ )}
+ {setup && connected && (
+
setSetup(undefined)}
+ />
+ )}
- {setup && connected &&
setSetup(undefined)} onFinished={onFinishOnboarding} />}
- ;
+ );
}
diff --git a/crates/wizard-gui/wizard-ui/src/overview/OverviewAgents.tsx b/crates/wizard-gui/wizard-ui/src/overview/OverviewAgents.tsx
new file mode 100644
index 0000000..90a3e31
--- /dev/null
+++ b/crates/wizard-gui/wizard-ui/src/overview/OverviewAgents.tsx
@@ -0,0 +1,94 @@
+import { useEffect, useRef, useState } from "react";
+import { hasAgentDetectionError, type AgentId, type useAgentState } from "../agents/agents_state";
+import { AgentConnectionPanel } from "../agents/AgentConnectionPanel";
+import { agentPageNames, agentPaths } from "../agents/navigation";
+import { currentModeLabels } from "../agents/AgentConfiguration";
+import { DesktopVersion } from "../agents/DesktopInstall";
+import { Button } from "../components/catalyst/button";
+import { Badge, BadgeButton } from "../components/catalyst/badge";
+import { StateNotice } from "../components/ui/StateNotice";
+import { OpenLogsButton } from "../logs/OpenLogsButton";
+import { AgentIcon, choices } from "../onboarding/agents";
+import type { HubAccountControl } from "../settings/HubAccount";
+
+const overviewChoices = ["claude_desktop", "codex", "claude", "opencode", "pi"].map(
+ (id) => choices.find((choice) => choice.id === id)!,
+);
+
+export function OverviewAgents({ account, agents }: {
+ account: HubAccountControl;
+ agents: ReturnType
;
+}) {
+ const [selected, setSelected] = useState();
+ const content = useRef(null);
+ const returnTo = useRef(undefined);
+ useEffect(() => {
+ if (selected) content.current?.querySelector('[role="radio"][tabindex="0"], h2')?.focus({ preventScroll: true });
+ else if (returnTo.current) {
+ // Let the nested plan dialog release its focus trap before restoring the row.
+ const frame = requestAnimationFrame(() => {
+ content.current?.querySelector(`[data-agent-status="${returnTo.current}"]`)?.focus({ preventScroll: true });
+ });
+ return () => cancelAnimationFrame(frame);
+ }
+ }, [selected]);
+ function openAgent(agent: AgentId) { returnTo.current = agent; setSelected(agent); }
+ return (
+
+ {selected && agents.status === "ready" ?
setSelected(undefined)} /> :
+
+ {agents.status !== "ready" ? (
+ : undefined}>
+ {agents.status === "loading" ? "Ищем установленных агентов…" : "Не удалось проверить приложения. Повторяем проверку автоматически. Подробности доступны в логах."}
+
+ ) : (
+
+ )}
+ }
+
+ );
+}
diff --git a/crates/wizard-gui/wizard-ui/src/overview/OverviewArtwork.tsx b/crates/wizard-gui/wizard-ui/src/overview/OverviewArtwork.tsx
index f5b79ac..cbb63ad 100644
--- a/crates/wizard-gui/wizard-ui/src/overview/OverviewArtwork.tsx
+++ b/crates/wizard-gui/wizard-ui/src/overview/OverviewArtwork.tsx
@@ -25,9 +25,10 @@ const numerals = {
};
/** Pen-written step numbers and quiet graphite drawings, kept crisp at any scale. */
-export function OverviewArtwork({ kind, connected = false, disabled, label, describedBy, onClick }: {
+export function OverviewArtwork({ kind, connected = false, step = true, disabled, label, describedBy, onClick }: {
kind: keyof typeof numerals;
connected?: boolean;
+ step?: boolean;
disabled: boolean;
label: string;
describedBy?: string;
@@ -38,7 +39,7 @@ export function OverviewArtwork({ kind, connected = false, disabled, label, desc
return
-
+ {step &&
@@ -51,7 +52,7 @@ export function OverviewArtwork({ kind, connected = false, disabled, label, desc
-
+ }
{kind === "account" && <>
diff --git a/crates/wizard-gui/wizard-ui/src/overview/OverviewCard.stories.tsx b/crates/wizard-gui/wizard-ui/src/overview/OverviewCard.stories.tsx
new file mode 100644
index 0000000..d04b70e
--- /dev/null
+++ b/crates/wizard-gui/wizard-ui/src/overview/OverviewCard.stories.tsx
@@ -0,0 +1,63 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { fn } from "storybook/test";
+import { Button } from "../components/catalyst/button";
+import { OverviewArtwork } from "./OverviewArtwork";
+import { OverviewCard, OverviewCardContent } from "./OverviewCard";
+import "./Overview.css";
+
+const meta = {
+ title: "Блоки/Шаг обзора",
+ component: OverviewCard,
+ tags: ["autodocs"],
+ args: { kind: "install", disabled: false },
+ decorators: [
+ (Story) => (
+
+
+
+ ),
+ ],
+ render: (args) => (
+
+
+
+ {args.kind === "account" ? "Войти" : "Установить агента"}
+
+ }
+ />
+
+ ),
+} satisfies Meta;
+export default meta;
+type Story = StoryObj;
+export const Available: Story = {
+ name: "Доступный шаг",
+ args: { children: null },
+};
+export const Locked: Story = {
+ name: "Недоступный шаг",
+ args: { children: null, disabled: true },
+};
+export const Account: Story = {
+ name: "Анимация аккаунта",
+ args: { children: null, kind: "account" },
+};
diff --git a/crates/wizard-gui/wizard-ui/src/overview/OverviewCard.tsx b/crates/wizard-gui/wizard-ui/src/overview/OverviewCard.tsx
index 00678d4..1563a7f 100644
--- a/crates/wizard-gui/wizard-ui/src/overview/OverviewCard.tsx
+++ b/crates/wizard-gui/wizard-ui/src/overview/OverviewCard.tsx
@@ -1,4 +1,25 @@
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
+import { Subheading } from "../components/catalyst/heading";
+import { Text } from "../components/catalyst/text";
+
+/** Shared card anatomy keeps headings and actions aligned across overview steps. */
+export function OverviewCardContent({ title, description, descriptionId, descriptionTitle, actions, view, headingLevel = 3 }: {
+ title: string;
+ description: ReactNode;
+ descriptionId?: string;
+ descriptionTitle?: string;
+ actions: ReactNode;
+ view?: string;
+ headingLevel?: 2 | 3;
+}) {
+ return
+
+ {title}
+ {description}
+
+
{actions}
+
;
+}
// Remember a completed intro for this app launch, including page navigation.
// A new launch/reload gets a fresh first hover; interrupted runs do not count.
@@ -8,11 +29,12 @@ let introSeen = false;
// the action counterclockwise. The pen lifts between the two gestures.
const strike = "M-34 128 C8 94 61 31 77 25 C96 17 47 111 14 182 C-9 230 0 237 31 207 L193 27 C229 -12 222 18 196 59 L49 281 C16 331 20 337 58 294 L276 66 C308 33 315 45 289 88 L124 347 C100 384 113 389 146 352 L327 150 C361 113 366 131 342 171 L233 353 C209 392 220 396 249 367 L356 276";
-export function OverviewCard({ kind, disabled, activationReady = true, suspended = false, children }: {
+export function OverviewCard({ kind, disabled, activationReady = true, suspended = false, onboarding = true, children }: {
kind: "account" | "install" | "configure";
disabled: boolean;
activationReady?: boolean;
suspended?: boolean;
+ onboarding?: boolean;
children: ReactNode;
}) {
const card = useRef(null);
@@ -24,8 +46,12 @@ export function OverviewCard({ kind, disabled, activationReady = true, suspended
const [buttonVisible, setButtonVisible] = useState(false);
useEffect(() => {
- if (disabled) { animation.current?.cancel(); setInkVisible(false); }
- }, [disabled]);
+ if (disabled || !onboarding) {
+ animation.current?.cancel();
+ setInkVisible(false);
+ setOutlinePending(false);
+ }
+ }, [disabled, onboarding]);
useEffect(() => {
let previousSize: { width: number; height: number } | undefined;
@@ -50,17 +76,18 @@ export function OverviewCard({ kind, disabled, activationReady = true, suspended
// Loading the existing account/agent state establishes a baseline. Only a
// real locked -> available transition requests a new-step hint.
useEffect(() => {
- if (kind === "account" || !activationReady) return;
+ if (!onboarding || kind === "account" || !activationReady) return;
if (previousDisabled.current === true && !disabled) setOutlinePending(true);
if (disabled) setOutlinePending(false);
previousDisabled.current = disabled;
- }, [kind, disabled, activationReady]);
+ }, [kind, disabled, activationReady, onboarding]);
const play = useCallback((mode: "intro" | "outline") => {
const element = path.current;
const button = card.current?.querySelector(".overview-card-actions > button");
- if (disabled || !element || !button || animation.current?.playState === "running"
- || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return false;
+ if (!onboarding || disabled || !element || !button || animation.current?.playState === "running"
+ || window.matchMedia("(prefers-reduced-motion: reduce)").matches
+ || document.documentElement.dataset.motion === "reduce") return false;
animation.current?.cancel();
// Work in CSS pixels so the trail and button outline also align in WebKit
@@ -115,10 +142,10 @@ export function OverviewCard({ kind, disabled, activationReady = true, suspended
};
setInkVisible(true);
return true;
- }, [disabled]);
+ }, [disabled, onboarding]);
useEffect(() => {
- if (!outlinePending || disabled || suspended || !buttonVisible) return;
+ if (!onboarding || !outlinePending || disabled || suspended || !buttonVisible) return;
let frame: number | undefined;
const showWhenVisible = () => {
if (document.visibilityState !== "visible") return;
@@ -134,13 +161,13 @@ export function OverviewCard({ kind, disabled, activationReady = true, suspended
if (frame !== undefined) cancelAnimationFrame(frame);
document.removeEventListener("visibilitychange", showWhenVisible);
};
- }, [outlinePending, disabled, suspended, buttonVisible, play]);
+ }, [onboarding, outlinePending, disabled, suspended, buttonVisible, play]);
function playIntroOnce() {
- if (kind === "account" && !suspended && !introSeen) play("intro");
+ if (onboarding && kind === "account" && !suspended && !introSeen) play("intro");
}
- return {
if (event.pointerType !== "touch") playIntroOnce();
}}
@@ -149,8 +176,8 @@ export function OverviewCard({ kind, disabled, activationReady = true, suspended
}}
onClickCapture={() => { animation.current?.cancel(); setInkVisible(false); }}>
{children}
-
+ {onboarding &&
-
+ }
;
}
diff --git a/crates/wizard-gui/wizard-ui/src/overview/useOverviewTransition.ts b/crates/wizard-gui/wizard-ui/src/overview/useOverviewTransition.ts
new file mode 100644
index 0000000..e7d8ebe
--- /dev/null
+++ b/crates/wizard-gui/wizard-ui/src/overview/useOverviewTransition.ts
@@ -0,0 +1,90 @@
+import { useLayoutEffect, useRef, useState, type RefObject } from "react";
+
+/** First setup folds its installation card into the persistent management action. */
+export function useOverviewTransition(root: RefObject, {
+ ready, connected, requested, suspended,
+}: { ready: boolean; connected: boolean; requested: boolean; suspended: boolean }) {
+ const [dashboard, setDashboard] = useState();
+ const [merging, setMerging] = useState(false);
+ const pending = useRef<{ ghost: HTMLElement; source: DOMRect; cards: Map } | undefined>(undefined);
+ const animations = useRef([]);
+
+ useLayoutEffect(() => {
+ if (!ready) return;
+ if (dashboard === undefined) { setDashboard(requested); return; }
+ if (!connected) { setDashboard(false); return; }
+ if (dashboard || !requested || suspended) return;
+ const source = root.current?.querySelector('[data-kind="install"]');
+ const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches ||
+ document.documentElement.dataset.motion === "reduce";
+ if (source && !reduced && typeof source.animate === "function") {
+ const bounds = source.getBoundingClientRect();
+ if (bounds.width > 0 && bounds.top < innerHeight && bounds.bottom > 0) {
+ const ghost = source.cloneNode(true) as HTMLElement;
+ ghost.inert = true;
+ ghost.setAttribute("aria-hidden", "true");
+ ghost.classList.add("overview-merge-ghost");
+ Object.assign(ghost.style, { left: `${bounds.left}px`, top: `${bounds.top}px`, width: `${bounds.width}px`, height: `${bounds.height}px` });
+ const cards = new Map();
+ root.current?.querySelectorAll('.overview-hero, .overview-card').forEach(card => {
+ cards.set(card.dataset.kind ?? "hero", card.getBoundingClientRect());
+ });
+ pending.current = { ghost, source: bounds, cards };
+ setMerging(true);
+ }
+ }
+ setDashboard(true);
+ }, [ready, connected, requested, suspended, dashboard, root]);
+
+ useLayoutEffect(() => {
+ const transition = pending.current;
+ const target = root.current?.querySelector('[data-management-target]');
+ if (!dashboard || !transition || !target) return;
+ pending.current = undefined;
+ const { ghost, source, cards } = transition;
+ // The balance notice can push the destination just below the fold. Reveal
+ // it before measuring; FLIP also carries the banner through the scroll.
+ const initialDestination = target.getBoundingClientRect();
+ if (initialDestination.bottom > innerHeight || initialDestination.top < 0) {
+ if (initialDestination.bottom > innerHeight * 1.5 || initialDestination.top < -innerHeight * .5) {
+ setMerging(false);
+ return;
+ }
+ target.scrollIntoView({ block: "nearest" });
+ }
+ const destination = target.getBoundingClientRect();
+ const dx = destination.left - source.left, dy = destination.top - source.top;
+ const sx = destination.width / source.width, sy = destination.height / source.height;
+ document.body.appendChild(ghost);
+ const animation = ghost.animate([
+ { transform: "translate(0, 0) scale(1)", opacity: 1, clipPath: "polygon(0 0, 100% 0, 100% 100%, 0 100%)", offset: 0 },
+ { transform: `translate(${dx * .35}px, ${dy * .28}px) scale(.78, .94)`, opacity: .96, clipPath: "polygon(4% 0, 96% 0, 76% 100%, 24% 100%)", offset: .35 },
+ { transform: `translate(${dx}px, ${dy}px) scale(${sx}, ${sy})`, opacity: .7, clipPath: "polygon(0 0, 100% 0, 100% 100%, 0 100%)", offset: .86 },
+ { transform: `translate(${dx}px, ${dy}px) scale(${sx}, ${sy})`, opacity: 0, offset: 1 },
+ ], { duration: 850, easing: "cubic-bezier(.22,.7,.18,1)", fill: "forwards" });
+ animations.current.push(animation);
+ animation.onfinish = () => { ghost.remove(); setMerging(false); };
+ animation.oncancel = () => ghost.remove();
+ root.current?.querySelectorAll('.overview-hero, .overview-card').forEach(card => {
+ const before = cards.get(card.dataset.kind ?? "hero");
+ if (!before) return;
+ const after = card.getBoundingClientRect();
+ animations.current.push(card.animate([
+ { transform: `translate(${before.left - after.left}px, ${before.top - after.top}px) scale(${before.width / after.width}, 1)` },
+ { transform: "none" },
+ ], { duration: 650, easing: "cubic-bezier(.22,.7,.18,1)" }));
+ });
+ animations.current.push(target.animate([
+ { transform: "scale(1)" }, { transform: "scale(.94)" },
+ { transform: "scale(1.035)" }, { transform: "scale(1)" },
+ ], { delay: 600, duration: 440, easing: "ease-out" }));
+ return () => { animation.cancel(); ghost.remove(); };
+ }, [dashboard, root]);
+
+ useLayoutEffect(() => () => {
+ animations.current.forEach(animation => animation.cancel());
+ pending.current?.ghost.remove();
+ }, []);
+
+ return { dashboard: dashboard ?? requested, merging };
+}
diff --git a/crates/wizard-gui/wizard-ui/src/preview/Application.stories.tsx b/crates/wizard-gui/wizard-ui/src/preview/Application.stories.tsx
new file mode 100644
index 0000000..c4d03cf
--- /dev/null
+++ b/crates/wizard-gui/wizard-ui/src/preview/Application.stories.tsx
@@ -0,0 +1,189 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { expect, userEvent, within, waitFor } from "storybook/test";
+import App from "../App";
+import { LogWindow } from "../logs/LogWindow";
+
+const meta = {
+ title: "Экраны/Приложение",
+ component: App,
+ parameters: { layout: "fullscreen" },
+ tags: ["!autodocs"],
+} satisfies Meta;
+export default meta;
+type Story = StoryObj;
+export const Overview: Story = { name: "Обзор" };
+export const ConfiguredOverview: Story = {
+ name: "Обзор · настроенные агенты",
+ parameters: { scenario: "all_agents" },
+};
+export const FirstSetup: Story = {
+ name: "Обзор · первое подключение",
+ parameters: { scenario: "unconfigured" },
+};
+export const EmptyBalance: Story = {
+ name: "Агент готов · пополнение хаба",
+ parameters: { scenario: "balance_empty" },
+};
+export const GuestHub: Story = {
+ name: "Гость · без баланса",
+ parameters: { scenario: "balance_guest" },
+};
+export const UnavailableBalance: Story = {
+ name: "Баланс недоступен",
+ parameters: { scenario: "balance_error" },
+};
+export const OverviewTransformation: Story = {
+ name: "Онбординг → две карточки",
+ parameters: { scenario: "onboarding_merge" },
+};
+export const MissingCLI: Story = {
+ name: "Установка CLI-агента",
+ parameters: { scenario: "missing", route: "/agents/claude" },
+};
+export const SignedOut: Story = {
+ name: "Без аккаунта",
+ parameters: { scenario: "offline" },
+};
+export const PendingSignIn: Story = {
+ name: "Ожидание входа",
+ parameters: { scenario: "pending_login" },
+};
+export const FirstLaunch: Story = {
+ name: "Первый запуск",
+ parameters: { scenario: "startup" },
+ play: async ({ canvas }) => {
+ await expect(
+ await canvas.findByRole(
+ "heading",
+ { name: "Ура! Wizard установлен." },
+ { timeout: 5000 },
+ ),
+ ).toBeVisible();
+ },
+};
+export const ClaudeDesktop: Story = {
+ name: "Claude Desktop",
+ parameters: { route: "/agents/claude-desktop" },
+};
+export const ChatGPT: Story = {
+ name: "ChatGPT и Codex",
+ parameters: { route: "/agents/codex" },
+};
+export const ClaudeCode: Story = {
+ name: "Claude Code",
+ parameters: { scenario: "all_agents", route: "/agents/claude" },
+};
+export const OpenCode: Story = {
+ name: "OpenCode",
+ parameters: { scenario: "all_agents", route: "/agents/opencode" },
+};
+export const Pi: Story = {
+ name: "Pi",
+ parameters: { scenario: "all_agents", route: "/agents/pi" },
+};
+export const Missing: Story = {
+ name: "Неустановленный агент",
+ parameters: { scenario: "missing", route: "/agents/claude-desktop" },
+};
+export const DetectionError: Story = {
+ name: "Ошибка обнаружения",
+ parameters: { scenario: "agents_error", route: "/agents/claude-desktop" },
+};
+export const ChatGPTDetectionError: Story = {
+ name: "Обзор · ошибка обнаружения ChatGPT",
+ parameters: { scenario: "chatgpt_error" },
+};
+export const DisabledConnection: Story = {
+ name: "Claude · отключённое подключение",
+ parameters: { scenario: "unconfigured", route: "/agents/claude-desktop" },
+};
+export const Checking: Story = {
+ name: "Проверка обновлений в фоне",
+ parameters: { scenario: "checking", route: "/agents/claude-desktop" },
+};
+export const WizardUpdate: Story = {
+ name: "Обновление Wizard · окно установки",
+ parameters: { scenario: "wizard_update" },
+};
+export const Current: Story = {
+ name: "Актуальная версия",
+ parameters: { scenario: "current", route: "/agents/claude-desktop" },
+};
+export const Downloads: Story = {
+ name: "Загрузки в панели",
+ parameters: { scenario: "downloads" },
+};
+export const NarrowMixedDownloads: Story = {
+ name: "Загрузки · одна завершена",
+ parameters: { scenario: "mixed_progress" },
+ globals: { viewport: { value: "narrow", isRotated: false } },
+};
+export const ReadyVersion: Story = {
+ name: "Версия готова к установке",
+ parameters: { scenario: "ready", route: "/agents/claude-desktop" },
+};
+export const ReadyChatGPT: Story = {
+ name: "ChatGPT · версия готова",
+ parameters: { scenario: "ready", route: "/agents/codex" },
+};
+export const FailedVersionCheck: Story = {
+ name: "Ошибка проверки версии",
+ parameters: { scenario: "check_error", route: "/agents/claude-desktop" },
+};
+export const LongContent: Story = {
+ name: "Длинные названия",
+ parameters: { scenario: "long_content", route: "/agents/claude-desktop" },
+};
+export const Settings: Story = {
+ name: "Настройки",
+ parameters: { route: "/settings" },
+};
+export const SettingsFailure: Story = {
+ name: "Ошибка настройки",
+ parameters: { scenario: "settings_error", route: "/settings" },
+ play: async ({ canvas }) => {
+ await userEvent.click(
+ await canvas.findByRole("switch", { name: "Работать в трее" }),
+ );
+ await expect(
+ await canvas.findByText(
+ "Не удалось сохранить настройку. Попробуйте ещё раз.",
+ ),
+ ).toBeVisible();
+ },
+};
+export const ProxyConflict: Story = {
+ name: "Конфликт системного прокси",
+ parameters: { scenario: "proxy_conflict", route: "/settings" },
+};
+export const Unsupported: Story = {
+ name: "Недоступная платформа",
+ parameters: { scenario: "unsupported", route: "/settings" },
+};
+export const AccountMenu: Story = {
+ name: "Меню аккаунта",
+ play: async ({ canvas, canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ const menu = canvas.queryByRole("button", { name: "Открыть меню" });
+ if (menu) await userEvent.click(menu);
+ await userEvent.click(
+ await page.findByRole("button", { name: /Меню аккаунта/ }),
+ );
+ await waitFor(() => expect(page.getByRole("menu")).toBeVisible());
+ },
+};
+export const Logs: Story = { name: "Логи", render: () => };
+export const NarrowOverview: Story = {
+ name: "Обзор · узкое окно",
+ globals: { viewport: { value: "narrow", isRotated: false } },
+};
+export const NarrowSettings: Story = {
+ name: "Настройки · узкое окно",
+ parameters: { route: "/settings" },
+ globals: { viewport: { value: "narrow", isRotated: false } },
+};
+export const DarkDesktop: Story = {
+ name: "Claude · тёмная тема",
+ parameters: { route: "/agents/claude-desktop" },
+ globals: { theme: "dark", viewport: { value: "desktop", isRotated: false } },
+};
diff --git a/crates/wizard-gui/wizard-ui/src/preview/Flows.stories.tsx b/crates/wizard-gui/wizard-ui/src/preview/Flows.stories.tsx
new file mode 100644
index 0000000..756402e
--- /dev/null
+++ b/crates/wizard-gui/wizard-ui/src/preview/Flows.stories.tsx
@@ -0,0 +1,421 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { expect, userEvent, within, waitFor } from "storybook/test";
+import App from "../App";
+import { finishDownloads } from "./mocks";
+
+const meta = {
+ title: "Сценарии/Переходы",
+ component: App,
+ parameters: { layout: "fullscreen" },
+ tags: ["!autodocs"],
+} satisfies Meta;
+export default meta;
+type Story = StoryObj;
+
+// Elements mount before the dialog's enter animation makes them visible.
+async function expectVisible(element: Promise) {
+ const target = await element;
+ await waitFor(() => expect(target).toBeVisible());
+}
+
+async function openPicker(canvas: ReturnType, page: ReturnType) {
+ await userEvent.click(await canvas.findByRole("button", { name: "Установить агента" }));
+ return page.findByRole("dialog", { name: "Установите агентов" });
+}
+
+export const Picker: Story = {
+ name: "Выбор приложения",
+ parameters: { onboarding: true },
+ play: async ({ canvas, canvasElement }) => {
+ await openPicker(canvas, within(canvasElement.ownerDocument.body));
+ await expectVisible(
+ within(canvasElement.ownerDocument.body).findByRole("dialog", {
+ name: "Установите агентов",
+ }),
+ );
+ },
+};
+export const DownloadAndCancel: Story = {
+ name: "Скачать → назад → свернуть → отменить",
+ parameters: { route: "/overview", onboarding: true },
+ play: async ({ canvas, canvasElement, step }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await step("Начать скачивание", async () => {
+ const picker = await openPicker(canvas, page);
+ await userEvent.click(within(picker).getAllByRole("button", { name: "Обновить" })[0]);
+ const installation = await page.findByRole("dialog", { name: "Установка агента" });
+ await userEvent.click(within(installation).getByRole("button", { name: "Скачать обновление" }));
+ await expectVisible(page.findByRole("button", { name: "Отменить" }));
+ });
+ await step("Вернуться к выбору, сохранив загрузку", async () => {
+ await userEvent.click(page.getByRole("button", { name: "Назад" }));
+ const dialog = await page.findByRole("dialog", {
+ name: "Установите агентов",
+ });
+ await expect(
+ within(dialog).getByRole("progressbar", {
+ name: "Скачивание Claude Desktop",
+ }),
+ ).toBeInTheDocument();
+ });
+ await step("Свернуть и открыть тот же процесс", async () => {
+ await userEvent.click(
+ page.getByRole("button", { name: "Свернуть установку" }),
+ );
+ await waitFor(() =>
+ expect(page.queryByRole("dialog")).not.toBeInTheDocument(),
+ );
+ const menu = canvas.queryByRole("button", { name: "Открыть меню" });
+ if (menu) await userEvent.click(menu);
+ const navigation = menu
+ ? within(await page.findByRole("dialog", { name: "Навигация" }))
+ : page;
+ await userEvent.click(
+ await navigation.findByRole("button", {
+ name: "Открыть установку Claude Desktop",
+ }),
+ );
+ await expectVisible(
+ page.findByRole("dialog", { name: "Установка агента" }),
+ );
+ await expect(within(page.getByRole("dialog", { name: "Установка агента" })).queryByRole("button", { name: "Назад" })).not.toBeInTheDocument();
+ await waitFor(() =>
+ expect(
+ page
+ .getByRole("dialog", { name: "Установка агента" })
+ .contains(canvasElement.ownerDocument.activeElement),
+ ).toBe(true),
+ );
+ });
+ await step("Отменить скачивание", async () => {
+ await userEvent.click(page.getByRole("button", { name: "Отменить" }));
+ const dialog = await page.findByRole("dialog", {
+ name: "Установка агента",
+ });
+ await expectVisible(
+ within(dialog).findByRole("button", {
+ name: "Скачать обновление",
+ }),
+ );
+ await waitFor(() =>
+ expect(dialog.contains(canvasElement.ownerDocument.activeElement)).toBe(
+ true,
+ ),
+ );
+ });
+ },
+};
+export const NarrowDownloadAndCancel: Story = {
+ ...DownloadAndCancel,
+ name: "Узкое окно · навигация → загрузка → отмена",
+ globals: { viewport: { value: "narrow", isRotated: false } },
+};
+export const NarrowActivity: Story = {
+ name: "Узкое окно · загрузки в левой панели",
+ parameters: { scenario: "downloads" },
+ globals: { viewport: { value: "medium", isRotated: false } },
+ play: async ({ canvas, canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await expect(canvas.queryByRole("button", { name: /^Открыть загрузки/ })).not.toBeInTheDocument();
+ await userEvent.click(await canvas.findByRole("button", { name: "Открыть меню" }));
+ let navigation = await page.findByRole("dialog", { name: "Навигация" });
+ await userEvent.click(within(navigation).getByRole("button", { name: "Открыть установку Claude Desktop" }));
+ const dialog = await page.findByRole("dialog", { name: "Установка агента" });
+ await expect(within(dialog).getAllByRole("progressbar")).toHaveLength(1);
+ await userEvent.keyboard("{Escape}");
+ await waitFor(() => expect(page.queryByRole("dialog")).not.toBeInTheDocument());
+ await userEvent.click(canvas.getByRole("button", { name: "Открыть меню" }));
+ navigation = await page.findByRole("dialog", { name: "Навигация" });
+ await expectVisible(within(navigation).findByRole("button", { name: "Открыть установку Claude Desktop" }));
+ await expectVisible(within(navigation).findByRole("button", { name: "Открыть установку ChatGPT" }));
+ },
+};
+export const ConnectionEditor: Story = {
+ name: "Подключение · применение только при изменениях",
+ parameters: { route: "/agents/claude-desktop" },
+ play: async ({ canvas }) => {
+ const apply = await canvas.findByRole("button", { name: "Применить" });
+ await expect(apply).toBeDisabled();
+ await expect(canvas.queryByRole("button", { name: "Отмена" })).not.toBeInTheDocument();
+ await userEvent.click(canvas.getByRole("radio", { name: "Без CoreInfra AI Hub" }));
+ await expect(apply).toBeEnabled();
+ await userEvent.click(canvas.getByRole("radio", { name: "API-доступ" }));
+ await expect(apply).toBeDisabled();
+ await expect(canvas.getByRole("radio", { name: "API-доступ" })).toBeChecked();
+ },
+};
+export const SubscriptionKey: Story = {
+ name: "Подключение · выбор ключа для API и подписки",
+ parameters: { route: "/agents/claude-desktop" },
+ play: async ({ canvas, canvasElement, step }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await step("Выбрать ключ для API", async () => {
+ await userEvent.click(await canvas.findByRole("button", { name: "Изменить токен" }));
+ await userEvent.click(await page.findByRole("menuitem", { name: /Команда · демо/ }));
+ await expect(canvas.getByRole("button", { name: "Применить" })).toBeEnabled();
+ });
+ await step("Сохранить выбранный ключ при переходе на подписку", async () => {
+ await userEvent.click(canvas.getByRole("radio", { name: "Своя подписка Claude" }));
+ const prompt = await page.findByRole("dialog", { name: "Включить системный прокси?" });
+ await userEvent.click(within(prompt).getByRole("button", { name: "Отмена" }));
+ await waitFor(() => expect(page.queryByRole("dialog")).not.toBeInTheDocument());
+ await expect(canvas.getByText(/Будет использован токен «Команда · демо»/)).toBeVisible();
+ await userEvent.click(canvas.getByRole("button", { name: "Изменить токен" }));
+ await expect(await page.findByRole("menuitem", { name: /Команда · демо/ })).toHaveAttribute("aria-current", "true");
+ await userEvent.keyboard("{Escape}");
+ });
+ await step("Применить подключение", async () => {
+ await userEvent.click(canvas.getByRole("button", { name: "Применить" }));
+ const plan = await page.findByRole("dialog", { name: "План изменений: Claude Desktop" });
+ await userEvent.click(within(plan).getByRole("button", { name: "Применить" }));
+ await waitFor(() => expect(page.queryByRole("dialog")).not.toBeInTheDocument());
+ await expect(canvas.getByRole("radio", { name: "Своя подписка Claude" })).toBeChecked();
+ await expect(canvas.getByText(/Будет использован токен «Команда · демо»/)).toBeVisible();
+ await expect(canvas.getByRole("button", { name: "Применить" })).toBeDisabled();
+ });
+ },
+};
+export const ReadyPicker: Story = {
+ ...Picker,
+ name: "Выбор · оба скачаны",
+ parameters: { scenario: "ready", onboarding: true },
+};
+export const MixedReadyPicker: Story = {
+ ...Picker,
+ name: "Выбор · скачано и доступно",
+ parameters: { scenario: "mixed_ready", onboarding: true },
+};
+export const MixedProgressPicker: Story = {
+ ...Picker,
+ name: "Выбор · скачано и скачивается",
+ parameters: { scenario: "mixed_progress", onboarding: true },
+};
+export const MixedErrorPicker: Story = {
+ ...Picker,
+ name: "Выбор · ошибка и скачано",
+ parameters: { scenario: "mixed_error", onboarding: true },
+};
+export const MissingPicker: Story = {
+ ...Picker,
+ name: "Выбор · приложения не установлены",
+ parameters: { scenario: "missing", onboarding: true },
+};
+export const CurrentPicker: Story = {
+ ...Picker,
+ name: "Выбор · актуальные версии",
+ parameters: { scenario: "current", onboarding: true },
+};
+export const SetupSelection: Story = {
+ name: "Настройка · выбор агента",
+ parameters: { scenario: "all_agents", onboarding: true },
+ play: async ({ canvas, canvasElement }) => {
+ await userEvent.click(
+ await canvas.findByRole("button", { name: "Настроить агента" }),
+ );
+ await expectVisible(
+ within(canvasElement.ownerDocument.body).findByRole("dialog", {
+ name: "Настройка агентов",
+ }),
+ );
+ },
+};
+export const SetupConfiguration: Story = {
+ name: "Панель управления · статус → подключение",
+ parameters: { scenario: "all_agents" },
+ play: async ({ canvas, canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.click(await canvas.findByRole("button", { name: "Панель управления" }));
+ const management = await page.findByRole("dialog", { name: "Управление агентами" });
+ await userEvent.click(within(management).getByRole("button", { name: "Настройки подключения Claude Desktop: CoreInfra AI Hub" }));
+ await expectVisible(within(management).findByRole("radio", { name: "API-доступ" }));
+ await expect(within(management).getByRole("button", { name: "Применить" })).toBeDisabled();
+ },
+};
+export const TwoDownloads: Story = {
+ name: "Две независимые загрузки",
+ parameters: { onboarding: true },
+ play: async ({ canvas, canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ let dialog = await openPicker(canvas, page);
+ await userEvent.click(
+ within(dialog).getAllByRole("button", { name: "Обновить" })[0],
+ );
+ await userEvent.click(await page.findByRole("button", { name: "Скачать обновление" }));
+ await userEvent.click(await page.findByRole("button", { name: "Назад" }));
+ dialog = await page.findByRole("dialog", { name: "Установите агентов" });
+ await userEvent.click(
+ within(within(dialog).getByRole("article", { name: "ChatGPT" })).getByRole("button", { name: "Обновить" }),
+ );
+ await userEvent.click(await page.findByRole("button", { name: "Скачать обновление" }));
+ await userEvent.click(await page.findByRole("button", { name: "Назад" }));
+ dialog = await page.findByRole("dialog", { name: "Установите агентов" });
+ await expect(within(dialog).getAllByRole("progressbar")).toHaveLength(2);
+ },
+};
+export const Ready: Story = {
+ name: "Скачано → установка",
+ parameters: { scenario: "ready", route: "/agents/claude-desktop" },
+ play: async ({ canvas, canvasElement }) => {
+ await userEvent.click(
+ await canvas.findByRole("button", { name: "Обновить" }),
+ );
+ const page = within(canvasElement.ownerDocument.body);
+ const dialog = await page.findByRole("dialog");
+ await waitFor(() =>
+ expect(
+ within(dialog).getByRole("button", { name: "Установить" }),
+ ).toBeEnabled(),
+ );
+ },
+};
+export const InstallWithConfirmation: Story = {
+ name: "Подтверждение → установка → готово",
+ parameters: { scenario: "confirmation", route: "/agents/claude-desktop" },
+ play: async ({ canvas, canvasElement, step }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.click(
+ await canvas.findByRole("button", { name: "Обновить" }),
+ );
+ const dialog = await page.findByRole("dialog");
+ const install = within(dialog).getByRole("button", { name: "Установить" });
+ await expect(install).toBeDisabled();
+ await step("Подтвердить замену приложения", async () => {
+ await userEvent.click(await within(dialog).findByRole("checkbox"));
+ await waitFor(() => expect(install).toBeEnabled());
+ });
+ await userEvent.click(install);
+ await expectVisible(
+ within(dialog).findByRole(
+ "button",
+ { name: "Готово" },
+ { timeout: 5000 },
+ ),
+ );
+ },
+};
+export const InstallFailure: Story = {
+ name: "Ошибка установки и повтор",
+ parameters: { scenario: "install_error", route: "/agents/claude-desktop" },
+ play: async ({ canvas, canvasElement }) => {
+ await userEvent.click(
+ await canvas.findByRole("button", { name: "Обновить" }),
+ );
+ await expectVisible(
+ within(canvasElement.ownerDocument.body).findByRole("button", {
+ name: "Повторить установку",
+ }),
+ );
+ },
+};
+export const Setup: Story = {
+ name: "Выбор → настройка → план → завершение",
+ parameters: { scenario: "onboarding_merge" },
+ play: async ({ canvas, canvasElement, step }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.click(
+ await canvas.findByRole("button", { name: "Настроить агента" }),
+ );
+ await step("Выбрать агента", async () => {
+ await userEvent.click(
+ await page.findByRole("radio", { name: "Claude Desktop" }),
+ );
+ const dialog = page.getByRole("dialog", { name: "Настройка агентов" });
+ await userEvent.click(
+ within(dialog).getByRole("button", { name: "Настроить агента" }),
+ );
+ });
+ await step("Просмотреть план", async () => {
+ await userEvent.click(
+ await page.findByRole("button", { name: "Завершить настройку" }),
+ );
+ await expectVisible(
+ page.findByRole("dialog", {
+ name: "План изменений: Claude Desktop",
+ }),
+ );
+ });
+ await step("Применить демонстрационный план", async () => {
+ const plan = page.getByRole("dialog", {
+ name: "План изменений: Claude Desktop",
+ });
+ await userEvent.click(
+ within(plan).getByRole("button", { name: "Завершить настройку" }),
+ );
+ await expectVisible(
+ page.findByRole("heading", { name: "Claude Desktop настроен" }),
+ );
+ });
+ await step("Перейти к рабочему обзору", async () => {
+ await userEvent.click(page.getByRole("button", { name: "Готово" }));
+ await expectVisible(canvas.findByRole("heading", { name: "Агент готов!" }));
+ await expect(canvas.queryByRole("heading", { name: "Начало работы" })).not.toBeInTheDocument();
+ const dashboard = canvas.getByRole("region", { name: "Хаб и агенты" });
+ await expect(within(dashboard).getByRole("button", { name: "Панель управления" })).toBeVisible();
+ await expect(within(dashboard).queryByRole("button", { name: /Установить/ })).not.toBeInTheDocument();
+ });
+ },
+};
+export const Backups: Story = {
+ name: "Резервные копии",
+ parameters: { route: "/agents/claude-desktop" },
+ play: async ({ canvas, canvasElement }) => {
+ await userEvent.click(
+ await canvas.findByRole("button", { name: "Резервные копии настроек" }),
+ );
+ const page = within(canvasElement.ownerDocument.body);
+ await expectVisible(
+ page.findByRole("dialog", {
+ name: "Резервные копии настроек Claude Desktop",
+ }),
+ );
+ },
+};
+export const EmptyBackups: Story = {
+ ...Backups,
+ name: "Пустые резервные копии",
+ parameters: { scenario: "empty_backups", route: "/agents/claude-desktop" },
+};
+export const FinishDownload: Story = {
+ name: "Прогресс → готово к установке",
+ parameters: { route: "/agents/claude-desktop" },
+ play: async ({ canvas, canvasElement }) => {
+ await userEvent.click(
+ await canvas.findByRole("button", { name: "Обновить" }),
+ );
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.click(await page.findByRole("button", { name: "Скачать обновление" }));
+ await page.findByRole("button", { name: "Отменить" });
+ finishDownloads();
+ const dialog = await page.findByRole("dialog");
+ await expectVisible(
+ within(dialog).findByRole("button", { name: "Установить" }),
+ );
+ },
+};
+
+export const AgentUpdate: Story = {
+ name: "Обновить → скачать → установить → новая версия",
+ parameters: { route: "/agents/claude-desktop" },
+ play: async ({ canvas, canvasElement, step }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await step("Открыть панель обновления", async () => {
+ await userEvent.click(await canvas.findByRole("button", { name: "Обновить" }));
+ await expectVisible(page.findByRole("dialog", { name: "Установка агента" }));
+ });
+ const dialog = page.getByRole("dialog", { name: "Установка агента" });
+ await step("Скачать обновление", async () => {
+ await userEvent.click(within(dialog).getByRole("button", { name: "Скачать обновление" }));
+ await within(dialog).findByRole("progressbar", { name: "Скачивание Claude Desktop" });
+ finishDownloads();
+ await waitFor(() => expect(within(dialog).getByRole("button", { name: "Установить" })).toBeEnabled());
+ });
+ await step("Установить и обновить номер версии", async () => {
+ await userEvent.click(within(dialog).getByRole("button", { name: "Установить" }));
+ await userEvent.click(await within(dialog).findByRole("button", { name: "Готово" }, { timeout: 5000 }));
+ await waitFor(() => expect(page.queryByRole("dialog")).not.toBeInTheDocument());
+ await expect(canvas.getByText("v1.0.124")).toBeVisible();
+ await expect(canvas.queryByRole("button", { name: "Обновить" })).not.toBeInTheDocument();
+ await expect(canvas.queryByText("Версия актуальна")).not.toBeInTheDocument();
+ });
+ },
+};
diff --git a/crates/wizard-gui/wizard-ui/src/preview/OverviewTransition.stories.tsx b/crates/wizard-gui/wizard-ui/src/preview/OverviewTransition.stories.tsx
new file mode 100644
index 0000000..fa695ea
--- /dev/null
+++ b/crates/wizard-gui/wizard-ui/src/preview/OverviewTransition.stories.tsx
@@ -0,0 +1,41 @@
+import { useState } from "react";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import App from "../App";
+import { showOverviewTransition } from "./mocks";
+import "./preview.css";
+
+function TransitionStory() {
+ const [played, setPlayed] = useState(false);
+ return <>
+
+
+ История · Переход в панель управления
+
+
После настройки первого агента карточка установки сворачивается в кнопку «Панель управления». Новые приложения устанавливаются внутри панели.
+
+ {
+ event.currentTarget.closest("details")?.removeAttribute("open");
+ setPlayed(true);
+ showOverviewTransition();
+ }}>{played ? "Переход показан" : "Показать переход"}
+ window.location.reload()}>Сбросить
+
+
Все действия выполняются на моках. «Сбросить» возвращает три карточки онбординга.
+
+
+ >;
+}
+
+const meta = {
+ id: "overview-transition",
+ title: "Сценарии/Переход в панель управления",
+ component: TransitionStory,
+ parameters: { layout: "fullscreen", scenario: "onboarding_merge", route: "/overview" },
+ tags: ["!autodocs"],
+} satisfies Meta;
+export default meta;
+type Story = StoryObj;
+
+export const InstallationIntoControlPanel: Story = {
+ name: "Установка → Панель управления",
+};
diff --git a/crates/wizard-gui/wizard-ui/src/preview/PreviewApp.tsx b/crates/wizard-gui/wizard-ui/src/preview/PreviewApp.tsx
new file mode 100644
index 0000000..5734978
--- /dev/null
+++ b/crates/wizard-gui/wizard-ui/src/preview/PreviewApp.tsx
@@ -0,0 +1,47 @@
+import { useState } from "react";
+import App from "../App";
+import { SubscriptionTokenPreviewContext } from "../agents/connection_preview";
+import { getTheme, setTheme } from "../settings/theme";
+import { scenario, scenarios, finishDownloads, setDownloadSpeed, showOverviewTransition } from "./mocks";
+import "../styles.css";
+import "./preview.css";
+
+function PreviewToolbar() {
+ const [fast, setFast] = useState(false);
+ const [dark, setDark] = useState(getTheme() === "dark");
+ return
+ UI-превью · Моки
+
+
Демонстрационные версии. Файлы не скачиваются, приложения не изменяются.
+
Сценарий
+
{
+ const url = new URL(window.location.href);
+ url.searchParams.set("scenario", event.target.value);
+ window.location.href = url.href;
+ }}>{Object.entries(scenarios).map(([value, label]) => {label} )}
+
+ {scenario === "onboarding_merge" && {
+ event.currentTarget.closest("details")?.removeAttribute("open");
+ showOverviewTransition();
+ }}>Показать переход }
+ { setFast(!fast); setDownloadSpeed(fast ? 1 : 6); }}>Скорость: {fast ? "×6" : "×1"}
+ Завершить загрузки
+ { setTheme(dark ? "light" : "dark"); setDark(!dark); }}>{dark ? "Светлая тема" : "Тёмная тема"}
+ window.location.reload()}>Сбросить
+
+
Закройте панель перед проверкой. {scenario === "startup" ? "Сброс повторяет анимацию первого запуска. Затем открывается весь интерфейс без входа в аккаунт."
+ : scenario === "onboarding_merge" ? "«Показать переход» сворачивает карточку установки в кнопку «Панель управления». Повторить — через «Сбросить». Полный сценарий также доступен через настройку Claude Desktop."
+ : scenario === "wizard_update" ? "Кнопка обновления в левой панели открывает окно. Скачивание и установка имитируются; приложение не меняется."
+ : scenario === "balance_empty" ? "«Пополнить» имитирует пополнение: через 0,6 секунды баланс станет 1 500 ₽. Настоящих платежей нет."
+ : scenario === "checking" ? "Проверка идёт в фоне: через 3 секунды появятся версии для скачивания."
+ : scenario === "downloads" ? "Загрузки замедлены, чтобы рассмотреть виджеты в левой панели." : "Загрузка длится около 36 секунд. Установка новых приложений доступна в панели управления."}
+
+ ;
+}
+
+export default function PreviewApp() {
+ return
+
+
+ ;
+}
diff --git a/crates/wizard-gui/wizard-ui/src/preview/main.tsx b/crates/wizard-gui/wizard-ui/src/preview/main.tsx
new file mode 100644
index 0000000..646a26c
--- /dev/null
+++ b/crates/wizard-gui/wizard-ui/src/preview/main.tsx
@@ -0,0 +1,11 @@
+import { startPreviewMocks } from "./mocks";
+import React from "react";
+import ReactDOM from "react-dom/client";
+
+// This separate HTML entry is never imported by the desktop app or its production bundle.
+startPreviewMocks();
+void Promise.all([import("./PreviewApp"), import("../settings/theme")]).then(([{ default: PreviewApp }, { initializeTheme }]) => {
+ initializeTheme();
+ if (!window.location.hash) window.location.hash = "/agents/claude-desktop";
+ ReactDOM.createRoot(document.getElementById("root")!).render( );
+});
diff --git a/crates/wizard-gui/wizard-ui/src/preview/mocks.ts b/crates/wizard-gui/wizard-ui/src/preview/mocks.ts
new file mode 100644
index 0000000..f26e521
--- /dev/null
+++ b/crates/wizard-gui/wizard-ui/src/preview/mocks.ts
@@ -0,0 +1,807 @@
+import { mockIPC, mockWindows } from "@tauri-apps/api/mocks";
+import type {
+ AgentId,
+ AgentChange,
+ RoutingMode,
+ PreparedAgentChange,
+ AgentStates,
+ TokenChoice,
+} from "../agents/agents_state";
+import type { DesktopApp, Phase } from "../agents/desktop_install_state";
+import type { UpdateState } from "../updates/update";
+import type { useSystemProxy } from "../settings/system_proxy";
+import type { HubSummary } from "../settings/hub_summary";
+
+export const scenarios = {
+ startup: "Первый запуск",
+ all_agents: "Все агенты",
+ unconfigured: "Агенты без подключения",
+ onboarding_merge: "Настройка → новый обзор",
+ balance_empty: "Агент готов · нулевой баланс",
+ balance_guest: "Гостевой доступ",
+ balance_error: "Баланс недоступен",
+ pending_login: "Вход в браузере",
+ long_content: "Длинные названия и тексты",
+ agents_error: "Ошибка обнаружения агентов",
+ chatgpt_error: "Ошибка обнаружения ChatGPT",
+ settings_error: "Ошибка сохранения настроек",
+ proxy_conflict: "Конфликт системного прокси",
+ empty_backups: "Нет резервных копий",
+ install_error: "Ошибка установки",
+ installed: "Установка завершена",
+ checking: "Проверка обновлений в фоне",
+ wizard_update: "Обновление Wizard",
+ check_error: "Ошибка проверки обновлений",
+ update: "Доступно обновление",
+ downloads: "Две загрузки в панели",
+ missing: "Агенты не установлены",
+ current: "Актуальная версия",
+ ready: "Скачано, можно установить",
+ mixed_ready: "Скачано + доступно обновление",
+ mixed_progress: "Скачано + идёт загрузка",
+ mixed_error: "Ошибка загрузки + скачано",
+ error: "Ошибка и повтор загрузки",
+ reconnecting: "Переподключение",
+ unknown: "Размер пока неизвестен",
+ confirmation: "Подтверждение и открытые приложения",
+ offline: "Без входа в аккаунт",
+ unsupported: "Платформа не поддерживается",
+} as const;
+export type Scenario = keyof typeof scenarios;
+const requestedScenario = new URLSearchParams(window.location.search).get(
+ "scenario",
+);
+export const scenario: Scenario =
+ requestedScenario && requestedScenario in scenarios
+ ? (requestedScenario as Scenario)
+ : "update";
+
+class Snapshots {
+ value: T & { revision: number };
+ waiting = new Set<(value: T & { revision: number }) => void>();
+ constructor(value: T) {
+ this.value = { ...value, revision: 0 };
+ }
+ publish(value: T) {
+ this.value = { ...value, revision: this.value.revision + 1 };
+ this.waiting.forEach((resolve) => resolve(this.value));
+ this.waiting.clear();
+ }
+ read(lastRevision?: number | null) {
+ return lastRevision === this.value.revision
+ ? new Promise((resolve) =>
+ this.waiting.add(resolve),
+ )
+ : Promise.resolve(this.value);
+ }
+}
+
+export type MockOptions = { onboarding?: boolean };
+
+export function createMockEnvironment(scenario: Scenario = "update", options: MockOptions = {}) {
+ const timeouts = new Set>();
+ const calls: string[] = [];
+ const openedHubPages: { hubId: string; section: string }[] = [];
+ let disposed = false;
+ function later(action: () => void, ms: number) {
+ const timer = setTimeout(() => {
+ timeouts.delete(timer);
+ if (!disposed) action();
+ }, ms);
+ timeouts.add(timer);
+ }
+ const versions = { claude: "1.0.124", chatgpt: "1.2026.321" };
+ const previousVersions = { claude: "1.0.121", chatgpt: "1.2026.310" };
+ const totals = { claude: 248 * 1048576, chatgpt: 186 * 1048576 };
+ const token = "demo-preview-token-not-a-credential";
+ const onboarding = options.onboarding || ["unconfigured", "onboarding_merge"].includes(scenario);
+ const routing = {
+ routing_mode: onboarding ? "disabled" as const : "hub" as const,
+ token,
+ proxy_needs_apply: false,
+ };
+ const found = scenario !== "missing" && scenario !== "startup";
+ const detectedVersion =
+ scenario === "current" || scenario === "installed"
+ ? versions
+ : previousVersions;
+ const agents = new Snapshots({
+ claude_desktop: found
+ ? {
+ status: "found",
+ data: {
+ ...routing,
+ path: "/Applications/Claude.app",
+ version: detectedVersion.claude,
+ },
+ }
+ : { status: "not_found" },
+ codex: found
+ ? {
+ status: "found",
+ data: {
+ ...routing,
+ cli: {
+ status: "found",
+ data: { path: "/usr/local/bin/codex", version: "0.112.0" },
+ },
+ desktop: scenario === "chatgpt_error" ? {
+ status: "error",
+ data: "Не удалось прочитать сведения о приложении ChatGPT.",
+ } : {
+ status: "found",
+ data: {
+ path: "/Applications/ChatGPT.app",
+ version: detectedVersion.chatgpt,
+ },
+ },
+ },
+ }
+ : { status: "not_found" },
+ claude:
+ scenario === "all_agents"
+ ? {
+ status: "found",
+ data: {
+ ...routing,
+ path: "/usr/local/bin/claude",
+ version: "2.1.0",
+ },
+ }
+ : { status: "not_found" },
+ opencode:
+ scenario === "all_agents"
+ ? {
+ status: "found",
+ data: {
+ ...routing,
+ path: "/usr/local/bin/opencode",
+ version: "1.0.20",
+ },
+ }
+ : { status: "not_found" },
+ pi:
+ scenario === "all_agents"
+ ? {
+ status: "found",
+ data: { ...routing, path: "/usr/local/bin/pi", version: "0.56.0" },
+ }
+ : { status: "not_found" },
+ });
+ const account = new Snapshots({
+ signed_in: !["offline", "startup", "pending_login"].includes(scenario),
+ active_hub_id: scenario === "long_content" || scenario === "balance_guest" ? "team-hub" : "preview-hub",
+ pending: scenario === "pending_login",
+ error: null,
+ profile: {
+ personal_hub_id: "preview-hub",
+ personal_hub_name: "preview",
+ username:
+ scenario === "long_content"
+ ? "Команда разработки и исследования пользовательского интерфейса"
+ : "UI Preview",
+ verified_email:
+ scenario === "long_content"
+ ? "interface.research.and.development@example.com"
+ : "preview@example.com",
+ hubs: [
+ {
+ hub_id: "preview-hub",
+ hub_name: "preview",
+ display_name: "UI Preview",
+ is_personal: true,
+ },
+ {
+ hub_id: "team-hub",
+ hub_name: "team",
+ display_name: "Командный хаб разработки и исследований",
+ is_personal: false,
+ },
+ ],
+ },
+ });
+ const summary = new Snapshots({
+ hub_id: account.value.active_hub_id,
+ role_in_hub: scenario === "balance_guest" ? "guest" : "owner",
+ balance_rub: ["balance_empty", "balance_guest", "onboarding_merge"].includes(scenario) ? 0 : 2500,
+ });
+ const proxy = new Snapshots({ enabled: !onboarding });
+ const update = new Snapshots(
+ scenario === "wizard_update" ? { status: "available", version: "1.0.6" }
+ : scenario === "checking" || scenario === "startup"
+ ? { status: "checking" }
+ : scenario === "check_error"
+ ? {
+ status: "failed",
+ message: "Не удалось проверить обновления. Повторим автоматически.",
+ }
+ : { status: "up_to_date" },
+ );
+ let updateGeneration = 0;
+ function downloadWizardUpdate() {
+ if (update.value.status !== "available" && !(update.value.status === "failed" && update.value.version)) return;
+ const generation = ++updateGeneration;
+ const total = 84 * 1048576;
+ let received = 0;
+ const tick = () => {
+ if (generation !== updateGeneration) return;
+ received = Math.min(total, received + 4 * 1048576);
+ update.publish(received === total ? { status: "ready_to_install", version: "1.0.6" }
+ : { status: "downloading", version: "1.0.6", received, total });
+ if (received < total) later(tick, 400);
+ };
+ update.publish({ status: "downloading", version: "1.0.6", received: 0, total });
+ later(tick, 400);
+ }
+ const tokens = new Snapshots({
+ hub_id: account.value.active_hub_id,
+ tokens: [
+ {
+ token,
+ name:
+ scenario === "long_content"
+ ? "Токен команды разработки и исследования пользовательского интерфейса"
+ : "Агенты · демо",
+ issued_at: 1780000000,
+ },
+ {
+ token: "demo-team-token-not-a-credential",
+ name: "Команда · демо",
+ issued_at: 1780000100,
+ },
+ ],
+ loading: false,
+ error: null,
+ });
+ const application = new Snapshots({
+ tray_enabled: true,
+ autostart_enabled: false,
+ supported: scenario !== "unsupported",
+ });
+ const systemProxy = new Snapshots<
+ NonNullable["state"]>
+ >({
+ status: scenario === "unsupported" ? "unsupported" : "off",
+ busy: false,
+ conflict: scenario === "proxy_conflict",
+ listener_running: true,
+ read_error: null,
+ operation_error: null,
+ });
+ const configured = new Snapshots({
+ details: [{ name: "Агенты · демо", hub_id: "preview-hub" }],
+ error: null,
+ });
+
+ function release(desktop: DesktopApp) {
+ return {
+ version: versions[desktop],
+ path: `/Applications/${desktop === "claude" ? "Claude" : "ChatGPT"}.app`,
+ notes: [],
+ confirmation:
+ scenario === "confirmation"
+ ? "Я понимаю, что текущая версия приложения будет заменена"
+ : null,
+ };
+ }
+ function available(desktop: DesktopApp): Phase {
+ return { status: "available", ...release(desktop), saved: null };
+ }
+ function initial(desktop: DesktopApp): Phase {
+ if (scenario === "mixed_error" && desktop === "claude")
+ return {
+ status: "failed",
+ operation: "download",
+ message: "Соединение прервано. Повторите скачивание.",
+ confirmation: null,
+ };
+ if (
+ ((scenario === "mixed_ready" || scenario === "mixed_progress") &&
+ desktop === "claude") ||
+ (scenario === "mixed_error" && desktop === "chatgpt")
+ )
+ return { status: "ready_to_install", ...release(desktop) };
+ if (scenario === "check_error")
+ return {
+ status: "failed",
+ operation: "check",
+ message: "Не удалось проверить версию. Повторим автоматически.",
+ confirmation: null,
+ };
+ if (scenario === "installed")
+ return { status: "installed", version: versions[desktop], notices: [] };
+ if (scenario === "install_error")
+ return {
+ status: "failed",
+ operation: "install",
+ message:
+ "Не удалось заменить приложение. Закройте его и повторите установку.",
+ confirmation: null,
+ };
+ if (scenario === "current") return { status: "up_to_date" };
+ if (scenario === "unsupported")
+ return {
+ status: "unsupported",
+ message: "Установка недоступна на этой платформе.",
+ };
+ if (scenario === "ready" || scenario === "confirmation")
+ return { status: "ready_to_install", ...release(desktop) };
+ if (
+ scenario === "offline" ||
+ scenario === "startup" ||
+ scenario === "checking"
+ )
+ return { status: "idle" };
+ return available(desktop);
+ }
+ const installs = {
+ claude: new Snapshots(initial("claude")),
+ chatgpt: new Snapshots(initial("chatgpt")),
+ };
+ const timers: Partial>> =
+ {};
+ const failedOnce = new Set();
+ let speed = 1;
+ function setDownloadSpeed(value: number) {
+ speed = value;
+ }
+ function stop(desktop: DesktopApp) {
+ clearInterval(timers[desktop]);
+ delete timers[desktop];
+ }
+ function finish(desktop: DesktopApp) {
+ stop(desktop);
+ installs[desktop].publish({
+ status: "ready_to_install",
+ ...release(desktop),
+ });
+ }
+ function finishDownloads() {
+ if (update.value.status === "downloading") {
+ updateGeneration++;
+ update.publish({ status: "ready_to_install", version: "1.0.6" });
+ }
+ for (const desktop of ["claude", "chatgpt"] as const) {
+ if (installs[desktop].value.status === "downloading") finish(desktop);
+ }
+ }
+
+ function download(desktop: DesktopApp, initialPercent = 0) {
+ const store = installs[desktop];
+ if (
+ store.value.status !== "available" &&
+ !(store.value.status === "failed" && store.value.operation === "download")
+ )
+ throw "Сначала проверьте доступную версию";
+ stop(desktop);
+ let received = (totals[desktop] * initialPercent) / 100;
+ let ticks = 0;
+ store.publish({
+ status: "downloading",
+ received,
+ total: scenario === "unknown" ? 0 : totals[desktop],
+ reconnecting: false,
+ });
+ timers[desktop] = setInterval(() => {
+ ticks++;
+ if (scenario === "error" && ticks === 6 && !failedOnce.has(desktop)) {
+ failedOnce.add(desktop);
+ stop(desktop);
+ store.publish({
+ status: "failed",
+ operation: "download",
+ message:
+ "Не удалось скачать приложение: соединение прервано. Повторите попытку.",
+ confirmation: null,
+ });
+ return;
+ }
+ const reconnecting =
+ scenario === "reconnecting" && ticks >= 6 && ticks <= 13;
+ if (!reconnecting)
+ received = Math.min(
+ totals[desktop],
+ received +
+ (totals[desktop] / (scenario === "downloads" ? 240 : 72)) * speed,
+ );
+ if (received >= totals[desktop]) {
+ finish(desktop);
+ return;
+ }
+ store.publish({
+ status: "downloading",
+ received,
+ total: scenario === "unknown" && ticks < 12 ? 0 : totals[desktop],
+ reconnecting,
+ });
+ }, 500);
+ }
+
+ function checkRelease(desktop: DesktopApp) {
+ const store = installs[desktop];
+ if (["downloading", "installing", "checking"].includes(store.value.status))
+ throw "Операция уже выполняется";
+ store.publish({ status: "checking" });
+ later(
+ () =>
+ store.publish(
+ scenario === "current" ||
+ (desktop === "claude"
+ ? agents.value.claude_desktop.status === "found" &&
+ agents.value.claude_desktop.data.version === versions.claude
+ : agents.value.codex.status === "found" &&
+ agents.value.codex.data.desktop.status === "found" &&
+ agents.value.codex.data.desktop.data.version ===
+ versions.chatgpt)
+ ? { status: "up_to_date" }
+ : available(desktop),
+ ),
+ scenario === "checking" ? 3000 : 600,
+ );
+ }
+
+ function checkIdleReleases() {
+ if (!account.value.signed_in) return;
+ for (const desktop of ["claude", "chatgpt"] as const) {
+ if (installs[desktop].value.status === "idle") checkRelease(desktop);
+ }
+ }
+
+ function start() {
+ if (scenario === "startup") {
+ // Replaying this mock deliberately simulates a fresh installation every time.
+ try {
+ localStorage.removeItem("coreinfra.startup.seen");
+ localStorage.removeItem("coreinfra.onboarding.completed");
+ } catch {
+ /* Startup also works when storage is unavailable. */
+ }
+ window.location.hash = "/overview";
+ }
+ mockWindows("main");
+ mockIPC(
+ async (command, payload) => {
+ if (disposed) return new Promise(() => {});
+ calls.push(command);
+ const args = (payload ?? {}) as Record;
+ const desktop = args.desktop as DesktopApp;
+ const revision = args.lastRevision as number | null | undefined;
+ switch (command) {
+ case "get_agent_state":
+ if (scenario === "agents_error")
+ throw "Не удалось прочитать настройки агента";
+ return agents.value;
+ case "wait_for_update":
+ return (await agents.read(revision)).revision;
+ case "get_desktop_install_state":
+ return installs[desktop].read(revision);
+ case "get_hub_account_state":
+ return account.read(revision);
+ case "get_hub_summary":
+ if (scenario === "balance_error") throw "Баланс временно недоступен";
+ return summary.value;
+ case "get_hub_tokens_state":
+ return tokens.read(revision);
+ case "get_configured_token_info":
+ return configured.read(revision);
+ case "get_proxy_state":
+ return proxy.read(revision);
+ case "get_update_state":
+ return update.read(revision);
+ case "get_application_settings":
+ return application.read(revision);
+ case "get_system_proxy_state":
+ return systemProxy.read(revision);
+ case "plugin:app|version":
+ return "1.0.5-preview";
+ case "check_desktop_release":
+ return checkRelease(desktop);
+ case "download_desktop_release":
+ return download(desktop);
+ case "cancel_desktop_download":
+ if (installs[desktop].value.status !== "downloading" &&
+ installs[desktop].value.status !== "ready_to_install" &&
+ !(installs[desktop].value.status === "failed" && installs[desktop].value.operation === "download"))
+ throw "Нет скачивания, которое можно отменить";
+ stop(desktop);
+ installs[desktop].publish(available(desktop));
+ return;
+ case "get_desktop_running_apps":
+ return scenario === "confirmation"
+ ? [desktop === "claude" ? "Claude" : "ChatGPT", "Codex"]
+ : [];
+ case "install_desktop_release": {
+ if (
+ installs[desktop].value.status !== "ready_to_install" &&
+ !(
+ installs[desktop].value.status === "failed" &&
+ installs[desktop].value.operation === "install"
+ )
+ )
+ throw "Сначала скачайте приложение";
+ if (scenario === "confirmation" && (!args.confirmed || !args.close))
+ throw "Подтвердите замену и закрытие приложения";
+ installs[desktop].publish({
+ status: "installing",
+ close: Boolean(args.close),
+ });
+ later(() => {
+ const next = { ...agents.value };
+ // Installation changes the application, never its connection settings.
+ const unconfigured = { routing_mode: "disabled" as const, token: null, proxy_needs_apply: false };
+ if (desktop === "claude")
+ next.claude_desktop = {
+ status: "found",
+ data: {
+ ...(next.claude_desktop.status === "found" ? next.claude_desktop.data : unconfigured),
+ path: release(desktop).path,
+ version: versions[desktop],
+ },
+ };
+ else
+ next.codex = {
+ status: "found",
+ data: {
+ ...(next.codex.status === "found" ? next.codex.data : unconfigured),
+ cli:
+ next.codex.status === "found"
+ ? next.codex.data.cli
+ : { status: "not_found" },
+ desktop: {
+ status: "found",
+ data: {
+ path: release(desktop).path,
+ version: versions[desktop],
+ },
+ },
+ },
+ };
+ agents.publish(next);
+ installs[desktop].publish({
+ status: "installed",
+ version: versions[desktop],
+ notices: [],
+ });
+ }, 1500);
+ return;
+ }
+ case "logout_hub_account":
+ account.publish({ ...account.value, signed_in: false });
+ return;
+ case "login_hub_account":
+ account.publish({ ...account.value, pending: true });
+ later(() => {
+ account.publish({
+ ...account.value,
+ signed_in: true,
+ pending: false,
+ });
+ checkIdleReleases();
+ }, 500);
+ return;
+ case "get_agent_backups":
+ return scenario === "empty_backups"
+ ? []
+ : [
+ { id: 3, time_created: "2026-11-18T17:10:00Z", files: {} },
+ { id: 2, time_created: "2026-11-17T09:25:00Z", files: {} },
+ ];
+ case "apply_direct_change":
+ return;
+ case "prepare_agent_change": {
+ const change = args.change as AgentChange;
+ const operation = Object.keys(change)[0] as keyof typeof change;
+ const agent = (
+ {
+ CodexSetRouting: "codex",
+ ClaudeSetRouting: "claude",
+ ClaudeDesktopSetRouting: "claude_desktop",
+ SetPiHub: "pi",
+ SetOpenCodeHub: "opencode",
+ } as Record
+ )[operation];
+ const mode = change[operation];
+ const choice = args.token as TokenChoice | null;
+ let resolvedToken: string | null = null;
+ if (mode !== "disabled" && choice?.kind === "existing") {
+ const existing = tokens.value.tokens.find((item) => item.token === choice.token);
+ if (!existing) throw "Выберите токен из текущего хаба";
+ resolvedToken = existing.token;
+ } else if (mode !== "disabled" && choice?.kind === "create") {
+ resolvedToken = `demo-${agent}-${tokens.value.tokens.length}-not-a-credential`;
+ const name = {
+ codex: "agent-codex",
+ claude: "agent-claude-code",
+ claude_desktop: "agent-claude-desktop",
+ opencode: "agent-opencode",
+ pi: "agent-pi",
+ }[agent];
+ tokens.publish({ ...tokens.value, tokens: [...tokens.value.tokens, {
+ token: resolvedToken,
+ name,
+ issued_at: Math.floor(Date.now() / 1000),
+ }] });
+ }
+ return {
+ agent,
+ change,
+ token: resolvedToken,
+ plan: { preview: true, agent, mode, token: resolvedToken },
+ info: [
+ { description: "Сохранить резервную копию настроек агента." },
+ {
+ description:
+ "Обновить режим подключения и токен CoreInfra Hub.",
+ },
+ ],
+ restarts_desktop: agent === "claude_desktop" || agent === "codex",
+ } satisfies PreparedAgentChange;
+ }
+ case "apply_agent_plan": {
+ const plan = args.plan as {
+ preview: boolean;
+ agent: AgentId;
+ mode: RoutingMode;
+ token: string | null;
+ };
+ if (!plan.preview)
+ throw "Превью принимает только демонстрационные планы";
+ const detection = agents.value[plan.agent];
+ if (detection.status === "found")
+ agents.publish({
+ ...agents.value,
+ [plan.agent]: {
+ ...detection,
+ data: { ...detection.data, routing_mode: plan.mode, token: plan.token, proxy_needs_apply: false },
+ },
+ });
+ return;
+ }
+ case "set_application_setting": {
+ if (scenario === "settings_error")
+ throw "Не удалось сохранить настройку. Попробуйте ещё раз.";
+ application.publish({
+ ...application.value,
+ [args.setting as string]: Boolean(args.enabled),
+ });
+ return;
+ }
+ case "set_system_proxy": {
+ if (systemProxy.value.conflict && !args.forced)
+ throw "Обнаружены другие настройки прокси";
+ systemProxy.publish({ ...systemProxy.value, busy: true });
+ return new Promise((resolve) =>
+ later(() => {
+ systemProxy.publish({
+ ...systemProxy.value,
+ status: args.enabled ? "on" : "off",
+ busy: false,
+ conflict: false,
+ });
+ resolve();
+ }, 400),
+ );
+ }
+ case "select_hub":
+ account.publish({
+ ...account.value,
+ active_hub_id: String(args.hubId),
+ });
+ tokens.publish({ ...tokens.value, hub_id: String(args.hubId) });
+ summary.publish({ ...summary.value, hub_id: String(args.hubId) });
+ return;
+ case "open_hub":
+ openedHubPages.push({ hubId: account.value.active_hub_id, section: String(args.section ?? "home") });
+ if (args.section === "payments") {
+ later(() => {
+ summary.publish({ ...summary.value, balance_rub: 1500 });
+ window.dispatchEvent(new Event("focus"));
+ }, 600);
+ }
+ return;
+ case "read_logs":
+ return `[2026-11-18 20:10:00] INFO ${args.source === "proxy" ? "Proxy" : "Wizard"}: ready\n[2026-11-18 20:10:01] INFO Background release check completed\n`;
+ case "request_update":
+ downloadWizardUpdate();
+ return;
+ case "cancel_update":
+ if (update.value.status === "downloading" || update.value.status === "ready_to_install") {
+ updateGeneration++;
+ update.publish({ status: "available", version: "1.0.6" });
+ }
+ return;
+ case "install_update":
+ if (update.value.status !== "ready_to_install") return;
+ update.publish({ status: "installing", version: "1.0.6" });
+ later(() => update.publish({ status: "up_to_date" }), 1000);
+ return;
+ case "ensure_agent_proxy":
+ proxy.publish({ enabled: true });
+ return;
+ case "refresh_hub_tokens":
+ case "launch_agent":
+ case "open_hub_registration":
+ case "open_logs":
+ return;
+ // All IPC stays local. Unknown actions fail visibly instead of reaching a real service.
+ default:
+ if (
+ command.startsWith("plugin:log|") ||
+ command === "plugin:window|set_theme"
+ )
+ return;
+ throw `Действие «${command}» не входит в превью установки.`;
+ }
+ },
+ { shouldMockEvents: true },
+ );
+ checkIdleReleases();
+ if (scenario === "checking" || scenario === "startup")
+ later(() => update.publish({ status: "up_to_date" }), 4000);
+ if (scenario === "downloads") {
+ download("claude", 38);
+ download("chatgpt", 64);
+ }
+ if (scenario === "mixed_progress") download("chatgpt", 38);
+ }
+
+ function dispose() {
+ disposed = true;
+ stop("claude");
+ stop("chatgpt");
+ timeouts.forEach(clearTimeout);
+ timeouts.clear();
+ for (const store of [
+ agents,
+ account,
+ proxy,
+ update,
+ tokens,
+ application,
+ systemProxy,
+ configured,
+ installs.claude,
+ installs.chatgpt,
+ ])
+ store.waiting.clear();
+ }
+ return {
+ start,
+ dispose,
+ finishDownloads,
+ setDownloadSpeed,
+ calls,
+ update,
+ openedHubPages,
+ agents,
+ tokens,
+ account,
+ summary,
+ installs,
+ application,
+ systemProxy,
+ };
+}
+
+let activeEnvironment: ReturnType | undefined;
+export function startPreviewMocks(selectedScenario: Scenario = scenario, options: MockOptions = {}) {
+ activeEnvironment?.dispose();
+ activeEnvironment = createMockEnvironment(selectedScenario, options);
+ activeEnvironment.start();
+ return activeEnvironment;
+}
+export function finishDownloads() {
+ activeEnvironment?.finishDownloads();
+}
+export function setDownloadSpeed(value: number) {
+ activeEnvironment?.setDownloadSpeed(value);
+}
+
+export function showOverviewTransition() {
+ const agents = activeEnvironment?.agents;
+ if (!agents || agents.value.claude_desktop.status !== "found") return;
+ agents.publish({ ...agents.value, claude_desktop: {
+ ...agents.value.claude_desktop,
+ data: { ...agents.value.claude_desktop.data, routing_mode: "hub" },
+ } });
+}
diff --git a/crates/wizard-gui/wizard-ui/src/preview/preview.css b/crates/wizard-gui/wizard-ui/src/preview/preview.css
new file mode 100644
index 0000000..4000b5d
--- /dev/null
+++ b/crates/wizard-gui/wizard-ui/src/preview/preview.css
@@ -0,0 +1,15 @@
+.preview-controls { position: fixed; z-index: 40; right: 16px; top: 12px; max-width: min(350px, calc(100vw - 32px)); border: 1px solid #d4d4d8; border-radius: 12px; background: #fafafa; color: #3f3f46; font: 12px/1.5 InterVariable, sans-serif; box-shadow: 0 4px 20px #0001; }
+.preview-controls summary { padding: 8px 12px; cursor: pointer; font-weight: 500; }
+.preview-controls { top: auto; bottom: 12px; max-height: calc(100dvh - 80px); overflow-y: auto; }
+.preview-controls[data-story="overview-transition"] { top: 12px; bottom: auto; max-width: min(350px, calc(100vw - 80px)); }
+body:has([role="dialog"]) .preview-controls { display: none; }
+.preview-controls-body { display: grid; gap: 10px; padding: 0 14px 14px; }
+.preview-controls-body select { width: 100%; padding: 8px; border: 1px solid #a1a1aa; border-radius: 6px; background: white; }
+.preview-controls-actions { display: flex; flex-wrap: wrap; gap: 6px; }
+.preview-controls-actions button { padding: 6px 9px; border: 1px solid #d4d4d8; border-radius: 6px; cursor: pointer; }
+.preview-controls-actions button:hover { background: #e4e4e7; }
+.preview-controls-actions button:disabled { opacity: .5; cursor: default; }
+:root[data-theme="dark"] .preview-controls { background: #27272a; color: #e4e4e7; border-color: #52525b; }
+:root[data-theme="dark"] .preview-controls-body select { background: #18181b; }
+:root[data-theme="dark"] .preview-controls-actions button { border-color: #52525b; }
+:root[data-theme="dark"] .preview-controls-actions button:hover { background: #3f3f46; }
diff --git a/crates/wizard-gui/wizard-ui/src/settings/HubAccount.tsx b/crates/wizard-gui/wizard-ui/src/settings/HubAccount.tsx
index 6bb5853..87f7e9e 100644
--- a/crates/wizard-gui/wizard-ui/src/settings/HubAccount.tsx
+++ b/crates/wizard-gui/wizard-ui/src/settings/HubAccount.tsx
@@ -1,5 +1,5 @@
import { useRef, useState, useSyncExternalStore, type MouseEvent } from "react";
-import { MenuButton, useClose } from "@headlessui/react";
+import { MenuButton } from "@headlessui/react";
import { ComputerDesktopIcon, EllipsisHorizontalIcon, MoonIcon, SunIcon } from "@heroicons/react/20/solid";
import { hubDisplayName, loginHubAccount, logoutHubAccount, openHub, openHubRegistration, selectHub, useHubAccount } from "./hub_account";
import { getTheme, setTheme, subscribeTheme } from "./theme";
@@ -8,7 +8,6 @@ import { SidebarItem, SidebarLabel } from "../components/catalyst/sidebar";
import { Text } from "../components/catalyst/text";
import { ErrorText } from "../components/ErrorText";
import { useOpenLogs } from "../logs/OpenLogsButton";
-import { settingsPath } from "../agents/navigation";
// Account state and actions are shared by the sidebar and agent pages.
export function useHubAccountControl() {
@@ -44,6 +43,7 @@ export function useHubAccountControl() {
if (!agentBusy) void run(() => selectHub(hubId));
},
open: () => void run(() => openHub(getTheme())),
+ topUp: () => void run(() => openHub(getTheme(), "payments")),
register: () => void run(openHubRegistration),
};
}
@@ -56,9 +56,8 @@ const themes = [
{ value: "system", label: "Системная тема", Icon: ComputerDesktopIcon },
] as const;
-export function HubAccountMenu({ hub, settingsCurrent }: { hub: HubAccountControl; settingsCurrent: boolean }) {
+export function HubAccountMenu({ hub }: { hub: HubAccountControl }) {
const { account } = hub;
- const closeSidebar = useClose();
const logs = useOpenLogs();
const typeaheadUntil = useRef(0);
const theme = useSyncExternalStore(subscribeTheme, getTheme);
@@ -145,9 +144,6 @@ export function HubAccountMenu({ hub, settingsCurrent }: { hub: HubAccountContro