Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8047: feat(onboarding): open the runtime guide issue directly instead of a welcome modal (#9289)
Jiayuan Zhang130aaa530232
diff --git a/apps/desktop/src/renderer/src/App.auth-recovery.test.tsx b/apps/desktop/src/renderer/src/App.auth-recovery.test.tsxindex b8e507ce5e..5a7ec84299 100644--- a/apps/desktop/src/renderer/src/App.auth-recovery.test.tsx+++ b/apps/desktop/src/renderer/src/App.auth-recovery.test.tsx@@ -40,10 +40,6 @@ vi.mock("@multica/core/auth", () => ({selector(state.auth),}));-vi.mock("@multica/core/onboarding", () => ({- useWelcomeStore: { getState: () => ({ reset: vi.fn() }) },-}));-vi.mock("@multica/core/workspace/queries", () => ({workspaceKeys: { list: () => ["workspace-list"] },}));diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsxindex 6c0a576083..c8546ffaa3 100644--- a/apps/desktop/src/renderer/src/App.tsx+++ b/apps/desktop/src/renderer/src/App.tsx@@ -3,7 +3,6 @@ import { useQueryClient } from "@tanstack/react-query";import { CoreProvider } from "@multica/core/platform";import { pickLocale, type SupportedLocale } from "@multica/core/i18n";import { useAuthStore } from "@multica/core/auth";-import { useWelcomeStore } from "@multica/core/onboarding";import { workspaceKeys } from "@multica/core/workspace/queries";import { useWorkspaceList } from "@multica/core/workspace";import { api } from "@multica/core/api";@@ -364,7 +363,6 @@ const sessionTeardown: SessionTeardown = {window.desktopAPI.reportAuthSession?.(userId),resetTabs: () => useTabStore.getState().reset(),closeOverlay: () => useWindowOverlayStore.getState().close(),- resetWelcome: () => useWelcomeStore.getState().reset(),clearDaemonToken: () => window.daemonAPI.clearToken(),stopDaemon: () => window.daemonAPI.stop(),};diff --git a/apps/desktop/src/renderer/src/components/workspace-route-layout.test.tsx b/apps/desktop/src/renderer/src/components/workspace-route-layout.test.tsxindex d828c9ff87..3e83ec4b82 100644--- a/apps/desktop/src/renderer/src/components/workspace-route-layout.test.tsx+++ b/apps/desktop/src/renderer/src/components/workspace-route-layout.test.tsx@@ -89,10 +89,6 @@ vi.mock("@multica/views/workspace/use-workspace-seen", () => ({useWorkspaceSeen: () => state.workspaceSeen,}));-vi.mock("@multica/views/workspace/welcome-after-onboarding", () => ({- WelcomeAfterOnboarding: () => null,-}));-vi.mock("@multica/views/layout", () => ({WorkspacePresencePrefetch: () => null,}));diff --git a/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx b/apps/desktop/src/renderer/src/components/workspace-route-layout.tsxindex 088cf36444..86df481d76 100644--- a/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx+++ b/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx@@ -10,7 +10,6 @@ import { getCurrentSlug, setCurrentWorkspace } from "@multica/core/platform";import { isWorkspaceDeletePending } from "@multica/core/workspace/pending-delete";import { useAuthStore } from "@multica/core/auth";import { useWorkspaceSeen } from "@multica/views/workspace/use-workspace-seen";-import { WelcomeAfterOnboarding } from "@multica/views/workspace/welcome-after-onboarding";import { WorkspacePresencePrefetch } from "@multica/views/layout";import { SourceBackfillModal } from "@multica/views/onboarding";import { useTabStore } from "@/stores/tab-store";@@ -57,12 +56,11 @@ export function WorkspaceRouteLayout() {const isAuthLoading = useAuthStore((s) => s.isLoading);// While a WindowOverlay is open (onboarding, accept-invite, new-workspace),// the underlying tab is still mounted in the React tree — so this layout- // and its WelcomeAfterOnboarding Modal would render UNDER the overlay.+ // and its SourceBackfillModal would render UNDER the overlay.// Because the modal uses a Portal that targets document.body, it ends up// rendered LATER in the DOM and visually outranks the overlay's z-50.- // Suppress the modal whenever any overlay is active; the moment the- // overlay closes the welcome hook re-evaluates and pops if its store- // signal is still set.+ // Suppress the modal whenever any overlay is active; it re-evaluates the+ // moment the overlay closes.const overlayActive = useWindowOverlayStore((s) => s.overlay !== null);// Workspace routes require auth. App.tsx renders <DesktopLoginPage>@@ -179,20 +177,12 @@ export function WorkspaceRouteLayout() {<WorkspaceSlugProvider slug={workspaceSlug}><WorkspacePresencePrefetch /><Outlet />- {/* Reads the welcome-store transient signal parked by- * OnboardingFlow.handleRuntimeNext. Suppressed while a WindowOverlay- * (onboarding / accept-invite / new-workspace) is open so the modal- * doesn't portal-jump in front of an active pre-workspace flow.- * Once the overlay closes the hook re-evaluates and pops the- * Modal — unless the store signal has already been consumed, in- * which case the hook renders null. */}- {!overlayActive && <WelcomeAfterOnboarding />}{/* Source-attribution backfill: same Dialog the web shell mounts* inside DashboardLayout. Desktop's WorkspaceRouteLayout doesn't* wrap DashboardLayout, so the modal has to be wired in directly- * here. Same overlay-suppression rule as WelcomeAfterOnboarding —- * a portal-rendered Dialog at z-50 would otherwise sit above an- * active pre-workspace overlay. */}+ * here. Suppressed while a WindowOverlay is open — a portal-rendered+ * Dialog at z-50 would otherwise sit above an active pre-workspace+ * overlay. */}{!overlayActive && <SourceBackfillModal />}</WorkspaceSlugProvider>);diff --git a/apps/desktop/src/renderer/src/platform/session-teardown.test.ts b/apps/desktop/src/renderer/src/platform/session-teardown.test.tsindex 614a0ee2b8..db8e1fbd3e 100644--- a/apps/desktop/src/renderer/src/platform/session-teardown.test.ts+++ b/apps/desktop/src/renderer/src/platform/session-teardown.test.ts@@ -14,7 +14,6 @@ function makeTeardown(reportAuthSession: vi.fn(),resetTabs: vi.fn(),closeOverlay: vi.fn(),- resetWelcome: vi.fn(),clearDaemonToken: vi.fn(async () => {}),stopDaemon: vi.fn(async () => {}),...overrides,@@ -33,7 +32,6 @@ describe("tearDownOnLogout", () => {expect(t.reportAuthSession).toHaveBeenCalledWith(null);expect(t.resetTabs).toHaveBeenCalledOnce();expect(t.closeOverlay).toHaveBeenCalledOnce();- expect(t.resetWelcome).toHaveBeenCalledOnce();expect(t.clearDaemonToken).toHaveBeenCalledOnce();expect(t.stopDaemon).toHaveBeenCalledOnce();});@@ -82,6 +80,5 @@ describe("tearDownOnSessionExpiry", () => {expect(t.reportAuthSession).toHaveBeenCalledWith(null);expect(t.resetTabs).toHaveBeenCalledOnce();expect(t.closeOverlay).toHaveBeenCalledOnce();- expect(t.resetWelcome).toHaveBeenCalledOnce();});});diff --git a/apps/desktop/src/renderer/src/platform/session-teardown.ts b/apps/desktop/src/renderer/src/platform/session-teardown.tsindex dc98b01b5c..ce6ecd89c8 100644--- a/apps/desktop/src/renderer/src/platform/session-teardown.ts+++ b/apps/desktop/src/renderer/src/platform/session-teardown.ts@@ -25,8 +25,6 @@ export interface SessionTeardown {resetTabs: () => void;/** Any pre-workspace overlay left open (invite, onboarding, …). */closeOverlay: () => void;- /** The one-shot post-onboarding welcome signal. */- resetWelcome: () => void;/** Credential the local daemon authenticates with. */clearDaemonToken: () => Promise<unknown>;/** The local daemon process itself. Resolves to an IPC result we ignore —@@ -47,7 +45,6 @@ export async function tearDownOnLogout(t: SessionTeardown): Promise<void> {t.reportAuthSession(null);t.resetTabs();t.closeOverlay();- t.resetWelcome();try {await t.clearDaemonToken();} catch {@@ -75,5 +72,4 @@ export function tearDownOnSessionExpiry(t: SessionTeardown): void {t.reportAuthSession(null);t.resetTabs();t.closeOverlay();- t.resetWelcome();}diff --git a/apps/web/app/(auth)/onboarding/page.tsx b/apps/web/app/(auth)/onboarding/page.tsxindex a48b1d1727..00c9a4e219 100644--- a/apps/web/app/(auth)/onboarding/page.tsx+++ b/apps/web/app/(auth)/onboarding/page.tsx@@ -17,7 +17,8 @@ import { CliInstallInstructions, OnboardingFlow } from "@multica/views/onboardin* `<OnboardingFlow />`. Kept minimal — guard on auth, render, exit.** Runtime-connected onboarding opens the Mika session that the final step- * created and started. Other exits land on the workspace issues list, or root+ * created and started; skipping the runtime opens the install-runtime guide+ * issue it created. Other exits land on the workspace issues list, or root* when no workspace exists.** `CliInstallInstructions` is passed in as the `runtimeInstructions`diff --git a/apps/web/app/[workspaceSlug]/layout.test.tsx b/apps/web/app/[workspaceSlug]/layout.test.tsxindex d2ab07b9cb..d00c09f860 100644--- a/apps/web/app/[workspaceSlug]/layout.test.tsx+++ b/apps/web/app/[workspaceSlug]/layout.test.tsx@@ -60,10 +60,6 @@ vi.mock("@multica/views/workspace/no-access-page", () => ({NoAccessPage: () => <div data-testid="no-access" />,}));-vi.mock("@multica/views/workspace/welcome-after-onboarding", () => ({- WelcomeAfterOnboarding: () => null,-}));-vi.mock("@multica/views/workspace/use-workspace-seen", () => ({useWorkspaceSeen: () => state.hasBeenSeen,}));diff --git a/apps/web/app/[workspaceSlug]/layout.tsx b/apps/web/app/[workspaceSlug]/layout.tsxindex ce2744e2ea..7de9e7a24b 100644--- a/apps/web/app/[workspaceSlug]/layout.tsx+++ b/apps/web/app/[workspaceSlug]/layout.tsx@@ -8,7 +8,6 @@ import { workspaceBySlugOptions } from "@multica/core/workspace";import { setCurrentWorkspace } from "@multica/core/platform";import { useAuthStore } from "@multica/core/auth";import { NoAccessPage } from "@multica/views/workspace/no-access-page";-import { WelcomeAfterOnboarding } from "@multica/views/workspace/welcome-after-onboarding";import { MulticaIcon } from "@multica/ui/components/common/multica-icon";import { useWorkspaceSeen } from "@multica/views/workspace/use-workspace-seen";import { workspaceSlugFromPathname } from "@/lib/workspace-slug-from-pathname";@@ -105,11 +104,6 @@ export default function WorkspaceLayout({return (<WorkspaceSlugProvider slug={workspaceSlug}>{children}- {/* Reads the welcome-store transient signal parked by- * OnboardingFlow.handleRuntimeNext. Runtime path → loading veil →- * blocking Modal with Helper + starter cards. Skip path → Modal- * with two seeded issues. No signal → null. */}- <WelcomeAfterOnboarding /></WorkspaceSlugProvider>);}diff --git a/apps/web/components/web-providers.tsx b/apps/web/components/web-providers.tsxindex 4d223a77e7..ee7aeb36d4 100644--- a/apps/web/components/web-providers.tsx+++ b/apps/web/components/web-providers.tsx@@ -4,7 +4,6 @@ import { useMemo } from "react";import { CoreProvider } from "@multica/core/platform";import { createBrowserCookieLocaleAdapter } from "@multica/core/i18n/browser";import type { LocaleResources, SupportedLocale } from "@multica/core/i18n";-import { useWelcomeStore } from "@multica/core/onboarding";import packageJson from "../package.json";import { WebNavigationProvider } from "@/platform/navigation";import { WebScrollRestorationProvider } from "@/platform/scroll-restoration";@@ -73,16 +72,7 @@ export function WebProviders({wsUrl={wsUrl || deriveWsUrl()}cookieAuth={cookieAuth}onLogin={setLoggedInCookie}- onLogout={() => {- // welcome-store holds the transient post-onboarding signal. Must- // clear on logout so user B logging into the same browser doesn't- // inherit user A's signal and have <WelcomeAfterOnboarding /> fire- // listAgents / createIssue against a workspace user B doesn't even- // belong to. The store's own docstring promises this reset; this- // is where it gets wired.- useWelcomeStore.getState().reset();- clearLoggedInCookie();- }}+ onLogout={clearLoggedInCookie}identity={identity}locale={locale}resources={resources}diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 7719f247ad..144e3fc677 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -1403,7 +1403,10 @@ export class ApiClient {return issue;}- async createIssue(data: CreateIssueRequest): Promise<Issue> {+ async createIssue(+ data: CreateIssueRequest,+ workspaceSlug?: string,+ ): Promise<Issue> {const requestedProperties = requestedIssueCreateProperties(data);if (requestedProperties) {const config = await this.getConfig();@@ -1424,6 +1427,7 @@ export class ApiClient {// render its localized "failed to create" toast.const raw = await this.fetch<unknown>("/api/issues", {method: "POST",+ headers: workspaceHeader(workspaceSlug),body: JSON.stringify(data),});const issue = parseWithFallback<Issue | null>(raw, CreateIssueResponseSchema, null, {diff --git a/packages/core/onboarding/index.ts b/packages/core/onboarding/index.tsindex 738bc9d73d..c732b8d05f 100644--- a/packages/core/onboarding/index.ts+++ b/packages/core/onboarding/index.ts@@ -25,10 +25,6 @@ export {type BootstrapMikaResult,type MikaOnboardingLanguage,} from "./use-bootstrap-mika";-export {- useWelcomeStore,- type WelcomeSignal,-} from "./welcome-store";export {MIKA_SYSTEM_KEY,isMikaAgent,diff --git a/packages/core/onboarding/welcome-store.test.ts b/packages/core/onboarding/welcome-store.test.tsdeleted file mode 100644index f0650e5bb4..0000000000--- a/packages/core/onboarding/welcome-store.test.ts+++ /dev/null@@ -1,38 +0,0 @@-import { beforeEach, describe, expect, it } from "vitest";-import { useWelcomeStore, type WelcomeSignal } from "./welcome-store";--const sample: WelcomeSignal = {- workspaceId: "ws-1",- choice: "skip",-};--describe("welcome-store", () => {- beforeEach(() => {- useWelcomeStore.getState().reset();- });-- it("set() stores the signal and clears any prior dismissed flag", () => {- useWelcomeStore.getState().dismiss();- expect(useWelcomeStore.getState().dismissed).toBe(true);- useWelcomeStore.getState().set(sample);- expect(useWelcomeStore.getState().signal).toEqual(sample);- // A fresh set() means a fresh Welcome session — dismissed resets so- // the next mount renders the new signal.- expect(useWelcomeStore.getState().dismissed).toBe(false);- });-- it("dismiss() marks dismissed without clearing the signal", () => {- useWelcomeStore.getState().set(sample);- useWelcomeStore.getState().dismiss();- expect(useWelcomeStore.getState().signal).toEqual(sample);- expect(useWelcomeStore.getState().dismissed).toBe(true);- });-- it("reset() clears signal AND dismissed (used on logout)", () => {- useWelcomeStore.getState().set(sample);- useWelcomeStore.getState().dismiss();- useWelcomeStore.getState().reset();- expect(useWelcomeStore.getState().signal).toBeNull();- expect(useWelcomeStore.getState().dismissed).toBe(false);- });-});diff --git a/packages/core/onboarding/welcome-store.ts b/packages/core/onboarding/welcome-store.tsdeleted file mode 100644index 7f3b2a1426..0000000000--- a/packages/core/onboarding/welcome-store.ts+++ /dev/null@@ -1,71 +0,0 @@-import { create } from "zustand";--/**- * Welcome signal — written by the runtime step only when the user skips- * connecting a runtime, then consumed exactly once by the- * `<WelcomeAfterOnboarding />` component in the workspace shell.- *- * The signal is the bridge between the onboarding screen and the workspace- * shell that succeeds it. `onboarded_at` is already true by the time we- * land in the workspace — this carries the transient no-runtime intent- * without persisting it on the user- * row (the v2 design persisted it as fields and leaked complexity- * everywhere).- *- * The signal is only needed when the user explicitly skips runtime setup.- * The workspace welcome hook seeds one install-runtime guide and shows it in- * a modal. Once a runtime appears, the Runtimes page offers the same Mika- * bootstrap used by the connected onboarding path. Runtime-connected- * onboarding creates Mika before reaching the workspace and does not use- * this signal.- */-export interface WelcomeSignal {- workspaceId: string;- choice: "skip";-}--interface WelcomeStoreState {- signal: WelcomeSignal | null;- /**- * True after the user has explicitly engaged with the Welcome surface —- * opened the runtime guide or closed the Skip modal.- * Components MUST treat `signal && !dismissed` as the render condition;- * `dismiss()` is what removes the modal from view.- */- dismissed: boolean;- set: (signal: WelcomeSignal) => void;- /**- * Mark the Welcome surface as engaged-with. Idempotent. Keeps the- * signal in the store as a record but components will stop rendering.- * We don't fully clear the store on dismiss so a debug peek (or a- * future analytics hook) can still see which path the user took.- */- dismiss: () => void;- /**- * Full reset — clear signal AND dismissed. Used by tests and by the- * user logout flow (so a different user logging into the same browser- * doesn't inherit a stale signal).- */- reset: () => void;-}--/**- * Zustand store, deliberately NOT persisted. Reloading the page drops the- * signal — that's the correct behavior: the user already finished- * onboarding (onboarded_at is set), and Welcome was a one-shot UI. We- * never want a refresh to re-trigger setup-guide creation.- *- * Why subscription model instead of read-once-consume: React 18+ StrictMode- * dev mode mounts components twice (mount → unmount → mount). If the- * component consumed the store in a `useState` initializer, the second- * mount would see an already-empty store and render null — Welcome would- * never appear in dev. Subscribing to a stable store + tracking dismissal- * in the store sidesteps both mounts seeing the same state.- */-export const useWelcomeStore = create<WelcomeStoreState>((set) => ({- signal: null,- dismissed: false,- set: (signal) => set({ signal, dismissed: false }),- dismiss: () => set({ dismissed: true }),- reset: () => set({ signal: null, dismissed: false }),-}));diff --git a/packages/ui/styles/base.css b/packages/ui/styles/base.cssindex 944c97283b..50ddc7faab 100644--- a/packages/ui/styles/base.css+++ b/packages/ui/styles/base.css@@ -73,47 +73,6 @@animation: onboarding-enter 0.4s ease both;}-/* Welcome-after-onboarding Modal: emoji pops in with two quick scale- * bounces so the celebration registers visually without being- * disruptive. ~700ms total. */-@keyframes welcome-emoji-pop {- 0% { transform: scale(0.4); opacity: 0; }- 35% { transform: scale(1.25); opacity: 1; }- 55% { transform: scale(0.92); }- 75% { transform: scale(1.12); }- 100% { transform: scale(1); }-}-.animate-welcome-emoji-pop {- animation: welcome-emoji-pop 0.7s cubic-bezier(0.4, 0, 0.2, 1) both;-}--/* Onboarding completion: success badge spring-pop.- * Lands with a subtle overshoot (scale 1.12 → 1) so the circle feels- * physical rather than linearly interpolated. Paired with the drawn- * checkmark below which kicks in after the badge has settled. */-@keyframes completion-badge {- 0% { transform: scale(0); opacity: 0; }- 60% { transform: scale(1.12); opacity: 1; }- 100% { transform: scale(1); opacity: 1; }-}--.animate-completion-badge {- animation: completion-badge 500ms cubic-bezier(0.5, 1.5, 0.4, 1) both;-}--/* Onboarding completion: SVG checkmark drawn by animating- * stroke-dashoffset from 1 → 0. Requires the target <path> to declare- * `pathLength={1}` and `strokeDasharray={1}` so the stroke length is- * normalized and the animation is geometry-agnostic. */-@keyframes completion-check {- from { stroke-dashoffset: 1; }- to { stroke-dashoffset: 0; }-}--.animate-completion-check {- animation: completion-check 400ms ease-out 350ms both;-}-/* Chat FAB: gentle color + border tint while a chat task is running.* Keeps the ring at the same thickness — only hue shifts towards brand* at half-cycle, no outer glow. */@@ -336,9 +295,6 @@ html[data-dnd-dragging="true"] * {@media (prefers-reduced-motion: reduce) {.animate-entrance-spin,.animate-onboarding-enter,- .animate-welcome-emoji-pop,- .animate-completion-badge,- .animate-completion-check,.animate-chat-impulse,.shimmer-text-window,.shimmer-text-copy,diff --git a/packages/views/locales/en/onboarding.json b/packages/views/locales/en/onboarding.jsonindex eab9066fab..a4a37defbc 100644--- a/packages/views/locales/en/onboarding.json+++ b/packages/views/locales/en/onboarding.json@@ -106,10 +106,6 @@"other_placeholder": "e.g. study group coordination"}},- "option_card": {- "other_label": "Other",- "other_aria": "Describe something else"- },"step_question": {"hint_pick": "You can skip this."},@@ -135,28 +131,7 @@"success_toast": "You're on the list. We'll email when cloud runtimes are live.","failed_toast": "Failed to join waitlist"},- "welcome_after_onboarding": {- "skip": {- "loading": "Setting up your workspace…",- "title": "Welcome to Multica!",- "subtitle": "We've added one issue to help you connect a runtime. When it's ready, start with Mika from Runtimes.",- "got_it": "Got it",- "status_in_progress": "In progress",- "error_title": "We couldn't set that up",- "error_body": "The runtime guide didn't get created. You can try again, or connect a runtime from the Runtimes page whenever you're ready.",- "retry": "Try again",- "dismiss": "Not now",- "cards": {- "install_runtime": {- "title": "Connect a runtime",- "subtitle": "Install Codex or Kimi, then start the guided Mika chat from Runtimes."- }- }- }- },"step_workspace": {- "eyebrow_first": "Your first workspace",- "eyebrow_resume": "Pick up or start fresh","headline_first": "Name your workspace.","headline_resume": "Continue with {{name}}, or start another.","lede_first": "A workspace is where your issues, agents, and projects live. You can invite teammates or spin up more workspaces later.",@@ -186,11 +161,9 @@"slug_reserved_error": "That workspace URL is reserved and cannot be used.","slug_conflict_toast": "Choose a different workspace URL","create_failed_toast": "Failed to create workspace",- "creation_disabled_eyebrow": "Workspace creation is disabled","creation_disabled_headline": "Ask your administrator for an invitation.","creation_disabled_lede": "This Multica instance does not allow new workspaces to be created. Once an administrator invites you to a workspace, accept the invitation and refresh to continue.","creation_disabled_logout": "Log out",- "creation_disabled_eyebrow_resume": "Your workspace","creation_disabled_headline_resume": "Continue with {{name}}.","creation_disabled_lede_resume": "Workspace creation is disabled on this instance, so you'll continue into your existing workspace."},@@ -204,8 +177,6 @@"status_all_online": "all online","status_none_online": "none online","status_n_online": "{{count}} online",- "online_label": "online",- "offline_label": "offline","empty_headline": "No agent runtime found on this computer yet.","empty_lede_prefix": "An agent runtime is an AI coding tool we connect to — like ","empty_lede_suffix": ". Install one and refresh, or pick a path below.",@@ -224,7 +195,6 @@"continue": "Start with Mika"},"step_platform": {- "eyebrow": "Connect a computer","headline": "Connect a computer to run your agent.","lede": "Connect a computer so Mika can start working.","hint_default": "You can connect later.",@@ -239,7 +209,6 @@"cloud_action": "Coming soon","cli_dialog_title": "Connect from the terminal","cli_dialog_pick_hint": "Pick a computer above.",- "cli_dialog_connect": "Connect & continue","runtimes_connected_one": "{{count}} computer connected","runtimes_connected_other": "{{count}} computers connected","live_listening": "Live · Waiting for your computer",@@ -255,6 +224,7 @@},"errors": {"skip_failed": "Failed to finish onboarding",+ "guide_failed": "The runtime guide didn't get created. Please try again.","mika_setup_failed": "Couldn't start your Mika workspace"},"mika_intro": {diff --git a/packages/views/locales/fr/onboarding.json b/packages/views/locales/fr/onboarding.jsonindex 5684e8e41d..b51671476f 100644--- a/packages/views/locales/fr/onboarding.json+++ b/packages/views/locales/fr/onboarding.json@@ -106,10 +106,6 @@"other_placeholder": "ex. coordination d'un groupe d'étude"}},- "option_card": {- "other_label": "Autre",- "other_aria": "Décrire autre chose"- },"step_question": {"hint_pick": "Vous pouvez passer cette étape."},@@ -135,28 +131,7 @@"success_toast": "Vous êtes sur la liste. Nous vous écrirons dès que les runtimes cloud seront actifs.","failed_toast": "Échec de l'inscription à la liste d'attente"},- "welcome_after_onboarding": {- "skip": {- "loading": "Configuration de votre espace de travail…",- "title": "Bienvenue sur Multica !",- "subtitle": "Nous avons ajouté une tâche pour vous aider à connecter un runtime. Une fois prêt, commencez avec Mika depuis Runtimes.",- "got_it": "Compris",- "status_in_progress": "En cours",- "error_title": "Nous n'avons pas pu mettre cela en place",- "error_body": "Le guide de runtime n'a pas été créé. Vous pouvez réessayer, ou connecter un runtime depuis la page Runtimes quand vous le souhaitez.",- "retry": "Réessayer",- "dismiss": "Pas maintenant",- "cards": {- "install_runtime": {- "title": "Connecter un runtime",- "subtitle": "Installez Codex ou Kimi, puis démarrez la discussion guidée avec Mika depuis Runtimes."- }- }- }- },"step_workspace": {- "eyebrow_first": "Votre premier espace de travail",- "eyebrow_resume": "Reprendre ou repartir de zéro","headline_first": "Nommez votre espace de travail.","headline_resume": "Continuez avec {{name}}, ou créez-en un autre.","lede_first": "Un espace de travail réunit vos tâches, vos agents et vos projets. Vous pourrez inviter des coéquipiers ou en créer d'autres plus tard.",@@ -186,11 +161,9 @@"slug_reserved_error": "Cette URL d'espace de travail est réservée et ne peut pas être utilisée.","slug_conflict_toast": "Choisissez une autre URL d'espace de travail","create_failed_toast": "Échec de la création de l'espace de travail",- "creation_disabled_eyebrow": "La création d'espaces de travail est désactivée","creation_disabled_headline": "Demandez une invitation à votre administrateur.","creation_disabled_lede": "Cette instance Multica n'autorise pas la création de nouveaux espaces de travail. Dès qu'un administrateur vous invite, acceptez l'invitation et actualisez pour continuer.","creation_disabled_logout": "Se déconnecter",- "creation_disabled_eyebrow_resume": "Votre espace de travail","creation_disabled_headline_resume": "Continuez avec {{name}}.","creation_disabled_lede_resume": "La création d'espaces de travail est désactivée sur cette instance : vous continuerez donc dans votre espace existant."},@@ -204,8 +177,6 @@"status_all_online": "tous en ligne","status_none_online": "aucun en ligne","status_n_online": "{{count}} en ligne",- "online_label": "en ligne",- "offline_label": "hors ligne","empty_headline": "Aucun runtime d'agent trouvé sur cet ordinateur pour l'instant.","empty_lede_prefix": "Un runtime d'agent est un outil de codage IA auquel nous nous connectons — comme ","empty_lede_suffix": ". Installez-en un et actualisez, ou choisissez une option ci-dessous.",@@ -224,7 +195,6 @@"continue": "Commencer avec Mika"},"step_platform": {- "eyebrow": "Connecter un ordinateur","headline": "Connectez un ordinateur pour exécuter votre agent.","lede": "Connectez un ordinateur pour que Mika puisse travailler.","hint_default": "Vous pouvez vous connecter plus tard.",@@ -239,7 +209,6 @@"cloud_action": "Bientôt disponible","cli_dialog_title": "Connecter depuis le terminal","cli_dialog_pick_hint": "Choisissez un ordinateur ci-dessus.",- "cli_dialog_connect": "Connecter et continuer","runtimes_connected_one": "{{count}} ordinateur connecté","runtimes_connected_other": "{{count}} ordinateurs connectés","live_listening": "En direct · En attente de votre ordinateur",@@ -255,6 +224,7 @@},"errors": {"skip_failed": "Échec de la finalisation de la prise en main",+ "guide_failed": "Le guide de runtime n'a pas été créé. Veuillez réessayer.","mika_setup_failed": "Impossible de démarrer votre espace de travail Mika"},"mika_intro": {diff --git a/packages/views/locales/ja/onboarding.json b/packages/views/locales/ja/onboarding.jsonindex 8234d1adf9..2d834cf2b8 100644--- a/packages/views/locales/ja/onboarding.json+++ b/packages/views/locales/ja/onboarding.json@@ -106,10 +106,6 @@"other_placeholder": "例: スタディグループの運営"}},- "option_card": {- "other_label": "その他",- "other_aria": "別の内容を入力"- },"step_question": {"hint_pick": "スキップできます。"},@@ -135,28 +131,7 @@"success_toast": "ウェイトリストに登録しました。クラウドランタイムが利用可能になったらメールでお知らせします。","failed_toast": "ウェイトリストに登録できませんでした"},- "welcome_after_onboarding": {- "skip": {- "loading": "ワークスペースを準備中…",- "title": "Multica へようこそ!",- "subtitle": "ランタイム接続を案内するタスクを 1 つ追加しました。準備できたら Runtimes から Mika と始められます。",- "got_it": "了解",- "status_in_progress": "進行中",- "error_title": "準備できませんでした",- "error_body": "ランタイム案内のタスクを作成できませんでした。再試行するか、準備ができたら Runtimes からランタイムを接続してください。",- "retry": "再試行",- "dismiss": "後で",- "cards": {- "install_runtime": {- "title": "ランタイムを接続",- "subtitle": "Codex または Kimi をインストールし、Runtimes から Mika の案内チャットを始めてください。"- }- }- }- },"step_workspace": {- "eyebrow_first": "最初のワークスペース",- "eyebrow_resume": "続きから、または新規作成","headline_first": "ワークスペースに名前を付けましょう。","headline_resume": "{{name}} で続けるか、別のワークスペースを始めましょう。","lede_first": "ワークスペースは、タスク、エージェント、プロジェクトが集まる場所です。あとでチームメイトを招待したり、ワークスペースを増やしたりできます。",@@ -186,11 +161,9 @@"slug_reserved_error": "そのワークスペース URL は予約済みのため使用できません。","slug_conflict_toast": "別のワークスペース URL を選んでください","create_failed_toast": "ワークスペースを作成できませんでした",- "creation_disabled_eyebrow": "ワークスペースの作成は無効です","creation_disabled_headline": "管理者に招待を依頼してください。","creation_disabled_lede": "この Multica インスタンスでは新しいワークスペースを作成できません。管理者からワークスペースに招待されたら、招待を承諾して更新し、続けてください。","creation_disabled_logout": "ログアウト",- "creation_disabled_eyebrow_resume": "あなたのワークスペース","creation_disabled_headline_resume": "{{name}} で続けましょう。","creation_disabled_lede_resume": "このインスタンスではワークスペースの作成が無効になっているため、既存のワークスペースへ続けて移動します。"},@@ -203,8 +176,6 @@"status_all_online": "すべてオンライン","status_none_online": "オンラインなし","status_n_online": "{{count}} 個オンライン",- "online_label": "オンライン",- "offline_label": "オフライン","empty_headline": "このコンピュータではまだエージェントランタイムが見つかりません。","empty_lede_prefix": "エージェントランタイムとは、私たちが接続する AI コーディングツールです — たとえば ","empty_lede_suffix": " など。1 つインストールして更新するか、下から進む方法を選んでください。",@@ -223,7 +194,6 @@"continue": "Mika と始める"},"step_platform": {- "eyebrow": "コンピュータを接続","headline": "エージェントを実行するコンピュータを接続しましょう。","lede": "コンピュータに接続して Mika を使い始めましょう。","hint_default": "後から接続できます。",@@ -238,7 +208,6 @@"cloud_action": "近日公開","cli_dialog_title": "ターミナルから接続","cli_dialog_pick_hint": "上でコンピュータを選んでください。",- "cli_dialog_connect": "接続して続ける","runtimes_connected_other": "コンピュータ {{count}} 台を接続済み","live_listening": "ライブ · あなたのコンピュータを待っています","stage_normal_prefix": "上のコマンドを実行してください。 ",@@ -253,6 +222,7 @@},"errors": {"skip_failed": "オンボーディングを完了できませんでした",+ "guide_failed": "ランタイム案内のタスクを作成できませんでした。もう一度お試しください。","mika_setup_failed": "Mika ワークスペースを開始できませんでした"},"mika_intro": {diff --git a/packages/views/locales/ko/onboarding.json b/packages/views/locales/ko/onboarding.jsonindex a002b3fb1e..46930adf74 100644--- a/packages/views/locales/ko/onboarding.json+++ b/packages/views/locales/ko/onboarding.json@@ -106,10 +106,6 @@"other_placeholder": "예: 스터디 그룹 운영"}},- "option_card": {- "other_label": "기타",- "other_aria": "다른 내용 입력"- },"step_question": {"hint_pick": "건너뛸 수 있습니다."},@@ -135,28 +131,7 @@"success_toast": "대기자 명단에 등록했습니다. 클라우드 런타임이 준비되면 이메일로 알려드릴게요.","failed_toast": "대기자 명단에 등록하지 못했습니다"},- "welcome_after_onboarding": {- "skip": {- "loading": "워크스페이스 설정 중...",- "title": "Multica에 오신 것을 환영합니다!",- "subtitle": "런타임 연결을 돕는 태스크 하나를 추가했습니다. 준비되면 Runtimes에서 Mika와 시작하세요.",- "got_it": "알겠습니다",- "status_in_progress": "진행 중",- "error_title": "준비하지 못했습니다",- "error_body": "런타임 안내 태스크를 만들지 못했습니다. 다시 시도하거나, 준비되면 Runtimes에서 런타임을 연결하세요.",- "retry": "다시 시도",- "dismiss": "나중에",- "cards": {- "install_runtime": {- "title": "런타임 연결",- "subtitle": "Codex 또는 Kimi를 설치한 뒤 Runtimes에서 Mika 안내 채팅을 시작하세요."- }- }- }- },"step_workspace": {- "eyebrow_first": "첫 워크스페이스",- "eyebrow_resume": "이어 하거나 새로 시작","headline_first": "워크스페이스 이름을 정하세요.","headline_resume": "{{name}}에서 계속하거나 새로 시작하세요.","lede_first": "워크스페이스는 태스크, 에이전트, 프로젝트가 모이는 곳입니다. 나중에 팀원을 초대하거나 워크스페이스를 더 만들 수 있습니다.",@@ -186,11 +161,9 @@"slug_reserved_error": "예약된 워크스페이스 URL이라 사용할 수 없습니다.","slug_conflict_toast": "다른 워크스페이스 URL을 선택하세요","create_failed_toast": "워크스페이스를 만들지 못했습니다",- "creation_disabled_eyebrow": "워크스페이스 생성이 비활성화되었습니다","creation_disabled_headline": "관리자에게 초대를 요청하세요.","creation_disabled_lede": "이 Multica instance에서는 새 워크스페이스를 만들 수 없습니다. 관리자가 기존 워크스페이스로 초대하면 초대를 수락한 뒤 새로고침해 계속하세요.","creation_disabled_logout": "로그아웃",- "creation_disabled_eyebrow_resume": "내 워크스페이스","creation_disabled_headline_resume": "{{name}}에서 계속하세요.","creation_disabled_lede_resume": "이 instance에서는 워크스페이스 생성이 비활성화되어 있으므로 기존 워크스페이스로 계속 이동합니다."},@@ -203,8 +176,6 @@"status_all_online": "모두 온라인","status_none_online": "온라인 없음","status_n_online": "{{count}}개 온라인",- "online_label": "온라인",- "offline_label": "오프라인","empty_headline": "아직 이 컴퓨터에서 에이전트 런타임을 찾지 못했습니다.","empty_lede_prefix": "에이전트 런타임은 우리가 연결하는 AI 코딩 도구입니다. 예: ","empty_lede_suffix": ". 하나 설치하고 새로고침하거나 아래 경로를 선택하세요.",@@ -223,7 +194,6 @@"continue": "Mika와 시작"},"step_platform": {- "eyebrow": "컴퓨터 연결","headline": "에이전트를 실행할 컴퓨터를 연결하세요.","lede": "컴퓨터를 연결해 Mika가 작업을 시작하게 하세요.","hint_default": "나중에 연결할 수 있습니다.",@@ -238,7 +208,6 @@"cloud_action": "준비 중","cli_dialog_title": "터미널에서 연결","cli_dialog_pick_hint": "위에서 컴퓨터를 선택하세요.",- "cli_dialog_connect": "연결하고 계속","runtimes_connected_other": "컴퓨터 {{count}}대 연결됨","live_listening": "실시간 · 컴퓨터를 기다리는 중","stage_normal_prefix": "위 명령을 실행하세요. ",@@ -253,6 +222,7 @@},"errors": {"skip_failed": "온보딩을 마치지 못했습니다",+ "guide_failed": "런타임 안내 태스크를 만들지 못했습니다. 다시 시도해 주세요.","mika_setup_failed": "Mika 워크스페이스를 시작하지 못했습니다"},"mika_intro": {diff --git a/packages/views/locales/zh-Hans/onboarding.json b/packages/views/locales/zh-Hans/onboarding.jsonindex 3a86e0b267..fea2e903d3 100644--- a/packages/views/locales/zh-Hans/onboarding.json+++ b/packages/views/locales/zh-Hans/onboarding.json@@ -106,10 +106,6 @@"other_placeholder": "例如:协调学习小组"}},- "option_card": {- "other_label": "其他",- "other_aria": "描述其他选项"- },"step_question": {"hint_pick": "可跳过。"},@@ -135,28 +131,7 @@"success_toast": "已加入候补名单。云运行时上线时会通过邮件通知你。","failed_toast": "加入候补名单失败"},- "welcome_after_onboarding": {- "skip": {- "loading": "正在为你准备工作区...",- "title": "欢迎来到 Multica!",- "subtitle": "我们建了一个任务帮你连接运行时。准备好后,在 \"运行时\" 页面就能开始使用 Mika。",- "got_it": "知道了",- "status_in_progress": "进行中",- "error_title": "没能帮你准备好",- "error_body": "运行时引导任务没有创建成功。可以重试,也可以随时在\"运行时\"页面自己连接。",- "retry": "重试",- "dismiss": "暂不",- "cards": {- "install_runtime": {- "title": "连接一个运行时",- "subtitle": "安装 Codex 或 Kimi,然后从 \"运行时\" 页面进入 Mika 的引导对话。"- }- }- }- },"step_workspace": {- "eyebrow_first": "你的第一个工作区",- "eyebrow_resume": "继续,或重新开始","headline_first": "给工作区起个名字。","headline_resume": "继续 {{name}},或新建一个。","lede_first": "工作区是任务、智能体和项目所在的地方。之后可以邀请同事,或再开一个工作区。",@@ -186,11 +161,9 @@"slug_reserved_error": "该工作区 URL 是系统保留的,无法使用。","slug_conflict_toast": "请换一个工作区 URL","create_failed_toast": "创建工作区失败",- "creation_disabled_eyebrow": "工作区创建已禁用","creation_disabled_headline": "请联系管理员邀请你加入工作区。","creation_disabled_lede": "该 Multica 实例不允许创建新的工作区。等管理员把你邀请到某个工作区后,接受邀请并刷新即可继续。","creation_disabled_logout": "退出登录",- "creation_disabled_eyebrow_resume": "你的工作区","creation_disabled_headline_resume": "继续使用 {{name}}。","creation_disabled_lede_resume": "该实例已禁用创建工作区,继续进入你已有的工作区即可。"},@@ -203,8 +176,6 @@"status_all_online": "全部在线","status_none_online": "全部离线","status_n_online": "{{count}} 个在线",- "online_label": "在线",- "offline_label": "离线","empty_headline": "这台电脑上还没有可用的智能体运行时。","empty_lede_prefix": "智能体运行时就是我们要连接的 AI 编程工具,比如 ","empty_lede_suffix": "。装好任意一个后点刷新,或从下面选择一种方式。",@@ -223,7 +194,6 @@"continue": "开始使用 Mika"},"step_platform": {- "eyebrow": "连接一台电脑","headline": "连接一台电脑来运行你的智能体。","lede": "连接一台电脑,让 Mika 开始工作。","hint_default": "可稍后连接。",@@ -238,7 +208,6 @@"cloud_action": "即将推出","cli_dialog_title": "通过终端连接","cli_dialog_pick_hint": "在上方选一台电脑。",- "cli_dialog_connect": "连接并继续","runtimes_connected_other": "已连接 {{count}} 台电脑","live_listening": "实时 · 正在等待你的电脑","stage_normal_prefix": "运行上面的命令。当 ",@@ -253,6 +222,7 @@},"errors": {"skip_failed": "完成上手引导失败",+ "guide_failed": "运行时引导任务没有创建成功,请重试。","mika_setup_failed": "无法启动 Mika 工作区"},"mika_intro": {diff --git a/packages/views/onboarding/components/option-card.tsx b/packages/views/onboarding/components/option-card.tsxindex 9cd255f5ea..a5078e32ef 100644--- a/packages/views/onboarding/components/option-card.tsx+++ b/packages/views/onboarding/components/option-card.tsx@@ -1,109 +1,6 @@"use client";-import { Input } from "@multica/ui/components/ui/input";import { cn } from "@multica/ui/lib/utils";-import { useT } from "../../i18n";--const OTHER_INPUT_MAX_LENGTH = 80;--/**- * Editorial radio-style option row used in the Step 1 questionnaire.- *- * Design reference: onboarding(3) `.opt` — thin border resting, and on- * select: filled inset ring + radio marker turns into a filled dot.- * Enter/Space select; full row is the hit target. ARIA radio inside a- * containing `<fieldset role="radiogroup">` in StepQuestionnaire.- */-export function OptionCard({- selected,- onSelect,- label,-}: {- selected: boolean;- onSelect: () => void;- label: string;-}) {- return (- <button- type="button"- role="radio"- aria-checked={selected}- onClick={onSelect}- className={cn(- "group flex w-full items-center gap-3.5 rounded-lg border bg-card px-4 py-2.5 text-left transition-all",- selected- ? "border-foreground shadow-[inset_0_0_0_1px_var(--color-foreground)]"- : "hover:border-foreground/20 hover:bg-accent/30",- )}- >- <RadioMark selected={selected} />- <span className="text-body font-normal leading-tight text-foreground">- {label}- </span>- </button>- );-}--/**- * "Other" variant — reveals an 80-char text input below the row once- * selected. Auto-focus on first open saves the user a click.- *- * Clearing `otherValue` when the user picks a sibling option is the- * parent questionnaire's job; this component stays focus-stable while- * the user is mid-typing.- */-export function OtherOptionCard({- selected,- onSelect,- otherValue,- onOtherChange,- placeholder,-}: {- selected: boolean;- onSelect: () => void;- otherValue: string;- onOtherChange: (value: string) => void;- placeholder: string;-}) {- const { t } = useT("onboarding");- return (- <div- className={cn(- "flex w-full flex-col rounded-lg border bg-card transition-all",- selected- ? "border-foreground shadow-[inset_0_0_0_1px_var(--color-foreground)]"- : "hover:border-foreground/20",- )}- >- <button- type="button"- role="radio"- aria-checked={selected}- onClick={onSelect}- className="flex w-full items-center gap-3.5 px-4 py-2.5 text-left"- >- <RadioMark selected={selected} />- <span className="text-body font-normal leading-tight text-foreground">- {t(($) => $.option_card.other_label)}- </span>- </button>- {selected && (- <div className="px-4 pb-3 pl-[44px]">- <Input- autoFocus- type="text"- value={otherValue}- onChange={(e) => onOtherChange(e.target.value)}- placeholder={placeholder}- maxLength={OTHER_INPUT_MAX_LENGTH}- className="h-8 rounded-none border-x-0 border-t-0 border-b px-0 text-body shadow-none focus-visible:border-foreground focus-visible:ring-0"- aria-label={placeholder}- />- </div>- )}- </div>- );-}export function RadioMark({ selected }: { selected: boolean }) {return (@@ -120,5 +17,3 @@ export function RadioMark({ selected }: { selected: boolean }) {</span>);}--export { OTHER_INPUT_MAX_LENGTH };diff --git a/packages/views/onboarding/onboarding-flow-skip.test.tsx b/packages/views/onboarding/onboarding-flow-skip.test.tsxnew file mode 100644index 0000000000..817849b5c7--- /dev/null+++ b/packages/views/onboarding/onboarding-flow-skip.test.tsx@@ -0,0 +1,263 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { ApiError } from "@multica/core/api";+import { I18nProvider } from "@multica/core/i18n/react";+import enCommon from "../locales/en/common.json";+import enOnboarding from "../locales/en/onboarding.json";+import enWorkspace from "../locales/en/workspace.json";++const TEST_RESOURCES = {+ en: { common: enCommon, onboarding: enOnboarding, workspace: enWorkspace },+};++const { mockCreateIssue, mockCompleteOnboarding, mockToastError } = vi.hoisted(+ () => ({+ mockCreateIssue: vi.fn(),+ mockCompleteOnboarding: vi.fn(),+ mockToastError: vi.fn(),+ }),+);++vi.mock("sonner", () => ({ toast: { error: mockToastError } }));++vi.mock("../auth", () => ({ useLogout: () => vi.fn() }));++vi.mock("@multica/core/api", async () => {+ const actual = await vi.importActual<Record<string, unknown>>(+ "@multica/core/api",+ );+ return {+ ...actual,+ api: {+ getBaseUrl: () => "https://multica.ai",+ createIssue: (...args: unknown[]) => mockCreateIssue(...args),+ },+ };+});++vi.mock("@multica/core/auth", () => ({+ useAuthStore: Object.assign(+ (selector: (s: { user: unknown }) => unknown) =>+ selector({ user: { id: "u-1", onboarding_questionnaire: {} } }),+ { getState: () => ({ user: { id: "u-1" } }) },+ ),+}));++vi.mock("@multica/core/workspace", () => ({+ useWorkspaceList: () => ({ workspaces: [], ready: true }),+}));++vi.mock("@multica/core/onboarding", async () => {+ const actual = await vi.importActual<Record<string, unknown>>(+ "@multica/core/onboarding",+ );+ return {+ ...actual,+ completeOnboarding: (...args: unknown[]) => mockCompleteOnboarding(...args),+ useBootstrapMika: () => ({ mutateAsync: vi.fn() }),+ };+});++const NEW_WORKSPACE = { id: "ws-new", slug: "new-ws", name: "New" };++vi.mock("./steps/step-workspace", () => ({+ StepWorkspace: ({ onCreated }: { onCreated: (ws: unknown) => void }) => (+ <button type="button" onClick={() => onCreated(NEW_WORKSPACE)}>+ create workspace+ </button>+ ),+}));++vi.mock("./steps/step-runtime-connect", () => ({+ StepRuntimeConnect: ({+ onNext,+ }: {+ onNext: (rt: null) => Promise<void>;+ }) => (+ <button type="button" onClick={() => void onNext(null)}>+ skip runtime+ </button>+ ),+}));++import { OnboardingFlow } from "./onboarding-flow";++function renderAtRuntimeStep() {+ const onComplete = vi.fn();+ render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <OnboardingFlow+ mode="new_workspace"+ onCancel={vi.fn()}+ onComplete={onComplete}+ />+ </I18nProvider>,+ );+ fireEvent.click(screen.getByRole("button", { name: "create workspace" }));+ return { onComplete, skip: screen.getByRole("button", { name: "skip runtime" }) };+}++function duplicateGuideConflict(body?: unknown) {+ return new ApiError(+ "Active duplicate issue exists",+ 409,+ "Conflict",+ body ?? {+ code: "active_duplicate_issue",+ error: "An active issue with this title already exists",+ issue: {+ id: "issue-existing",+ identifier: "NEW-1",+ title: "Connect a runtime to start with Mika",+ },+ },+ );+}++beforeEach(() => {+ mockCreateIssue.mockReset();+ mockCompleteOnboarding.mockReset();+ mockToastError.mockReset();+});++describe("OnboardingFlow — skipping runtime setup", () => {+ it("creates the guide issue in the new workspace, then opens it", async () => {+ mockCreateIssue.mockResolvedValueOnce({ id: "issue-guide" });+ mockCompleteOnboarding.mockResolvedValueOnce(undefined);+ const { onComplete, skip } = renderAtRuntimeStep();++ fireEvent.click(skip);++ await waitFor(() => {+ expect(onComplete).toHaveBeenCalledWith(NEW_WORKSPACE, {+ kind: "issue",+ issueId: "issue-guide",+ });+ });+ const [body, workspaceSlug] = mockCreateIssue.mock.calls[0]!;+ expect(workspaceSlug).toBe("new-ws");+ expect(body).toMatchObject({+ title: "Connect a runtime to start with Mika",+ status: "in_progress",+ assignee_type: "member",+ assignee_id: "u-1",+ });+ expect(mockCompleteOnboarding).toHaveBeenCalledWith(+ "runtime_skipped",+ "ws-new",+ );+ // Completing onboarding refreshes the user, and the web shell unmounts the+ // flow as soon as it is marked onboarded — so the guide must exist first.+ expect(mockCreateIssue.mock.invocationCallOrder[0]).toBeLessThan(+ mockCompleteOnboarding.mock.invocationCallOrder[0]!,+ );+ });++ it("stays on the step when the guide cannot be created", async () => {+ mockCreateIssue+ .mockRejectedValueOnce(new Error("network down"))+ .mockResolvedValueOnce({ id: "issue-guide" });+ mockCompleteOnboarding.mockResolvedValue(undefined);+ const { onComplete, skip } = renderAtRuntimeStep();++ fireEvent.click(skip);+ await waitFor(() => expect(mockToastError).toHaveBeenCalledOnce());+ expect(mockCompleteOnboarding).not.toHaveBeenCalled();+ expect(onComplete).not.toHaveBeenCalled();++ fireEvent.click(skip);+ await waitFor(() => {+ expect(onComplete).toHaveBeenCalledWith(NEW_WORKSPACE, {+ kind: "issue",+ issueId: "issue-guide",+ });+ });+ });++ it("reuses the guide issue when only completing onboarding failed", async () => {+ mockCreateIssue.mockResolvedValueOnce({ id: "issue-guide" });+ mockCompleteOnboarding+ .mockRejectedValueOnce(new Error("network down"))+ .mockResolvedValueOnce(undefined);+ const { onComplete, skip } = renderAtRuntimeStep();++ fireEvent.click(skip);+ await waitFor(() => expect(mockToastError).toHaveBeenCalledOnce());+ expect(onComplete).not.toHaveBeenCalled();++ fireEvent.click(skip);+ await waitFor(() => {+ expect(onComplete).toHaveBeenCalledWith(NEW_WORKSPACE, {+ kind: "issue",+ issueId: "issue-guide",+ });+ });+ expect(mockCreateIssue).toHaveBeenCalledTimes(1);+ });++ // A reload drops the in-memory guide id while onboarding is still+ // incomplete, so the next Skip hits the server's duplicate guard.+ it("opens the existing guide after a reload between creating it and completing onboarding", async () => {+ mockCreateIssue+ .mockResolvedValueOnce({ id: "issue-existing" })+ .mockRejectedValueOnce(duplicateGuideConflict());+ mockCompleteOnboarding+ .mockRejectedValueOnce(new Error("network down"))+ .mockResolvedValueOnce(undefined);++ const first = renderAtRuntimeStep();+ fireEvent.click(first.skip);+ await waitFor(() => expect(mockToastError).toHaveBeenCalledOnce());+ cleanup();++ const reloaded = renderAtRuntimeStep();+ fireEvent.click(reloaded.skip);+ await waitFor(() => {+ expect(reloaded.onComplete).toHaveBeenCalledWith(NEW_WORKSPACE, {+ kind: "issue",+ issueId: "issue-existing",+ });+ });+ expect(mockCompleteOnboarding).toHaveBeenCalledTimes(2);+ expect(mockToastError).toHaveBeenCalledOnce();+ });++ it("opens the existing guide when the create response was lost", async () => {+ mockCreateIssue+ .mockRejectedValueOnce(new TypeError("Failed to fetch"))+ .mockRejectedValueOnce(duplicateGuideConflict());+ mockCompleteOnboarding.mockResolvedValue(undefined);+ const { onComplete, skip } = renderAtRuntimeStep();++ fireEvent.click(skip);+ await waitFor(() => expect(mockToastError).toHaveBeenCalledOnce());+ expect(mockCompleteOnboarding).not.toHaveBeenCalled();++ fireEvent.click(skip);+ await waitFor(() => {+ expect(onComplete).toHaveBeenCalledWith(NEW_WORKSPACE, {+ kind: "issue",+ issueId: "issue-existing",+ });+ });+ });++ it("does not treat a 409 without a valid duplicate body as the guide", async () => {+ mockCreateIssue.mockRejectedValueOnce(+ duplicateGuideConflict({ code: "active_duplicate_issue" }),+ );+ const { onComplete, skip } = renderAtRuntimeStep();++ fireEvent.click(skip);++ await waitFor(() => expect(mockToastError).toHaveBeenCalledOnce());+ expect(mockCompleteOnboarding).not.toHaveBeenCalled();+ expect(onComplete).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/onboarding/onboarding-flow.tsx b/packages/views/onboarding/onboarding-flow.tsxindex cc43950ab6..e536aaa1d9 100644--- a/packages/views/onboarding/onboarding-flow.tsx+++ b/packages/views/onboarding/onboarding-flow.tsx@@ -1,14 +1,20 @@"use client";-import { useCallback, useState } from "react";+import { useCallback, useRef, useState } from "react";import { toast } from "sonner";+import {+ api,+ ApiError,+ DuplicateIssueErrorBodySchema,+ type DuplicateIssueErrorBody,+ parseWithFallback,+} from "@multica/core/api";import { useAuthStore } from "@multica/core/auth";import {completeOnboarding,ONBOARDING_STEP_ORDER,saveQuestionnaire,useBootstrapMika,- useWelcomeStore,type OnboardingStep,type QuestionnaireAnswers,} from "@multica/core/onboarding";@@ -21,7 +27,12 @@ import { StepWorkspace } from "./steps/step-workspace";import { StepRuntimeConnect } from "./steps/step-runtime-connect";import { StepPlatformFork } from "./steps/step-platform-fork";import { OnboardingLogoutButton } from "./components/onboarding-logout-button";-import { getMikaOnboarding, pickContentLang } from "./templates";+import {+ getMikaOnboarding,+ INSTALL_RUNTIME_ISSUE_BODY,+ INSTALL_RUNTIME_ISSUE_TITLE,+ pickContentLang,+} from "./templates";import { useT } from "../i18n";const EMPTY_QUESTIONNAIRE: QuestionnaireAnswers = {@@ -82,21 +93,23 @@ function mergeQuestionnaire(/*** Shell's onComplete contract carries the workspace plus an optional* destination. Runtime-connected onboarding opens the real Mika conversation- * started by the final step; other exits land on the workspace issue list.+ * started by the final step; runtime-skipped onboarding opens the guide issue+ * it created; the Welcome skip lands on the workspace issue list.** Three exit shapes feed onComplete:* - Skip-existing (Welcome): completeOnboarding marks onboarded; navigate* to the existing workspace's issue list.- * - Runtime-skipped (no runtime on Step 3): completeOnboarding marks- * onboarded; we push a {choice:"skip"} welcome signal and navigate- * to the workspace. The welcome hook in the workspace shell creates- * one install-runtime guide issue on landing.+ * - Runtime-skipped (no runtime on Step 3): create one install-runtime guide+ * issue assigned to the member, mark onboarding complete, and open that+ * issue. Once a runtime appears, the Runtimes page offers the same Mika+ * bootstrap used by the connected path.* - Runtime-connected: create or repair the workspace's Mika on the selected* runtime, start one hidden onboarding kickoff, mark onboarding complete,* and open Mika's real chat. No fixed specialist team is created.*- * This file never touches createAgent / createIssue. The runtime-skipped- * guide flow remains in `packages/views/workspace/welcome-after-onboarding.tsx`.+ * Both workspace-provisioning exits finish their writes BEFORE+ * completeOnboarding: it refreshes the user, and the web shell unmounts this+ * flow and redirects as soon as `onboarded_at` is set.*/interface OnboardingFlowProps {onComplete: (@@ -124,11 +137,7 @@ interface OnboardingFlowProps {runtimesPending?: boolean;}-export function OnboardingFlow(props: OnboardingFlowProps) {- return <OnboardingStepFlow {...props} />;-}--function OnboardingStepFlow({+export function OnboardingFlow({onComplete,mode = "first_run",onCancel,@@ -158,6 +167,11 @@ function OnboardingStepFlow({// rail. Only the workspace step sets it today.const [stepBusy, setStepBusy] = useState(false);const bootstrapMika = useBootstrapMika(workspace?.id ?? "");+ // Keyed by workspace so retrying Skip after completeOnboarding failed reuses+ // the guide issue instead of creating a second one.+ const guideIssueRef = useRef<{ workspaceId: string; issueId: string } | null>(+ null,+ );// Fetched at Step 0 + Step 2. Step 2 uses it to detect a pre-existing// workspace from an earlier abandoned onboarding (so StepWorkspace shows@@ -286,6 +300,46 @@ function OnboardingStepFlow({}return;}+ let issueId =+ guideIssueRef.current?.workspaceId === workspace.id+ ? guideIssueRef.current.issueId+ : null;+ if (!issueId) {+ const contentLang = pickContentLang(i18n.language);+ try {+ const issue = await api.createIssue(+ {+ title: INSTALL_RUNTIME_ISSUE_TITLE[contentLang],+ description: INSTALL_RUNTIME_ISSUE_BODY[contentLang],+ status: "in_progress",+ priority: "high",+ assignee_type: "member",+ assignee_id: user.id,+ },+ workspace.slug,+ );+ issueId = issue.id;+ } catch (err) {+ // A reload, or a create whose response was lost, leaves the guide+ // from an earlier attempt in place; the duplicate guard then+ // answers with that issue, which is the one to open.+ const duplicate =+ err instanceof ApiError && err.status === 409+ ? parseWithFallback<DuplicateIssueErrorBody | null>(+ err.body,+ DuplicateIssueErrorBodySchema,+ null,+ { endpoint: "POST /api/issues (active_duplicate_issue)" },+ )+ : null;+ if (!duplicate) {+ toast.error(t(($) => $.errors.guide_failed));+ return;+ }+ issueId = duplicate.issue.id;+ }+ guideIssueRef.current = { workspaceId: workspace.id, issueId };+ }try {await completeOnboarding("runtime_skipped", workspace.id);} catch (err) {@@ -294,13 +348,9 @@ function OnboardingStepFlow({);return;}- useWelcomeStore.getState().set({- workspaceId: workspace.id,- choice: "skip",- });- onComplete(workspace, undefined);+ onComplete(workspace, { kind: "issue", issueId });},- [answers, bootstrapMika, i18n.language, workspace, onComplete, t],+ [answers, bootstrapMika, i18n.language, workspace, onComplete, t, user.id],);const handleBack = useCallback((from: OnboardingStep) => {@@ -328,7 +378,7 @@ function OnboardingStepFlow({// reach the workspace step, whose own back button means "leave" — and// leaving there would strand a workspace with no runtime, no Mika, and no// guidance. The remaining exits both end somewhere coherent: Skip runs the- // runtime-skipped path (guide issue + land in the new workspace), and+ // runtime-skipped path (create the guide issue and open it), and// continuing provisions Mika.// Log out lives at the foot of the progress rail rather than pinned to the// window corner: pinned put it outside the measure and above Back, whichdiff --git a/packages/views/onboarding/steps/step-platform-fork.tsx b/packages/views/onboarding/steps/step-platform-fork.tsxindex 666c969255..0a76fd3ca6 100644--- a/packages/views/onboarding/steps/step-platform-fork.tsx+++ b/packages/views/onboarding/steps/step-platform-fork.tsx@@ -72,6 +72,7 @@ export function StepPlatformFork({const [dialog, setDialog] = useState<DialogState>(null);const [connecting, setConnecting] = useState(false);+ const [skipping, setSkipping] = useState(false);const [model, setModel] = useState("");const picker = useRuntimePicker(wsId, wsSlug);@@ -100,6 +101,16 @@ export function StepPlatformFork({}};+ const handleSkip = async () => {+ if (skipping) return;+ setSkipping(true);+ try {+ await onNext(null);+ } finally {+ setSkipping(false);+ }+ };+const footerHint = t(($) => $.step_platform.hint_default);return (@@ -140,8 +151,10 @@ export function StepPlatformFork({<Buttonvariant="ghost"className="w-full"- onClick={() => onNext(null)}+ disabled={skipping}+ onClick={handleSkip}>+ {skipping && <Loader2 className="h-4 w-4 animate-spin" />}{t(($) => $.step_runtime.skip)}</Button></StepFooter>diff --git a/packages/views/onboarding/steps/step-runtime-connect.tsx b/packages/views/onboarding/steps/step-runtime-connect.tsxindex 97e25d630b..4bc84c1026 100644--- a/packages/views/onboarding/steps/step-runtime-connect.tsx+++ b/packages/views/onboarding/steps/step-runtime-connect.tsx@@ -165,6 +165,7 @@ function FancyView({const onlineCount = runtimes.filter((r) => r.status === "online").length;const [submitting, setSubmitting] = useState(false);+ const [skipping, setSkipping] = useState(false);const [model, setModel] = useState("");const [refreshing, setRefreshing] = useState(false);@@ -191,10 +192,12 @@ function FancyView({const handleSkip = async () => {if (submitting) return;setSubmitting(true);+ setSkipping(true);try {await onNext(null);} finally {setSubmitting(false);+ setSkipping(false);}};// Starting with Mika only makes sense when a runtime is selected.@@ -249,6 +252,7 @@ function FancyView({{phase === "empty" && (<EmptyViewonSkip={handleSkip}+ skipping={skipping}onRefresh={handleRefresh}refreshing={refreshing}/>@@ -271,7 +275,9 @@ function FancyView({disabled={!canContinue || submitting}onClick={handleContinue}>- {submitting && <Loader2 className="h-4 w-4 animate-spin" />}+ {submitting && !skipping && (+ <Loader2 className="h-4 w-4 animate-spin" />+ )}{t(($) => $.step_runtime.continue)}</Button>)}@@ -282,6 +288,7 @@ function FancyView({disabled={submitting}onClick={handleSkip}>+ {skipping && <Loader2 className="h-4 w-4 animate-spin" />}{t(($) => $.step_runtime.skip)}</Button>)}@@ -393,10 +400,12 @@ function FoundView({function EmptyView({onSkip,+ skipping,onRefresh,refreshing,}: {onSkip: () => void;+ skipping: boolean;onRefresh: () => void;refreshing: boolean;}) {@@ -430,6 +439,7 @@ function EmptyView({subtitle={t(($) => $.step_runtime.empty_skip_subtitle)}actionLabel={t(($) => $.step_runtime.empty_skip_action)}onAction={onSkip}+ busy={skipping}/><ComingSoonCard@@ -518,17 +528,21 @@ function EmptyCard({subtitle,actionLabel,onAction,+ busy,}: {title: string;subtitle: string;actionLabel: string;onAction: () => void;+ busy: boolean;}) {return (<buttontype="button"onClick={onAction}- className="group flex items-center justify-between gap-4 rounded-lg border bg-card px-5 py-4 text-left transition-colors hover:border-foreground/30 hover:bg-muted/30"+ disabled={busy}+ aria-busy={busy}+ className="group flex items-center justify-between gap-4 rounded-lg border bg-card px-5 py-4 text-left transition-colors hover:border-foreground/30 hover:bg-muted/30 disabled:pointer-events-none"><div className="min-w-0"><div className="text-body font-medium text-foreground">{title}</div>@@ -541,7 +555,11 @@ function EmptyCard({className="inline-flex shrink-0 items-center gap-1.5 rounded-full border bg-background px-4 py-2 text-label font-medium text-foreground transition-colors group-hover:border-foreground group-hover:bg-foreground group-hover:text-background">{actionLabel}- <ArrowRight className="h-3.5 w-3.5" />+ {busy ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <ArrowRight className="h-3.5 w-3.5" />+ )}</span></button>);diff --git a/packages/views/onboarding/templates/install-runtime-issue.ts b/packages/views/onboarding/templates/install-runtime-issue.tsindex 76ca57d87e..91eea11f3f 100644--- a/packages/views/onboarding/templates/install-runtime-issue.ts+++ b/packages/views/onboarding/templates/install-runtime-issue.ts@@ -1,14 +1,10 @@/*** Skip path: "Connect a runtime to start with Mika".*- * Written to a new issue (assigned to the user themselves) by the welcome- * hook when the user took the Skip exit on Step 3. Content is the- * install-runtime tutorial; each supported locale can recommend the+ * Written to a new issue (assigned to the user themselves) by OnboardingFlow+ * when the user takes the Skip exit on Step 3, which then opens it. Content+ * is the install-runtime tutorial; each supported locale can recommend the* quickest runtime path that best fits that audience.- *- * Title is stable — kept identical to the v2 server-side- * `NoRuntimeIssueTitle` so any existing dedupe code elsewhere keeps- * matching by title.*//**diff --git a/packages/views/package.json b/packages/views/package.jsonindex 865d0f73e0..633af494f3 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -40,7 +40,6 @@"./squads/components": "./squads/components/index.ts","./workspace/workspace-avatar": "./workspace/workspace-avatar.tsx","./workspace/no-access-page": "./workspace/no-access-page.tsx",- "./workspace/welcome-after-onboarding": "./workspace/welcome-after-onboarding.tsx","./workspace/use-workspace-seen": "./workspace/use-workspace-seen.ts","./layout": "./layout/index.ts","./layout/route-icon-components": "./layout/route-icon-components.tsx",diff --git a/packages/views/workspace/welcome-after-onboarding.test.tsx b/packages/views/workspace/welcome-after-onboarding.test.tsxdeleted file mode 100644index 21e07c8325..0000000000--- a/packages/views/workspace/welcome-after-onboarding.test.tsx+++ /dev/null@@ -1,215 +0,0 @@-import type { ReactNode } from "react";-import { beforeEach, describe, expect, it, vi } from "vitest";-import { fireEvent, render, screen, waitFor } from "@testing-library/react";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { I18nProvider } from "@multica/core/i18n/react";-import { useWelcomeStore } from "@multica/core/onboarding";-import enCommon from "../locales/en/common.json";-import enOnboarding from "../locales/en/onboarding.json";-import {- NavigationProvider,- type NavigationAdapter,-} from "../navigation";-import { WelcomeAfterOnboarding } from "./welcome-after-onboarding";--const mockUser = {- id: "user-1",- name: "Test",- email: "[email protected]",- avatar_url: null,- onboarded_at: "2026-01-01T00:00:00Z",- onboarding_questionnaire: {},- starter_content_state: null,- language: null,- profile_description: "",- created_at: "",- updated_at: "",-};--vi.mock("@multica/core/auth", () => ({- useAuthStore: Object.assign(- (selector?: (state: { user: typeof mockUser }) => unknown) => {- const state = { user: mockUser };- return selector ? selector(state) : state;- },- { getState: () => ({ user: mockUser }) },- ),- registerAuthStore: vi.fn(),- createAuthStore: vi.fn(),-}));--const mockCreateIssue = vi.fn();-const mockGetWorkspace = vi.fn();--vi.mock("@multica/core/paths", async () => {- const actual = await vi.importActual<typeof import("@multica/core/paths")>(- "@multica/core/paths",- );- return {- ...actual,- useCurrentWorkspace: () => ({- id: "ws-1",- slug: "test-ws",- name: "Test WS",- }),- };-});--vi.mock("@multica/core/api", () => ({- api: {- createIssue: (...args: unknown[]) => mockCreateIssue(...args),- getWorkspace: (...args: unknown[]) => mockGetWorkspace(...args),- },-}));--const mockPush = vi.fn();-const navigationAdapter: NavigationAdapter = {- push: (path: string) => mockPush(path),- replace: vi.fn(),- back: vi.fn(),- pathname: "/test",- searchParams: new URLSearchParams(),- hash: "",- getShareableUrl: (path: string) => `https://test.local${path}`,-};--function TestProviders({ children }: { children: ReactNode }) {- const queryClient = new QueryClient({- defaultOptions: { queries: { retry: false } },- });- queryClient.setQueryData(- ["workspaces", "list"],- [{ id: "ws-1", slug: "test-ws" }],- );-- return (- <QueryClientProvider client={queryClient}>- <I18nProvider- locale="en"- resources={{- en: { common: enCommon, onboarding: enOnboarding },- }}- >- <NavigationProvider value={navigationAdapter}>- {children}- </NavigationProvider>- </I18nProvider>- </QueryClientProvider>- );-}--function renderWelcome() {- return render(<WelcomeAfterOnboarding />, { wrapper: TestProviders });-}--beforeEach(() => {- mockCreateIssue.mockReset();- mockGetWorkspace.mockReset();- mockPush.mockReset();- useWelcomeStore.getState().reset();-});--describe("WelcomeAfterOnboarding", () => {- it("renders nothing when no skip signal is present", () => {- const { container } = renderWelcome();- expect(container.firstChild).toBeNull();- expect(mockCreateIssue).not.toHaveBeenCalled();- });-- it("does not seed issues for a different workspace", () => {- useWelcomeStore.getState().set({- workspaceId: "ws-2",- choice: "skip",- });-- const { container } = renderWelcome();- expect(container.firstChild).toBeNull();- expect(mockCreateIssue).not.toHaveBeenCalled();- });-- it("provisions the no-runtime guide, then opens the completion modal", async () => {- mockCreateIssue.mockResolvedValueOnce({- id: "issue-install",- identifier: "MUL-1",- workspace_id: "ws-1",- });- useWelcomeStore.getState().set({- workspaceId: "ws-1",- choice: "skip",- });-- renderWelcome();-- expect(screen.getByText(/Setting up your workspace/i)).toBeInTheDocument();- await waitFor(() => {- expect(screen.getByText(/Welcome to Multica/i)).toBeInTheDocument();- });-- expect(mockCreateIssue).toHaveBeenCalledTimes(1);- expect(mockCreateIssue.mock.calls[0]![0]).toMatchObject({- title: "Connect a runtime to start with Mika",- status: "in_progress",- assignee_type: "member",- assignee_id: "user-1",- });- expect(mockCreateIssue.mock.calls[0]![0].description).toContain(- "Start with Mika",- );-- fireEvent.click(screen.getByRole("button", { name: /got it/i }));- await waitFor(() => {- expect(mockPush).toHaveBeenCalledWith("/test-ws/issues/issue-install");- });- });-- // The surface is one-shot and the signal is not persisted, so dismissing on- // failure used to be terminal: no guide issue, no message, nothing to- // reload. A failure has to stay on screen and offer a way forward.- it("offers a retry instead of dismissing when guide provisioning fails", async () => {- mockCreateIssue.mockRejectedValueOnce(new Error("network down"));- useWelcomeStore.getState().set({- workspaceId: "ws-1",- choice: "skip",- });-- renderWelcome();-- expect(- await screen.findByRole("button", { name: /try again/i }),- ).toBeInTheDocument();- expect(useWelcomeStore.getState().dismissed).toBe(false);- });-- it("provisions the guide issue when the member retries", async () => {- mockCreateIssue- .mockRejectedValueOnce(new Error("network down"))- .mockResolvedValueOnce({ id: "issue-install", workspace_id: "ws-1" });- useWelcomeStore.getState().set({- workspaceId: "ws-1",- choice: "skip",- });-- renderWelcome();-- fireEvent.click(await screen.findByRole("button", { name: /try again/i }));-- expect(await screen.findByText(/Welcome to Multica/i)).toBeInTheDocument();- expect(mockCreateIssue).toHaveBeenCalledTimes(2);- });-- it("dismisses only when the member chooses to", async () => {- mockCreateIssue.mockRejectedValueOnce(new Error("network down"));- useWelcomeStore.getState().set({- workspaceId: "ws-1",- choice: "skip",- });-- renderWelcome();-- fireEvent.click(await screen.findByRole("button", { name: /not now/i }));-- await waitFor(() => {- expect(useWelcomeStore.getState().dismissed).toBe(true);- });- });-});diff --git a/packages/views/workspace/welcome-after-onboarding.tsx b/packages/views/workspace/welcome-after-onboarding.tsxdeleted file mode 100644index b8932a393a..0000000000--- a/packages/views/workspace/welcome-after-onboarding.tsx+++ /dev/null@@ -1,297 +0,0 @@-"use client";--import { useEffect, useState } from "react";-import { useQueryClient } from "@tanstack/react-query";-import { Loader2 } from "lucide-react";-import { api } from "@multica/core/api";-import { useAuthStore } from "@multica/core/auth";-import { issueKeys } from "@multica/core/issues/queries";-import { useWelcomeStore } from "@multica/core/onboarding";-import { paths, useCurrentWorkspace } from "@multica/core/paths";-import type { CreateIssueRequest, Issue } from "@multica/core/types";-import { workspaceKeys } from "@multica/core/workspace/queries";-import { Button } from "@multica/ui/components/ui/button";-import {- Dialog,- DialogContent,- DialogDescription,- DialogTitle,-} from "@multica/ui/components/ui/dialog";-import { useT } from "../i18n";-import { useNavigation } from "../navigation";-import {- INSTALL_RUNTIME_ISSUE_BODY,- INSTALL_RUNTIME_ISSUE_TITLE,- pickContentLang,-} from "../onboarding/templates";--/**- * One-shot welcome experience for users who explicitly skipped runtime- * setup during onboarding.- *- * Runtime-connected onboarding creates Mika before entering the workspace- * and therefore never writes this no-runtime signal.- */-export function WelcomeAfterOnboarding() {- const me = useAuthStore((state) => state.user);- const currentWorkspace = useCurrentWorkspace();- const signal = useWelcomeStore((state) => state.signal);- const dismissed = useWelcomeStore((state) => state.dismissed);- const dismiss = useWelcomeStore((state) => state.dismiss);-- // The store is global while this component is workspace-scoped. Wait- // until the matching workspace is visible before seeding guide issues.- if (- !me ||- !signal ||- dismissed ||- !currentWorkspace ||- currentWorkspace.id !== signal.workspaceId- ) {- return null;- }-- return (- <SkipWelcome- workspaceId={signal.workspaceId}- onDismiss={dismiss}- />- );-}--/**- * Module-level dedupe keeps React StrictMode double-mounts from racing- * identical issue or comment creation requests.- */-const pendingIssueSeed = new Map<string, Promise<Issue>>();--function seedIssueDeduped(- cacheKey: string,- body: CreateIssueRequest,-): Promise<Issue> {- const existing = pendingIssueSeed.get(cacheKey);- if (existing) return existing;-- const promise = api.createIssue(body);- pendingIssueSeed.set(cacheKey, promise);- promise- .finally(() => {- if (pendingIssueSeed.get(cacheKey) === promise) {- pendingIssueSeed.delete(cacheKey);- }- })- .catch(() => {});- return promise;-}--interface SkipBundle {- installIssueId: string;-}--interface SkipWelcomeProps {- workspaceId: string;- onDismiss: () => void;-}--/**- * Provision one focused runtime guide before showing the completion modal.- * Once a runtime appears, the Runtimes page offers "Start with Mika" and- * runs the same real bootstrap used by connected onboarding.- */-function SkipWelcome({ workspaceId, onDismiss }: SkipWelcomeProps) {- const { t, i18n } = useT("onboarding");- const navigation = useNavigation();- const queryClient = useQueryClient();- const me = useAuthStore((state) => state.user);-- const [bundle, setBundle] = useState<SkipBundle | null>(null);- const [failed, setFailed] = useState(false);-- useEffect(() => {- if (!me || bundle || failed) return;-- let cancelled = false;- void (async () => {- try {- const lang = pickContentLang(i18n.language);- const installRuntime = await seedIssueDeduped(- `${workspaceId}:install-runtime`,- {- title: INSTALL_RUNTIME_ISSUE_TITLE[lang],- description: INSTALL_RUNTIME_ISSUE_BODY[lang],- status: "in_progress",- priority: "high",- assignee_type: "member",- assignee_id: me.id,- },- );- void queryClient.invalidateQueries({- queryKey: issueKeys.all(workspaceId),- });- if (!cancelled) {- setBundle({ installIssueId: installRuntime.id });- }- } catch {- if (!cancelled) setFailed(true);- }- })();-- return () => {- cancelled = true;- };- }, [bundle, failed, i18n.language, me, queryClient, workspaceId]);-- if (!me) return null;-- // A failure used to dismiss the surface silently. Nothing recovered it: the- // welcome signal is deliberately not persisted, onboarding is already marked- // complete, and seedIssueDeduped's cache is one in-flight promise — so a- // blip left the member with no guide issue, no message, and no way back.- // Retry re-runs the effect (the `failed` guard is what gates it), and- // dismissing is now a choice rather than the default.- if (failed) {- return (- <Dialog- open={true}- modal={true}- onOpenChange={(open) => {- if (!open) onDismiss();- }}- >- <DialogContent className="max-w-md sm:max-w-md">- <DialogTitle className="text-title font-semibold">- {t(($) => $.welcome_after_onboarding.skip.error_title)}- </DialogTitle>- <DialogDescription className="text-body text-muted-foreground">- {t(($) => $.welcome_after_onboarding.skip.error_body)}- </DialogDescription>- <div className="mt-6 flex justify-end gap-2">- <Button variant="ghost" onClick={onDismiss}>- {t(($) => $.welcome_after_onboarding.skip.dismiss)}- </Button>- <Button onClick={() => setFailed(false)}>- {t(($) => $.welcome_after_onboarding.skip.retry)}- </Button>- </div>- </DialogContent>- </Dialog>- );- }-- if (!bundle) {- return (- <FullScreenLoading- label={t(($) => $.welcome_after_onboarding.skip.loading)}- />- );- }-- const handleGotIt = async () => {- onDismiss();- const slug = await resolveWorkspaceSlug(queryClient, workspaceId);- navigation.push(paths.workspace(slug).issueDetail(bundle.installIssueId));- };-- return (- <Dialog- open={true}- modal={true}- onOpenChange={(open) => {- if (!open) onDismiss();- }}- >- <DialogContent- className="max-w-xl sm:max-w-xl"- aria-describedby="welcome-after-onboarding-skip-subtitle"- >- <div className="flex flex-col items-center gap-4 pt-6">- <div className="text-6xl animate-welcome-emoji-pop" aria-hidden>- 🎉- </div>- <DialogTitle className="text-center text-display-sm font-semibold">- {t(($) => $.welcome_after_onboarding.skip.title)}- </DialogTitle>- <DialogDescription- id="welcome-after-onboarding-skip-subtitle"- className="text-center text-body text-muted-foreground max-w-md"- >- {t(($) => $.welcome_after_onboarding.skip.subtitle)}- </DialogDescription>- </div>-- <div className="mt-6 flex flex-col gap-2">- <SkipPreviewCard- cardKey="install_runtime"- statusLabel={t(- ($) => $.welcome_after_onboarding.skip.status_in_progress,- )}- />- </div>-- <div className="mt-6 flex justify-end">- <Button size="lg" onClick={handleGotIt}>- {t(($) => $.welcome_after_onboarding.skip.got_it)}- </Button>- </div>- </DialogContent>- </Dialog>- );-}--function SkipPreviewCard({- cardKey,- statusLabel,-}: {- cardKey: "install_runtime";- statusLabel: string;-}) {- const { t } = useT("onboarding");-- return (- <div className="flex items-start gap-3 rounded-lg border bg-background px-3 py-2.5">- <div className="flex-1 min-w-0">- <div className="flex flex-wrap items-center gap-2">- <p className="text-body font-medium leading-tight">- {t(($) => $.welcome_after_onboarding.skip.cards[cardKey].title)}- </p>- <span- className="rounded-full bg-primary/10 px-2 py-0.5 text-micro font-medium text-primary"- >- {statusLabel}- </span>- </div>- <p className="mt-1 text-caption text-muted-foreground leading-snug">- {t(($) => $.welcome_after_onboarding.skip.cards[cardKey].subtitle)}- </p>- </div>- </div>- );-}--function FullScreenLoading({ label }: { label: string }) {- return (- <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm">- <div className="flex flex-col items-center gap-3">- <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />- <p className="text-body text-muted-foreground">{label}</p>- </div>- </div>- );-}--async function resolveWorkspaceSlug(- queryClient: ReturnType<typeof useQueryClient>,- workspaceId: string,-): Promise<string> {- const cached = queryClient- .getQueriesData<{ id: string; slug: string }[] | undefined>({- queryKey: workspaceKeys.list(),- })- .map(([, data]) => data)- .find(Boolean);- const hit = cached?.find((workspace) => workspace.id === workspaceId);- if (hit) return hit.slug;-- const workspace = await api.getWorkspace(workspaceId);- return workspace.slug;-}