All files / src/onboarding wizard-webview-provider.ts

81.13% Statements 499/615
64.23% Branches 88/137
75.86% Functions 22/29
81.13% Lines 499/615

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 7331x 1x 1x 1x             1x   1x         1x           1x         1x 1x 1x     1x 1x     1x 1x 1x   1x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x   41x 41x 41x 41x 41x 41x 41x 41x 41x                           41x 41x   41x 41x 41x     41x 41x                                                                                                   41x               41x 41x 41x 41x 41x 41x   41x 43x 1x 1x 1x   42x 42x 42x 43x 43x 43x 43x 43x   43x 43x 43x 43x 43x 43x   43x 43x 43x 43x 43x 43x 43x 43x 43x 43x   43x 43x 43x 43x   43x 52x 43x   43x 3x 2x 2x 2x 2x 2x 2x 3x 43x 43x   41x 52x 52x 9x 9x 52x     52x 18x 18x 52x 4x 4x 52x     52x 14x 1x 14x 13x 13x     14x 52x 3x 3x 52x         52x     52x 1x 1x 52x 2x 2x 1x 1x 1x 2x 52x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 52x   52x 52x   41x 1x 1x 1x 1x 1x 1x 1x 1x   41x 4x 4x 4x 4x 2x 2x 1x 1x 4x 4x 4x 4x 4x 4x     4x 4x   41x 18x 18x 18x 18x 1x 1x 1x 17x 17x 17x 17x 18x 18x 18x 18x 18x   41x 24x 24x 24x   24x 24x 3x 3x 3x   3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 21x 21x 21x 21x 21x 21x 21x 21x 24x 24x 24x 24x   41x 13x 2x 2x     2x 13x 13x   41x 17x     17x   17x 3x 3x 3x   14x 14x 14x 14x 14x 17x                                     17x 3x 3x 3x 2x 1x 3x 3x 1x 1x   2x 3x 3x 2x 1x 1x   3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x             11x 11x 11x 11x 11x   11x 11x 11x 11x 17x 17x 17x 17x 17x 17x 17x 17x 17x   41x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   2x   2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x   41x           9x 9x   41x 9x 9x       9x 9x 9x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x   3x 9x 9x       9x 9x 9x 9x 9x 9x 9x 9x 8x 1x 9x 9x 9x 9x 9x   41x 51x     51x 51x 51x 51x 51x 51x 51x 51x 51x   41x 14x 14x 14x 12x 12x 12x 12x 12x 12x 12x 12x 2x 2x 2x 2x 2x 2x 2x 2x 2x 14x 14x 14x 14x   41x 3x 3x 1x 1x 1x 2x 2x 3x 2x 3x 3x 3x 3x 3x 3x 3x   41x 138x 55x 55x 138x 138x   41x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x   42x 42x       42x   42x 42x 42x       42x     42x 41x   3x 3x 3x             3x 3x 1x 1x 3x     2x 2x 2x 3x           2x 2x           2x 2x 2x 2x   2x 1x 1x 1x 1x 1x 1x     2x   2x 1x 2x   2x 2x                       42x 42x 42x 42x 42x 42x  
import * as crypto from "node:crypto";
import * as path from "node:path";
import * as vscode from "vscode";
import {
    Auth0Service,
    AuthError,
    BackendFault,
    isApiError,
    type AuthConfig,
} from "@dataflint/mcp-server";
import { Logger } from "../logger";
import type { Bullet, WizardTrigger } from "../telemetry-events";
import {
    assertNever,
    ExtensionToWebview,
    WebviewToExtension,
} from "./messages";
import {
    config,
    REMOTE_MCP_URL,
    remoteMcpInstallUri,
    serverUrlForDomain,
} from "../config";
import {
    extractSignedInUser,
    extractSignedInUserFromSecret,
} from "../extract-user-info";
import { OnboardingState } from "./onboarding-state";
import { applyResolved } from "./persona-applier";
import { Persona, PersonaSelection, resolve } from "./persona-resolver";
import { resolveSigninIntent } from "./signin-resolver";
import type { SigninIntent } from "./messages";
import { ReadyRunner } from "./ready-runner";
import { SignInFailed, SignInRunner } from "./sign-in-runner";
import { StickyTenantHint } from "./sticky-hint";
import type { ProbeOutcome, TenantProbeDeps } from "./tenant-probe";
 
const VIEW_TYPE = "dataflintOnboarding";
const PANEL_TITLE = "Welcome to DataFlint";
const SUPPORT_URL = "https://docs.dataflint.io/support";
 
