A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
rebuild first-run onboarding as an inline flow (#2340)
kt83b2d32545d6
diff --git a/packages/coding-agent/.changes/onboarding-inline-first-run.md b/packages/coding-agent/.changes/onboarding-inline-first-run.mdnew file mode 100644index 0000000000..9414c29aa7--- /dev/null+++ b/packages/coding-agent/.changes/onboarding-inline-first-run.md@@ -0,0 +1,7 @@+- Changed the first-run onboarding to a compact block anchored top-left: the brand mark over its animated field, a short description of what Prime Agent does, and a single action to log in with Prime Intellect.+- Changed onboarding to run every step inside that block: the Prime Intellect login, team selection, and the new questions all mount under the mark instead of opening full-pane modals or dropping to the prompt dock.+- Added a provider step after login where several providers can be connected in one pass, with a search field, a scrolling list, and check marks on providers already signed in.+- Added a trace-sharing question at the end of onboarding, which writes the agent traces setting and notes it can be changed later with /traces.+- Changed first launch to run one sequence for everyone: credentials already on disk (a Prime CLI token, an API key in the environment) no longer skip onboarding or divert it to the model picker; they only make the sign-in step instant.+- Changed team selection to be skipped when the account has no team or exactly one, and to list accounts by name with their handle.+- Changed onboarding to stay quiet: provider progress chatter, the credentials-saved status line, and the telemetry notice no longer appear during first launch; the telemetry notice surfaces on the next launch instead.diff --git a/packages/coding-agent/src/core/agent-session-services.ts b/packages/coding-agent/src/core/agent-session-services.tsindex 8da9b04bc0..4ef2512d48 100644--- a/packages/coding-agent/src/core/agent-session-services.ts+++ b/packages/coding-agent/src/core/agent-session-services.ts@@ -42,6 +42,12 @@ export interface CreateAgentSessionServicesOptions {*/noBuiltinHerdrReporter?: boolean;telemetryDisabled?: true;+ /**+ * Hold the telemetry disclosure back on a first interactive launch, where it+ * would land on the onboarding screen. Onboarding marks itself shown, so the+ * notice appears on the next launch; sessions that never onboard disclose now.+ */+ deferTelemetryNoticeForOnboarding?: boolean;}export interface AgentSessionCreationOptions {@@ -186,6 +192,10 @@ export async function createAgentSessionServices(if (!options.telemetryDisabled &&isTelemetryEnabled(settingsManager) &&+ // A first interactive launch belongs to onboarding, where the notice would+ // land on the welcome screen; it surfaces on the next launch once+ // onboarding marks itself shown. Sessions that never onboard disclose now.+ (settingsManager.getOnboardingShown() || !options.deferTelemetryNoticeForOnboarding) &&!settingsManager.getTelemetryNoticeShown()) {diagnostics.push({diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.tsindex 47bddcfb12..61a683f421 100644--- a/packages/coding-agent/src/main.ts+++ b/packages/coding-agent/src/main.ts@@ -817,6 +817,11 @@ async function prepareRuntimeServices(options: {// the parent's and a subagent quit would release the still-active pane.noBuiltinHerdrReporter: (options.sessionOptionsOverride?.rlmDepth ?? 0) > 0,telemetryDisabled: config.telemetryDisabled,+ // Interactive launches hold the notice back for onboarding, which marks+ // itself shown; every other mode discloses immediately. Deriving it from+ // the session config covers the daemon-hosted path too, which creates the+ // session the TUI actually talks to.+ deferTelemetryNoticeForOnboarding: config.executionMode === "interactive",resourceLoaderOptions: {additionalExtensionPaths: config.extensions,additionalSkillPaths: config.skills,diff --git a/packages/coding-agent/src/modes/interactive/auth-flows.ts b/packages/coding-agent/src/modes/interactive/auth-flows.tsindex f3556e1562..6329dfd494 100644--- a/packages/coding-agent/src/modes/interactive/auth-flows.ts+++ b/packages/coding-agent/src/modes/interactive/auth-flows.ts@@ -27,6 +27,7 @@ import {compareAuthSelectorProviders,OAuthSelectorComponent,} from "./components/oauth-selector.js";+import { OnboardingChoiceComponent } from "./components/onboarding-choice.js";import { PrimeTeamSelectorComponent } from "./components/prime-team-selector.js";import { theme } from "./theme/theme.js";@@ -101,9 +102,14 @@ export interface ProviderAuthFlowsHost {* the prompt area. Returns a callback that unmounts the panel and restores* the previous content and focus.*/- showAuthPanel(component: Component): () => void;+ /** `onReset` settles the caller's step when a session reset unmounts the panel. */+ showAuthPanel(component: Component, options?: { heading?: string; onReset?: () => void }): () => void;/** Terminal rows available to auth panels; selectors size their lists to it. */getAuthPanelRows(): number;+ /** True while onboarding owns the screen and supplies its own heading. */+ isOnboardingSurface?(): boolean;+ /** Quits the app from an onboarding panel, where the editor has no focus. */+ exitApp?(): void;/** Models currently visible to the host; used to detect providers configured via external credentials. */getAvailableModels(): Promise<ReadonlyArray<{ provider: string }>>;/** Invoked after stored credentials change so the host can refresh dependent UI. */@@ -138,6 +144,26 @@ export class ProviderAuthFlows {return this.showLoginDialog(providerId, label ?? provider.name, "service");}+ /**+ * Panel chrome for login dialogs. Onboarding renders its own heading above+ * the panel, so it drops both the transcript rule and the panel title.+ */+ private loginDialogOptions(): { topRule: boolean; hideTitle: boolean; onExit?: () => void } {+ const onboarding = this.isOnboarding();+ // While onboarding owns the screen the dialog answers the exit keys+ // itself; the editor that normally owns them has no focus yet.+ return {+ topRule: !onboarding,+ hideTitle: onboarding,+ ...(onboarding ? { onExit: () => this.host.exitApp?.() } : {}),+ };+ }++ /** Onboarding narrates itself; step chatter belongs to the chat surfaces. */+ private isOnboarding(): boolean {+ return this.host.isOnboardingSurface?.() ?? false;+ }+runLogin(options: ProviderLoginOptions = {}): Promise<AuthenticationResult> {const { authType, initialCategory } = options;const providerOptions = this.getLoginProviderOptions(authType);@@ -307,9 +333,11 @@ export class ProviderAuthFlows {const actionLabel = authType === "oauth" ? `Logged in to ${providerName}` : `Saved API key for ${providerName}`;await this.host.onAuthChanged?.();- this.host.showStatus(- `${actionLabel}. Credentials saved to ${credentialPath}${statusSuffix ? `. ${statusSuffix}` : ""}`,- );+ if (!this.isOnboarding()) {+ this.host.showStatus(+ `${actionLabel}. Credentials saved to ${credentialPath}${statusSuffix ? `. ${statusSuffix}` : ""}`,+ );+ }this.host.onLoginCompleted?.();return {status: "success",@@ -341,7 +369,14 @@ export class ProviderAuthFlows {}private async showBedrockSetupDialog(providerId: string, providerName: string): Promise<AuthenticationResult> {- const dialog = new LoginDialogComponent(this.host.ui, providerId, () => {}, providerName, "Amazon Bedrock setup");+ const dialog = new LoginDialogComponent(+ this.host.ui,+ providerId,+ () => {},+ providerName,+ "Amazon Bedrock setup",+ this.loginDialogOptions(),+ );const closeDialog = this.host.showAuthPanel(dialog);try {@@ -372,6 +407,34 @@ export class ProviderAuthFlows {teams: PrimeTeam[],currentTeamId: string | undefined,): Promise<PrimeTeam | null | undefined> {+ if (this.host.isOnboardingSurface?.()) {+ return new Promise((resolve) => {+ let close: (() => void) | undefined;+ const options = [+ { label: "Personal account" },+ ...teams.map((team) => ({ label: team.name, ...(team.slug ? { detail: team.slug } : {}) })),+ ];+ const current = teams.findIndex((team) => team.teamId === currentTeamId);+ const choice = new OnboardingChoiceComponent(+ options,+ (index) => {+ close?.();+ resolve(index === 0 ? null : (teams[index - 1] ?? null));+ },+ () => {+ close?.();+ resolve(undefined);+ },+ {+ prompt: "Which account should Prime Agent use?",+ selectedIndex: current >= 0 ? current + 1 : 0,+ requestRender: () => this.host.ui.requestRender(),+ onExit: () => this.host.exitApp?.(),+ },+ );+ close = this.host.showAuthPanel(choice, { onReset: () => resolve(undefined) });+ });+ }return new Promise((resolve) => {let close: (() => void) | undefined;const selector = new PrimeTeamSelectorComponent(@@ -410,7 +473,9 @@ export class ProviderAuthFlows {return "Using team from PRIME_TEAM_ID.";}- dialog.showProgress("Loading Prime teams...");+ if (!this.isOnboarding()) {+ dialog.showProgress("Loading Prime teams...");+ }const teams = await fetchPrimeTeams(apiKey, resolvePrimeInferenceAuthConfig().baseUrl, {signal: dialog.signal,});@@ -421,6 +486,13 @@ export class ProviderAuthFlows {this.host.modelRegistry.authStorage.setPrimeInferenceTeamSelection(null, apiKey);return "Using personal account.";}+ // A single team is not a choice during onboarding; /login still offers it+ // alongside the personal account so the selection stays reversible.+ if (this.isOnboarding() && teams.length === 1 && teams[0]) {+ const onlyTeam = teams[0];+ this.host.modelRegistry.authStorage.setPrimeInferenceTeamSelection(onlyTeam, apiKey);+ return `Using team "${onlyTeam.name}".`;+ }const storedTeam = this.host.modelRegistry.authStorage.getPrimeInferenceTeamSelection();const currentTeamId = storedTeam === null ? undefined : storedTeam?.teamId;@@ -449,6 +521,11 @@ export class ProviderAuthFlows {const teamStatus = await this.selectPrimeInferenceTeam(apiKey, dialog);closeDialog();+ // A reset unmounts the dialog and aborts its signal: completing now would+ // refresh the registry and notify a session that was already torn down.+ if (dialog.signal.aborted) {+ return { status: "cancelled" };+ }return await this.completeProviderAuthentication(PRIME_INFERENCE_PROVIDER_ID,PRIME_INFERENCE_PROVIDER_NAME,@@ -478,9 +555,11 @@ export class ProviderAuthFlows {PRIME_INFERENCE_PROVIDER_ID,(_success, _message) => {},PRIME_INFERENCE_PROVIDER_NAME,+ undefined,+ this.loginDialogOptions(),);- const closeDialog = this.host.showAuthPanel(dialog);+ const closeDialog = this.host.showAuthPanel(dialog, { heading: "Login with Prime Intellect" });// The browser challenge gets its own controller so a manually pasted key// can stop the polling without tearing down the dialog.@@ -514,7 +593,10 @@ export class ProviderAuthFlows {armManualInput("Complete the sign-in in your browser, or paste an API key below:");},onProgress: (message) => {- dialog.showProgress(message);+ // Onboarding narrates itself; step chatter stays in the chat flows.+ if (!this.isOnboarding()) {+ dialog.showProgress(message);+ }},signal: browserAbort.signal,},@@ -555,7 +637,9 @@ export class ProviderAuthFlows {if (result.source === "manual") {browserAbort.abort();- dialog.showProgress("Checking Prime Inference access...");+ if (!this.isOnboarding()) {+ dialog.showProgress("Checking Prime Inference access...");+ }const access = await checkPrimeInferenceAccess(result.apiKey, resolvePrimeInferenceAuthConfig().baseUrl, {signal: dialog.signal,});@@ -594,6 +678,8 @@ export class ProviderAuthFlows {PRIME_AGENT_TRACES_PROVIDER_ID,(_success, _message) => {},PRIME_AGENT_TRACES_PROVIDER_NAME,+ undefined,+ this.loginDialogOptions(),);const closeDialog = this.host.showAuthPanel(dialog);@@ -628,7 +714,10 @@ export class ProviderAuthFlows {armManualInput("Complete the sign-in in your browser, or paste a Prime API key below:");},onProgress: (message) => {- dialog.showProgress(message);+ // Onboarding narrates itself; step chatter stays in the chat flows.+ if (!this.isOnboarding()) {+ dialog.showProgress(message);+ }},signal: browserAbort.signal,},@@ -695,7 +784,14 @@ export class ProviderAuthFlows {providerName: string,kind: "provider" | "service" = "provider",): Promise<AuthenticationResult> {- const dialog = new LoginDialogComponent(this.host.ui, providerId, (_success, _message) => {}, providerName);+ const dialog = new LoginDialogComponent(+ this.host.ui,+ providerId,+ (_success, _message) => {},+ providerName,+ undefined,+ this.loginDialogOptions(),+ );const closeDialog = this.host.showAuthPanel(dialog);@@ -752,7 +848,14 @@ export class ProviderAuthFlows {const usesCallbackServer = providerInfo?.usesCallbackServer ?? false;- const dialog = new LoginDialogComponent(this.host.ui, providerId, (_success, _message) => {}, providerName);+ const dialog = new LoginDialogComponent(+ this.host.ui,+ providerId,+ (_success, _message) => {},+ providerName,+ undefined,+ this.loginDialogOptions(),+ );const closeDialog = this.host.showAuthPanel(dialog);diff --git a/packages/coding-agent/src/modes/interactive/components/login-dialog.ts b/packages/coding-agent/src/modes/interactive/components/login-dialog.tsindex 55d765a05f..9f19be8a6d 100644--- a/packages/coding-agent/src/modes/interactive/components/login-dialog.ts+++ b/packages/coding-agent/src/modes/interactive/components/login-dialog.ts@@ -16,6 +16,7 @@ import { theme } from "../theme/theme.js";import { formatKeyText, keyHint } from "./keybinding-hints.js";import { MenuPanel, MenuSearchInput } from "./menu-panel.js";import { shouldTreatAsBack } from "./modal-back.js";+import { isOnboardingExitKey } from "./onboarding-exit.js";function isTextEntryKeybinding(key: string): boolean {const parts = key.toLowerCase().split("+");@@ -45,6 +46,7 @@ export class LoginDialogComponent extends Container implements Focusable {private continueRejecter?: (error: Error) => void;private authUrl?: string;private authActions?: Text;+ private inputSpacer?: Spacer;// Focusable implementation - propagate to input for IME cursor positioningprivate _focused = false;@@ -62,6 +64,7 @@ export class LoginDialogComponent extends Container implements Focusable {private onComplete: (success: boolean, message?: string) => void,providerNameOverride?: string,titleOverride?: string,+ private dialogOptions: { topRule?: boolean; hideTitle?: boolean; onExit?: () => void } = {},) {super();this.tui = tui;@@ -71,7 +74,13 @@ export class LoginDialogComponent extends Container implements Focusable {const title = titleOverride ?? `Login to ${providerName}`;// The top rule keeps the inline login section separate from the transcript.- const panel = new MenuPanel({ title, inline: true, topRule: true });+ // Surfaces that own the screen above the panel (onboarding) turn both the+ // rule and the title off: they already say where the user is.+ const panel = new MenuPanel({+ title: this.dialogOptions.hideTitle ? "" : title,+ inline: true,+ topRule: this.dialogOptions.topRule ?? true,+ });this.addChild(panel);// Dynamic content area@@ -79,7 +88,8 @@ export class LoginDialogComponent extends Container implements Focusable {panel.addChild(this.contentContainer);// Input (always present, used when needed)- this.input = new MenuSearchInput("Paste value", true);+ // Plain field: the enclosing rules read as clutter in the login panel.+ this.input = new MenuSearchInput("Paste value", true, true);this.input.onSubmit = () => {if (this.inputResolver) {this.inputResolver(this.input.getValue());@@ -93,6 +103,11 @@ export class LoginDialogComponent extends Container implements Focusable {return this.abortController.signal;}+ /** Cancel from outside the panel, e.g. when a session reset unmounts it. */+ abort(): void {+ this.cancel();+ }+private cancel(): void {this.abortController.abort();if (this.inputRejecter) {@@ -168,6 +183,13 @@ export class LoginDialogComponent extends Container implements Focusable {/** Append the paste field plus the single key-hint line at the panel bottom. */private addInputField(): void {this.contentContainer.removeChild(this.input);+ if (this.inputSpacer) {+ this.contentContainer.removeChild(this.inputSpacer);+ } else {+ // A blank row keeps the key hints off the field. It is retained so a+ // second prompt moves it instead of stacking another blank row.+ this.inputSpacer = new Spacer(1);+ }if (this.authActions) {this.contentContainer.removeChild(this.authActions);} else {@@ -175,6 +197,7 @@ export class LoginDialogComponent extends Container implements Focusable {}this.contentContainer.addChild(this.input);this.inputVisible = true;+ this.contentContainer.addChild(this.inputSpacer);this.contentContainer.addChild(this.authActions);this.authActions.setText(this.getAuthActionsText());}@@ -273,6 +296,7 @@ export class LoginDialogComponent extends Container implements Focusable {this.contentContainer.clear();this.authUrl = undefined;this.authActions = undefined;+ this.inputSpacer = undefined;// The cleared panel no longer shows the paste field.this.inputVisible = false;this.contentContainer.addChild(new Spacer(1));@@ -289,6 +313,8 @@ export class LoginDialogComponent extends Container implements Focusable {private addInstructions(instructions: string): void {const codeMatch = /^(?:Code|Enter code):\s*(.+)$/i.exec(instructions.trim());if (codeMatch?.[1]) {+ // A blank row separates the sign-in link from the code below it.+ this.contentContainer.addChild(new Spacer(1));this.addLabel("Verification code");this.contentContainer.addChild(new Text(theme.bold(theme.fg("text", codeMatch[1])), 0, 0));return;@@ -352,6 +378,13 @@ export class LoginDialogComponent extends Container implements Focusable {handleInput(data: string): void {const kb = getKeybindings();+ // On the onboarding surface the exit keys must quit the app; cancel+ // would drop the user into an unconfigured chat instead.+ if (this.dialogOptions.onExit && isOnboardingExitKey(data)) {+ this.dialogOptions.onExit();+ return;+ }+if (this.authUrl &&kb.matches(data, "app.clipboard.copyLoginUrl") &&diff --git a/packages/coding-agent/src/modes/interactive/components/menu-panel.ts b/packages/coding-agent/src/modes/interactive/components/menu-panel.tsindex f41366b2dc..f3fa15b9d9 100644--- a/packages/coding-agent/src/modes/interactive/components/menu-panel.ts+++ b/packages/coding-agent/src/modes/interactive/components/menu-panel.ts@@ -322,6 +322,10 @@ export class MenuSearchInput implements Component, Focusable, FullWidthMenuCompoconstructor(private readonly placeholder: string,private readonly inline = false,+ /** Inline only: drop the enclosing rules and render just the field. */+ private readonly plain = false,+ /** Drop the "> " prompt for surfaces that mark selection with their own caret. */+ private readonly hidePrompt = false,) {}get focused(): boolean {@@ -358,14 +362,28 @@ export class MenuSearchInput implements Component, Focusable, FullWidthMenuComporender(width: number): string[] {if (this.inline) {- const border = theme.fg("borderMuted", "─".repeat(Math.max(0, width)));let content = this.input.render(Math.max(1, width - 2))[0] ?? "";+ if (this.hidePrompt) {+ content = this.stripInputPrompt(content);+ }if (this.getValue() === "") {- content = this.focused- ? `${content.trimEnd()}${theme.fg("dim", this.placeholder)}`- : `> ${theme.fg("dim", this.placeholder)}`;+ const placeholder = theme.fg("dim", this.placeholder);+ if (this.hidePrompt) {+ // Sit the caret on the first placeholder character so the field keeps+ // the same left edge as the text above it.+ content = this.focused+ ? `\x1b[7m${this.placeholder.slice(0, 1)}\x1b[27m${theme.fg("dim", this.placeholder.slice(1))}`+ : placeholder;+ } else {+ content = this.focused ? `${content.trimEnd()}${placeholder}` : `> ${placeholder}`;+ }}- return [border, truncateToWidth(` ${content}`, width, "", true), border];+ const field = truncateToWidth(` ${content}`, width, "", true);+ if (this.plain) {+ return [field];+ }+ const border = theme.fg("borderMuted", "─".repeat(Math.max(0, width)));+ return [border, field, border];}const safeWidth = Math.max(FIELD_PADDING_X * 2 + 1, width);const innerWidth = Math.max(1, safeWidth - FIELD_PADDING_X * 2);diff --git a/packages/coding-agent/src/modes/interactive/components/onboarding-choice.ts b/packages/coding-agent/src/modes/interactive/components/onboarding-choice.tsnew file mode 100644index 0000000000..ee9d3a7542--- /dev/null+++ b/packages/coding-agent/src/modes/interactive/components/onboarding-choice.ts@@ -0,0 +1,143 @@+import {+ type Component,+ getKeybindings,+ truncateToWidth,+ visibleWidth,+ wrapTextWithAnsi,+} from "@earendil-works/pi-tui";+import { getResolvedThemeColors, theme } from "../theme/theme.js";+import { isOnboardingExitKey } from "./onboarding-exit.js";+import { onboardingHighlightBackground } from "./onboarding-highlight.js";++export interface OnboardingChoiceOption {+ label: string;+ /** Identifier shown after the label, dimmer than the name it belongs to. */+ detail?: string;+}++interface OnboardingChoiceOptions {+ prompt?: string;+ /** Muted sentence under the prompt, before the options. */+ description?: string;+ /** Grey footnote under the list, e.g. how to change the answer later. */+ note?: string;+ rowWidth?: number;+ selectedIndex?: number;+ requestRender?: () => void;+ /** Quits the app while onboarding owns the screen. */+ onExit?: () => void;+}++const MARKER_WIDTH = 2;+const MIN_ROW_WIDTH = 30;+const ROW_TRAILING = 6;+const DESCRIPTION_WIDTH = 50;++/**+ * A question in the onboarding block: a prompt, a list of options in the same+ * selection language as the first-run actions, and an optional grey footnote.+ */+export class OnboardingChoiceComponent implements Component {+ private selectedIndex: number;++ constructor(+ private readonly options: readonly OnboardingChoiceOption[],+ private readonly onSelect: (index: number) => void,+ private readonly onCancel: () => void,+ private readonly config: OnboardingChoiceOptions = {},+ ) {+ this.selectedIndex = Math.max(0, Math.min(config.selectedIndex ?? 0, options.length - 1));+ }++ invalidate(): void {+ // Render output is derived from current theme and selection state.+ }++ handleInput(keyData: string): void {+ if (isOnboardingExitKey(keyData)) {+ this.config.onExit?.();+ return;+ }+ const kb = getKeybindings();+ if (kb.matches(keyData, "tui.select.up")) {+ this.move(-1);+ return;+ }+ if (kb.matches(keyData, "tui.select.down")) {+ this.move(1);+ return;+ }+ if (kb.matches(keyData, "tui.select.confirm")) {+ this.onSelect(this.selectedIndex);+ return;+ }+ if (kb.matches(keyData, "tui.select.cancel")) {+ this.onCancel();+ }+ }++ render(width: number): string[] {+ const safeWidth = Math.max(1, width);+ // Panels carry their own leading blank row and one column of indent, so the+ // host can render every flow panel at the same offset.+ const lines: string[] = [this.line(safeWidth, "")];+ if (this.config.prompt) {+ lines.push(this.line(safeWidth, theme.fg("text", this.config.prompt)));+ lines.push(this.line(safeWidth, ""));+ }+ if (this.config.description) {+ for (const row of wrapTextWithAnsi(+ this.config.description,+ Math.max(1, Math.min(DESCRIPTION_WIDTH, safeWidth - 2)),+ )) {+ lines.push(this.line(safeWidth, theme.fg("muted", row)));+ }+ lines.push(this.line(safeWidth, ""));+ }+ const labelWidth = this.options.reduce(+ (max, option) =>+ Math.max(max, visibleWidth(option.detail ? `${option.label} ${option.detail}` : option.label)),+ 0,+ );+ const rowWidth = Math.min(+ safeWidth,+ this.config.rowWidth ?? Math.max(MIN_ROW_WIDTH, MARKER_WIDTH + labelWidth + ROW_TRAILING),+ );+ const background = onboardingHighlightBackground(getResolvedThemeColors());+ this.options.forEach((option, index) => {+ const selected = index === this.selectedIndex;+ const name = `${selected ? "> " : " "}${option.label}`;+ const detail = this.formatDetail(option);+ const plain = truncateToWidth(`${name}${detail}`, rowWidth, "");+ const pad = " ".repeat(Math.max(0, rowWidth - visibleWidth(plain)));+ // The identifier reads as a subtitle of the name, so it stays dimmer.+ const styled = selected+ ? background(theme.bold(theme.fg("text", name)) + theme.fg("dim", `${detail}${pad}`))+ : theme.fg("muted", name) + theme.fg("dim", `${detail}${pad}`);+ lines.push(this.line(safeWidth, styled));+ });+ if (this.config.note) {+ lines.push(this.line(safeWidth, ""));+ lines.push(this.line(safeWidth, theme.fg("dim", this.config.note)));+ }+ return lines;+ }++ private formatDetail(option: OnboardingChoiceOption): string {+ return option.detail ? ` @${option.detail}` : "";+ }++ private move(delta: number): void {+ const next = this.selectedIndex + delta;+ if (next < 0 || next >= this.options.length) {+ return;+ }+ this.selectedIndex = next;+ this.config.requestRender?.();+ }++ private line(width: number, content: string): string {+ const truncated = truncateToWidth(content ? ` ${content}` : "", width, "");+ return truncated + " ".repeat(Math.max(0, width - visibleWidth(truncated)));+ }+}diff --git a/packages/coding-agent/src/modes/interactive/components/onboarding-exit.ts b/packages/coding-agent/src/modes/interactive/components/onboarding-exit.tsnew file mode 100644index 0000000000..4b200bba1f--- /dev/null+++ b/packages/coding-agent/src/modes/interactive/components/onboarding-exit.ts@@ -0,0 +1,10 @@+import { getKeybindings } from "@earendil-works/pi-tui";++/**+ * Onboarding owns the screen before the editor exists, so its panels answer the+ * exit keys themselves; otherwise Ctrl+C does nothing and the user is trapped.+ */+export function isOnboardingExitKey(keyData: string): boolean {+ const kb = getKeybindings();+ return kb.matches(keyData, "app.clear") || kb.matches(keyData, "app.exit");+}diff --git a/packages/coding-agent/src/modes/interactive/components/onboarding-highlight.ts b/packages/coding-agent/src/modes/interactive/components/onboarding-highlight.tsnew file mode 100644index 0000000000..c90f3e30fb--- /dev/null+++ b/packages/coding-agent/src/modes/interactive/components/onboarding-highlight.ts@@ -0,0 +1,33 @@+import { blendColor, isLightColor, type Rgb, rgbTo256 } from "@earendil-works/pi-tui";+import { theme } from "../theme/theme.js";++/** How far a selected row lifts off the canvas; lower reads more transparent. */+const HIGHLIGHT_LIFT = 0.08;+const DARK_CANVAS: Rgb = { r: 16, g: 16, b: 16 };+const LIGHT_CANVAS: Rgb = { r: 255, g: 255, b: 255 };++function parseHexColor(value: string | undefined): Rgb | undefined {+ const match = /^#?([0-9a-f]{6})$/i.exec(value?.trim() ?? "");+ if (!match?.[1]) {+ return undefined;+ }+ const int = Number.parseInt(match[1], 16);+ return { r: (int >> 16) & 255, g: (int >> 8) & 255, b: int & 255 };+}++/**+ * The selected-row wash shared by every onboarding surface: the canvas lifted a+ * few percent toward the text colour, rather than the picker's solid fill.+ */+export function onboardingHighlightBackground(colors: Record<string, string>): (text: string) => string {+ const text = parseHexColor(colors.text);+ const onDark = !text || isLightColor(text);+ const canvas = parseHexColor(colors.background) ?? (onDark ? DARK_CANVAS : LIGHT_CANVAS);+ const lift: Rgb = onDark ? { r: 255, g: 255, b: 255 } : { r: 0, g: 0, b: 0 };+ const washed = blendColor(lift, canvas, HIGHLIGHT_LIFT);+ const ansi =+ theme.colorMode === "truecolor"+ ? `\x1b[48;2;${washed.r};${washed.g};${washed.b}m`+ : `\x1b[48;5;${rgbTo256(washed)}m`;+ return (value: string) => `${ansi}${value}\x1b[49m`;+}diff --git a/packages/coding-agent/src/modes/interactive/components/onboarding-picker.ts b/packages/coding-agent/src/modes/interactive/components/onboarding-picker.tsnew file mode 100644index 0000000000..03829998f3--- /dev/null+++ b/packages/coding-agent/src/modes/interactive/components/onboarding-picker.ts@@ -0,0 +1,225 @@+import { type Component, type Focusable, getKeybindings, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";+import { getResolvedThemeColors, theme } from "../theme/theme.js";+import { MenuSearchInput } from "./menu-panel.js";+import { isOnboardingExitKey } from "./onboarding-exit.js";+import { onboardingHighlightBackground } from "./onboarding-highlight.js";++export interface OnboardingPickerItem {+ id: string;+ label: string;+ /** Already signed in: the row is marked with a check rather than a note. */+ connected?: boolean;+}++interface OnboardingPickerOptions {+ prompt?: string;+ searchPlaceholder?: string;+ note?: string;+ continueLabel?: string;+ visibleRows?: number;+ rowWidth?: number;+ requestRender?: () => void;+ /** Quits the app while onboarding owns the screen. */+ onExit?: () => void;+}++const MARKER_WIDTH = 2;+const MIN_ROW_WIDTH = 34;+const ROW_TRAILING = 6;+const DEFAULT_VISIBLE_ROWS = 6;++/**+ * A searchable list in the onboarding block: a pinned continue action, then the+ * matching entries in a scrolling viewport. Entries stay selectable repeatedly,+ * so a user can connect several providers before moving on.+ */+export class OnboardingPickerComponent implements Component, Focusable {+ /** The list marks selection with its own caret, so the field hides the prompt. */+ private readonly search: MenuSearchInput;+ private selectedIndex = 0;+ private scrollTop = 0;+ private _focused = false;++ constructor(+ private readonly items: readonly OnboardingPickerItem[],+ private readonly onSelect: (id: string) => void,+ private readonly onContinue: () => void,+ private readonly onCancel: () => void,+ private readonly config: OnboardingPickerOptions = {},+ ) {+ this.search = new MenuSearchInput(config.searchPlaceholder ?? "Search", true, true, true);+ }++ get focused(): boolean {+ return this._focused;+ }++ set focused(value: boolean) {+ this._focused = value;+ this.search.focused = value;+ }++ invalidate(): void {+ this.search.invalidate();+ }++ handleInput(keyData: string): void {+ if (isOnboardingExitKey(keyData)) {+ this.config.onExit?.();+ return;+ }+ const kb = getKeybindings();+ if (kb.matches(keyData, "tui.select.up")) {+ this.move(-1);+ return;+ }+ if (kb.matches(keyData, "tui.select.down")) {+ this.move(1);+ return;+ }+ if (kb.matches(keyData, "tui.select.confirm")) {+ if (this.selectedIndex === 0) {+ this.onContinue();+ return;+ }+ const item = this.getFiltered()[this.selectedIndex - 1];+ if (item) {+ this.onSelect(item.id);+ }+ return;+ }+ if (kb.matches(keyData, "tui.select.cancel")) {+ this.onCancel();+ return;+ }+ this.search.handleInput(keyData);+ this.selectedIndex = Math.min(this.selectedIndex, this.getFiltered().length);+ this.scrollTop = 0;+ this.config.requestRender?.();+ }++ render(width: number): string[] {+ const safeWidth = Math.max(1, width);+ const filtered = this.getFiltered();+ const visibleRows = this.config.visibleRows ?? DEFAULT_VISIBLE_ROWS;+ this.clampScroll(filtered.length, visibleRows);++ const rowWidth = this.getRowWidth(safeWidth);+ const background = onboardingHighlightBackground(getResolvedThemeColors());+ const lines: string[] = [this.line(safeWidth, "")];+ if (this.config.prompt) {+ lines.push(this.line(safeWidth, theme.fg("text", this.config.prompt)));+ lines.push(this.line(safeWidth, ""));+ }+ // The field renders its own single-column indent, matching the prompt above.+ const field = this.search.render(safeWidth)[0] ?? "";+ lines.push(+ truncateToWidth(field, safeWidth, "", true) + " ".repeat(Math.max(0, safeWidth - visibleWidth(field))),+ );+ lines.push(this.line(safeWidth, ""));+ lines.push(+ this.renderRow(+ safeWidth,+ rowWidth,+ this.config.continueLabel ?? "Continue",+ false,+ this.selectedIndex === 0,+ background,+ ),+ );++ const end = Math.min(filtered.length, this.scrollTop + visibleRows);+ for (let index = this.scrollTop; index < end; index++) {+ const item = filtered[index];+ if (!item) continue;+ lines.push(+ this.renderRow(+ safeWidth,+ rowWidth,+ item.label,+ item.connected === true,+ this.selectedIndex === index + 1,+ background,+ ),+ );+ }+ const remaining = filtered.length - end;+ if (remaining > 0 || this.scrollTop > 0) {+ const hint = remaining > 0 ? `${remaining} more below` : "top of list";+ lines.push(this.line(safeWidth, theme.fg("dim", ` ${hint}`)));+ }+ if (this.config.note) {+ lines.push(this.line(safeWidth, ""));+ lines.push(this.line(safeWidth, theme.fg("dim", this.config.note)));+ }+ return lines;+ }++ private renderRow(+ width: number,+ rowWidth: number,+ label: string,+ connected: boolean,+ selected: boolean,+ background: (value: string) => string,+ ): string {+ const name = `${selected ? "> " : " "}${label}`;+ const mark = connected ? " \u2713" : "";+ const pad = " ".repeat(Math.max(0, rowWidth - visibleWidth(truncateToWidth(`${name}${mark}`, rowWidth, ""))));+ const styledMark = connected ? theme.fg("success", " \u2713") : "";+ const styled = selected+ ? background(theme.bold(theme.fg("text", name)) + styledMark + theme.fg("dim", pad))+ : theme.fg("muted", name) + styledMark + theme.fg("dim", pad);+ return this.line(width, styled);+ }++ private getRowWidth(width: number): number {+ const longest = this.items.reduce(+ (max, item) => Math.max(max, visibleWidth(item.label) + (item.connected ? 3 : 0)),+ 0,+ );+ return Math.min(+ Math.max(1, width - 1),+ this.config.rowWidth ?? Math.max(MIN_ROW_WIDTH, MARKER_WIDTH + longest + ROW_TRAILING),+ );+ }++ private getFiltered(): readonly OnboardingPickerItem[] {+ const query = this.search.getValue().trim().toLowerCase();+ if (!query) {+ return this.items;+ }+ return this.items.filter(+ (item) => item.label.toLowerCase().includes(query) || item.id.toLowerCase().includes(query),+ );+ }++ private move(delta: number): void {+ const filtered = this.getFiltered();+ const next = this.selectedIndex + delta;+ if (next < 0 || next > filtered.length) {+ return;+ }+ this.selectedIndex = next;+ const visibleRows = this.config.visibleRows ?? DEFAULT_VISIBLE_ROWS;+ if (next >= 1) {+ const itemIndex = next - 1;+ if (itemIndex < this.scrollTop) {+ this.scrollTop = itemIndex;+ } else if (itemIndex >= this.scrollTop + visibleRows) {+ this.scrollTop = itemIndex - visibleRows + 1;+ }+ }+ this.config.requestRender?.();+ }++ private clampScroll(total: number, visibleRows: number): void {+ const maxScroll = Math.max(0, total - visibleRows);+ this.scrollTop = Math.max(0, Math.min(this.scrollTop, maxScroll));+ }++ private line(width: number, content: string): string {+ const truncated = truncateToWidth(content ? ` ${content}` : "", width, "");+ return truncated + " ".repeat(Math.max(0, width - visibleWidth(truncated)));+ }+}diff --git a/packages/coding-agent/src/modes/interactive/components/prime-onboarding-splash.ts b/packages/coding-agent/src/modes/interactive/components/prime-onboarding-splash.tsindex 5cc7dfe945..de38dbc616 100644--- a/packages/coding-agent/src/modes/interactive/components/prime-onboarding-splash.ts+++ b/packages/coding-agent/src/modes/interactive/components/prime-onboarding-splash.ts@@ -1,20 +1,41 @@-import { type Component, getKeybindings, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";-import { PRIME_BUTTERFLY_LOGO } from "../../../themes/prime-logo.js";-import { type ThemeColor, theme } from "../theme/theme.js";+import {+ type Component,+ getKeybindings,+ truncateToWidth,+ visibleWidth,+ wrapTextWithAnsi,+} from "@earendil-works/pi-tui";+import { PRIME_COMPACT_BUTTERFLY_LOGO } from "../../../themes/prime-logo.js";+import { getResolvedThemeColors, type ThemeColor, theme } from "../theme/theme.js";+import { isOnboardingExitKey } from "./onboarding-exit.js";+import { onboardingHighlightBackground } from "./onboarding-highlight.js";interface PrimeOnboardingSplashOptions {+ /** Terminal rows; the block fills them so the prompt dock stays covered. */getRows?: () => number;requestRender?: () => void;animationIntervalMs?: number;- continueActionLabel?: string;+ /** Quits the app: the editor that normally owns Ctrl+C has no focus yet. */+ onExit?: () => void;}-const LOGO_LINES = PRIME_BUTTERFLY_LOGO.split("\n");+const LOGO_LINES = PRIME_COMPACT_BUTTERFLY_LOGO.split("\n");const LOGO_WIDTH = LOGO_LINES.reduce((max, line) => Math.max(max, visibleWidth(line)), 0);const ANIMATION_INTERVAL_MS = 120;-const LAB_FIELD_HEIGHT = 14;-const LAB_FIELD_MIN_WIDTH = 42;-const LAB_FIELD_MAX_WIDTH = 78;+/** Matches BrandSplashHeader so the mark keeps its place when the block unmounts. */+const PADDING_X = 1;+/** The mark sits a little further right than the text column. */+const LOGO_INDENT = 5;+const LOGIN_ACTION_LABEL = "Log in with Prime Intellect";+const MARKER_WIDTH = 2;+/** What the agent is, wrapped under the welcome line. */+const DESCRIPTION_PARAGRAPHS = [+ "A self-improving RLM harness with persistent context, recursive subagents, and direct swarm communication.",+ "It learns from its history by refining its own memories, skills, prompts, and subagent specifications.",+];+const DESCRIPTION_WIDTH = 56;+const MIN_HIGHLIGHT_WIDTH = 30;+const HIGHLIGHT_TRAILING = 6;type SplashTone = Extract<ThemeColor, "accent" | "borderMuted" | "dim" | "mdLink" | "muted" | "text" | "warning">;@@ -22,23 +43,6 @@ interface SplashCell {char: string;tone: SplashTone;priority: number;- bold?: boolean;- italic?: boolean;-}--interface StyledText {- text: string;- tone: SplashTone;- bold?: boolean;- italic?: boolean;- transparentSpaces?: boolean;-}--type PanelTextLine = StyledText[];--interface PanelLine {- left: number;- parts: PanelTextLine;}interface QuietZone {@@ -48,14 +52,22 @@ interface QuietZone {bottom: number;}+/**+ * First-run onboarding, rendered as an inline block anchored to the top left+ * rather than a full-screen modal: the compact brand mark over its lab field,+ * the welcome line beneath it, and two actions in the same selection language+ * as the model and provider pickers.+ */export class PrimeOnboardingSplashComponent implements Component {private frame = 0;private animationInterval?: ReturnType<typeof setInterval>;- private progressMessage?: string;+ /** Stack, so a nested panel restores the one it covered when it closes. */+ private panels: { panel: Component; heading?: string }[] = [];+ /** Once a flow owns the block, the intro never comes back. */+ private flowStarted = false;constructor(private readonly onSelect: () => void,- private readonly onCancel: () => void,private readonly options: PrimeOnboardingSplashOptions = {},) {if (options.requestRender) {@@ -67,7 +79,7 @@ export class PrimeOnboardingSplashComponent implements Component {}invalidate(): void {- // Render output is derived from current theme.+ // Render output is derived from current theme and selection state.}dispose(): void {@@ -78,153 +90,184 @@ export class PrimeOnboardingSplashComponent implements Component {this.animationInterval = undefined;}- showProgress(message: string): void {- this.progressMessage = message;- this.dispose();+ /**+ * Mount a flow panel (a provider login, a question) inside the block, under+ * the welcome line. Panels nest: a selector opened on top of a login dialog+ * restores that dialog when it closes. Passing undefined pops the top panel.+ */+ setPanel(panel: Component | undefined, heading?: string): void {+ if (panel) {+ this.panels.push({ panel, ...(heading ? { heading } : {}) });+ this.flowStarted = true;+ } else {+ this.panels.pop();+ }this.options.requestRender?.();}- render(width: number): string[] {- const safeWidth = Math.max(1, width);- const panelLines = this.renderPanel(safeWidth);- const targetRows = this.getTargetRows(panelLines.length);- const topPadding = Math.max(0, Math.floor((targetRows - panelLines.length) / 2));- const logoZone = this.logoQuietZone(safeWidth, topPadding, targetRows);- const canvas = this.renderBackdrop(safeWidth, targetRows, logoZone);- panelLines.forEach((line, index) => {- this.drawStyledText(canvas, line.left, topPadding + index, line.parts, 8);- });- return canvas.map((line) => this.renderCells(line));- }-handleInput(keyData: string): void {- if (this.progressMessage) {+ if (isOnboardingExitKey(keyData)) {+ this.options.onExit?.();+ return;+ }+ if (this.getActivePanel()) {return;}const kb = getKeybindings();if (kb.matches(keyData, "tui.select.confirm")) {this.onSelect();- return;- }- if (kb.matches(keyData, "tui.select.cancel")) {- this.onCancel();}+ // Cancel is deliberately unbound: signing in is the only way forward, and+ // the gaps between steps must not drop the user into an unconfigured chat.}- private formatContinueHint(): PanelTextLine {- if (this.progressMessage) {- return [{ text: this.progressMessage, tone: "muted" }];+ render(width: number): string[] {+ const safeWidth = Math.max(1, width);+ const layout = this.getLayout(safeWidth);+ const lines = [this.line(safeWidth, 0, "")];+ lines.push(...this.renderMarkRows(layout.fieldWidth).map((row) => this.line(safeWidth, layout.fieldLeft, row)));+ lines.push(this.line(safeWidth, 0, ""));+ lines.push(this.line(safeWidth, layout.contentLeft, this.renderHeadingLine()));+ if (!this.getActivePanel() && !this.flowStarted) {+ lines.push(this.line(safeWidth, 0, ""));+ const descriptionWidth = Math.max(1, Math.min(DESCRIPTION_WIDTH, safeWidth - layout.contentLeft));+ DESCRIPTION_PARAGRAPHS.forEach((paragraph, index) => {+ if (index > 0) {+ lines.push(this.line(safeWidth, 0, ""));+ }+ for (const row of wrapTextWithAnsi(paragraph, descriptionWidth)) {+ lines.push(this.line(safeWidth, layout.contentLeft, theme.fg("muted", row)));+ }+ });+ }+ // The panel brings its own leading padding; a second blank row reads as a gap.+ if (!this.getActivePanel()) {+ lines.push(this.line(safeWidth, 0, ""));}- const actionLabel = this.options.continueActionLabel ?? "login with Prime Intellect";- return [- { text: "Press ", tone: "muted" },- { text: "Enter", tone: "accent", bold: true },- { text: ` to ${actionLabel}`, tone: "muted" },- ];+ const activePanel = this.getActivePanel();+ if (activePanel) {+ // The inline panel indents its own content by one column, so drop one+ // here to keep it flush with the welcome line.+ const panelLeft = Math.max(0, layout.contentLeft - 1);+ const panelWidth = Math.max(1, safeWidth - panelLeft);+ for (const row of activePanel.render(panelWidth)) {+ lines.push(this.line(safeWidth, panelLeft, row));+ }+ } else if (!this.flowStarted) {+ lines.push(...this.renderActions(safeWidth, layout));+ }+ // Onboarding owns the pane from the welcome screen through the last+ // question: pad out the remaining rows so the prompt dock stays covered.+ const rows = this.options.getRows?.();+ if (rows !== undefined && Number.isFinite(rows)) {+ while (lines.length < Math.floor(rows)) {+ lines.push(this.line(safeWidth, 0, ""));+ }+ }+ return lines;}- private formatBrandLine(): PanelTextLine {- return [- { text: "Welcome to ", tone: "text" },- { text: "PRIME", tone: "text", bold: true },- { text: " Agent", tone: "text", italic: true },- ];+ /**+ * The field spans the full pane width; the mark, the welcome line and the+ * actions are all left aligned at the pane edge.+ */+ private getLayout(width: number): {+ contentLeft: number;+ contentWidth: number;+ fieldLeft: number;+ fieldWidth: number;+ } {+ const labels = [LOGIN_ACTION_LABEL, "Continue later"];+ const labelWidth = labels.reduce((max, label) => Math.max(max, visibleWidth(label)), 0);+ const contentWidth = Math.min(+ Math.max(1, width - PADDING_X * 2),+ Math.max(MIN_HIGHLIGHT_WIDTH, MARKER_WIDTH + labelWidth + HIGHLIGHT_TRAILING),+ );+ // The field spans the pane; the mark sits a little in from the left edge.+ return { contentLeft: PADDING_X, contentWidth, fieldLeft: 0, fieldWidth: width };}- private renderPanel(width: number): PanelLine[] {- const lines: PanelLine[] = [];-- for (const line of this.renderLogoBlock(width)) {- lines.push(this.centerParts(line, width));- }- lines.push({ left: 0, parts: [] });- lines.push({ left: 0, parts: [] });- lines.push({ left: 0, parts: [] });- lines.push(this.centerParts(this.formatBrandLine(), width));- lines.push(this.centerParts(this.formatContinueHint(), width));-- return lines;+ /** The panel that owns the block names itself; otherwise the brand line. */+ /** The panel currently on top of the stack, if any. */+ getActivePanel(): Component | undefined {+ return this.panels[this.panels.length - 1]?.panel;}- private renderLogoBlock(width: number): PanelTextLine[] {- const logoWidth = Math.min(LOGO_WIDTH, width);- return LOGO_LINES.map((line) => {- const paddedLine = line + " ".repeat(Math.max(0, LOGO_WIDTH - visibleWidth(line)));- return [{ text: truncateToWidth(paddedLine, logoWidth, ""), tone: "text", transparentSpaces: true }];- });+ private renderHeadingLine(): string {+ const heading = this.panels[this.panels.length - 1]?.heading;+ if (heading) {+ return theme.bold(theme.fg("text", heading));+ }+ return this.renderBrandLine();}- private renderBackdrop(width: number, rows: number, quietZone: QuietZone | undefined): SplashCell[][] {- const canvas = Array.from({ length: rows }, () =>- Array.from({ length: width }, (): SplashCell => ({ char: " ", tone: "dim", priority: 0 })),+ private renderBrandLine(): string {+ return (+ theme.fg("text", "Welcome to ") ++ theme.bold(theme.fg("text", "PRIME")) ++ theme.italic(theme.fg("text", " Agent")));-- this.drawLabField(canvas, width, rows, quietZone);-- return canvas;}- private drawLabField(canvas: SplashCell[][], width: number, rows: number, quietZone: QuietZone | undefined): void {- if (width < LAB_FIELD_MIN_WIDTH || rows < LAB_FIELD_HEIGHT + 2) {- return;- }-- const labWidth = Math.max(LAB_FIELD_MIN_WIDTH, Math.min(LAB_FIELD_MAX_WIDTH, width - 6));- const left = Math.max(0, Math.floor((width - labWidth) / 2));- const fieldTop = quietZone ? quietZone.top - 2 : Math.floor((rows - LAB_FIELD_HEIGHT) / 2);- const top = Math.max(0, Math.min(rows - LAB_FIELD_HEIGHT, fieldTop));+ /** Signing in is the only way forward, so the block offers a single action. */+ private renderActions(width: number, layout: { contentLeft: number; contentWidth: number }): string[] {+ const highlightWidth = layout.contentWidth;+ const content = truncateToWidth(`> ${LOGIN_ACTION_LABEL}`, highlightWidth, "");+ const padded = content + " ".repeat(Math.max(0, highlightWidth - visibleWidth(content)));+ const styled = this.getHighlightBackground()(theme.bold(theme.fg("text", padded)));+ return [this.line(width, layout.contentLeft, styled)];+ }- for (let labY = 0; labY < LAB_FIELD_HEIGHT; labY++) {- for (let labX = 0; labX < labWidth; labX++) {- const x = left + labX;- const y = top + labY;- const cell = this.labCell(labX, labY, labWidth);- if (!cell) {- continue;- }- if (cell.tone === "mdLink" && this.isInsideQuietZone(x, y, quietZone)) {- continue;+ private renderMarkRows(fieldWidth: number): string[] {+ const rows = LOGO_LINES.length;+ const markLeft = LOGO_INDENT;+ const canvas: SplashCell[][] = Array.from({ length: rows }, () =>+ Array.from({ length: fieldWidth }, (): SplashCell => ({ char: " ", tone: "dim", priority: 0 })),+ );+ const quietZone: QuietZone = { left: markLeft, right: markLeft + LOGO_WIDTH - 1, top: 0, bottom: rows - 1 };+ this.drawField(canvas, fieldWidth, rows, quietZone);+ LOGO_LINES.forEach((line, y) => {+ [...line].forEach((char, x) => {+ if (char !== " ") {+ this.put(canvas, markLeft + x, y, char, "text", 8, fieldWidth);}- this.put(canvas, x, y, cell.char, cell.tone, cell.priority);- }- }+ });+ });+ return canvas.map((row) => this.renderCells(row));}- private labCell(x: number, y: number, width: number): SplashCell | undefined {- const height = LAB_FIELD_HEIGHT;+ /** The lab field of the old full-screen splash, scaled to the mark's band. */+ private drawField(canvas: SplashCell[][], width: number, height: number, quietZone: QuietZone): void {const frame = this.frame;- let cell: SplashCell | undefined;- const setCell = (char: string, tone: SplashTone, priority: number) => {- if (!cell || priority >= cell.priority) {- cell = { char, tone, priority };- }- };-- const hash = this.mod(x * 37 + y * 53 + frame * 11 + x * y * 3, 101);- if (hash < 3) {- setCell("·", "dim", 1);- }+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ const hash = this.mod(x * 37 + y * 53 + frame * 11 + x * y * 3, 101);+ if (hash < 3) {+ this.put(canvas, x, y, "\u00b7", "dim", 1, width);+ }- const centerX = Math.floor((width * 36) / 100);- const centerY = Math.floor((height * 54) / 100);- const contour = Math.abs(x - centerX) + Math.abs(y - centerY) * 4 + Math.floor(x / 6) - frame;- if (x < Math.floor((width * 82) / 100) && this.mod(contour, 24) === 12) {- setCell((x + y) % 5 === 0 ? "╌" : "·", "borderMuted", 2);- }+ const centerX = Math.floor((width * 36) / 100);+ const centerY = Math.floor((height * 54) / 100);+ const contour = Math.abs(x - centerX) + Math.abs(y - centerY) * 4 + Math.floor(x / 6) - frame;+ if (x < Math.floor((width * 82) / 100) && this.mod(contour, 24) === 12) {+ this.put(canvas, x, y, (x + y) % 5 === 0 ? "\u254c" : "\u00b7", "borderMuted", 2, width);+ }- const horizonY = Math.floor((height * 58) / 100);- if (y === horizonY && x % 2 === 0 && this.mod(x + frame, 13) < 2) {- setCell("─", x > Math.floor((width * 60) / 100) ? "accent" : "dim", 3);- }+ const horizonY = Math.floor((height * 58) / 100);+ if (y === horizonY && x % 2 === 0 && this.mod(x + frame, 13) < 2) {+ this.put(canvas, x, y, "\u2500", this.mod(x + frame, 3) === 0 ? "accent" : "dim", 3, width);+ }- const scanStart = Math.max(0, Math.floor(width / 2) - 5);- if (x >= scanStart) {- const scanOffset = x - scanStart;- if (scanOffset % 4 === 0) {- const scanIndex = Math.floor(scanOffset / 4);- const segment = this.mod(y + scanIndex * 2 + Math.floor(frame / 2), 6);- if (y > 0 && y < height - 1 && segment < 2) {- setCell((scanIndex + y) % 4 === 0 ? "┃" : "╎", "mdLink", 4);+ // Scan columns trail the mark to the right; ambient dots, contours and+ // traces still drift across the full width, including left of it.+ if (x >= quietZone.left && !this.isInsideQuietZone(x, y, quietZone)) {+ if (x % 4 === 0) {+ const scanIndex = Math.floor(x / 4);+ const segment = this.mod(y + scanIndex * 2 + Math.floor(frame / 2), 6);+ if (y > 0 && y < height - 1 && segment < 2) {+ this.put(canvas, x, y, (scanIndex + y) % 4 === 0 ? "\u2503" : "\u254e", "mdLink", 4, width);+ }+ }}}}@@ -236,54 +279,29 @@ export class PrimeOnboardingSplashComponent implements Component {: traceIndex === 1? Math.floor((height * 49) / 100): Math.floor((height * 72) / 100);- let wave = this.mod(x * 2 + frame + traceIndex * 7, 16);- if (wave > 7) {- wave = 15 - wave;- }- const traceY = base + Math.trunc((wave - 3) / 2);- if (y !== traceY) {- continue;- }-- if (this.mod(x + frame + traceIndex * 13, 41) === 0) {- setCell("◆", "warning", 5);- } else if (this.mod(x + frame, 12) === 0) {- setCell("•", "accent", 5);- } else {- setCell("·", "accent", 3);+ for (let x = 0; x < width; x++) {+ let wave = this.mod(x * 2 + frame + traceIndex * 7, 16);+ if (wave > 7) {+ wave = 15 - wave;+ }+ const traceY = base + Math.trunc((wave - 3) / 2);+ if (this.mod(x + frame + traceIndex * 13, 41) === 0) {+ this.put(canvas, x, traceY, "\u25c6", "warning", 6, width);+ } else if (this.mod(x + frame, 12) === 0) {+ this.put(canvas, x, traceY, "\u2022", "accent", 6, width);+ } else {+ this.put(canvas, x, traceY, "\u00b7", "accent", 3, width);+ }}}-- return cell;}- private isInsideQuietZone(x: number, y: number, quietZone: QuietZone | undefined): boolean {- return (- quietZone !== undefined &&- x >= quietZone.left &&- x <= quietZone.right &&- y >= quietZone.top &&- y <= quietZone.bottom- );+ private getHighlightBackground(): (text: string) => string {+ return onboardingHighlightBackground(getResolvedThemeColors());}- private drawStyledText(- canvas: SplashCell[][],- left: number,- y: number,- parts: PanelTextLine,- priority: number,- ): void {- let x = left;- for (const part of parts) {- for (const char of part.text) {- const width = Math.max(0, visibleWidth(char));- if (char !== " " || !part.transparentSpaces) {- this.put(canvas, x, y, char, part.tone, priority, part.bold, part.italic);- }- x += Math.max(1, width);- }- }+ private isInsideQuietZone(x: number, y: number, zone: QuietZone): boolean {+ return x >= zone.left && x <= zone.right && y >= zone.top && y <= zone.bottom;}private put(@@ -293,44 +311,27 @@ export class PrimeOnboardingSplashComponent implements Component {char: string,tone: SplashTone,priority: number,- bold = false,- italic = false,+ width: number,): void {- if (y < 0 || y >= canvas.length) return;+ if (y < 0 || y >= canvas.length || x < 0 || x >= width) return;const row = canvas[y];- if (!row || x < 0 || x >= row.length) return;- if (row[x] && row[x].priority > priority) return;- row[x] = { char, tone, priority, bold, italic };+ if (!row || !row[x] || row[x].priority > priority) return;+ row[x] = { char, tone, priority };}private renderCells(cells: SplashCell[]): string {let rendered = "";let currentTone: SplashTone | undefined;- let currentBold = false;- let currentItalic = false;let segment = "";-const flush = () => {if (!segment || !currentTone) return;- let styled = theme.fg(currentTone, segment);- if (currentItalic) {- styled = theme.italic(styled);- }- if (currentBold) {- styled = theme.bold(styled);- }- rendered += styled;+ rendered += theme.fg(currentTone, segment);segment = "";};-for (const cell of cells) {- const bold = cell.bold === true;- const italic = cell.italic === true;- if (cell.tone !== currentTone || bold !== currentBold || italic !== currentItalic) {+ if (cell.tone !== currentTone) {flush();currentTone = cell.tone;- currentBold = bold;- currentItalic = italic;}segment += cell.char;}@@ -338,38 +339,13 @@ export class PrimeOnboardingSplashComponent implements Component {return rendered;}- private mod(value: number, divisor: number): number {- return ((value % divisor) + divisor) % divisor;+ private line(width: number, indent: number, content: string): string {+ const text = " ".repeat(indent) + content;+ const truncated = truncateToWidth(text, width, "");+ return truncated + " ".repeat(Math.max(0, width - visibleWidth(truncated)));}- private visiblePartsWidth(parts: PanelTextLine): number {- return parts.reduce((sum, part) => sum + visibleWidth(part.text), 0);- }-- private logoQuietZone(width: number, topPadding: number, rows: number): QuietZone | undefined {- const logoWidth = Math.min(LOGO_WIDTH, width);- if (logoWidth < 1 || rows < 1) {- return undefined;- }- const left = Math.max(0, Math.floor((width - logoWidth) / 2));- return {- left,- right: Math.min(width - 1, left + logoWidth - 1),- top: Math.max(0, topPadding),- bottom: Math.min(rows - 1, topPadding + LOGO_LINES.length - 1),- };- }-- private centerParts(parts: PanelTextLine, width: number): PanelLine {- const left = Math.max(0, Math.floor((width - this.visiblePartsWidth(parts)) / 2));- return { left, parts };- }-- private getTargetRows(contentLineCount: number): number {- const requestedRows = this.options.getRows?.();- if (requestedRows && Number.isFinite(requestedRows)) {- return Math.max(contentLineCount, Math.floor(requestedRows));- }- return contentLineCount;+ private mod(value: number, divisor: number): number {+ return ((value % divisor) + divisor) % divisor;}}diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex 82477c66b3..9aa83a7177 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -121,7 +121,7 @@ import {} from "../../core/messages.js";import { findExactModelReferenceMatch, resolveModelScopeFromModels } from "../../core/model-resolver.js";import { parseNewSessionCommand } from "../../core/new-session-command.js";-import { resolvePrimeAgentTracesBaseUrl } from "../../core/prime-inference-auth.js";+import { PRIME_INFERENCE_PROVIDER_ID, resolvePrimeAgentTracesBaseUrl } from "../../core/prime-inference-auth.js";import { resolvePrimeInferencePostLoginModelAction } from "../../core/prime-inference-model-selection.js";import { parseCommandArgs } from "../../core/prompt-templates.js";import { formatMissingSessionCwdPrompt, MissingSessionCwdError } from "../../core/session-cwd.js";@@ -222,6 +222,8 @@ import {} from "./components/keybinding-hints.js";import { createMermaidMarkdownTransform } from "./components/mermaid.js";import type { AuthSelectorProvider } from "./components/oauth-selector.js";+import { OnboardingChoiceComponent } from "./components/onboarding-choice.js";+import { OnboardingPickerComponent } from "./components/onboarding-picker.js";import { PrimeOnboardingSplashComponent } from "./components/prime-onboarding-splash.js";import { PromptContextLine } from "./components/prompt-context-line.js";import { styleArgumentTokens } from "./components/prompt-highlight.js";@@ -267,12 +269,7 @@ import type {InteractiveModeLocalToolRendererDefinition,InteractiveModeUiServices,} from "./interactive-mode-services.js";-import {- isOnboardingModelReady,- type OnboardingStartupState,- shouldRunOnboarding,- shouldRunPrimeCliOnboardingSplash,-} from "./onboarding.js";+import { isOnboardingModelReady, type OnboardingStartupState, shouldRunOnboarding } from "./onboarding.js";import type { ClientPromptStashStore, PromptStash, PromptStashState } from "./prompt-stash-state.js";import { QueueSelection, type QueueSelectionItem } from "./queue-selection.js";import { formatResumeHint } from "./resume-hint.js";@@ -433,6 +430,13 @@ export interface BrandSplashHeaderOptions {topPadding?: boolean;getModelId?: () => string | undefined;getExtraMetadata?: () => readonly BrandSplashMetadataLine[];+ /** Suppress the header entirely, e.g. while inline onboarding owns the top rows. */+ getHidden?: () => boolean;+}++/** Flow panels that can settle their pending step when unmounted early. */+function isAbortablePanel(component: Component): component is Component & { abort(): void } {+ return typeof (component as { abort?: unknown }).abort === "function";}export class BrandSplashHeader implements Component {@@ -455,6 +459,9 @@ export class BrandSplashHeader implements Component {}render(width: number): string[] {+ if (this.options.getHidden?.()) {+ return [];+ }const safeWidth = Math.max(1, width);const paddingX = safeWidth > 1 ? 1 : 0;const contentWidth = Math.max(1, safeWidth - paddingX * 2);@@ -530,7 +537,6 @@ type GoalAnnouncementSnapshot = {type ModelFallbackWarningAction = "show" | "suppress";interface OnboardingSplashHandle {- showProgress(message: string): void;dismiss(): void;}@@ -1081,7 +1087,7 @@ export class InteractiveMode {private connectionModelsRefreshVersion = 0;private connectionModelsRefreshInFlight: { version: number; promise: Promise<AgentConnectionModel[]> } | undefined;private closeConfigurationMenu: (() => void) | undefined;- private inlineAuthPanelClosers: (() => void)[] = [];+ private inlineAuthPanelClosers: ((reason?: "reset") => void)[] = [];private configurationModelSelection: Promise<void> | undefined;private connectionState: AgentConnectionState | undefined;private connectionResourceSnapshot: AgentConnectionResourceSnapshot | undefined;@@ -1155,6 +1161,18 @@ export class InteractiveMode {private builtInHeader: Component | undefined = undefined;+ /** True while the inline onboarding block owns the top rows (header stays hidden). */+ private onboardingUiActive = false;++ /** The mounted onboarding block, so flow panels can render inside it. */+ private onboardingSplash: PrimeOnboardingSplashComponent | undefined = undefined;++ /** Tears the block down and settles the pending flow, e.g. on a session reset. */+ private onboardingAbort: (() => void) | undefined = undefined;++ /** Aborted when onboarding is torn down so in-flight steps stop waiting. */+ private onboardingFlowAbort: AbortController | undefined = undefined;+private customHeader: (Component & { dispose?(): void }) | undefined = undefined;private getLocalSessionHost(): InteractiveModeLocalSessionHost {@@ -1515,6 +1533,7 @@ export class InteractiveMode {this.builtInHeader = new BrandSplashHeader(this.version, () => this.getCurrentCwd(), verboseInstructions, {topPadding: true,getModelId: () => this.getCurrentModelId(),+ getHidden: () => this.onboardingUiActive,});this.headerContainer.addChild(this.builtInHeader);this.headerContainer.addChild(new Spacer(1));@@ -1860,10 +1879,6 @@ export class InteractiveMode {return shouldRunOnboarding(this.getOnboardingState());}- private shouldRunPrimeCliOnboardingSplash(): boolean {- return shouldRunPrimeCliOnboardingSplash(this.getOnboardingState());- }-private markOnboardingShown(): void {if (!this.settingsManager.getOnboardingShown()) {this.settingsManager.setOnboardingShown(true);@@ -1876,15 +1891,16 @@ export class InteractiveMode {}const startedAt = Date.now();- const showPrimeCliSplash = this.shouldRunPrimeCliOnboardingSplash();let outcome: TelemetryOnboardingOutcome = "aborted";try {- await this.runOnboardingFlow(showPrimeCliSplash);- outcome = isOnboardingModelReady(this.getOnboardingState()) ? "success" : "aborted";+ // The flow reports completion itself: a user who already had a working+ // model would otherwise look "ready" straight after cancelling it, and+ // the questions they never saw would be skipped for good.+ const completed = await this.runOnboardingFlow();+ outcome = completed && isOnboardingModelReady(this.getOnboardingState()) ? "success" : "aborted";if (outcome === "success") {- // Only a completed onboarding counts as seen: an escaped splash or a- // failed login leaves the flag unset so the next launch retries, and- // shouldRunOnboarding already skips users who configured a model.+ // Only a completed onboarding counts as seen: a cancelled sign-in+ // leaves the flag unset so the next launch retries the flow.this.markOnboardingShown();await this.settingsManager.flush();}@@ -1908,46 +1924,149 @@ export class InteractiveMode {}}- private async showOnboardingModelSelection(splash: OnboardingSplashHandle): Promise<void> {- splash.dismiss();- await this.showConfigurationMenu("models");- }-- private async runOnboardingFlow(showPrimeCliSplash = this.shouldRunPrimeCliOnboardingSplash()): Promise<void> {+ /** Runs the first-launch sequence. Resolves true only when every step ran. */+ private async runOnboardingFlow(): Promise<boolean> {this.modelRegistry.refresh();- if (showPrimeCliSplash) {- const splash = await this.showOnboardingSplash("choose a model");- if (!splash) {- return;- }-- await this.showOnboardingModelSelection(splash);- return;+ const abort = new AbortController();+ this.onboardingFlowAbort = abort;+ const splash = await this.showOnboardingSplash();+ if (!splash) {+ return false;}- const availableModels = await this.getModelCandidates();- if (availableModels.length > 0) {- await this.showConfigurationMenu("models");- return;+ // One sequence for every first launch. Signing in is instant when a Prime+ // CLI token is already on disk, so users who arrive with credentials still+ // reach the same account, provider and trace questions.+ const authResult = await this.createAuthFlows().runPrimeInferenceLogin();+ if (abort.signal.aborted || authResult.status !== "success") {+ splash.dismiss();+ return false;}- const splash = await this.showOnboardingSplash();- if (!splash) {- return;+ await this.prepareForModelSelectionAfterLogin(authResult, abort.signal);+ if (abort.signal.aborted) {+ return false;+ }+ await this.askOnboardingProviders(abort.signal);+ if (abort.signal.aborted) {+ return false;}+ await this.askOnboardingTraceOptIn();+ if (abort.signal.aborted) {+ return false;+ }+ splash.dismiss();+ return true;+ }- splash.showProgress("Signing in to Prime Intellect...");- // The splash covers the whole screen, so the login panel must render as an- // overlay above it instead of inline behind it.- const authResult = await this.createAuthFlows({ overlay: true }).runPrimeInferenceLogin();- if (authResult.status !== "success") {- splash.dismiss();+ /**+ * Optional step: connect more providers before the first chat. The picker+ * stays mounted between logins so several can be connected in one pass.+ */+ private async askOnboardingProviders(signal: AbortSignal): Promise<void> {+ if (!this.onboardingSplash) {return;}+ const authFlows = this.createAuthFlows();+ for (;;) {+ // A reset that cancels a provider login must end the question too,+ // otherwise the next picker opens in the editor and waits for input.+ // The signal is passed in: tearing the block down clears the field.+ if (signal.aborted) {+ return;+ }+ // One row per provider: a provider offering both a subscription and an+ // API key would otherwise appear twice under the same name.+ const options = [+ ...new Map(+ authFlows+ .getLoginProviderOptions()+ .filter((option) => option.id !== PRIME_INFERENCE_PROVIDER_ID && option.category !== "service")+ .map((option) => [option.id, option]),+ ).values(),+ ];+ if (options.length === 0) {+ return;+ }+ const items = options.map((option) => ({+ id: option.id,+ label: option.name,+ ...(this.modelRegistry.getProviderAuthStatus(option.id).configured ? { connected: true } : {}),+ }));+ const picked = await new Promise<string | undefined>((resolve) => {+ let settled = false;+ let close: (() => void) | undefined;+ const settle = (id: string | undefined) => {+ if (settled) {+ return;+ }+ settled = true;+ close?.();+ resolve(id);+ };+ const picker = new OnboardingPickerComponent(+ items,+ (id) => settle(id),+ () => settle(undefined),+ () => settle(undefined),+ {+ prompt: "Connect other providers, or continue.",+ searchPlaceholder: "Search providers",+ note: "You can add providers anytime with /login.",+ onExit: () => void this.shutdown(),+ requestRender: () => this.ui.requestRender(),+ },+ );+ close = this.showInlineAuthPanel(picker, { onReset: () => settle(undefined) });+ this.ui.requestRender();+ });+ if (!picked) {+ return;+ }+ const option = options.find((candidate) => candidate.id === picked);+ if (option) {+ await authFlows.loginProvider(option);+ }+ }+ }- splash.showProgress("Preparing models...");- await this.prepareForModelSelectionAfterLogin(authResult);- await this.showOnboardingModelSelection(splash);+ /** Final onboarding question: trace collection, with a reminder it is reversible. */+ private askOnboardingTraceOptIn(): Promise<void> {+ const splash = this.onboardingSplash;+ if (!splash) {+ return Promise.resolve();+ }+ return new Promise<void>((resolve) => {+ let closed = false;+ let close: (() => void) | undefined;+ const finish = (enabled?: boolean) => {+ if (closed) {+ return;+ }+ closed = true;+ if (enabled !== undefined) {+ this.settingsManager.setAgentTracesEnabled(enabled);+ void this.settingsManager.flush();+ }+ close?.();+ resolve();+ };+ const choice = new OnboardingChoiceComponent(+ [{ label: "Share" }, { label: "Not now" }],+ (index) => finish(index === 0),+ () => finish(undefined),+ {+ onExit: () => void this.shutdown(),+ prompt: "Share agent traces with Prime Intellect?",+ description:+ "Trace sharing helps us train better open-source models and improve the open agent ecosystem for everyone.",+ note: "You can change this anytime with /traces.",+ requestRender: () => this.ui.requestRender(),+ },+ );+ close = this.showInlineAuthPanel(choice, { onReset: () => finish(undefined) });+ this.ui.requestRender();+ });}private getMarkdownThemeWithSettings(): MarkdownTheme {@@ -3645,8 +3764,11 @@ export class InteractiveMode {// menu is still torn down by the closeConfigurationMenu call below.// Innermost panels close first, ending at the pre-login content.for (const close of this.inlineAuthPanelClosers.splice(0).reverse()) {- close();+ close("reset");}+ // A reset mid-onboarding leaves the block with no flow to host: tear it+ // down too, so the overlay, its animation and the pending step all end.+ this.onboardingAbort?.();this.closeConfigurationMenu?.();this.cancelActiveConnectionExtensionUiRequests();this.closeHeartbeatManager();@@ -6301,6 +6423,8 @@ export class InteractiveMode {private getPromptContextLabel(maxWidth: number): string | undefined {if (maxWidth < 1) return undefined;+ // Onboarding owns the screen; chat chrome under it reads as clutter.+ if (this.onboardingUiActive) return undefined;return theme.fg("dim",truncateToWidth(formatConversationDetailStatus(this.toolOutputExpanded, this.editDiffsExpanded), maxWidth, ""),@@ -8865,7 +8989,7 @@ export class InteractiveMode {}}- private showOnboardingSplash(continueActionLabel?: string): Promise<OnboardingSplashHandle | undefined> {+ private showOnboardingSplash(): Promise<OnboardingSplashHandle | undefined> {return new Promise((resolve) => {let settled = false;let dismissed = false;@@ -8885,26 +9009,39 @@ export class InteractiveMode {dismissed = true;selector?.dispose();handle?.hide();+ this.onboardingSplash = undefined;+ this.onboardingAbort = undefined;+ this.onboardingFlowAbort = undefined;+ this.onboardingUiActive = false;+ this.builtInHeader?.invalidate();this.ui.requestRender();};selector = new PrimeOnboardingSplashComponent(() => {- selector?.dispose();- settle({- showProgress: (message) => selector?.showProgress(message),- dismiss,- });- },- () => {- dismiss();- settle(undefined);+ // The field keeps animating behind the flow panels; only dismissal+ // stops it.+ settle({ dismiss });},{getRows: () => this.ui.terminal.rows,+ // Nothing else owns Ctrl+C yet, so the block exits the app itself.+ onExit: () => void this.shutdown(),requestRender: () => this.ui.requestRender(),- ...(continueActionLabel ? { continueActionLabel } : {}),},);+ // The block owns the pane while onboarding runs: the brand header hides+ // so the two marks never stack, and flow panels mount inside the block.+ this.onboardingAbort = () => {+ // Cancel the running step first: after Enter the splash promise is+ // already settled, so dismissing alone would leave the login waiting+ // on an unmounted dialog and remount later panels in the prompt dock.+ this.onboardingFlowAbort?.abort();+ dismiss();+ settle(undefined);+ };+ this.onboardingUiActive = true;+ this.onboardingSplash = selector;+ this.builtInHeader?.invalidate();handle = this.ui.showOverlay(selector, {width: "100%",maxHeight: "100%",@@ -8914,26 +9051,20 @@ export class InteractiveMode {});}- private createAuthFlows(options: { overlay?: boolean } = {}): ProviderAuthFlows {- const showAuthPanel = options.overlay- ? (component: Component) => {- const handle = this.showFullPaneOverlay(component, {- maxContentWidth: 88,- suspendFullscreenMouse: true,- });- return () => {- handle.hide();- this.ui.requestRender();- };- }- : (component: Component) => this.showInlineAuthPanel(component);+ private createAuthFlows(): ProviderAuthFlows {+ const showAuthPanel = (component: Component, options?: { heading?: string; onReset?: () => void }) =>+ this.showInlineAuthPanel(component, options);return new ProviderAuthFlows({ui: this.ui,modelRegistry: this.modelRegistry,showStatus: (message) => this.showStatus(message),showError: (message) => this.showError(message),showAuthPanel,+ exitApp: () => void this.shutdown(),getAuthPanelRows: () => Math.max(1, Math.min(20, this.ui.terminal.rows - 3)),+ // Onboarding renders its own heading above the panel and asks its+ // questions in the onboarding selection language.+ isOnboardingSurface: () => this.onboardingUiActive,getAvailableModels: () => this.getConnectionAvailableModels(),onAuthChanged: async () => {await this.refreshConnectionModelsAfterAuthChange();@@ -8955,7 +9086,42 @@ export class InteractiveMode {* resetExtensionUI tears the whole stack down on session resets. Each* closer runs once, so a reset cannot stomp a picker opened afterwards.*/- private showInlineAuthPanel(component: Component): () => void {+ private showInlineAuthPanel(+ component: Component,+ options?: { heading?: string; onReset?: () => void },+ ): (reason?: "reset") => void {+ // Onboarding owns the top of the screen: mount the panel inside its block+ // rather than down in the prompt dock.+ const splash = this.onboardingSplash;+ if (splash) {+ splash.setPanel(component, options?.heading);+ this.ui.setFocus(component);+ this.ui.requestRender();+ let splashPanelClosed = false;+ const closeSplashPanel = (reason?: "reset") => {+ if (splashPanelClosed) return;+ splashPanelClosed = true;+ const index = this.inlineAuthPanelClosers.indexOf(closeSplashPanel);+ if (index !== -1) {+ this.inlineAuthPanelClosers.splice(index, 1);+ }+ // A reset unmounts the panel without its flow finishing: settle the+ // step the caller is awaiting, or it waits on a dead panel forever.+ if (reason === "reset") {+ options?.onReset?.();+ if (isAbortablePanel(component)) {+ component.abort();+ }+ }+ splash.setPanel(undefined);+ // The splash ignores keys while a panel is mounted, so focus has to+ // land on whichever panel the pop restored, not on the block itself.+ this.ui.setFocus(splash.getActivePanel() ?? splash);+ this.ui.requestRender();+ };+ this.inlineAuthPanelClosers.push(closeSplashPanel);+ return closeSplashPanel;+ }const previousChildren = [...this.editorContainer.children];const previousFocus = previousChildren.find((child) => isFocusable(child) && child.focused) ?? this.editor;this.editorContainer.clear();@@ -8963,9 +9129,15 @@ export class InteractiveMode {this.ui.setFocus(component);this.ui.requestRender();let closed = false;- const close = () => {+ const close = (reason?: "reset") => {if (closed) return;closed = true;+ if (reason === "reset") {+ options?.onReset?.();+ if (isAbortablePanel(component)) {+ component.abort();+ }+ }const index = this.inlineAuthPanelClosers.indexOf(close);if (index !== -1) {this.inlineAuthPanelClosers.splice(index, 1);@@ -8981,7 +9153,15 @@ export class InteractiveMode {return close;}- private async prepareForModelSelectionAfterLogin(authResult: AuthenticationResult): Promise<boolean> {+ private async prepareForModelSelectionAfterLogin(+ authResult: AuthenticationResult,+ abortSignal?: AbortSignal,+ ): Promise<boolean> {+ // A reset rebinds the session; selection prepared for the old one must+ // not be applied to the new one.+ if (abortSignal?.aborted) {+ return false;+ }const currentModel = this.getCurrentModel();// The agent core uses unknown/unknown as its no-model sentinel.const selectedModel =@@ -9005,6 +9185,9 @@ export class InteractiveMode {}if (action.fallbackModel) {+ if (abortSignal?.aborted) {+ return false;+ }try {await this.applySelectedModel(action.fallbackModel);await this.settingsManager.flush();diff --git a/packages/coding-agent/src/modes/interactive/onboarding.ts b/packages/coding-agent/src/modes/interactive/onboarding.tsindex ed8ebb1167..250cc06e60 100644--- a/packages/coding-agent/src/modes/interactive/onboarding.ts+++ b/packages/coding-agent/src/modes/interactive/onboarding.ts@@ -1,6 +1,4 @@import type { Api, Model } from "@earendil-works/pi-ai";-import type { AuthStatus } from "../../core/auth-storage.js";-import { PRIME_INFERENCE_PROVIDER_ID } from "../../core/prime-inference-auth.js";export interface OnboardingSettingsReader {getOnboardingShown(): boolean;@@ -9,7 +7,6 @@ export interface OnboardingSettingsReader {export interface OnboardingModelRegistryReader {refresh(): void;hasConfiguredAuth(model: Model<Api>): boolean;- getProviderAuthStatus(provider: string): AuthStatus;}export interface OnboardingStartupState {@@ -18,28 +15,19 @@ export interface OnboardingStartupState {model: Model<Api> | undefined;}-export function shouldRunPrimeCliOnboardingSplash(state: OnboardingStartupState): boolean {- if (state.settingsManager.getOnboardingShown()) {- return false;- }- if (!state.model || state.model.provider !== PRIME_INFERENCE_PROVIDER_ID) {- return false;- }- const authStatus = state.modelRegistry.getProviderAuthStatus(PRIME_INFERENCE_PROVIDER_ID);- return authStatus.source === "prime_cli";-}-export function isOnboardingModelReady(state: OnboardingStartupState): boolean {return state.model !== undefined && state.modelRegistry.hasConfiguredAuth(state.model);}+/**+ * First launch is defined by the settings flag alone. Credentials found on disk+ * (a Prime CLI token, an API key in the environment) no longer skip the flow:+ * they only make the sign-in step instant.+ */export function shouldRunOnboarding(state: OnboardingStartupState): boolean {if (state.settingsManager.getOnboardingShown()) {return false;}state.modelRegistry.refresh();- if (shouldRunPrimeCliOnboardingSplash(state)) {- return true;- }- return !isOnboardingModelReady(state);+ return true;}diff --git a/packages/coding-agent/test/agent-session-services.test.ts b/packages/coding-agent/test/agent-session-services.test.tsindex b9958a67be..2013132888 100644--- a/packages/coding-agent/test/agent-session-services.test.ts+++ b/packages/coding-agent/test/agent-session-services.test.ts@@ -64,6 +64,7 @@ describe("createAgentSessionFromServices", () => {mkdirSync(tempDir, { recursive: true });cleanupPaths.push(tempDir);const settingsManager = SettingsManager.inMemory();+ settingsManager.setOnboardingShown(true);const services = await createAgentSessionServices({cwd: tempDir,@@ -79,6 +80,54 @@ describe("createAgentSessionFromServices", () => {expect(settingsManager.getTelemetryNoticeShown()).toBe(true);});+ it("defers the telemetry disclosure on a first interactive launch", async () => {+ vi.stubEnv("DO_NOT_TRACK", "0");+ vi.stubEnv("PRIME_AGENT_TELEMETRY", "1");+ const tempDir = join(tmpdir(), `pi-session-telemetry-first-run-${Date.now()}`);+ mkdirSync(tempDir, { recursive: true });+ cleanupPaths.push(tempDir);+ // A settings profile that has never seen onboarding: the notice would land+ // on the welcome screen, so it waits for the next launch.+ const settingsManager = SettingsManager.inMemory();++ const services = await createAgentSessionServices({+ cwd: tempDir,+ agentDir: tempDir,+ settingsManager,+ noBuiltinHerdrReporter: true,+ deferTelemetryNoticeForOnboarding: true,+ resourceLoaderOptions: { noPromptTemplates: true, noThemes: true },+ });++ expect(services.diagnostics).not.toContainEqual(+ expect.objectContaining({ message: expect.stringContaining("pseudonymous usage") }),+ );+ expect(settingsManager.getTelemetryNoticeShown()).toBe(false);+ });++ it("discloses telemetry immediately for sessions that never onboard", async () => {+ vi.stubEnv("DO_NOT_TRACK", "0");+ vi.stubEnv("PRIME_AGENT_TELEMETRY", "1");+ const tempDir = join(tmpdir(), `pi-session-telemetry-headless-${Date.now()}`);+ mkdirSync(tempDir, { recursive: true });+ cleanupPaths.push(tempDir);+ // No onboarding will run here, so holding the notice back would hide it forever.+ const settingsManager = SettingsManager.inMemory();++ const services = await createAgentSessionServices({+ cwd: tempDir,+ agentDir: tempDir,+ settingsManager,+ noBuiltinHerdrReporter: true,+ resourceLoaderOptions: { noPromptTemplates: true, noThemes: true },+ });++ expect(services.diagnostics).toContainEqual(+ expect.objectContaining({ message: expect.stringContaining("pseudonymous usage") }),+ );+ expect(settingsManager.getTelemetryNoticeShown()).toBe(true);+ });+it("honors an explicit daemon-carried telemetry opt-out", async () => {vi.stubEnv("DO_NOT_TRACK", "0");vi.stubEnv("PRIME_AGENT_TELEMETRY", "1");diff --git a/packages/coding-agent/test/auth-flows.test.ts b/packages/coding-agent/test/auth-flows.test.tsindex 50f53b790e..eb4ea9bbb7 100644--- a/packages/coding-agent/test/auth-flows.test.ts+++ b/packages/coding-agent/test/auth-flows.test.ts@@ -11,6 +11,7 @@ import { ModelRegistry } from "../src/core/model-registry.js";import { PRIME_INFERENCE_PROVIDER_ID } from "../src/core/prime-inference-auth.js";import { createAgentSession } from "../src/core/sdk.js";import { SessionManager } from "../src/core/session-manager.js";+import type { AuthenticationResult } from "../src/modes/interactive/auth-flows.js";import { ProviderAuthFlows, type ProviderAuthFlowsHost } from "../src/modes/interactive/auth-flows.js";import { ExtensionSelectorComponent } from "../src/modes/interactive/components/extension-selector.js";import { LoginDialogComponent } from "../src/modes/interactive/components/login-dialog.js";@@ -92,6 +93,44 @@ function createHost(authStorage: AuthStorage): {};}+describe("Prime login completion guard", () => {+ it("does not complete the Prime login after the dialog was aborted", async () => {+ const onAuthChanged = vi.fn();+ const host = {+ modelRegistry: { refresh: vi.fn(), authStorage: { setPrimeInferenceApiKey: vi.fn() } },+ onAuthChanged,+ isOnboardingSurface: () => true,+ };+ const flows = new ProviderAuthFlows(host as never);+ const complete = (+ flows as unknown as {+ completePrimeInferenceLogin: (+ apiKey: string,+ dialog: unknown,+ close: () => void,+ team?: unknown,+ ) => Promise<AuthenticationResult>;+ }+ ).completePrimeInferenceLogin;+ const controller = new AbortController();+ controller.abort();+ const dialog = { signal: controller.signal } as never;+ const select = vi+ .spyOn(+ flows as unknown as { selectPrimeInferenceTeam: () => Promise<string | undefined> },+ "selectPrimeInferenceTeam",+ )+ .mockResolvedValue(undefined);++ const result = await complete.call(flows, "key", dialog, () => {}, undefined);++ expect(result).toEqual({ status: "cancelled" });+ expect(onAuthChanged).not.toHaveBeenCalled();+ expect(host.modelRegistry.refresh).not.toHaveBeenCalled();+ expect(select).toHaveBeenCalledOnce();+ });+});+describe("ProviderAuthFlows", () => {let tempDir: string;let authJsonPath: string;diff --git a/packages/coding-agent/test/interactive-mode-onboarding-completion.test.ts b/packages/coding-agent/test/interactive-mode-onboarding-completion.test.tsindex 7fa42c394a..381a5c780f 100644--- a/packages/coding-agent/test/interactive-mode-onboarding-completion.test.ts+++ b/packages/coding-agent/test/interactive-mode-onboarding-completion.test.ts@@ -28,8 +28,8 @@ function makeContext(options: { modelReady: boolean }): Context {flush: vi.fn(async () => {}),},shouldRunOnboarding: () => true,- shouldRunPrimeCliOnboardingSplash: () => false,- runOnboardingFlow: vi.fn(async () => {}),+ // The flow reports completion; readiness alone no longer persists the flag.+ runOnboardingFlow: vi.fn(async () => true),markOnboardingShown: InteractiveMode.prototype["markOnboardingShown" as keyof typeof InteractiveMode.prototype] as (this: Context) => void,diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.tsindex de458155f5..3087d15699 100644--- a/packages/coding-agent/test/interactive-mode-status.test.ts+++ b/packages/coding-agent/test/interactive-mode-status.test.ts@@ -3471,16 +3471,17 @@ describe("InteractiveMode session switch command catalog", () => {describe("InteractiveMode Prime CLI onboarding", () => {type OnboardingSplashHandle = {- showProgress(message: string): void;dismiss(): void;};type OnboardingHarness = {shouldRunOnboarding(): boolean;markOnboardingShown(): void;runStartupOnboarding(): Promise<boolean>;- runOnboardingFlow(showPrimeCliSplash?: boolean): Promise<void>;+ runOnboardingFlow(): Promise<boolean>;applySelectedModel(model: AgentConnectionModel): Promise<void>;prepareForModelSelectionAfterLogin(authResult: AuthenticationResult): Promise<boolean>;+ askOnboardingProviders(signal: AbortSignal): Promise<void>;+ askOnboardingTraceOptIn(): Promise<void>;setupAutocompleteProvider(): void;};type OnboardingFake = OnboardingHarness & {@@ -4206,7 +4207,7 @@ describe("InteractiveMode Prime CLI onboarding", () => {expect(fakeThis.uiServices.settingsManager.setOnboardingShown).toHaveBeenCalledWith(true);});- test("persists onboarding only after the one-shot flow completes", async () => {+ test("persists onboarding only after the flow completes", async () => {let shown = false;let flushed = false;const fakeThis = createPrimeCliHarness(false);@@ -4217,71 +4218,93 @@ describe("InteractiveMode Prime CLI onboarding", () => {fakeThis.uiServices.settingsManager.flush = vi.fn(async () => {flushed = true;});- fakeThis.runOnboardingFlow = vi.fn(async (showPrimeCliSplash?: boolean) => {- expect(showPrimeCliSplash).toBe(true);- // The flag persists only after the flow completes with a ready model.+ fakeThis.runOnboardingFlow = vi.fn(async () => {expect(shown).toBe(false);expect(flushed).toBe(false);+ return true;});await expect(runStartupOnboarding.call(fakeThis)).resolves.toBe(true);expect(fakeThis.uiServices.settingsManager.setOnboardingShown).toHaveBeenCalledWith(true);expect(fakeThis.uiServices.settingsManager.flush).toHaveBeenCalledTimes(1);- expect(fakeThis.runOnboardingFlow).toHaveBeenCalledWith(true);});- test("cancelled Prime CLI splash exits onboarding before opening configuration", async () => {+ test("reports no completion when the block never mounts", async () => {const fakeThis = createPrimeCliHarness(false);fakeThis.showOnboardingSplash = vi.fn(async () => undefined);fakeThis.showConfigurationMenu = vi.fn(async () => {});- await expect(runOnboardingFlow.call(fakeThis)).resolves.toBeUndefined();+ await expect(runOnboardingFlow.call(fakeThis)).resolves.toBe(false);expect(fakeThis.showConfigurationMenu).not.toHaveBeenCalled();});- test("opens the Models tab after the Prime CLI splash", async () => {+ test("runs the sign-in flow even when Prime CLI credentials are on disk", async () => {const fakeThis = createPrimeCliHarness(false);- const configuration = createDeferred<void>();const dismiss = vi.fn();- fakeThis.showOnboardingSplash = vi.fn(async () => ({ showProgress: vi.fn(), dismiss }));- fakeThis.showConfigurationMenu = vi.fn(() => configuration.promise);+ fakeThis.showOnboardingSplash = vi.fn(async () => ({ dismiss }));+ fakeThis.createAuthFlows = vi.fn(() => ({+ runPrimeInferenceLogin: vi.fn(async () => ({+ status: "success" as const,+ providerId: PRIME_INFERENCE_PROVIDER_ID,+ providerName: "Prime Inference",+ authType: "api_key" as const,+ kind: "provider" as const,+ })),+ }));+ fakeThis.prepareForModelSelectionAfterLogin = vi.fn(async () => true);+ fakeThis.showConfigurationMenu = vi.fn(async () => {});- const onboarding = runOnboardingFlow.call(fakeThis);- await flushAsyncWork();+ await expect(runOnboardingFlow.call(fakeThis)).resolves.toBe(true);- expect(fakeThis.showConfigurationMenu).toHaveBeenCalledWith("models");+ expect(fakeThis.showOnboardingSplash).toHaveBeenCalledWith();+ expect(fakeThis.prepareForModelSelectionAfterLogin).toHaveBeenCalledTimes(1);+ // The model picker is no longer part of first launch.+ expect(fakeThis.showConfigurationMenu).not.toHaveBeenCalled();expect(dismiss).toHaveBeenCalledOnce();- expect(dismiss.mock.invocationCallOrder[0]).toBeLessThan(- vi.mocked(fakeThis.showConfigurationMenu).mock.invocationCallOrder[0]!,- );-- configuration.resolve();- await expect(onboarding).resolves.toBeUndefined();-- expect(dismiss).toHaveBeenCalledTimes(1);});- test("opens the Models tab when models are already available", async () => {+ test("never opens the model picker, even when models are already available", async () => {const fakeThis = createPrimeCliHarness(false);fakeThis.connectionState = createConnectionState({ model: undefined });fakeThis.getModelCandidates = vi.fn(async () => [primeModel]);+ fakeThis.showOnboardingSplash = vi.fn(async () => ({ showProgress: vi.fn(), dismiss: vi.fn() }));+ fakeThis.createAuthFlows = vi.fn(() => ({+ runPrimeInferenceLogin: vi.fn(async () => ({+ status: "success" as const,+ providerId: PRIME_INFERENCE_PROVIDER_ID,+ providerName: "Prime Inference",+ authType: "api_key" as const,+ kind: "provider" as const,+ })),+ }));+ fakeThis.prepareForModelSelectionAfterLogin = vi.fn(async () => true);fakeThis.showConfigurationMenu = vi.fn(async () => {});- await expect(runOnboardingFlow.call(fakeThis, false)).resolves.toBeUndefined();+ await expect(runOnboardingFlow.call(fakeThis)).resolves.toBe(true);- expect(fakeThis.getModelCandidates).toHaveBeenCalledTimes(1);- expect(fakeThis.showConfigurationMenu).toHaveBeenCalledWith("models");+ expect(fakeThis.showConfigurationMenu).not.toHaveBeenCalled();});- test("opens Prime login before the Models tab when no models are available", async () => {+ test("keeps onboarding pending when a configured user cancels the sign-in", async () => {+ // The harness already carries a working model and stored credentials.const fakeThis = createPrimeCliHarness(false);- fakeThis.connectionState = createConnectionState({ model: undefined });- fakeThis.getModelCandidates = vi.fn(async () => []);- const showProgress = vi.fn();- const dismiss = vi.fn();- fakeThis.showOnboardingSplash = vi.fn(async () => ({ showProgress, dismiss }));+ fakeThis.uiServices.settingsManager.setOnboardingShown = vi.fn();+ fakeThis.uiServices.settingsManager.flush = vi.fn(async () => {});+ // The user already has a working model, so readiness alone would look like+ // a completed flow; only the flow's own result may persist the flag.+ fakeThis.runOnboardingFlow = vi.fn(async () => false);++ await expect(runStartupOnboarding.call(fakeThis)).resolves.toBe(true);++ expect(fakeThis.uiServices.settingsManager.setOnboardingShown).not.toHaveBeenCalled();+ expect(fakeThis.uiServices.settingsManager.flush).not.toHaveBeenCalled();+ });++ test("reports no completion when a reset interrupts the last question", async () => {+ const fakeThis = createPrimeCliHarness(false);+ fakeThis.showOnboardingSplash = vi.fn(async () => ({ dismiss: vi.fn() }));fakeThis.createAuthFlows = vi.fn(() => ({runPrimeInferenceLogin: vi.fn(async () => ({status: "success" as const,@@ -4292,26 +4315,80 @@ describe("InteractiveMode Prime CLI onboarding", () => {})),}));fakeThis.prepareForModelSelectionAfterLogin = vi.fn(async () => true);- const configuration = createDeferred<void>();- fakeThis.showConfigurationMenu = vi.fn(() => configuration.promise);+ fakeThis.askOnboardingProviders = vi.fn(async () => {});+ // The reset settles the trace question and aborts the flow behind it.+ fakeThis.askOnboardingTraceOptIn = vi.fn(async () => {+ (fakeThis as unknown as { onboardingFlowAbort?: AbortController }).onboardingFlowAbort?.abort();+ });- const onboarding = runOnboardingFlow.call(fakeThis, false);- await flushAsyncWork();+ await expect(runOnboardingFlow.call(fakeThis)).resolves.toBe(false);+ });- expect(fakeThis.showOnboardingSplash).toHaveBeenCalledWith();- expect(showProgress).toHaveBeenNthCalledWith(1, "Signing in to Prime Intellect...");- expect(showProgress).toHaveBeenNthCalledWith(2, "Preparing models...");- expect(fakeThis.prepareForModelSelectionAfterLogin).toHaveBeenCalledTimes(1);- expect(fakeThis.showConfigurationMenu).toHaveBeenCalledWith("models");- expect(dismiss).toHaveBeenCalledOnce();- expect(dismiss.mock.invocationCallOrder[0]).toBeLessThan(- vi.mocked(fakeThis.showConfigurationMenu).mock.invocationCallOrder[0]!,+ test("stops asking for providers once the flow is aborted", async () => {+ const askOnboardingProviders = (InteractiveMode.prototype as unknown as OnboardingHarness).askOnboardingProviders;+ const abort = new AbortController();+ const showInlineAuthPanel = vi.fn();+ const fakeThis = {+ onboardingSplash: { setPanel: vi.fn(), getActivePanel: () => undefined },+ onboardingFlowAbort: abort,+ createAuthFlows: vi.fn(() => ({+ getLoginProviderOptions: vi.fn(() => [{ id: "openai", name: "OpenAI", category: "provider" }]),+ })),+ modelRegistry: { getProviderAuthStatus: vi.fn(() => ({ configured: false })) },+ ui: { requestRender: vi.fn() },+ showInlineAuthPanel,+ };+ // A reset aborts the flow and then tears the block down, which clears the+ // field: the question has to end on the signal it was handed.+ abort.abort();+ fakeThis.onboardingFlowAbort = undefined as unknown as AbortController;++ await expect(askOnboardingProviders.call(fakeThis, abort.signal)).resolves.toBeUndefined();++ expect(showInlineAuthPanel).not.toHaveBeenCalled();+ });++ test("settles the pending step when a reset unmounts its panel", () => {+ const showInlineAuthPanel = (+ InteractiveMode.prototype as unknown as {+ showInlineAuthPanel(component: unknown, options?: { onReset?: () => void }): (reason?: "reset") => void;+ }+ ).showInlineAuthPanel;+ const closers: ((reason?: "reset") => void)[] = [];+ const fakeThis = {+ onboardingSplash: { setPanel: vi.fn(), getActivePanel: () => undefined },+ ui: { setFocus: vi.fn(), requestRender: vi.fn() },+ inlineAuthPanelClosers: closers,+ };+ let settled = false;+ showInlineAuthPanel.call(+ fakeThis,+ {},+ {+ onReset: () => {+ settled = true;+ },+ },);- configuration.resolve();- await expect(onboarding).resolves.toBeUndefined();+ closers[0]?.("reset");++ expect(settled).toBe(true);+ });- expect(dismiss).toHaveBeenCalledTimes(1);+ test("ends the flow when the sign-in does not succeed", async () => {+ const fakeThis = createPrimeCliHarness(false);+ const dismiss = vi.fn();+ fakeThis.showOnboardingSplash = vi.fn(async () => ({ dismiss }));+ fakeThis.createAuthFlows = vi.fn(() => ({+ runPrimeInferenceLogin: vi.fn(async () => ({ status: "cancelled" as const })),+ }));+ fakeThis.prepareForModelSelectionAfterLogin = vi.fn(async () => true);++ await expect(runOnboardingFlow.call(fakeThis)).resolves.toBe(false);++ expect(fakeThis.prepareForModelSelectionAfterLogin).not.toHaveBeenCalled();+ expect(dismiss).toHaveBeenCalledOnce();});});diff --git a/packages/coding-agent/test/login-dialog.test.ts b/packages/coding-agent/test/login-dialog.test.tsindex b9682af645..5450664a7b 100644--- a/packages/coding-agent/test/login-dialog.test.ts+++ b/packages/coding-agent/test/login-dialog.test.ts@@ -192,6 +192,39 @@ describe("LoginDialogComponent", () => {}});+ it("keeps one blank row above the key hints across repeated prompts", () => {+ const dialog = new LoginDialogComponent(createFakeTui(), "prime-inference", () => {}, "Prime Inference");+ dialog.showPrompt("Enter API key:");+ const first = dialog.render(80).length;+ dialog.showPrompt("Enter API key:");++ // The second prompt adds its own separator and title, and moves the blank+ // row above the key hints instead of stacking another one.+ expect(dialog.render(80).length - first).toBe(2);+ });++ it("quits the app from ctrl+c only while onboarding passes onExit", async () => {+ const dialog = new LoginDialogComponent(+ createFakeTui(),+ "prime-inference",+ () => {},+ "Prime Inference",+ undefined,+ { onExit: () => onExitCalls.push("exit") },+ );+ const onExitCalls: string[] = [];++ dialog.handleInput("\x03");++ expect(onExitCalls).toEqual(["exit"]);++ const plain = new LoginDialogComponent(createFakeTui(), "prime-inference", () => {}, "Prime Inference");+ const prompt = plain.showPrompt("Enter API key:");+ plain.handleInput("\x03");+ // Outside onboarding, ctrl+c keeps cancelling the prompt.+ await expect(prompt).rejects.toThrow("Login cancelled");+ });+it("cancels the prompt with esc and ctrl+c", async () => {for (const key of ["\x1b", "\x03"]) {const dialog = new LoginDialogComponent(createFakeTui(), "prime-inference", () => {}, "Prime Inference");diff --git a/packages/coding-agent/test/onboarding-choice.test.ts b/packages/coding-agent/test/onboarding-choice.test.tsnew file mode 100644index 0000000000..fcb1677fec--- /dev/null+++ b/packages/coding-agent/test/onboarding-choice.test.ts@@ -0,0 +1,70 @@+import { setKeybindings, visibleWidth } from "@earendil-works/pi-tui";+import stripAnsi from "strip-ansi";+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { KeybindingsManager } from "../src/core/keybindings.js";+import { OnboardingChoiceComponent } from "../src/modes/interactive/components/onboarding-choice.js";+import { initTheme } from "../src/modes/interactive/theme/theme.js";++describe("OnboardingChoiceComponent", () => {+ beforeAll(() => {+ initTheme("dark");+ });++ beforeEach(() => {+ setKeybindings(new KeybindingsManager());+ });++ it("renders the prompt, the options and a grey note in the onboarding language", () => {+ const component = new OnboardingChoiceComponent(+ [{ label: "Share agent traces" }, { label: "Not now" }],+ () => {},+ () => {},+ {+ prompt: "Help improve Prime Agent by sharing agent traces?",+ note: "You can change this anytime with /traces.",+ },+ );+ const lines = component.render(90);+ const output = stripAnsi(lines.join("\n"));++ expect(output).toContain("Help improve Prime Agent by sharing agent traces?");+ expect(output).toContain("> Share agent traces");+ expect(output).toContain(" Not now");+ expect(output).toContain("You can change this anytime with /traces.");+ for (const line of lines) {+ expect(visibleWidth(line)).toBe(90);+ }+ });++ it("marks the active option with a caret and a selection wash", () => {+ const component = new OnboardingChoiceComponent(+ [{ label: "Personal account" }, { label: "Prime Intellect" }],+ () => {},+ () => {},+ );+ const lines = component.render(90);+ const selected = lines.find((line) => stripAnsi(line).includes("Personal account"));+ const other = lines.find((line) => stripAnsi(line).includes("Prime Intellect"));++ expect(selected ?? "").toMatch(/\x1b\[(4[0-9]|10[0-7]|48[;:])/);+ expect(other ?? "").not.toMatch(/\x1b\[(4[0-9]|10[0-7]|48[;:])/);+ });++ it("reports the confirmed option and cancellation", () => {+ const onSelect = vi.fn();+ const onCancel = vi.fn();+ const component = new OnboardingChoiceComponent(+ [{ label: "One" }, { label: "Two" }, { label: "Three" }],+ onSelect,+ onCancel,+ );++ component.handleInput("\x1b[B");+ component.handleInput("\x1b[B");+ component.handleInput("\r");+ expect(onSelect).toHaveBeenCalledWith(2);++ component.handleInput("\x1b");+ expect(onCancel).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/coding-agent/test/onboarding-picker.test.ts b/packages/coding-agent/test/onboarding-picker.test.tsnew file mode 100644index 0000000000..bfb73faf28--- /dev/null+++ b/packages/coding-agent/test/onboarding-picker.test.ts@@ -0,0 +1,83 @@+import { setKeybindings, visibleWidth } from "@earendil-works/pi-tui";+import stripAnsi from "strip-ansi";+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { KeybindingsManager } from "../src/core/keybindings.js";+import { OnboardingPickerComponent } from "../src/modes/interactive/components/onboarding-picker.js";+import { initTheme } from "../src/modes/interactive/theme/theme.js";++const items = [+ { id: "anthropic", label: "Anthropic (Claude Pro/Max)" },+ { id: "openai", label: "ChatGPT Plus/Pro", connected: true },+ { id: "copilot", label: "GitHub Copilot" },+ { id: "xai", label: "xAI (Grok)" },+ { id: "bedrock", label: "Amazon Bedrock" },+ { id: "azure", label: "Azure OpenAI" },+ { id: "groq", label: "Groq" },+ { id: "mistral", label: "Mistral" },+];++const render = (component: OnboardingPickerComponent) => stripAnsi(component.render(90).join("\n"));++describe("OnboardingPickerComponent", () => {+ beforeAll(() => {+ initTheme("dark");+ });++ beforeEach(() => {+ setKeybindings(new KeybindingsManager());+ });++ it("pins continue, shows a search field and a bounded viewport", () => {+ const component = new OnboardingPickerComponent(+ items,+ () => {},+ () => {},+ () => {},+ {+ prompt: "Connect other providers, or continue.",+ searchPlaceholder: "Search providers",+ },+ );+ const lines = component.render(90);+ const output = stripAnsi(lines.join("\n"));++ expect(output).toContain("Connect other providers, or continue.");+ expect(output).toContain("Search providers");+ expect(output).toContain("> Continue");+ expect(output).toContain("Anthropic (Claude Pro/Max)");+ // Six entries at a time, with the remainder called out.+ expect(output).not.toContain("Mistral");+ expect(output).toContain("2 more below");+ for (const line of lines) {+ expect(visibleWidth(line)).toBe(90);+ }+ });++ it("filters as the user types", () => {+ const component = new OnboardingPickerComponent(+ items,+ () => {},+ () => {},+ () => {},+ );+ for (const char of "groq") {+ component.handleInput(char);+ }+ const output = render(component);++ expect(output).toContain("Groq");+ expect(output).not.toContain("Anthropic (Claude Pro/Max)");+ });++ it("continues from the pinned action and cancels on escape", () => {+ const onContinue = vi.fn();+ const onCancel = vi.fn();+ const component = new OnboardingPickerComponent(items, () => {}, onContinue, onCancel);++ component.handleInput("\r");+ expect(onContinue).toHaveBeenCalledTimes(1);++ component.handleInput("\x1b");+ expect(onCancel).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/coding-agent/test/onboarding-startup.test.ts b/packages/coding-agent/test/onboarding-startup.test.tsindex 36bd49f6ca..4fa2bd3230 100644--- a/packages/coding-agent/test/onboarding-startup.test.ts+++ b/packages/coding-agent/test/onboarding-startup.test.ts@@ -1,12 +1,7 @@import type { Api, Model } from "@earendil-works/pi-ai";import { describe, expect, test } from "vitest";-import type { AuthStatus } from "../src/core/auth-storage.js";import { PRIME_INFERENCE_PROVIDER_ID } from "../src/core/prime-inference-auth.js";-import {- type OnboardingStartupState,- shouldRunOnboarding,- shouldRunPrimeCliOnboardingSplash,-} from "../src/modes/interactive/onboarding.js";+import { type OnboardingStartupState, shouldRunOnboarding } from "../src/modes/interactive/onboarding.js";function makeModel(provider: string): Model<Api> {return { id: "test-model", provider } as Model<Api>;@@ -16,7 +11,6 @@ function makeState(overrides: {onboardingShown: boolean;model: Model<Api> | undefined;modelHasAuth?: boolean;- primeAuthSource?: AuthStatus["source"];}): OnboardingStartupState {return {settingsManager: {@@ -25,60 +19,25 @@ function makeState(overrides: {modelRegistry: {refresh: () => {},hasConfiguredAuth: () => overrides.modelHasAuth ?? false,- getProviderAuthStatus: () => ({- configured: overrides.primeAuthSource !== undefined,- source: overrides.primeAuthSource,- }),},model: overrides.model,};}describe("startup onboarding decision", () => {- test("runs onboarding on first launch with Prime CLI auth", () => {- const state = makeState({- onboardingShown: false,- model: makeModel(PRIME_INFERENCE_PROVIDER_ID),- modelHasAuth: true,- primeAuthSource: "prime_cli",- });- expect(shouldRunPrimeCliOnboardingSplash(state)).toBe(true);- expect(shouldRunOnboarding(state)).toBe(true);- });-- test("runs onboarding on first launch when no model is available", () => {+ test("runs on a first launch, including when credentials are already on disk", () => {expect(shouldRunOnboarding(makeState({ onboardingShown: false, model: undefined }))).toBe(true);- });-- test("does not reopen onboarding after dismissal when the current model has no local auth", () => {expect(- shouldRunOnboarding(makeState({ onboardingShown: true, model: makeModel("anthropic"), modelHasAuth: false })),- ).toBe(false);+ shouldRunOnboarding(+ makeState({ onboardingShown: false, model: makeModel(PRIME_INFERENCE_PROVIDER_ID), modelHasAuth: true }),+ ),+ ).toBe(true);});- test("does not reopen onboarding after dismissal when no model is available", () => {+ test("never reopens once the flag is set", () => {expect(shouldRunOnboarding(makeState({ onboardingShown: true, model: undefined }))).toBe(false);- });-- test("skips onboarding once completed with a ready model", () => {- const state = makeState({- onboardingShown: true,- model: makeModel(PRIME_INFERENCE_PROVIDER_ID),- modelHasAuth: true,- primeAuthSource: "prime_cli",- });- expect(shouldRunPrimeCliOnboardingSplash(state)).toBe(false);- expect(shouldRunOnboarding(state)).toBe(false);- });-- test("skips the Prime CLI splash for non-Prime providers with ready auth", () => {- const state = makeState({- onboardingShown: false,- model: makeModel("anthropic"),- modelHasAuth: true,- primeAuthSource: "stored",- });- expect(shouldRunPrimeCliOnboardingSplash(state)).toBe(false);- expect(shouldRunOnboarding(state)).toBe(false);+ expect(+ shouldRunOnboarding(makeState({ onboardingShown: true, model: makeModel("anthropic"), modelHasAuth: true })),+ ).toBe(false);});});diff --git a/packages/coding-agent/test/prime-onboarding-splash.test.ts b/packages/coding-agent/test/prime-onboarding-splash.test.tsindex 9d19129176..2e8b58471a 100644--- a/packages/coding-agent/test/prime-onboarding-splash.test.ts+++ b/packages/coding-agent/test/prime-onboarding-splash.test.ts@@ -1,10 +1,13 @@-import { setKeybindings, visibleWidth } from "@earendil-works/pi-tui";+import { setKeybindings } from "@earendil-works/pi-tui";import stripAnsi from "strip-ansi";import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { KeybindingsManager } from "../src/core/keybindings.js";import { PrimeOnboardingSplashComponent } from "../src/modes/interactive/components/prime-onboarding-splash.js";import { initTheme } from "../src/modes/interactive/theme/theme.js";-import { PRIME_BUTTERFLY_LOGO } from "../src/themes/prime-logo.js";+import { PRIME_COMPACT_BUTTERFLY_LOGO } from "../src/themes/prime-logo.js";++const logoLines = PRIME_COMPACT_BUTTERFLY_LOGO.split("\n");+const firstLogoLine = logoLines[0]?.trim() ?? "";describe("PrimeOnboardingSplashComponent", () => {beforeAll(() => {@@ -19,108 +22,101 @@ describe("PrimeOnboardingSplashComponent", () => {vi.useRealTimers();});- it("renders a minimal first-run login action", () => {- const component = new PrimeOnboardingSplashComponent(- () => {},- () => {},- { getRows: () => 36 },- );+ it("exits the app on ctrl+c and ctrl+d instead of trapping the user", () => {+ for (const key of ["\x03", "\x04"]) {+ const onExit = vi.fn();+ const splash = new PrimeOnboardingSplashComponent(() => {}, { onExit });++ splash.handleInput(key);++ expect(onExit).toHaveBeenCalledOnce();+ }+ });++ it("renders the brand mark with the welcome line beneath it", () => {+ const component = new PrimeOnboardingSplashComponent(() => {}, { getRows: () => 36 });const lines = component.render(100);- const output = stripAnsi(lines.join("\n"));+ const rendered = lines.map((line) => stripAnsi(line));+ const output = rendered.join("\n");- expect(lines).toHaveLength(36);+ expect(output).toContain(firstLogoLine);expect(output).toContain("Welcome to PRIME Agent");- expect(output).toContain("Press Enter to login with Prime Intellect");- expect(output).toContain("·");- expect(output).not.toContain("prime agent");- expect(output).not.toContain("Research and infrastructure assistant for high-context work.");- expect(output).not.toContain("• Inspect logs, evals, training runs, and environments.");- expect(output).not.toContain("• Keep context alive in Python state and artifacts.");- expect(output).not.toContain("• Delegate focused work through recursive RLM calls.");- expect(output).not.toContain("long-context coding tasks");- expect(output).not.toContain("Login with Prime Intellect");- expect(output).not.toContain("████▀▀▀██▄");- expect(output).not.toContain("Get Started");- expect(output).not.toContain("One account for models, inference, and coding sessions.");- expect(output).not.toContain("Choose your model and start building.");- expect(output).not.toContain("╭───╮");- expect(output).not.toContain("PRIME INTELLECT");- expect(output).not.toContain("cancel");- expect(output).not.toContain("A coding agent connected to Prime Intellect.");- expect(output).not.toContain("Continue with Prime Intellect");- expect(output).not.toContain("Use one account for managed inference, model access, and usage.");- expect(output).not.toContain("/* BUILD */");- expect(output).not.toContain("/* EVALUATE */");- expect(output).not.toContain("/* TRAIN */");- expect(output).not.toContain("/* DEPLOY */");- expect(output).not.toContain("required for first-time setup");- expect(output).not.toContain("Start with your Prime Intellect account.");- expect(output).not.toContain("Log in with Prime Intellect");- expect(output).not.toContain("→");- expect(output).not.toContain("Use a subscription");- expect(output).not.toContain("Use an API key");- expect(output).toContain(PRIME_BUTTERFLY_LOGO.split("\n")[0].trim());- for (const line of lines) {- expect(visibleWidth(line)).toBeLessThanOrEqual(100);+ expect(output).toContain("> Log in with Prime Intellect");+ // Signing in is the only route forward.+ expect(output).not.toContain("Continue later");+ // The description is present and wrapped inside the block rather than+ // running past its width; the wording itself is not the behaviour.+ const descriptionRows = rendered.filter((line) => line.trim().length > 0);+ expect(descriptionRows.length).toBeGreaterThan(logoLines.length);+ for (const line of rendered) {+ expect(stripAnsi(line).trimEnd().length).toBeLessThanOrEqual(100);}++ const lastLogoRow = rendered.findIndex((line) => line.includes(logoLines[logoLines.length - 1]?.trim() ?? ""));+ const brandRow = rendered.findIndex((line) => line.includes("Welcome to PRIME Agent"));+ const actionRow = rendered.findIndex((line) => line.includes("Log in with Prime Intellect"));+ expect(brandRow).toBeGreaterThan(lastLogoRow);+ expect(actionRow).toBeGreaterThan(brandRow);+ });++ it("left aligns the mark, the welcome line and the actions", () => {+ const component = new PrimeOnboardingSplashComponent(() => {}, { getRows: () => 40 });+ const rendered = component.render(100).map((line) => stripAnsi(line));+ const output = rendered.join("\n");++ expect(output).not.toContain("Enter");+ expect(output).not.toContain("Esc");++ const brandLine = rendered.find((line) => line.includes("Welcome to PRIME Agent"));+ const actionLine = rendered.find((line) => line.includes("Log in with Prime Intellect"));+ // One shared left edge for the welcome line and the action.+ expect(brandLine?.indexOf("Welcome")).toBe(actionLine?.indexOf(">"));+ // Everything hugs the left edge; only the animated field spans the pane.+ expect(brandLine?.search(/\S/)).toBeLessThanOrEqual(2);+ // The mark is indented a little further right than the text column, but is+ // still left aligned rather than centred (the field spans the pane, so the+ // mark's own glyphs pin its position rather than leading whitespace).+ const wingGlyphs = "\u259f\u2588\u2588\u2599";+ const markLine = rendered.find((line) => line.includes(wingGlyphs));+ expect(markLine).toBeDefined();+ const markColumn = markLine?.indexOf(wingGlyphs) ?? -1;+ expect(markColumn).toBeGreaterThan(brandLine?.search(/\S/) ?? 0);+ expect(markColumn).toBeLessThanOrEqual(16);});it("starts Prime login on confirm", () => {let selected = false;- const component = new PrimeOnboardingSplashComponent(- () => {- selected = true;- },- () => {},- );+ const component = new PrimeOnboardingSplashComponent(() => {+ selected = true;+ });component.handleInput("\r");expect(selected).toBe(true);});- it("renders a model selection action when auth is already available", () => {- const component = new PrimeOnboardingSplashComponent(- () => {},- () => {},- { getRows: () => 36, continueActionLabel: "choose a model" },- );+ it("never falls back to the intro once a flow has started", () => {+ const component = new PrimeOnboardingSplashComponent(() => {}, { getRows: () => 36 });+ component.setPanel({ render: () => ["panel row"], invalidate: () => {} }, "Login with Prime Intellect");+ // Between two flow panels the block must not flash the first screen back.+ component.setPanel(undefined);const output = stripAnsi(component.render(100).join("\n"));- expect(output).toContain("Press Enter to choose a model");- expect(output).not.toContain("Press Enter to login with Prime Intellect");- });-- it("shows progress and ignores input while onboarding advances", () => {- const onSelect = vi.fn();- const onCancel = vi.fn();- const component = new PrimeOnboardingSplashComponent(onSelect, onCancel, { getRows: () => 36 });-- component.showProgress("Preparing models...");- component.handleInput("\r");- component.handleInput("\x1b");-- const output = stripAnsi(component.render(100).join("\n"));- expect(output).toContain("Preparing models...");- expect(output).not.toContain("Press Enter");- expect(onSelect).not.toHaveBeenCalled();- expect(onCancel).not.toHaveBeenCalled();+ expect(output).toContain("Welcome to PRIME Agent");+ expect(output).not.toContain("Log in with Prime Intellect");+ expect(output).not.toContain("monitor dozens of experiments");});- it("animates the splash at an interactive cadence", () => {+ it("animates the mark at an interactive cadence", () => {vi.useFakeTimers();let renderRequests = 0;- const component = new PrimeOnboardingSplashComponent(- () => {},- () => {},- {- getRows: () => 36,- requestRender: () => {- renderRequests++;- },- animationIntervalMs: 20,+ const component = new PrimeOnboardingSplashComponent(() => {}, {+ getRows: () => 36,+ requestRender: () => {+ renderRequests++;},- );+ animationIntervalMs: 20,+ });const firstRender = stripAnsi(component.render(100).join("\n"));vi.advanceTimersByTime(60);@@ -130,22 +126,5 @@ describe("PrimeOnboardingSplashComponent", () => {expect(renderRequests).toBe(3);expect(secondRender).not.toBe(firstRender);expect(secondRender).toContain("Welcome to PRIME Agent");- expect(secondRender).toContain("Press Enter to login with Prime Intellect");- });-- it("centers stacked content in narrow terminals", () => {- const component = new PrimeOnboardingSplashComponent(- () => {},- () => {},- { getRows: () => 40 },- );- const rendered = component.render(60).map((line) => stripAnsi(line));- const logoLine = rendered.find((line) => line.includes(PRIME_BUTTERFLY_LOGO.split("\n")[0].trim()));- const brandLine = rendered.find((line) => line.includes("Welcome to PRIME Agent"));- const hintLine = rendered.find((line) => line.includes("Press Enter to login with Prime Intellect"));-- expect(logoLine?.search(/\S/)).toBeGreaterThan(0);- expect(brandLine?.search(/\S/)).toBeGreaterThan(0);- expect(hintLine?.search(/\S/)).toBeGreaterThan(0);});});diff --git a/packages/coding-agent/test/suite/regressions/4658-onboarding-transitions.test.ts b/packages/coding-agent/test/suite/regressions/4658-onboarding-transitions.test.tsindex 57475c4125..aa9eb3d73f 100644--- a/packages/coding-agent/test/suite/regressions/4658-onboarding-transitions.test.ts+++ b/packages/coding-agent/test/suite/regressions/4658-onboarding-transitions.test.ts@@ -10,7 +10,6 @@ import { initTheme } from "../../../src/modes/interactive/theme/theme.js";import { createHarness, type Harness } from "../harness.js";interface OnboardingSplashHandle {- showProgress(message: string): void;dismiss(): void;}@@ -72,13 +71,11 @@ describe("ENG-4658 onboarding transitions", () => {}});- test("dismisses the splash before opening first-launch model selection inline", async () => {+ test("finishes first-launch onboarding after login without the model picker", async () => {const harness = await createHarness({ provider: "prime-inference", withConfiguredAuth: false });harnesses.push(harness);const order: string[] = [];- const configuration = deferred<void>();const splash: OnboardingSplashHandle = {- showProgress: (message) => order.push(`progress:${message}`),dismiss: () => order.push("dismiss"),};const fakeThis = Object.create(InteractiveMode.prototype) as InteractiveOnboardingHarness;@@ -103,29 +100,19 @@ describe("ENG-4658 onboarding transitions", () => {});fakeThis.showConfigurationMenu = vi.fn((tab) => {order.push(`configuration:${tab}`);- return configuration.promise;+ return Promise.resolve();});- const onboarding = fakeThis.runOnboardingFlow(false);- await vi.waitFor(() => expect(fakeThis.showConfigurationMenu).toHaveBeenCalledWith("models"));-- // The splash covers the screen, so onboarding logins must mount above it- // as overlays instead of inline behind it.- expect(fakeThis.createAuthFlows).toHaveBeenCalledWith({ overlay: true });-- expect(order.slice(-2)).toEqual(["dismiss", "configuration:models"]);- configuration.resolve();- await onboarding;+ await fakeThis.runOnboardingFlow(false);+ // The login and the questions after it mount inside the onboarding block,+ // so the flows are the inline ones rather than overlays.+ expect(fakeThis.createAuthFlows).toHaveBeenCalledWith();expect(fakeThis.showOnboardingSplash).toHaveBeenCalledWith();- expect(order).toEqual([- "progress:Signing in to Prime Intellect...",- "login",- "progress:Preparing models...",- "prepare",- "dismiss",- "configuration:models",- ]);+ // Onboarding now ends at the trace question; the model picker is no longer+ // part of the first-launch sequence.+ expect(fakeThis.showConfigurationMenu).not.toHaveBeenCalled();+ expect(order).toEqual(["login", "prepare", "dismiss"]);});test("swaps the inline picker for the login panel and restores the draft after closing", async () => {