export class WizardWebviewProvider {
    private currentPanel: vscode.WebviewPanel | undefined;
    private wizardRunId: string | undefined;
    private wizardStartTimeMs: number | undefined;
    private openTrigger: WizardTrigger = "manual";
    private hasCompleted: boolean = false;
    private lastSeenBullet: Bullet = "connected";
    private selectedPersona: Persona | undefined;
    private bootstrapAuthConfig: AuthConfig | undefined;
    private readonly signInRunner: SignInRunner;
    private readonly stickyHint: StickyTenantHint;
    private logger = Logger.getInstance();
 
    constructor(
        private readonly context: vscode.ExtensionContext,
        private readonly readyRunner: ReadyRunner,
        private readonly onboardingState: OnboardingState,
        private readonly onCompletionStateChanged?: () => void | Promise<void>,
        private readonly onSignOut?: () => Promise<void>
    ) {
        this.stickyHint = new StickyTenantHint(context.globalState);
        this.signInRunner = new SignInRunner(async (authConfig) => {
            const auth0 = new Auth0Service(openSystemUrl, () => authConfig);
            // Always force a fresh Auth0 login for wizard sign-ins. Two
            // reasons it must be unconditional:
            //   1. Switch-account: handleSignOut() deletes the local auth
            //      secret *before* the user re-signs-in, so we can't use the
            //      secret as a "deliberate re-sign-in" signal. Without
            //      prompt=login Auth0's still-live SSO cookie would silently
            //      re-bind the same account — defeating the switch entirely.
            //   2. Silent SSO re-auth omits the refresh_token, which breaks
            //      the Self fallback in probe routing.
            // On a genuine first sign-in (no SSO cookie) prompt=login is a
            // no-op, so this is safe to apply everywhere.
            return await auth0.authenticate({ prompt: "login" });
        }, this.buildProbeDeps());
    }
 
    private buildProbeDeps(): TenantProbeDeps {
        const env = () => config.getEnvironment();
        const urlFor = (customerDomain: string | null): string =>
            serverUrlForDomain(customerDomain, env());
 
        return {
            probeOne: async ({
                customerDomain,
                accessToken,
            }): Promise<ProbeOutcome> => {
                const url = `${urlFor(customerDomain)}/api/copilot/prompts`;
                this.logger.info(`[probe] GET ${url}`);
                let response: Response;
                try {
                    response = await fetch(url, {
                        headers: { Authorization: `Bearer ${accessToken}` },
                    });
                } catch (cause) {
                    this.logger.warn(
                        `[probe] network error reaching ${url}: ${cause instanceof Error ? cause.message : String(cause)}`
                    );
                    return { ok: false, cause };
                }
                if (response.status === 200) {
                    this.logger.info(`[probe] ${url} → 200`);
                    return { ok: true };
                }
                let body = "";
                try {
                    body = await response.text();
                } catch {
                    // ignore body read errors — treat as bare status
                }
                let errorCode: string | undefined;
                try {
                    const parsed = JSON.parse(body);
                    if (typeof parsed?.error_code === "string") {
                        errorCode = parsed.error_code;
                    }
                } catch {
                    // non-JSON body, no error_code available
                }
                const bodySummary =
                    body.length > 200 ? `${body.slice(0, 200)}…` : body;
                this.logger.warn(
                    `[probe] ${url} → ${response.status}${errorCode ? ` (${errorCode})` : ""} body=${bodySummary || "<empty>"}`
                );
                return {
                    ok: false,
                    errorCode,
                    cause: new Error(
                        `probe ${url} responded ${response.status}${errorCode ? ` (${errorCode})` : ""}`
                    ),
                };
            },
 
            setStickyHint: (tenant) => {
                this.stickyHint.write(tenant).catch((err) => {
                    this.logger.warn(
                        `Failed to persist sticky tenant hint: ${err instanceof Error ? err.message : String(err)}`
                    );
                });
            },
 
            logger: {
                warn: (msg) => this.logger.warn(msg),
                info: (msg) => this.logger.info(msg),
            },
        };
    }
 
    open(opts?: { trigger?: WizardTrigger }): void {
        if (this.currentPanel) {
            this.currentPanel.reveal(vscode.ViewColumn.Active);
            return;
        }
 
        this.wizardRunId = crypto.randomUUID();
        this.wizardStartTimeMs = Date.now();
        this.hasCompleted = false;
        this.openTrigger = opts?.trigger ?? "manual";
        Logger.getInstance().trackEvent("wizard.opened", {
            trigger: this.openTrigger,
            wizard_run_id: this.wizardRunId,
        });
 
        const webviewRoot = vscode.Uri.file(
            path.join(this.context.extensionPath, "out", "webview")
        );
        const resourcesRoot = vscode.Uri.file(
            path.join(this.context.extensionPath, "resources")
        );
 
        this.currentPanel = vscode.window.createWebviewPanel(
            VIEW_TYPE,
            PANEL_TITLE,
            vscode.ViewColumn.Active,
            {
                enableScripts: true,
                retainContextWhenHidden: true,
                localResourceRoots: [webviewRoot, resourcesRoot],
            }
        );
 
        this.currentPanel.webview.html = this.buildHtml(
            this.currentPanel.webview,
            webviewRoot
        );
 
        this.currentPanel.webview.onDidReceiveMessage((message) =>
            this.handleMessage(message)
        );
 
        this.currentPanel.onDidDispose(() => {
            if (!this.hasCompleted) {
                Logger.getInstance().trackEvent("wizard.dismissed", {
                    last_seen_bullet: this.lastSeenBullet,
                    persona: this.selectedPersona ?? "cloud",
                    wizard_run_id: this.wizardRunId ?? "",
                });
            }
            this.currentPanel = undefined;
        });
    }
 
    private async handleMessage(message: WebviewToExtension): Promise<void> {
        switch (message.type) {
            case "ready":
                await this.sendInit();
                return;
            case "log":
                this.logger[message.level](`[wizard] ${message.message}`);
                return;
            case "persona_advance":
                await this.handlePersonaAdvance(message.selection);
                return;
            case "signin_clicked":
                await this.handleSigninClicked(message.intent);
                return;
            case "switch_account":
                await this.handleSignOut();
                return;
            case "bullet_run":
                if (message.bullet === "connected") {
                    await this.runBullet1();
                } else if (message.bullet === "signed_in") {
                    await this.handleSignInRun();
                } else if (message.bullet === "ready_to_assist") {
                    await this.runBullet3();
                }
                return;
            case "done_clicked":
                await this.handleDoneClick();
                return;
            case "show_logs":
                await vscode.commands.executeCommand(
                    "dataflint-copilot.showLogs"
                );
                return;
            case "contact_support":
                await vscode.env.openExternal(vscode.Uri.parse(SUPPORT_URL));
                return;
            case "sign_out":
                await this.handleSignOut();
                return;
            case "copy_mcp_url":
                try {
                    await vscode.env.clipboard.writeText(REMOTE_MCP_URL);
                } catch (error) {
                    this.logger.warn(`Copying the MCP URL failed: ${error}`);
                }
                return;
            case "install_mcp":
                try {
                    const installUri = remoteMcpInstallUri(
                        vscode.env.uriScheme,
                        vscode.version
                    );
                    if (installUri) {
                        await vscode.env.openExternal(
                            vscode.Uri.parse(installUri, true)
                        );
                    }
                } catch (error) {
                    this.logger.warn(`Installing the MCP failed: ${error}`);
                }
                return;
            default:
                return assertNever(message);
        }
    }
 
    private async handleSignOut(): Promise<void> {
        Logger.getInstance().trackEvent("wizard.sign_out_clicked", {
            wizard_run_id: this.wizardRunId ?? "",
        });
        if (this.onSignOut) {
            await this.onSignOut();
        }
        this.post({ type: "signed_out" });
    }
 
    private async handleSigninClicked(intent: SigninIntent): Promise<void> {
        const settings = resolveSigninIntent(intent);
        await applyResolved(settings);
        this.selectedPersona =
            intent.kind === "cloud"
                ? "cloud"
                : intent.kind === "enterprise"
                  ? "enterprise"
                  : "internal_dev";
        Logger.getInstance().trackEvent("wizard.persona_selected", {
            persona: this.selectedPersona,
            wizard_run_id: this.wizardRunId ?? "",
        });
        await this.runBullet1();
        if (!this.bootstrapAuthConfig) {
            return;
        }
        await this.runBullet2();
    }
 
    private async handlePersonaAdvance(
        selection: PersonaSelection
    ): Promise<void> {
        const result = resolve(selection);
        if (!result.ok) {
            this.post({ type: "persona_rejected", error: result.error });
            return;
        }
        await applyResolved(result.resolved);
        this.selectedPersona = selection.persona;
        Logger.getInstance().trackEvent("wizard.persona_selected", {
            persona: selection.persona,
            wizard_run_id: this.wizardRunId ?? "",
        });
        this.post({ type: "persona_accepted" });
        await this.runBullet1();
    }
 
    private async runBullet1(): Promise<void> {
        this.post({ type: "bullet_running", bullet: "connected" });
        let authConfig: AuthConfig;
        try {
            // Force re-fetch — persona may have changed since the last bootstrap.
            authConfig = await config.bootstrapAuth({ force: true });
        } catch (err) {
            const fault =
                err instanceof BackendFault
                    ? err
                    : new BackendFault("unknown", "network", err);
            this.post({
                type: "bullet_failed",
                bullet: "connected",
                error_code: fault.reason,
                message: `Couldn’t reach DataFlint at ${fault.host}. Check your connection and retry.`,
            });
            Logger.getInstance().trackEvent("wizard.check_failed", {
                bullet: "connected",
                error_code: fault.reason,
                persona: this.selectedPersona ?? "cloud",
                wizard_run_id: this.wizardRunId ?? "",
            });
            return;
        }
        this.bootstrapAuthConfig = authConfig;
        this.post({
            type: "bullet_passed",
            bullet: "connected",
            authDomain: authConfig.domain,
        });
        Logger.getInstance().trackEvent("wizard.check_passed", {
            bullet: "connected",
            persona: this.selectedPersona ?? "cloud",
            wizard_run_id: this.wizardRunId ?? "",
        });
    }
 
    private async handleSignInRun(): Promise<void> {
        if (!this.bootstrapAuthConfig) {
            await this.runBullet1();
            if (!this.bootstrapAuthConfig) {
                return; // bootstrap failed, don't cascade to sign-in
            }
        }
        await this.runBullet2();
    }
 
    private async runBullet2(): Promise<void> {
        if (!this.bootstrapAuthConfig) {
            return;
        }
        this.post({ type: "bullet_running", bullet: "signed_in" });
 
        if (this.selectedPersona === "enterprise") {
            await this.runBullet2Enterprise(this.bootstrapAuthConfig);
            return;
        }
 
        let resolution;
        try {
            resolution = await this.signInRunner.signInAndResolveTenant(
                this.bootstrapAuthConfig
            );
        } catch (err) {
            const reason =
                err instanceof SignInFailed ? err.reason : "oauth_failed";
            this.bootstrapAuthConfig = undefined;
            this.post({
                type: "bullet_failed",
                bullet: "signed_in",
                error_code: reason,
                message: "Sign-in didn’t go through. Please try again.",
            });
            Logger.getInstance().trackEvent("wizard.check_failed", {
                bullet: "signed_in",
                error_code: reason,
                persona: this.selectedPersona ?? "cloud",
                wizard_run_id: this.wizardRunId ?? "",
            });
            return;
        }
 
        if (!resolution.ok) {
            this.bootstrapAuthConfig = undefined;
            const errorCode =
                resolution.reason === "not_in_any_tenant"
                    ? "tenant_not_found"
                    : "probe_failed";
            const causeText =
                resolution.reason === "error" && resolution.cause
                    ? resolution.cause instanceof Error
                        ? resolution.cause.message
                        : String(resolution.cause)
                    : undefined;
            const message =
                resolution.reason === "not_in_any_tenant"
                    ? "Your DataFlint account isn’t activated. Visit dataflint.io to finish setup, or pick Enterprise if your company has a private DataFlint instance."
                    : causeText
                      ? `Sign-in completed but the connectivity probe failed: ${causeText}`
                      : "Sign-in didn’t go through. Please try again.";
            this.post({
                type: "bullet_failed",
                bullet: "signed_in",
                error_code: errorCode,
                message,
            });
            Logger.getInstance().trackEvent("wizard.check_failed", {
                bullet: "signed_in",
                error_code: errorCode,
                persona: this.selectedPersona ?? "cloud",
                wizard_run_id: this.wizardRunId ?? "",
            });
            return;
        }
 
        // Order matters: commit customerDomain FIRST so the auth-secret
        // storage key (which is per-customerDomain) reflects the resolved
        // tenant; only then persist the auth. Otherwise the next session
        // would read auth from the new tenant's storage slot and miss the
        // freshly-signed-in token.
        await applyResolved({
            customerDomain: resolution.customerDomain,
            environment: config.getEnvironment(),
        });
        await config.setAuthSecret(JSON.stringify(resolution.auth));
 
        const signedInUser = extractSignedInUser(resolution.auth);
        this.post({
            type: "bullet_passed",
            bullet: "signed_in",
            ...(signedInUser ? { signedInUser } : {}),
        });
        Logger.getInstance().trackEvent("wizard.check_passed", {
            bullet: "signed_in",
            persona: this.selectedPersona ?? "cloud",
            wizard_run_id: this.wizardRunId ?? "",
        });
        await this.runBullet3();
    }
 
    private async runBullet2Enterprise(authConfig: AuthConfig): Promise<void> {
        let auth;
        try {
            auth = await this.signInRunner.signIn(authConfig);
        } catch (err) {
            const reason =
                err instanceof SignInFailed ? err.reason : "oauth_failed";
            this.bootstrapAuthConfig = undefined;
            this.post({
                type: "bullet_failed",
                bullet: "signed_in",
                error_code: reason,
                message: "Sign-in didn’t go through. Please try again.",
            });
            Logger.getInstance().trackEvent("wizard.check_failed", {
                bullet: "signed_in",
                error_code: reason,
                persona: "enterprise",
                wizard_run_id: this.wizardRunId ?? "",
            });
            return;
        }
 
        await config.setAuthSecret(JSON.stringify(auth));
 
        const signedInUser = extractSignedInUser(auth);
        this.post({
            type: "bullet_passed",
            bullet: "signed_in",
            ...(signedInUser ? { signedInUser } : {}),
        });
        Logger.getInstance().trackEvent("wizard.check_passed", {
            bullet: "signed_in",
            persona: "enterprise",
            wizard_run_id: this.wizardRunId ?? "",
        });
        await this.runBullet3();
    }
 
    private async hasLocalAuth(): Promise<boolean> {
        // Lazy gate for the signed-in state: trust the stored auth secret
        // instead of probing the backend. Expiry/refresh is handled by
        // Auth0Service (isTokenExpired) the next time a real request fires,
        // and the Continue button always re-runs the ready check which
        // actually hits the API.
        return (await config.getAuthSecret()) !== undefined;
    }
 
    private async sendInit(): Promise<void> {
        const alreadyConnected = await this.hasLocalAuth();
        let currentConnection;
        // Send currentConnection when connected OR when re-opening due to
        // failed activation — in the latter case the user already has a
        // persona in settings and Page 1 should reflect it.
        const wantInferred =
            alreadyConnected || this.openTrigger === "activation_not_completed";
        if (wantInferred) {
            const inferred = inferPersonaFromSettings(
                config.getCustomerDomain(),
                config.getEnvironment()
            );
            let authDomain: string | undefined;
            let signedInUser;
            if (alreadyConnected) {
                try {
                    authDomain = config.getAuthConfig().domain;
                } catch {
                    authDomain = undefined;
                }
                signedInUser = extractSignedInUserFromSecret(
                    await config.getAuthSecret()
                );
            }
            currentConnection = inferred
                ? { ...inferred, authDomain, signedInUser }
                : undefined;
        }
        this.post({
            type: "init",
            // Show Trial/Internal personas only when running a local
            // extension build (F5 / Extension Development Host). Installed
            // builds never show them, regardless of the environment setting.
            devMode:
                this.context.extensionMode === vscode.ExtensionMode.Development,
            logoUri: this.buildLogoUri(),
            remoteMcpUrl: REMOTE_MCP_URL,
            installEditorName: remoteMcpInstallUri(
                vscode.env.uriScheme,
                vscode.version
            )
                ? vscode.env.appName
                : undefined,
            trigger: this.openTrigger,
            alreadyConnected,
            currentConnection,
        });
    }
 
    private buildLogoUri(): string {
        if (!this.currentPanel) {
            return "";
        }
        const logoPath = vscode.Uri.file(
            path.join(
                this.context.extensionPath,
                "resources",
                "dataflint-logo.svg"
            )
        );
        return this.currentPanel.webview.asWebviewUri(logoPath).toString();
    }
 
    private async runBullet3(): Promise<void> {
        this.post({ type: "bullet_running", bullet: "ready_to_assist" });
        const result = await this.readyRunner.runReadyCheck();
        if (result.ok) {
            this.post({ type: "bullet_passed", bullet: "ready_to_assist" });
            Logger.getInstance().trackEvent("wizard.check_passed", {
                bullet: "ready_to_assist",
                persona: this.selectedPersona ?? "cloud",
                wizard_run_id: this.wizardRunId ?? "",
            });
            return;
        }
        this.post({
            type: "bullet_failed",
            bullet: "ready_to_assist",
            error_code: result.errorCode,
            message: readyFailureMessage(result.errorCode, result.cause),
        });
        Logger.getInstance().trackEvent("wizard.check_failed", {
            bullet: "ready_to_assist",
            error_code: result.errorCode,
            persona: this.selectedPersona ?? "cloud",
            wizard_run_id: this.wizardRunId ?? "",
        });
    }
 
    private async handleDoneClick(): Promise<void> {
        const connected = await this.readyRunner.isConnected();
        if (!connected) {
            await this.runBullet3();
            return;
        }
        await this.onboardingState.markCompleted();
        this.hasCompleted = true;
        await this.onCompletionStateChanged?.();
        Logger.getInstance().trackEvent("wizard.completed", {
            persona: this.selectedPersona ?? "cloud",
            time_to_complete_ms:
                Date.now() - (this.wizardStartTimeMs ?? Date.now()),
            wizard_run_id: this.wizardRunId ?? "",
        });
        this.currentPanel?.dispose();
    }
 
    private post(message: ExtensionToWebview): void {
        if (message.type === "bullet_running") {
            this.lastSeenBullet = message.bullet;
        }
        this.currentPanel?.webview.postMessage(message);
    }
 
    private buildHtml(
        webview: vscode.Webview,
        webviewRoot: vscode.Uri
    ): string {
        const scriptUri = webview.asWebviewUri(
            vscode.Uri.joinPath(webviewRoot, "onboarding.js")
        );
        const styleUri = webview.asWebviewUri(
            vscode.Uri.joinPath(webviewRoot, "onboarding.css")
        );
        const nonce = randomNonce();
        const csp = [
            `default-src 'none'`,
            `style-src ${webview.cspSource} 'unsafe-inline'`,
            `script-src 'nonce-${nonce}'`,
            `img-src ${webview.cspSource} data:`,
            `font-src ${webview.cspSource}`,
        ].join("; ");
 
        const logoUri = this.buildLogoUri();
        return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="${csp}">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preload" as="image" href="${logoUri}" type="image/svg+xml">
    <link rel="stylesheet" href="${styleUri}">
    <title>${PANEL_TITLE}</title>
</head>
<body>
    <div id="root"></div>
    <script nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>`;
    }
}
 
function inferPersonaFromSettings(
    customerDomain: string | null,
    environment: string
):
    | {
          persona: Persona;
          enterpriseCode?: string;
          internalDevSub?: "staging" | "local";
      }
    | undefined {
    if (customerDomain === "self") {
        return { persona: "cloud" };
    }
    if (customerDomain) {
        return { persona: "enterprise", enterpriseCode: customerDomain };
    }
    if (environment === "prod") {
        return { persona: "cloud" };
    }
    if (environment === "staging" || environment === "local") {
        return { persona: "internal_dev", internalDevSub: environment };
    }
    return undefined;
}
 
function readyFailureMessage(
    code:
        | "auth_failed"
        | "not_activated"
        | "probe_failed"
        | "port_in_use"
        | "unknown",
    cause?: unknown
): string {
    switch (code) {
        case "auth_failed":
            return "Sign-in expired. Please sign in again.";
        case "not_activated": {
            const detail = isApiError(cause) ? cause.detail : undefined;
            const suffix =
                " Run “DataFlint: Logout” from the command palette to switch accounts.";
            if (detail) {
                return `${detail}. Ask your DataFlint admin to add you.${suffix}`;
            }
            return `Your DataFlint account isn’t set up. Ask your admin to add you.${suffix}`;
        }
        case "probe_failed":
            return "Couldn’t reach DataFlint. Check your connection and retry.";
        case "port_in_use":
            return "Port is already in use. Try restarting VS Code.";
        case "unknown":
            return "Something went wrong starting DataFlint. Open Logs for details.";
    }
}
 
async function openSystemUrl(url: string): Promise<void> {
    const opened = await vscode.env.openExternal(vscode.Uri.parse(url));
    if (!opened) {
        // The user declined the IDE's "Allow opening URL?" prompt. Signal
        // cancellation so the auth flow stops waiting for the 5-minute
        // OAuth callback instead of leaving the wizard stuck in-progress.
        throw AuthError.cancelled();
    }
}
 
function randomNonce(): string {
    return crypto
        .randomBytes(24)
        .toString("base64")
        .replace(/[^a-zA-Z0-9]/g, "");
}