Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Animate the Meet switch-buddy opening, and check providers sooner (CHOO-3236) (#932)

Louis Amaudruz23be81c6d29a
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller.ts
index 7bf011bc8..dcc324c90 100644
--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/controller.ts
@@ -1,12 +1,14 @@
import { homedir } from 'node:os';
+import { machineProvider } from '@main/core/managed-agents/owned-machines';
import { getServer } from '@main/core/switch-servers/servers-store';
import type {
EmbeddedControllerOverview,
MachineDetailsChange,
} from '@shared/core/embedded-controller/embedded-controller';
+import type { MachineProvider } from '@shared/core/managed-agents/managed-agents';
import { createRPCController } from '@shared/lib/ipc/rpc';
import { defaultWorkspacePath, serverWorkspacesDir } from './controller-files';
-import { embeddedControllerService } from './embedded-controllers';
+import { embeddedControllerService, providerPrecheck } from './embedded-controllers';
/** "Run managed agents on this computer", per Switch server. */
export const embeddedControllerController = createRPCController({
@@ -28,6 +30,19 @@ export const embeddedControllerController = createRPCController({
recheckProviders: (serverId: string): Promise<void> =>
embeddedControllerService.recheckProviders(serverId),
+ /**
+ * Checks this computer's providers now, ahead of any controller, for the
+ * one started later to take; as onboarding opens. Returns at once.
+ */
+ precheckProviders: (): void => providerPrecheck.start(),
+
+ /**
+ * What that check has found so far, as a machine's providers read; null
+ * when it was not started in this session.
+ */
+ precheckedProviders: async (): Promise<MachineProvider[] | null> =>
+ (await providerPrecheck.results())?.map(machineProvider) ?? null,
+
/** Renames this computer as a machine and/or changes its description, on the server. */
updateDetails: (params: { serverId: string; changes: MachineDetailsChange }): Promise<void> =>
embeddedControllerService.updateDetails(params.serverId, params.changes),
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.test.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.test.ts
index 0b61d597d..d698b5dee 100644
--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.test.ts
@@ -90,6 +90,7 @@ function service(overrides: Partial<EmbeddedControllerDeps> = {}): EmbeddedContr
revokeGraceMs: 200,
stopTimeoutMs: 200,
movedAgents: async () => moved,
+ providerSeed: () => null,
...overrides,
});
services.push(created);
@@ -170,6 +171,14 @@ afterEach(async () => {
});
describe('EmbeddedControllerService', () => {
+ it('hands the controller the provider checks made ahead of it', async () => {
+ await enabled({ providerSeed: () => '/data/provider-precheck.json' });
+ const args = calls[0]!.args;
+ expect(
+ args.slice(args.indexOf('--provider-seed'), args.indexOf('--provider-seed') + 2)
+ ).toEqual(['--provider-seed', '/data/provider-precheck.json']);
+ });
+
it('enrolls, keeps the credential in the secrets store only, and hands it to the child on stdin', async () => {
await enabled();
expect(management.enroll).toHaveBeenCalledWith(WORKSPACE, {
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.ts
index 0978f3a83..7add58c52 100644
--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controller-service.ts
@@ -88,6 +88,8 @@ export type EmbeddedControllerDeps = {
stopTimeoutMs: number;
/** The Console agents moved onto this computer's controller for the server, by name. */
movedAgents: (serverId: string) => Promise<string[]>;
+ /** Provider checks made ahead of the controller, for it to take, or null when there are none. */
+ providerSeed: () => string | null;
};
const SUPPORTED_PLATFORMS: readonly NodeJS.Platform[] = ['darwin', 'linux', 'win32'];
@@ -95,6 +97,10 @@ const SUPPORTED_PLATFORMS: readonly NodeJS.Platform[] = ['darwin', 'linux', 'win
/** Every provider's sign-in check runs at once; the slowest allows itself 15 seconds. */
const RECHECK_TIMEOUT_MS = 60_000;
+function providerSeedArgs(file: string | null): string[] {
+ return file === null ? [] : ['--provider-seed', file];
+}
+
/** Why managed agents cannot run on `platform`, or null when they can. */
export function unsupportedPlatformReason(platform: NodeJS.Platform): string | null {
return SUPPORTED_PLATFORMS.includes(platform)
@@ -479,6 +485,7 @@ export class EmbeddedControllerService {
'--credential-stdin',
'--shared-host-bundle',
this.deps.bundles.sharedHost(),
+ ...providerSeedArgs(this.deps.providerSeed()),
],
env: {
...this.deps.env(),
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controllers.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controllers.ts
index 1343ab90f..f31aca427 100644
--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controllers.ts
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/embedded-controllers.ts
@@ -1,4 +1,5 @@
import { execFile, execFileSync, spawn } from 'node:child_process';
+import { readFile } from 'node:fs/promises';
import { hostname, release } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
@@ -23,6 +24,7 @@ import {
import { DEFAULT_BACKOFF } from './controller-supervisor';
import { EmbeddedControllerService } from './embedded-controller-service';
import { gatewayManagementPort } from './management-port';
+import { ProviderPrecheck } from './provider-precheck';
const execute = promisify(execFile);
@@ -69,6 +71,34 @@ function computerName(): string {
return hostname();
}
+/** Started as onboarding opens; see {@link ProviderPrecheck}. */
+export const providerPrecheck = new ProviderPrecheck({
+ execPath: process.execPath,
+ bundles: {
+ controller: resolveAgentControllerBundlePath,
+ sharedHost: resolveSharedHostBundlePath,
+ },
+ env: () => process.env,
+ seedFile: () => join(base(), 'provider-precheck.json'),
+ probeDir: () => join(base(), 'provider-precheck'),
+ execute: async (executable, args, env) => {
+ // Every provider's check allows itself well under this; it is a backstop.
+ await execute(executable, args, { env, timeout: 120_000, windowsHide: true });
+ },
+ log: {
+ warn: (message, fields) => log.warn(message, { event: 'embedded_controller', ...fields }),
+ },
+ read: async (file) => {
+ try {
+ return await readFile(file, 'utf8');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
+ throw error;
+ }
+ },
+ now: Date.now,
+});
+
export const embeddedControllerService = new EmbeddedControllerService({
platform: process.platform,
machine: () => ({
@@ -122,4 +152,5 @@ export const embeddedControllerService = new EmbeddedControllerService({
}
return names;
},
+ providerSeed: () => providerPrecheck.seedFile(),
});
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/provider-precheck.test.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/provider-precheck.test.ts
new file mode 100644
index 000000000..b56372914
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/provider-precheck.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it, vi } from 'vitest';
+import { ProviderPrecheck, type ProviderPrecheckDeps } from './provider-precheck';
+
+function precheck(overrides: Partial<ProviderPrecheckDeps> = {}) {
+ let clock = 1_000_000;
+ const execute = vi.fn(async () => {});
+ const warn = vi.fn();
+ const service = new ProviderPrecheck({
+ execPath: '/app/electron',
+ bundles: {
+ controller: () => '/app/agent-controller.mjs',
+ sharedHost: () => '/app/shared-host.mjs',
+ },
+ env: () => ({ PATH: '/usr/bin' }),
+ seedFile: () => '/data/provider-precheck.json',
+ probeDir: () => '/data/provider-precheck',
+ execute,
+ log: { warn },
+ read: async () => null,
+ now: () => clock,
+ ...overrides,
+ });
+ return { service, execute, warn, advance: (ms: number) => (clock += ms) };
+}
+
+describe('ProviderPrecheck', () => {
+ it("runs the controller's own precheck, on Electron as Node, and offers its file after", async () => {
+ const { service, execute } = precheck();
+ expect(service.seedFile()).toBeNull();
+ service.start();
+ expect(execute).toHaveBeenCalledWith(
+ '/app/electron',
+ [
+ '/app/agent-controller.mjs',
+ 'precheck',
+ '--out',
+ '/data/provider-precheck.json',
+ '--probe-dir',
+ '/data/provider-precheck',
+ '--shared-host-bundle',
+ '/app/shared-host.mjs',
+ ],
+ { PATH: '/usr/bin', ELECTRON_RUN_AS_NODE: '1', SWITCH_CONTROLLER_LOG_LEVEL: 'warn' }
+ );
+ expect(service.seedFile()).toBe('/data/provider-precheck.json');
+ });
+
+ it('runs once while running or fresh, and again once stale', async () => {
+ const { service, execute, advance } = precheck();
+ service.start();
+ service.start();
+ await vi.waitFor(() => expect(execute).toHaveBeenCalledTimes(1));
+ await Promise.resolve();
+ service.start();
+ expect(execute).toHaveBeenCalledTimes(1);
+ advance(10 * 60 * 1000);
+ service.start();
+ expect(execute).toHaveBeenCalledTimes(2);
+ });
+
+ it('says so in the log when it fails, leaving the checks to the controller', async () => {
+ const { service, warn } = precheck({
+ execute: async () => {
+ throw new Error('spawn failed');
+ },
+ });
+ service.start();
+ await vi.waitFor(() =>
+ expect(warn).toHaveBeenCalledWith('Could not check the providers ahead of the controller', {
+ error: 'spawn failed',
+ })
+ );
+ });
+
+ it('offers what it has found so far, fresh and from this session', async () => {
+ const at = (offset: number) => new Date(1_000_000 + offset).toISOString();
+ const file = JSON.stringify({
+ providers: [
+ { status: { provider: 'claude', installed: true, auth: 'ok', checked_at: at(500) } },
+ { status: { provider: 'codex', installed: true, auth: 'missing', checked_at: at(600) } },
+ {
+ status: {
+ provider: 'cursor',
+ installed: false,
+ auth: 'unknown',
+ checked_at: at(-60_000),
+ },
+ },
+ ],
+ });
+ const { service, advance } = precheck({ read: async () => file });
+ expect(await service.results()).toBeNull();
+ service.start();
+ expect(await service.results()).toEqual([
+ { provider: 'claude', installed: true, auth: 'ok' },
+ { provider: 'codex', installed: true, auth: 'missing' },
+ ]);
+ advance(10 * 60 * 1000 + 1_000);
+ expect(await service.results()).toEqual([]);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/provider-precheck.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/provider-precheck.ts
new file mode 100644
index 000000000..94a17fee5
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/provider-precheck.ts
@@ -0,0 +1,118 @@
+/**
+ * Checks this computer's providers as onboarding opens, before it is enrolled
+ * as a machine anywhere, with the controller's own `precheck`: the same
+ * checks its controller runs, on the same binary and environment. The
+ * controller started later takes the results (`--provider-seed`), so its
+ * first report already says what is signed in, rather than checking from
+ * scratch once enrolled.
+ */
+export type ProviderPrecheckDeps = {
+ execPath: string;
+ bundles: { controller: () => string; sharedHost: () => string };
+ env: () => NodeJS.ProcessEnv;
+ /** Where the results go, written as each check comes back. */
+ seedFile: () => string;
+ /** Where the checks run, and the CLIs keep what they write when asked their version. */
+ probeDir: () => string;
+ /** Runs the check to its end; rejects, saying why, when it fails. */
+ execute: (executable: string, args: string[], env: NodeJS.ProcessEnv) => Promise<void>;
+ log: { warn: (message: string, fields?: Record<string, unknown>) => void };
+ /** The file's text, or null when there is none yet. */
+ read: (file: string) => Promise<string | null>;
+ now: () => number;
+};
+
+/** A provider as the precheck found it, in the terms a controller reports it to Switch. */
+export type PrecheckedProvider = {
+ provider: string;
+ installed: boolean;
+ auth: 'ok' | 'expired' | 'missing' | 'unknown';
+};
+
+/** A check older than this is made again when asked; the controller takes none older either. */
+const FRESH_MS = 10 * 60 * 1000;
+
+export class ProviderPrecheck {
+ private running: Promise<void> | null = null;
+ private startedAt: number | null = null;
+
+ constructor(private readonly deps: ProviderPrecheckDeps) {}
+
+ /** Starts the checks, unless they are running or ran a short while ago. */
+ start(): void {
+ if (this.running) return;
+ if (this.startedAt !== null && this.deps.now() - this.startedAt < FRESH_MS) return;
+ this.startedAt = this.deps.now();
+ this.running = this.deps
+ .execute(
+ this.deps.execPath,
+ [
+ this.deps.bundles.controller(),
+ 'precheck',
+ '--out',
+ this.deps.seedFile(),
+ '--probe-dir',
+ this.deps.probeDir(),
+ '--shared-host-bundle',
+ this.deps.bundles.sharedHost(),
+ ],
+ { ...this.deps.env(), ELECTRON_RUN_AS_NODE: '1', SWITCH_CONTROLLER_LOG_LEVEL: 'warn' }
+ )
+ .catch((error: unknown) => {
+ // The controller checks every provider itself, as it did before.
+ this.deps.log.warn('Could not check the providers ahead of the controller', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ })
+ .finally(() => {
+ this.running = null;
+ });
+ }
+
+ /**
+ * The file of checks for a controller starting now, or null when none were
+ * started in this session. Results still coming in are fine: the controller
+ * takes those already written and checks the rest itself.
+ */
+ seedFile(): string | null {
+ return this.startedAt === null ? null : this.deps.seedFile();
+ }
+
+ /**
+ * What the checks started in this session have found so far, still fresh;
+ * null when none were started. For a page that cannot wait for this
+ * computer's controller to report.
+ */
+ async results(): Promise<PrecheckedProvider[] | null> {
+ if (this.startedAt === null) return null;
+ const text = await this.deps.read(this.deps.seedFile());
+ if (text === null) return [];
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch (error) {
+ this.deps.log.warn('The provider checks made ahead of the controller are not readable', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return [];
+ }
+ const entries = (parsed as { providers?: unknown }).providers;
+ if (!Array.isArray(entries)) return [];
+ return entries.flatMap((entry): PrecheckedProvider[] => {
+ const status = (entry as { status?: Record<string, unknown> }).status;
+ if (!status) return [];
+ const { provider, installed, auth, checked_at: checkedAt } = status;
+ if (
+ typeof provider !== 'string' ||
+ typeof installed !== 'boolean' ||
+ (auth !== 'ok' && auth !== 'expired' && auth !== 'missing' && auth !== 'unknown') ||
+ typeof checkedAt !== 'string'
+ )
+ return [];
+ // Checked before this session's start: a file left from an earlier one.
+ const at = Date.parse(checkedAt);
+ if (!(at >= this.startedAt! - 1000) || this.deps.now() - at >= FRESH_MS) return [];
+ return [{ provider, installed, auth }];
+ });
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-flow.tsx b/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-flow.tsx
index 44db616a8..787282b44 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-flow.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/onboarding/onboarding-flow.tsx
@@ -12,6 +12,7 @@ import { switchServersStore } from '@renderer/features/switch-servers/switch-ser
import { useSwitchCloud } from '@renderer/features/switch-servers/use-switch-cloud';
import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { describeFailure } from '@renderer/lib/errors/describe-failure';
+import { rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { report } from '@renderer/lib/telemetry/report';
import { WizardChromeProvider } from '@renderer/lib/ui/wizard-frame';
@@ -97,6 +98,12 @@ function funnelPath(page: OnboardingPage): RendererTelemetryEvents['onboarding_p
export const OnboardingFlow = observer(function OnboardingFlow() {
const { navigate } = useNavigate();
const page = onboardingStore.page;
+ // switch-buddy runs on this computer at the end, whatever server is chosen:
+ // its providers are checked now, while the person signs in, so the buddy's
+ // page knows what is signed in by the time it opens.
+ useEffect(() => {
+ void rpc.embeddedController.precheckProviders();
+ }, []);
// Every page as it opens, so the last one an install reports is where it
// stopped.
useEffect(() => {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-face.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-face.tsx
new file mode 100644
index 000000000..c3e67936d
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-face.tsx
@@ -0,0 +1,136 @@
+import { motion } from 'motion/react';
+import { useEffect, useState } from 'react';
+
+/**
+ * switch-buddy's face drawn as a vector, the same picture as its avatar
+ * image, so it can blink and smile. Drawn in the image's own 256×256 frame:
+ * the face is a rounded square turned a few degrees, the eyes sit inside it.
+ */
+const BODY = '#8FB1F7';
+const INK = '#16181D';
+const TILT = 5.7;
+const EYES = [
+ { x: 96.6, y: 125.1, glintX: 100.6, glintY: 120.2 },
+ { x: 158.1, y: 128, glintX: 162.2, glintY: 123.1 },
+];
+const EYE_RADIUS = 14.5;
+
+type Expression = { blink: boolean; smile: boolean };
+
+const BLINK_CLOSE = { duration: 0.07, ease: [0.4, 0, 1, 1] } as const;
+const BLINK_OPEN = { duration: 0.12, ease: [0, 0, 0.2, 1] } as const;
+const SMILE_SPRING = { type: 'spring', stiffness: 260, damping: 18 } as const;
+
+export function BuddyFace({ size, expression }: { size: number; expression: Expression }) {
+ // A smile is the eyes alone: each round eye gives way to a curved, happy one.
+ const smiling = expression.smile && !expression.blink;
+ return (
+ <svg width={size} height={size} viewBox="0 0 256 256" aria-hidden className="block">
+ <g transform={`rotate(${TILT} 128 128)`}>
+ <rect x={48} y={48} width={160} height={160} rx={38} fill={BODY} />
+ {EYES.map((eye) => (
+ <g key={eye.x}>
+ <motion.g
+ initial={false}
+ animate={{
+ scaleY: expression.blink ? 0.08 : smiling ? 0.3 : 1,
+ opacity: smiling ? 0 : 1,
+ }}
+ transition={
+ expression.blink
+ ? BLINK_CLOSE
+ : smiling
+ ? { ...SMILE_SPRING, opacity: { duration: 0.1 } }
+ : { ...BLINK_OPEN, opacity: { duration: 0.12, delay: 0.04 } }
+ }
+ >
+ <circle cx={eye.x} cy={eye.y} r={EYE_RADIUS} fill={INK} />
+ <circle cx={eye.glintX} cy={eye.glintY} r={4} fill="#fff" />
+ </motion.g>
+ <motion.path
+ d={`M${eye.x - 12} ${eye.y + 4} Q${eye.x} ${eye.y - 14} ${eye.x + 12} ${eye.y + 4}`}
+ fill="none"
+ stroke={INK}
+ strokeWidth={7}
+ strokeLinecap="round"
+ initial={false}
+ animate={{
+ pathLength: smiling ? 1 : 0,
+ opacity: smiling ? 1 : 0,
+ y: smiling ? 0 : 4,
+ }}
+ transition={{
+ pathLength: SMILE_SPRING,
+ y: SMILE_SPRING,
+ opacity: { duration: smiling ? 0.08 : 0.14 },
+ }}
+ />
+ </g>
+ ))}
+ </g>
+ </svg>
+ );
+}
+
+function between(min: number, max: number): number {
+ return min + Math.random() * (max - min);
+}
+
+/**
+ * A face that blinks every few seconds, now and then twice, and smiles once
+ * in a while, never both at once. Still while `alive` is false.
+ */
+export function useBuddyExpression(alive: boolean): Expression {
+ const [expression, setExpression] = useState<Expression>({ blink: false, smile: false });
+
+ useEffect(() => {
+ if (!alive) return;
+ const timers = new Set<ReturnType<typeof setTimeout>>();
+ let stopped = false;
+ const later = (seconds: number, run: () => void) => {
+ const timer = setTimeout(() => {
+ timers.delete(timer);
+ if (!stopped) run();
+ }, seconds * 1000);
+ timers.add(timer);
+ };
+ let smiling = false;
+
+ const blinkOnce = (then: () => void) => {
+ setExpression((current) => ({ ...current, blink: true }));
+ later(0.11, () => {
+ setExpression((current) => ({ ...current, blink: false }));
+ then();
+ });
+ };
+ const scheduleBlink = (seconds: number) =>
+ later(seconds, () => {
+ if (smiling) return scheduleBlink(between(0.8, 1.6));
+ blinkOnce(() => {
+ if (Math.random() < 0.18)
+ later(0.16, () => blinkOnce(() => scheduleBlink(between(2.6, 5.4))));
+ else scheduleBlink(between(2.6, 5.4));
+ });
+ });
+ const scheduleSmile = (seconds: number) =>
+ later(seconds, () => {
+ smiling = true;
+ setExpression({ blink: false, smile: true });
+ later(between(1.3, 2), () => {
+ smiling = false;
+ setExpression({ blink: false, smile: false });
+ scheduleSmile(between(7, 12));
+ });
+ });
+
+ scheduleBlink(between(0.9, 1.6));
+ scheduleSmile(between(3.2, 4.4));
+ return () => {
+ stopped = true;
+ for (const timer of timers) clearTimeout(timer);
+ setExpression({ blink: false, smile: false });
+ };
+ }, [alive]);
+
+ return expression;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-intro-lines.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-intro-lines.tsx
index 8f741bb54..b7c9b9bd2 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-intro-lines.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-intro-lines.tsx
@@ -1,24 +1,36 @@
import type { ReactNode } from 'react';
-/** switch-buddy's few lines about itself, as Meet switch-buddy shows them. */
+/** switch-buddy's few lines about itself. */
+export function buddyIntroLines(firstName: string | null): string[] {
+ return [
+ `Hey${firstName ? ` ${firstName}` : ''}! I’ll be your assistant for everything Switch.`,
+ 'I can create new agents for you.',
+ 'Also bring your human and agent teams into different rooms.',
+ '…and set up and manage your workflows, permissions and guardrails!',
+ 'Ready to go?',
+ ];
+}
+
+/** The lines, as bubbles, all at once. */
export function BuddyIntroLines({ firstName }: { firstName: string | null }) {
return (
- <div className="mx-auto flex w-full max-w-[540px] flex-col items-start gap-3">
- <Line>
- Hey{firstName ? ` ${firstName}` : ''}! I’ll be your assistant for everything Switch.
- </Line>
- <Line>I can create new agents for you.</Line>
- <Line>Also bring your human and agent teams into different rooms.</Line>
- <Line>…and set up and manage your workflows, permissions and guardrails!</Line>
- <Line>Ready to go?</Line>
- </div>
+ <IntroBubbles>
+ {buddyIntroLines(firstName).map((line) => (
+ <IntroBubble key={line}>{line}</IntroBubble>
+ ))}
+ </IntroBubbles>
);
}
-function Line({ children }: { children: ReactNode }) {
+export function IntroBubbles({ children }: { children: ReactNode }) {
return (
- <p className="rounded-2xl bg-background px-4 py-3 text-sm text-foreground shadow-sm">
- {children}
- </p>
+ <div className="mx-auto flex w-full max-w-[540px] flex-col items-start gap-3">{children}</div>
);
}
+
+export const INTRO_BUBBLE_CLASS =
+ 'rounded-2xl bg-background px-4 py-3 text-sm text-foreground shadow-sm emdark:bg-background-2';
+
+function IntroBubble({ children }: { children: ReactNode }) {
+ return <p className={INTRO_BUBBLE_CLASS}>{children}</p>;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-providers.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-providers.test.ts
index a28bc14cc..327084a74 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-providers.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-providers.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import type { OwnedMachine } from '@shared/core/managed-agents/managed-agents';
-import { buddyProviders } from './buddy-providers';
+import { type BuddyProvider, buddyProviders, startButtons } from './buddy-providers';
const PROVIDERS = [
{ id: 'claude', name: 'Claude Code' },
@@ -49,3 +49,47 @@ describe('buddyProviders', () => {
expect(buddyProviders(PROVIDERS, null).every((p) => p.state === 'checking')).toBe(true);
});
});
+
+describe('startButtons', () => {
+ const states = (entries: Record<string, BuddyProvider['state']>): BuddyProvider[] =>
+ PROVIDERS.map((provider) => ({ ...provider, state: entries[provider.id] ?? 'checking' }));
+ const ids = (buttons: BuddyProvider[] | null) => buttons?.map((provider) => provider.id) ?? null;
+
+ it('decides as soon as Claude Code and Codex are known and one is ready', () => {
+ expect(ids(startButtons(states({ claude: 'ready', codex: 'ready' }), false))).toEqual([
+ 'claude',
+ 'codex',
+ ]);
+ expect(ids(startButtons(states({ claude: 'ready', codex: 'sign-in' }), false))).toEqual([
+ 'claude',
+ ]);
+ });
+
+ it('waits while one of them is still being checked', () => {
+ expect(startButtons(states({ claude: 'ready' }), false)).toBeNull();
+ expect(startButtons(states({ codex: 'ready' }), false)).toBeNull();
+ });
+
+ it('waits for the rest when neither is ready, then offers what is', () => {
+ expect(startButtons(states({ claude: 'install', codex: 'sign-in' }), false)).toBeNull();
+ expect(
+ ids(
+ startButtons(
+ states({
+ claude: 'install',
+ codex: 'sign-in',
+ opencode: 'ready',
+ cursor: 'install',
+ antigravity: 'install',
+ }),
+ false
+ )
+ )
+ ).toEqual(['opencode']);
+ });
+
+ it('offers what is ready once out of patience', () => {
+ expect(ids(startButtons(states({ codex: 'ready' }), true))).toEqual(['codex']);
+ expect(ids(startButtons(states({}), true))).toEqual([]);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-providers.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-providers.ts
index 266198b57..11195d3d3 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-providers.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-providers.ts
@@ -15,7 +15,7 @@ export type BuddyProvider = { id: string; name: string; state: BuddyProviderStat
export function buddyProviders(
providers: readonly Pick<AgentProviderDefinition, 'id' | 'name'>[],
- machine: OwnedMachine | null
+ machine: Pick<OwnedMachine, 'providers'> | null
): BuddyProvider[] {
return providers.map((provider) => {
const reported = machine?.providers.find((entry) => entry.provider === provider.id);
@@ -31,3 +31,42 @@ export function buddyProviders(
return { id: provider.id, name: provider.name, state };
});
}
+
+/** How many providers Meet switch-buddy offers to start with outright; the rest are a click further. */
+export const START_BUTTONS = 2;
+
+/** The order the "Start with …" buttons go in: the most used first. */
+const PREFERRED = ['claude', 'codex'];
+
+function startOrder(providers: BuddyProvider[]): BuddyProvider[] {
+ const rank = (id: string) => {
+ const at = PREFERRED.indexOf(id);
+ return at === -1 ? PREFERRED.length : at;
+ };
+ return [...providers].sort((a, b) => rank(a.id) - rank(b.id));
+}
+
+/**
+ * The "Start with …" buttons, once they can be decided, or null while not.
+ *
+ * Decided as soon as the preferred providers (Claude Code, Codex) are known
+ * and one of them is ready: their checks are quick, while the others start a
+ * process of their own to answer and are rarely the ones offered. With
+ * neither ready, every check is waited for, or until `outOfPatience`.
+ */
+export function startButtons(
+ providers: BuddyProvider[],
+ outOfPatience: boolean
+): BuddyProvider[] | null {
+ const known = (provider: BuddyProvider) => provider.state !== 'checking';
+ const preferred = providers.filter((provider) => PREFERRED.includes(provider.id));
+ const decided =
+ outOfPatience ||
+ providers.every(known) ||
+ (preferred.every(known) && preferred.some((provider) => provider.state === 'ready'));
+ if (!decided) return null;
+ return startOrder(providers.filter((provider) => provider.state === 'ready')).slice(
+ 0,
+ START_BUTTONS
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/meet-buddy-intro.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/meet-buddy-intro.tsx
new file mode 100644
index 000000000..b244aed00
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/meet-buddy-intro.tsx
@@ -0,0 +1,281 @@
+import { motion, useAnimate, useReducedMotion } from 'motion/react';
+import { useEffect, useRef, useState } from 'react';
+import { BuddyFace, useBuddyExpression } from './buddy-face';
+import { INTRO_BUBBLE_CLASS, IntroBubbles, buddyIntroLines } from './buddy-intro-lines';
+
+/**
+ * Meet switch-buddy's opening, as a short scene:
+ *
+ * 1. The avatar's tile rises into the middle of the screen.
+ * 2. As it settles, switch-buddy is tossed up out of it and lands in place,
+ * squashing on impact; the tile gives under it.
+ * 3. Just before it comes to rest, the title and the line under it slide in.
+ * 4. The page makes room and the lines arrive as chat bubbles, one at a time,
+ * each springing in and typing itself out.
+ *
+ * From then on it blinks and smiles now and then. Every motion is a spring or
+ * a gravity curve, and nothing overlaps more than the next beat needs.
+ *
+ * With reduced motion, or when `play` is false (coming back to the page), it
+ * is drawn at rest.
+ */
+
+const TILE = 80;
+const FACE = TILE * 0.8;
+
+/** Seconds from the page opening. */
+const BEAT = {
+ tileIn: 0.12,
+ toss: 0.4,
+ title: 0.92,
+ subtitle: 1.04,
+ talk: 1.5,
+ firstBubble: 1.82,
+} as const;
+
+/** A thrown object rises on a quadratic ease-out and falls on its mirror. */
+const RISE: [number, number, number, number] = [0.333, 0.667, 0.667, 1];
+const FALL: [number, number, number, number] = [0.333, 0, 0.667, 0.333];
+
+/** How far it starts below its resting place (hidden in the tile) and how high above it the toss peaks. */
+const START_BELOW = FACE * 1.1;
+const PEAK_ABOVE = FACE * 0.42;
+/** Under gravity, time to cover a height goes as its square root. */
+const FLIGHT = 0.64;
+const RISE_SHARE =
+ Math.sqrt(START_BELOW + PEAK_ABOVE) /
+ (Math.sqrt(START_BELOW + PEAK_ABOVE) + Math.sqrt(PEAK_ABOVE));
+
+/** Characters typed per second. */
+const TYPING_RATE = 80;
+/** The pause after a bubble finishes before the next one appears. */
+const BUBBLE_GAP = 0.2;
+/** How long a bubble's spring runs before its text starts. */
+const TYPING_LEAD = 0.09;
+
+const ENTER_SPRING = { type: 'spring', stiffness: 170, damping: 21, mass: 1 } as const;
+const TEXT_SPRING = { type: 'spring', stiffness: 260, damping: 26 } as const;
+const BUBBLE_SPRING = { type: 'spring', stiffness: 480, damping: 19, mass: 0.9 } as const;
+const LAYOUT_SPRING = { type: 'spring', stiffness: 150, damping: 24 } as const;
+
+function seconds(value: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, value * 1000));
+}
+
+export function MeetBuddyIntro({
+ firstName,
+ play,
+ onPlayed,
+}: {
+ firstName: string | null;
+ play: boolean;
+ onPlayed: () => void;
+}) {
+ const reduced = useReducedMotion() ?? false;
+ const animated = play && !reduced;
+ const [scope, animate] = useAnimate<HTMLDivElement>();
+ const [landed, setLanded] = useState(!animated);
+ const [talking, setTalking] = useState(!animated);
+ const [bubble, setBubble] = useState(animated ? -1 : Number.POSITIVE_INFINITY);
+ const expression = useBuddyExpression(landed && !reduced);
+ const lines = buddyIntroLines(firstName);
+ const playedRef = useRef(onPlayed);
+ playedRef.current = onPlayed;
+
+ useEffect(() => {
+ if (!animated) return;
+ let live = true;
+ void (async () => {
+ void animate(
+ '[data-intro="tile"]',
+ { opacity: [0, 1], y: [30, 0] },
+ {
+ opacity: { duration: 0.32, ease: 'easeOut', delay: BEAT.tileIn },
+ y: { ...ENTER_SPRING, delay: BEAT.tileIn },
+ }
+ );
+ await seconds(BEAT.toss);
+ if (!live) return;
+ void animate(
+ '[data-intro="face"]',
+ { y: [START_BELOW, -PEAK_ABOVE, 0], rotate: [-14, 4, 0] },
+ {
+ duration: FLIGHT,
+ y: { duration: FLIGHT, times: [0, RISE_SHARE, 1], ease: [RISE, FALL] },
+ rotate: { duration: FLIGHT, times: [0, RISE_SHARE, 1], ease: ['easeOut', 'easeInOut'] },
+ }
+ );
+ // The beats run on the clock, not on each animation finishing.
+ await seconds(FLIGHT);
+ if (!live) return;
+ // The landing: the face squashes and recovers, the tile gives a little under it.
+ void animate(
+ '[data-intro="face"]',
+ { scaleY: 1, scaleX: 1 },
+ {
+ scaleY: { type: 'spring', stiffness: 520, damping: 13, velocity: -4.2 },
+ scaleX: { type: 'spring', stiffness: 520, damping: 13, velocity: 3.2 },
+ }
+ );
+ void animate(
+ '[data-intro="tile"]',
+ { y: 0 },
+ { type: 'spring', stiffness: 380, damping: 15, velocity: 70 }
+ );
+ setLanded(true);
+ await seconds(BEAT.talk - BEAT.toss - FLIGHT);
+ if (!live) return;
+ setTalking(true);
+ await seconds(BEAT.firstBubble - BEAT.talk);
+ if (live) setBubble(0);
+ })();
+ return () => {
+ live = false;
+ // Leaving part-way counts as having seen it: coming back draws it at rest.
+ playedRef.current();
+ };
+ }, [animated, animate]);
+
+ const nextBubble = (index: number) => {
+ void seconds(BUBBLE_GAP).then(() => {
+ setBubble((current) => (current === index ? index + 1 : current));
+ if (index === lines.length - 1) playedRef.current();
+ });
+ };
+
+ return (
+ <div ref={scope} className="contents">
+ <motion.div
+ layout={animated ? 'position' : false}
+ transition={LAYOUT_SPRING}
+ className="flex flex-col items-center gap-2 text-center"
+ >
+ <span
+ data-intro="tile"
+ className="relative inline-flex shrink-0 items-center justify-center rounded-[22%] bg-[linear-gradient(180deg,rgb(231_246_249/0.2),rgb(136_145_147/0.2))] emdark:bg-[linear-gradient(180deg,rgb(231_246_249/0.12),rgb(136_145_147/0.07))]"
+ style={{
+ width: TILE,
+ height: TILE,
+ opacity: animated ? 0 : 1,
+ // Only the bottom edge clips: switch-buddy is hidden below it
+ // before the toss, and free above it during.
+ clipPath: `inset(-200% -100% 0 -100% round 0 0 ${TILE * 0.22}px ${TILE * 0.22}px)`,
+ }}
+ >
+ <span
+ data-intro="face"
+ className="block"
+ style={{
+ transformOrigin: '50% 85%',
+ transform: animated ? `translateY(${START_BELOW}px)` : undefined,
+ }}
+ >
+ <BuddyFace size={FACE} expression={expression} />
+ </span>
+ </span>
+ <motion.h1
+ className="mt-2 text-2xl font-semibold"
+ initial={animated ? { opacity: 0, y: 12 } : false}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{
+ ...TEXT_SPRING,
+ delay: BEAT.title,
+ opacity: { duration: 0.28, delay: BEAT.title },
+ }}
+ >
+ Meet switch-buddy
+ </motion.h1>
+ <motion.p
+ className="text-sm text-foreground-muted"
+ initial={animated ? { opacity: 0, y: 10 } : false}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{
+ ...TEXT_SPRING,
+ delay: BEAT.subtitle,
+ opacity: { duration: 0.28, delay: BEAT.subtitle },
+ }}
+ >
+ Your first AI assistant in Switch
+ </motion.p>
+ </motion.div>
+ {talking && (
+ <IntroBubbles>
+ {lines.map((line, index) => (
+ <TypedBubble
+ key={line}
+ text={line}
+ state={index < bubble ? 'done' : index === bubble ? 'typing' : 'waiting'}
+ animated={animated}
+ onTyped={() => nextBubble(index)}
+ />
+ ))}
+ </IntroBubbles>
+ )}
+ </div>
+ );
+}
+
+/**
+ * One line as a chat bubble. It holds its full size from the start, the text
+ * still to come drawn transparent, so nothing around it moves as it types.
+ * Screen readers get the whole line at once.
+ */
+function TypedBubble({
+ text,
+ state,
+ animated,
+ onTyped,
+}: {
+ text: string;
+ state: 'waiting' | 'typing' | 'done';
+ animated: boolean;
+ onTyped: () => void;
+}) {
+ const [typed, setTyped] = useState(animated ? 0 : text.length);
+ const typedRef = useRef(onTyped);
+ typedRef.current = onTyped;
+
+ useEffect(() => {
+ if (state !== 'typing') return;
+ // A timer rather than animation frames: a window the browser is not
+ // painting stops those, and the next bubble waits on this one finishing.
+ const start = performance.now() + TYPING_LEAD * 1000;
+ const total = (text.length / TYPING_RATE) * 1000;
+ let timer: ReturnType<typeof setTimeout>;
+ const step = () => {
+ const elapsed = performance.now() - start;
+ if (elapsed >= 0) {
+ // Eased so the first characters come a touch quicker than the last.
+ const progress = Math.min(1, elapsed / total);
+ const eased = 1 - (1 - progress) ** 1.6;
+ setTyped(Math.round(eased * text.length));
+ if (progress >= 1) {
+ typedRef.current();
+ return;
+ }
+ }
+ timer = setTimeout(step, 16);
+ };
+ timer = setTimeout(step, 16);
+ return () => clearTimeout(timer);
+ }, [state, text]);
+
+ const shown = state === 'done' ? text.length : state === 'waiting' ? 0 : typed;
+ return (
+ <motion.p
+ className={INTRO_BUBBLE_CLASS}
+ style={{ transformOrigin: '0% 100%' }}
+ initial={animated ? { opacity: 0, scale: 0.6, y: 10 } : false}
+ animate={
+ state === 'waiting' ? { opacity: 0, scale: 0.6, y: 10 } : { opacity: 1, scale: 1, y: 0 }
+ }
+ transition={{ ...BUBBLE_SPRING, opacity: { duration: 0.14 } }}
+ >
+ <span className="sr-only">{text}</span>
+ <span aria-hidden>
+ {text.slice(0, shown)}
+ <span className="text-transparent">{text.slice(shown)}</span>
+ </span>
+ </motion.p>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/meet-buddy-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/meet-buddy-page.tsx
index 4c6ff2921..d5310b5bd 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/meet-buddy-page.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/meet-buddy-page.tsx
@@ -1,8 +1,10 @@
import { observer } from 'mobx-react-lite';
-import { useEffect, useMemo, useState } from 'react';
+import { motion } from 'motion/react';
+import { useEffect, useMemo, useRef, useState } from 'react';
import { useManagedAgents } from '@renderer/features/managed-agents/use-managed-agents';
import { onboardingStore } from '@renderer/features/onboarding/onboarding-store';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { AgentIcon } from '@renderer/lib/components/agent-icon';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { report } from '@renderer/lib/telemetry/report';
import { Button } from '@renderer/lib/ui/button';
@@ -11,42 +13,29 @@ import { OnboardingSurface, useWizardExit } from '@renderer/lib/ui/wizard-frame'
import { agentProviders } from '@shared/core/providers/agent-provider-registry';
import { BuddyAvatar } from './buddy-avatar';
import { firstNameOf, isBuddy } from './buddy-identity';
-import { BuddyIntroLines } from './buddy-intro-lines';
-import { type BuddyProvider, buddyProviders } from './buddy-providers';
+import { buddyProviders, startButtons } from './buddy-providers';
import { reportBuddyStep } from './buddy-telemetry';
import { createBuddy } from './create-buddy';
+import { MeetBuddyIntro } from './meet-buddy-intro';
import { ProviderSetup } from './provider-setup';
import { useThisComputer } from './use-this-computer';
-/** How many providers the page offers to start with outright; the rest are a click further. */
-const START_BUTTONS = 2;
-
/**
- * How long the page waits for every provider's check before offering what is
+ * How long the page waits for the provider checks before offering what is
* ready anyway: a provider whose check never comes back must not hold the rest.
*/
const CHECK_PATIENCE_MS = 45_000;
-/** The order the "Start with …" buttons go in: the most used first. */
-const PREFERRED = ['claude', 'codex'];
-
-function startOrder(providers: BuddyProvider[]): BuddyProvider[] {
- const rank = (id: string) => {
- const at = PREFERRED.indexOf(id);
- return at === -1 ? PREFERRED.length : at;
- };
- return [...providers].sort((a, b) => rank(a.id) - rank(b.id));
-}
-
/**
* Meet switch-buddy: who it is, in its own short lines, and the quickest way
* to start it.
*
- * A provider already installed and signed in on this computer is offered as
- * "Start with …" straight away, for the first two; the others, and providers
- * still to set up, are behind "Use another provider". It can be skipped, for
- * the chat to open without the buddy, asking for a provider there. Someone who
- * already has a buddy (replaying these pages) is offered to open it instead.
+ * A provider already installed and signed in on this computer is offered
+ * straight away, for the first two; the others, and providers still to set
+ * up, are behind "Use other AI providers". With none signed in it can be
+ * skipped, for the chat to open without the buddy, asking for a provider
+ * there. Someone who already has a buddy (replaying these pages) is offered
+ * to open it instead.
*
* This computer starts running agents for the workspace as the page opens, so
* what its providers are ready for is known by the time it has been read.
@@ -64,38 +53,46 @@ export const MeetBuddyPage = observer(function MeetBuddyPage({
}) {
const exit = useWizardExit();
const [settingUp, setSettingUp] = useState(false);
- const { state: computer } = useThisComputer(serverId, workspaceId);
- const providers = useMemo(
- () => buddyProviders(agentProviders(), computer.kind === 'ready' ? computer.machine : null),
- [computer]
+ const { state: computer, earlyProviders } = useThisComputer(serverId, workspaceId);
+ // What this computer's controller reports, or until it does, what Console
+ // found checking the providers as onboarding opened.
+ const reported = useMemo(
+ () =>
+ computer.kind === 'ready'
+ ? computer.machine
+ : earlyProviders
+ ? { providers: earlyProviders }
+ : null,
+ [computer, earlyProviders]
);
+ const providers = useMemo(() => buddyProviders(agentProviders(), reported), [reported]);
const [outOfPatience, setOutOfPatience] = useState(false);
- const machineReady = computer.kind === 'ready';
+ const machineReady = reported !== null;
useEffect(() => {
if (!machineReady) return;
const timer = setTimeout(() => setOutOfPatience(true), CHECK_PATIENCE_MS);
return () => clearTimeout(timer);
}, [machineReady]);
- // The Start buttons appear once, with every check back, rather than one at
- // a time as each returns: the row would change under the eye, and whichever
- // answered first would hold the main button until the preferred one came.
- const checked =
- machineReady && (outOfPatience || providers.every((provider) => provider.state !== 'checking'));
+ // The Start buttons appear once, together, and stay as they first were:
+ // the row would change under the eye if each were added as its check came
+ // back.
+ const decided = machineReady ? startButtons(providers, outOfPatience) : null;
+ const [firstDecided, setFirstDecided] = useState<string[] | null>(null);
+ useEffect(() => {
+ if (decided && firstDecided === null) setFirstDecided(decided.map((provider) => provider.id));
+ }, [decided, firstDecided]);
+ const checked = firstDecided !== null;
const ready = useMemo(
- () =>
- checked
- ? startOrder(providers.filter((provider) => provider.state === 'ready')).slice(
- 0,
- START_BUTTONS
- )
- : [],
- [checked, providers]
+ () => (firstDecided ?? []).flatMap((id) => providers.filter((provider) => provider.id === id)),
+ [firstDecided, providers]
);
const existing = useManagedAgents(serverId).data?.find(isBuddy) ?? null;
const [starting, setStarting] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const user = switchServersStore.statusFor(serverId)?.user ?? null;
const firstName = firstNameOf(user?.name);
+ // The opening plays once: back from setting up a provider, it is at rest.
+ const introPlayed = useRef(false);
const skip = () => {
reportBuddyStep('skip', null);
@@ -108,9 +105,27 @@ export const MeetBuddyPage = observer(function MeetBuddyPage({
setSettingUp(true);
};
- const startWith = async (providerId: string) => {
+ // A provider chosen before this computer's controller is up: started once it is.
+ const [waitingToStart, setWaitingToStart] = useState<string | null>(null);
+ useEffect(() => {
+ if (waitingToStart === null) return;
+ if (computer.kind === 'failed') {
+ setWaitingToStart(null);
+ setStarting(null);
+ return;
+ }
if (computer.kind !== 'ready') return;
+ const providerId = waitingToStart;
+ setWaitingToStart(null);
+ void startWithRef.current(providerId);
+ }, [computer, waitingToStart]);
+
+ const startWith = async (providerId: string) => {
setStarting(providerId);
+ if (computer.kind !== 'ready') {
+ setWaitingToStart(providerId);
+ return;
+ }
reportBuddyStep('start', providerId);
setError(null);
try {
@@ -128,14 +143,13 @@ export const MeetBuddyPage = observer(function MeetBuddyPage({
setStarting(null);
}
};
+ const startWithRef = useRef(startWith);
+ startWithRef.current = startWith;
const header = (
<div className="flex flex-col items-center gap-2 text-center">
- <BuddyAvatar size={settingUp ? 48 : 80} shape="tile" />
+ <BuddyAvatar size={48} shape="tile" />
<h1 className="mt-2 text-2xl font-semibold">Meet switch-buddy</h1>
- {!settingUp && (
- <p className="text-sm text-foreground-muted">Your first AI assistant in Switch</p>
- )}
</div>
);
@@ -159,7 +173,6 @@ export const MeetBuddyPage = observer(function MeetBuddyPage({
</OnboardingSurface>
);
- const busy = starting !== null;
return (
<OnboardingSurface
exit={exit}
@@ -174,42 +187,24 @@ export const MeetBuddyPage = observer(function MeetBuddyPage({
Open switch-buddy
</Button>
) : (
- <div className="relative flex gap-2">
- <Button variant="outline" onClick={skip} disabled={busy}>
- Skip
- </Button>
- {ready.map((provider, index) => (
- <Button
- key={provider.id}
- variant={index === 0 ? 'default' : 'outline'}
- onClick={() => void startWith(provider.id)}
- disabled={busy}
- >
- {starting === provider.id && <Spinner className="size-3.5" />}
- Start with {provider.name}
- </Button>
- ))}
- <Button
- variant={ready.length === 0 ? 'default' : 'outline'}
- onClick={openSetup}
- disabled={busy}
- >
- {ready.length === 0 ? 'Set up AI provider' : 'Use another provider'}
- </Button>
- {/* Beside the buttons, not between them: the row stays where it is
- while this computer is still being checked. */}
- {computer.kind !== 'failed' && !checked && (
- <span className="absolute top-1/2 left-full ml-3 flex -translate-y-1/2 items-center gap-1.5 text-xs whitespace-nowrap text-foreground-muted">
- <Spinner className="size-3" />
- Checking AI providers…
- </span>
- )}
- </div>
+ <StartChoices
+ checking={computer.kind !== 'failed' && !checked}
+ ready={ready}
+ starting={starting}
+ onStart={(providerId) => void startWith(providerId)}
+ onSetUp={openSetup}
+ onSkip={skip}
+ />
)
}
>
- {header}
- <BuddyIntroLines firstName={firstName} />
+ <MeetBuddyIntro
+ firstName={firstName}
+ play={!introPlayed.current}
+ onPlayed={() => {
+ introPlayed.current = true;
+ }}
+ />
{computer.kind === 'failed' && (
<p role="alert" className="text-center text-sm text-destructive">
{computer.error}
@@ -223,3 +218,77 @@ export const MeetBuddyPage = observer(function MeetBuddyPage({
</OnboardingSurface>
);
});
+
+/**
+ * How to start the buddy, once this computer's providers are known. With a
+ * provider already signed in, those are the way, beside another provider; no
+ * Skip, though the flow's own way out stays at the top. With none, set one up
+ * or skip.
+ */
+export function StartChoices({
+ checking,
+ ready,
+ starting,
+ onStart,
+ onSetUp,
+ onSkip,
+}: {
+ checking: boolean;
+ ready: { id: string; name: string }[];
+ starting: string | null;
+ onStart: (providerId: string) => void;
+ onSetUp: () => void;
+ onSkip: () => void;
+}) {
+ const busy = starting !== null;
+ const shown = checking ? 'checking' : ready.length > 0 ? 'signed-in' : 'none';
+ return (
+ <motion.div
+ key={shown}
+ initial={{ opacity: 0, y: 6 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ type: 'spring', stiffness: 260, damping: 26 }}
+ className="flex flex-col items-center gap-3"
+ >
+ {shown === 'checking' ? (
+ <span className="flex h-9 items-center gap-1.5 text-xs text-foreground-muted">
+ <Spinner className="size-3" />
+ Checking AI providers…
+ </span>
+ ) : shown === 'signed-in' ? (
+ <>
+ <p className="text-sm text-foreground-muted">How’d you like to power switch-buddy?</p>
+ <div className="flex flex-wrap items-center justify-center gap-2">
+ <span className="text-sm text-foreground-muted">Already signed in:</span>
+ {ready.map((provider) => (
+ <Button
+ key={provider.id}
+ variant="outline"
+ onClick={() => onStart(provider.id)}
+ disabled={busy}
+ >
+ {starting === provider.id ? (
+ <Spinner className="size-3.5" />
+ ) : (
+ <AgentIcon id={provider.id} size={16} />
+ )}
+ {provider.name}
+ </Button>
+ ))}
+ <span className="text-sm text-foreground-muted">or</span>
+ <Button variant="outline" onClick={onSetUp} disabled={busy}>
+ Use other AI providers
+ </Button>
+ </div>
+ </>
+ ) : (
+ <div className="flex gap-2">
+ <Button variant="outline" onClick={onSkip}>
+ Skip
+ </Button>
+ <Button onClick={onSetUp}>Set up AI provider</Button>
+ </div>
+ )}
+ </motion.div>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/use-this-computer.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/use-this-computer.ts
index db1b223da..bc52d2ed5 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/use-this-computer.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/use-this-computer.ts
@@ -89,6 +89,16 @@ export function useThisComputer(serverId: string, workspaceId: string) {
}, [serverId, machines]);
const machine = machines.data?.find((m) => m.local?.kind === 'this-computer') ?? null;
+ const reported = machine !== null && machine.providers.length > 0;
+
+ // Console's own check of the providers, made as onboarding opened: what
+ // the page goes by until this computer's controller reports.
+ const early = useQuery({
+ queryKey: ['provider-precheck'],
+ queryFn: () => rpc.embeddedController.precheckedProviders(),
+ enabled: !reported,
+ refetchInterval: 1_000,
+ });
const state: ThisComputer = setupError
? { kind: 'failed', error: setupError }
: machines.data === null
@@ -99,7 +109,8 @@ export function useThisComputer(serverId: string, workspaceId: string) {
: machine && machine.providers.length > 0
? { kind: 'ready', machine }
: { kind: 'starting' };
- return { state, recheck };
+ const earlyProviders = !reported && early.data && early.data.length > 0 ? early.data : null;
+ return { state, recheck, earlyProviders };
}
/** How many providers this computer last reported ready. */
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/meet-buddy-intro.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/meet-buddy-intro.test.tsx
new file mode 100644
index 000000000..1a6b7ce4d
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/meet-buddy-intro.test.tsx
@@ -0,0 +1,70 @@
+/**
+ * Meet switch-buddy's opening plays once. Coming back to the page draws it at
+ * rest, with every line there.
+ */
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+vi.hoisted(() => {
+ window.electronAPI ??= {
+ invoke: () => Promise.resolve(undefined),
+ eventOn: () => () => {},
+ eventSend: () => {},
+ } as unknown as typeof window.electronAPI;
+});
+
+import { buddyIntroLines } from '@renderer/features/switch-buddy/buddy-intro-lines';
+import { MeetBuddyIntro } from '@renderer/features/switch-buddy/meet-buddy-intro';
+import '@renderer/index.css';
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+afterEach(async () => {
+ await act(async () => root?.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+async function render(play: boolean, onPlayed = () => {}) {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () =>
+ root!.render(<MeetBuddyIntro firstName="Max" play={play} onPlayed={onPlayed} />)
+ );
+}
+
+/** What each bubble shows on screen. */
+function shownLines(): string[] {
+ return [...container!.querySelectorAll('p > span[aria-hidden]')].map((span) =>
+ [...span.childNodes]
+ .filter((node) => node.nodeType === Node.TEXT_NODE)
+ .map((node) => node.textContent)
+ .join('')
+ );
+}
+
+describe('Meet switch-buddy opening', () => {
+ it('is drawn at rest when it has already played', async () => {
+ await render(false);
+ expect(container!.textContent).toContain('Meet switch-buddy');
+ expect(shownLines()).toEqual(buddyIntroLines('Max'));
+ });
+
+ it('starts with the tile alone and nothing typed', async () => {
+ await render(true);
+ expect(shownLines()).toEqual([]);
+ expect(container!.querySelectorAll('[data-intro="tile"]')).toHaveLength(1);
+ });
+
+ it('counts as seen when left part-way', async () => {
+ const onPlayed = vi.fn();
+ await render(true, onPlayed);
+ await act(async () => root?.unmount());
+ root = null;
+ expect(onPlayed).toHaveBeenCalled();
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/meet-buddy-start-choices.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/meet-buddy-start-choices.test.tsx
new file mode 100644
index 000000000..ae4cefe66
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/meet-buddy-start-choices.test.tsx
@@ -0,0 +1,85 @@
+/**
+ * How Meet switch-buddy offers to start the buddy: with a provider already
+ * signed in, those and another provider, no Skip; with none, set one up or
+ * skip.
+ */
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+vi.hoisted(() => {
+ window.electronAPI ??= {
+ invoke: () => Promise.resolve(undefined),
+ eventOn: () => () => {},
+ eventSend: () => {},
+ } as unknown as typeof window.electronAPI;
+});
+
+vi.mock('@renderer/lib/components/agent-icon', () => ({
+ AgentIcon: ({ id }: { id: string }) => <span data-provider-icon={id} />,
+}));
+
+import { StartChoices } from '@renderer/features/switch-buddy/meet-buddy-page';
+import '@renderer/index.css';
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+afterEach(async () => {
+ await act(async () => root?.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+const handlers = () => ({ onStart: vi.fn(), onSetUp: vi.fn(), onSkip: vi.fn() });
+
+async function render(props: React.ComponentProps<typeof StartChoices>) {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () => root!.render(<StartChoices {...props} />));
+}
+
+function buttons(): string[] {
+ return [...container!.querySelectorAll('button')].map((button) => button.textContent ?? '');
+}
+
+describe('Meet switch-buddy start choices', () => {
+ it('offers the providers already signed in, and another, with no Skip', async () => {
+ const on = handlers();
+ await render({
+ checking: false,
+ ready: [
+ { id: 'claude', name: 'Claude Code' },
+ { id: 'codex', name: 'Codex' },
+ ],
+ starting: null,
+ ...on,
+ });
+ expect(container!.textContent).toContain('How’d you like to power switch-buddy?');
+ expect(container!.textContent).toContain('Already signed in:');
+ expect(buttons()).toEqual(['Claude Code', 'Codex', 'Use other AI providers']);
+ expect(
+ [...container!.querySelectorAll('[data-provider-icon]')].map((icon) =>
+ icon.getAttribute('data-provider-icon')
+ )
+ ).toEqual(['claude', 'codex']);
+ await act(async () => container!.querySelectorAll('button')[1]!.click());
+ expect(on.onStart).toHaveBeenCalledWith('codex');
+ });
+
+ it('offers to set one up, or skip, when none is signed in', async () => {
+ const on = handlers();
+ await render({ checking: false, ready: [], starting: null, ...on });
+ expect(buttons()).toEqual(['Skip', 'Set up AI provider']);
+ await act(async () => container!.querySelectorAll('button')[0]!.click());
+ expect(on.onSkip).toHaveBeenCalled();
+ });
+
+ it('offers nothing while the providers are being checked', async () => {
+ await render({ checking: true, ready: [], starting: null, ...handlers() });
+ expect(buttons()).toEqual([]);
+ expect(container!.textContent).toContain('Checking AI providers…');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-flow.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-flow.test.tsx
index 5b06c385d..822ccc6ef 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-flow.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-flow.test.tsx
@@ -27,9 +27,15 @@ vi.hoisted(() => {
} as unknown as typeof window.electronAPI;
});
+const precheckProviders = vi.hoisted(() => vi.fn());
+
vi.mock('@renderer/lib/ipc', () => ({
events: { on: () => () => {} },
- rpc: { remoteHosts: { listHosts }, switchServers: { switchCloud } },
+ rpc: {
+ remoteHosts: { listHosts },
+ switchServers: { switchCloud },
+ embeddedController: { precheckProviders },
+ },
}));
vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({
@@ -201,6 +207,12 @@ async function type(input: HTMLInputElement, value: string): Promise<void> {
}
describe('the first-run flow', () => {
+ it("checks this computer's providers as it opens, for switch-buddy at the end", async () => {
+ precheckProviders.mockClear();
+ await renderFlow();
+ expect(precheckProviders).toHaveBeenCalledTimes(1);
+ });
+
it('asks how to run Switch once you get started, without the remote host path', async () => {
const el = await renderFlow();
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-workspaces.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-workspaces.test.tsx
index 425f3b3e5..3d796ca04 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-workspaces.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/onboarding-workspaces.test.tsx
@@ -36,6 +36,7 @@ vi.mock('@renderer/lib/ipc', () => ({
listJoinableWorkspaces,
switchCloud: () => Promise.resolve(null),
},
+ embeddedController: { precheckProviders: () => {} },
},
events: { on: () => () => {}, emit: () => {} },
}));
diff --git a/console/packages/agent-controller/src/controller.test.ts b/console/packages/agent-controller/src/controller.test.ts
index a18ce1e88..364a67ccc 100644
--- a/console/packages/agent-controller/src/controller.test.ts
+++ b/console/packages/agent-controller/src/controller.test.ts
@@ -79,6 +79,7 @@ function deps(server = core.url): ControllerDeps {
locator: new FakeLocator(),
rechecks: new ProviderRechecks(),
refreshPath: async () => {},
+ providerSeed: [],
tools: async () => [],
fetch,
openWebSocket: core.openWebSocket,
diff --git a/console/packages/agent-controller/src/controller.ts b/console/packages/agent-controller/src/controller.ts
index 3be3d89c5..ce1b5aebe 100644
--- a/console/packages/agent-controller/src/controller.ts
+++ b/console/packages/agent-controller/src/controller.ts
@@ -34,6 +34,7 @@ import type { SelfUpdater } from './self-update';
import {
noSessionMidTurn,
type ProviderLocator,
+ type ProviderSeed,
ProviderStatuses,
StatusCollector,
statusFingerprint,
@@ -95,6 +96,8 @@ export type ControllerDeps = {
*/
rechecks: ProviderRechecks;
refreshPath: () => Promise<void>;
+ /** Provider checks made before this controller started, taken as its own (`ProviderStatuses.seed`). */
+ providerSeed: ProviderSeed;
/** `git`, `gh` and vendor tools, as sessions here would be set up with them (`toolStatuses`). */
tools: () => Promise<ToolStatus[]>;
fetch: Fetch;
@@ -412,6 +415,7 @@ export async function runController(
log,
onChange: () => reporter?.request(),
});
+ providers.seed(deps.providerSeed);
const collector = new StatusCollector({
store,
runtime,
diff --git a/console/packages/agent-controller/src/main.ts b/console/packages/agent-controller/src/main.ts
index 52abf559f..db65695d9 100644
--- a/console/packages/agent-controller/src/main.ts
+++ b/console/packages/agent-controller/src/main.ts
@@ -1,5 +1,5 @@
import { realpathSync } from 'node:fs';
-import { rm } from 'node:fs/promises';
+import { mkdir, rm } from 'node:fs/promises';
import { homedir, hostname } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { parseArgs } from 'node:util';
@@ -44,15 +44,16 @@ import {
defaultSharedHostBundle,
resolveSharedHostBundle,
} from './handover';
-import { createLogger, errorMessage } from './log';
+import { createLogger, errorMessage, type Logger } from './log';
import { loginShellPath, withUserBinDirs } from './login-path';
import { dataLayout, ensureDataDir, resolveDataDir, serverWorkspacesDir } from './paths';
import { ProviderRechecks } from './provider-rechecks';
+import { readProviderSeed, writeProviderSeed } from './provider-seed';
import { definitionProblem } from './reconcile';
import { isManagedRelease, readCurrent, throughCurrent } from './releases';
import { emptyObservation, InProcessRuntime, observeOnDisk, probeProvider } from './runtime';
import { AgentRuntimes } from './runtimes';
-import { type ControllerInfoChange, PROTOCOL_VERSION, type UpdatedBy } from './schemas';
+import { type ControllerInfoChange, PROTOCOL_VERSION, PROVIDERS, type UpdatedBy } from './schemas';
import {
CONTROLLER_CREDENTIAL,
defaultSecretStoreKind,
@@ -96,7 +97,13 @@ import {
serviceState,
uninstallService,
} from './service';
-import { contractPlatform, mapAgentProcess, PathProviderLocator, toolStatuses } from './status';
+import {
+ contractPlatform,
+ mapAgentProcess,
+ PathProviderLocator,
+ ProviderStatuses,
+ toolStatuses,
+} from './status';
import { ControllerStore } from './store';
import { SystemdRuntime, systemctl } from './systemd-runtime';
import { installPrefix, isNewer, latestRelease, releasesRepository } from './update';
@@ -131,7 +138,11 @@ Commands:
the releases Switch names, beside the ones before.
--updated-by-console, which Switch Console passes to a controller it
runs on an SSH host, says Console updates it: it follows no release
- Switch names, and tells Switch so.
+ Switch names, and tells Switch so. --provider-seed <file> takes the
+ provider checks precheck wrote, so the first report carries them.
+ precheck --out <file> --probe-dir <dir> [--shared-host-bundle <path>]
+ Check every provider's installation and sign-in as run would, with no
+ enrollment, writing the results to <file> as each comes back.
set-info [--name <name>] [--description <text>] [--data-dir <dir>]
Rename this machine and/or change its description on the server, with
this controller's own credential. Either or both; --description ""
@@ -368,6 +379,74 @@ async function setInfoCommand(args: string[]): Promise<number> {
}
}
+/**
+ * Puts the login shell's PATH, and the user's own bin folders, on this
+ * process's: a controller started by a service or an app has neither, and
+ * would not find the provider CLIs a person installed.
+ */
+function pathRefresher(log: Logger): () => Promise<void> {
+ return async () => {
+ if (process.platform === 'win32') return;
+ const shell = process.env.SHELL ?? (process.platform === 'darwin' ? '/bin/zsh' : '/bin/bash');
+ const path = await loginShellPath(shell, process.env.PATH ?? '');
+ if (path === null)
+ log.warn(
+ "Could not read the login shell's PATH; provider CLIs, git and gh are looked for on this process's own",
+ { shell, path: process.env.PATH }
+ );
+ process.env.PATH = withUserBinDirs(path ?? process.env.PATH ?? '', homedir());
+ };
+}
+
+/**
+ * Checks every provider as `run` would, before there is any enrollment, and
+ * writes what it finds to `--out` as each check comes back, for a `run`
+ * started later to take (`--provider-seed`).
+ */
+async function precheckCommand(args: string[]): Promise<number> {
+ const { values } = parseArgs({
+ args,
+ options: {
+ out: { type: 'string' },
+ 'probe-dir': { type: 'string' },
+ 'shared-host-bundle': { type: 'string' },
+ },
+ strict: true,
+ });
+ if (!values.out || !values['probe-dir'])
+ throw new UsageError('precheck needs --out <file> and --probe-dir <dir>.');
+ const out = resolve(values.out);
+ const probeDir = resolve(values['probe-dir']);
+ await mkdir(probeDir, { recursive: true, mode: 0o700 });
+ const log = createLogger({
+ level: process.env.SWITCH_CONTROLLER_LOG_LEVEL,
+ write: (line) => process.stderr.write(line),
+ });
+ await pathRefresher(log)();
+ const sharedHostBundle = bundlePath(values['shared-host-bundle']);
+ const providers = new ProviderStatuses({
+ locator: new PathProviderLocator(() => process.env.PATH, join(probeDir, 'version-probe')),
+ runtime: {
+ probe: (provider, binaryPath, cwd) =>
+ probeProvider(sharedHostBundle, provider, binaryPath, cwd, process.env),
+ },
+ sealed: null,
+ probeCwd: probeDir,
+ now: Date.now,
+ log,
+ onChange: () => {},
+ });
+ // One write at a time, each with every result so far.
+ let writing = Promise.resolve();
+ const write = () => {
+ writing = writing.then(() => writeProviderSeed(out, providers.results()));
+ return writing;
+ };
+ await Promise.all(PROVIDERS.map((provider) => providers.check(provider).then(write)));
+ await writing;
+ return EXIT_OK;
+}
+
async function runCommand(args: string[]): Promise<number> {
const { values } = parseArgs({
args,
@@ -383,6 +462,7 @@ async function runCommand(args: string[]): Promise<number> {
'agent-runtime': { type: 'string' },
'releases-dir': { type: 'string' },
'updated-by-console': { type: 'boolean' },
+ 'provider-seed': { type: 'string' },
},
strict: true,
});
@@ -411,18 +491,11 @@ async function runCommand(args: string[]): Promise<number> {
write: (line) => process.stderr.write(line),
});
// Read again on every provider recheck, so a CLI installed since start is found.
- const refreshPath = async () => {
- if (process.platform === 'win32') return;
- const shell = process.env.SHELL ?? (process.platform === 'darwin' ? '/bin/zsh' : '/bin/bash');
- const path = await loginShellPath(shell, process.env.PATH ?? '');
- if (path === null)
- log.warn(
- "Could not read the login shell's PATH; provider CLIs, git and gh are looked for on this process's own",
- { shell, path: process.env.PATH }
- );
- process.env.PATH = withUserBinDirs(path ?? process.env.PATH ?? '', homedir());
- };
+ const refreshPath = pathRefresher(log);
await refreshPath();
+ const providerSeed = values['provider-seed']
+ ? await readProviderSeed(resolve(values['provider-seed']), log)
+ : [];
const credential = values['credential-stdin']
? await readCredential(process.stdin, CREDENTIAL_STDIN_TIMEOUT_MS)
: null;
@@ -562,6 +635,7 @@ async function runCommand(args: string[]): Promise<number> {
locator: new PathProviderLocator(() => process.env.PATH, join(dataDir, 'version-probe')),
rechecks,
refreshPath,
+ providerSeed,
tools: () => toolStatuses(process.env.PATH, process.platform, cliToolsBase()),
fetch,
openWebSocket: nodeWebSocket,
@@ -1085,6 +1159,8 @@ export async function main(argv: string[]): Promise<number> {
return await uninstallServiceCommand(rest);
case 'doctor':
return await doctorCommand(rest);
+ case 'precheck':
+ return await precheckCommand(rest);
case 'update':
return await updateCommand(rest);
case undefined:
diff --git a/console/packages/agent-controller/src/provider-seed.test.ts b/console/packages/agent-controller/src/provider-seed.test.ts
new file mode 100644
index 000000000..c3fc11ef9
--- /dev/null
+++ b/console/packages/agent-controller/src/provider-seed.test.ts
@@ -0,0 +1,38 @@
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { silentLogger } from './log';
+import { readProviderSeed, writeProviderSeed } from './provider-seed';
+
+let dir: string;
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'provider-seed-'));
+});
+afterEach(() => rmSync(dir, { recursive: true, force: true }));
+
+describe('provider checks handed to the controller', () => {
+ it('reads back what was written', async () => {
+ const seed = [
+ {
+ status: {
+ provider: 'claude',
+ installed: true,
+ version: '2.1.0',
+ auth: 'ok' as const,
+ auth_source: 'local' as const,
+ checked_at: '2026-10-19T10:00:00.000Z',
+ },
+ path: '/usr/local/bin/claude',
+ },
+ ];
+ await writeProviderSeed(join(dir, 'seed.json'), seed);
+ expect(await readProviderSeed(join(dir, 'seed.json'), silentLogger)).toEqual(seed);
+ });
+
+ it('is empty when there is no file, or it cannot be read', async () => {
+ expect(await readProviderSeed(join(dir, 'missing.json'), silentLogger)).toEqual([]);
+ writeFileSync(join(dir, 'bad.json'), '{"providers": [{"status": {}}]}');
+ expect(await readProviderSeed(join(dir, 'bad.json'), silentLogger)).toEqual([]);
+ });
+});
diff --git a/console/packages/agent-controller/src/provider-seed.ts b/console/packages/agent-controller/src/provider-seed.ts
new file mode 100644
index 000000000..31dcb6723
--- /dev/null
+++ b/console/packages/agent-controller/src/provider-seed.ts
@@ -0,0 +1,51 @@
+import { readFile, rename, writeFile } from 'node:fs/promises';
+import { z } from 'zod';
+import { errorMessage, type Logger } from './log';
+import { providerStatusSchema } from './schemas';
+import type { ProviderSeed } from './status';
+
+/**
+ * Provider checks written by `precheck` and read by `run --provider-seed`:
+ * Switch Console checks the providers as onboarding opens, before this
+ * computer is enrolled anywhere, and hands the result to the controller it
+ * starts later, so the controller's first report already says what is signed
+ * in.
+ */
+const providerSeedFileSchema = z.object({
+ providers: z.array(z.object({ status: providerStatusSchema, path: z.string().nullable() })),
+});
+
+/** Writes `seed` whole, so a reader never finds it half written. */
+export async function writeProviderSeed(file: string, seed: ProviderSeed): Promise<void> {
+ const temporary = `${file}.${process.pid}.tmp`;
+ await writeFile(temporary, JSON.stringify({ providers: seed }), { mode: 0o600 });
+ await rename(temporary, file);
+}
+
+/**
+ * The checks in `file`; none when there is no file. One that cannot be read
+ * is said in the log and left out: the controller checks for itself, as it
+ * would have without it.
+ */
+export async function readProviderSeed(file: string, log: Logger): Promise<ProviderSeed> {
+ let text: string;
+ try {
+ text = await readFile(file, 'utf8');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
+ log.warn('Could not read the provider checks handed over; checking every provider here', {
+ file,
+ error: errorMessage(error),
+ });
+ return [];
+ }
+ try {
+ return providerSeedFileSchema.parse(JSON.parse(text)).providers;
+ } catch (error) {
+ log.warn('The provider checks handed over are not readable; checking every provider here', {
+ file,
+ error: errorMessage(error),
+ });
+ return [];
+ }
+}
diff --git a/console/packages/agent-controller/src/status.test.ts b/console/packages/agent-controller/src/status.test.ts
index 71c8d8843..aa11aaa61 100644
--- a/console/packages/agent-controller/src/status.test.ts
+++ b/console/packages/agent-controller/src/status.test.ts
@@ -6,7 +6,12 @@ import { vertexCredentialFixture, writeNodeCli } from '@switch-console/agent-pro
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { silentLogger } from './log';
import { type AgentObservation, emptyObservation } from './runtime';
-import { type AgentAssignment, type SealedLoginResponse, statusReportSchema } from './schemas';
+import {
+ type AgentAssignment,
+ type ProviderStatus,
+ type SealedLoginResponse,
+ statusReportSchema,
+} from './schemas';
import { SealedLogins } from './sealed-logins';
import {
mapAgentProcess,
@@ -290,6 +295,74 @@ describe('ProviderStatuses', () => {
});
});
+describe('ProviderStatuses taking checks made before it started', () => {
+ function statuses(clock: () => number) {
+ const runtime = new FakeRuntime();
+ let changes = 0;
+ const providers = new ProviderStatuses({
+ locator: new FakeLocator(),
+ runtime,
+ sealed: null,
+ probeCwd: '/tmp',
+ now: clock,
+ log: silentLogger,
+ onChange: () => changes++,
+ });
+ return { providers, runtime, changes: () => changes };
+ }
+
+ function seeded(
+ provider: string,
+ auth: 'ok' | 'missing',
+ at: number,
+ installed = true
+ ): { status: ProviderStatus; path: string | null } {
+ return {
+ status: {
+ provider,
+ installed,
+ version: installed ? '1.0.0' : null,
+ auth: installed ? auth : 'unknown',
+ auth_source: installed && auth === 'ok' ? 'local' : null,
+ checked_at: new Date(at).toISOString(),
+ },
+ path: installed ? `/bin/${provider}` : null,
+ };
+ }
+
+ it('reports a provider signed in on its own, or not installed, without checking it again', async () => {
+ const { providers, runtime, changes } = statuses(() => NOW);
+ providers.seed([seeded('claude', 'ok', NOW - 1_000), seeded('cursor', 'ok', NOW, false)]);
+ expect(changes()).toBe(1);
+ expect(providers.snapshot().map((status) => [status.provider, status.auth])).toEqual([
+ ['claude', 'ok'],
+ ['cursor', 'unknown'],
+ ]);
+ await providers.refreshStale();
+ // Every provider but the two seeded is checked here.
+ expect(runtime.probes).toBe(3);
+ expect(await providers.binaryPath('claude')).toBe('/bin/claude');
+ });
+
+ it('checks for itself what a login given to the machine could change, and what is stale', async () => {
+ const { providers, changes } = statuses(() => NOW);
+ providers.seed([
+ seeded('codex', 'missing', NOW),
+ seeded('claude', 'ok', NOW - PROVIDER_TTL_MS),
+ ]);
+ expect(changes()).toBe(0);
+ expect(providers.snapshot()).toEqual([]);
+ });
+
+ it('leaves a provider it has already checked as it found it', async () => {
+ const { providers } = statuses(() => NOW);
+ await providers.check('claude');
+ const own = providers.snapshot().find((status) => status.provider === 'claude');
+ providers.seed([seeded('claude', 'ok', NOW + 5)]);
+ expect(providers.snapshot().find((status) => status.provider === 'claude')).toEqual(own);
+ });
+});
+
describe('ProviderStatuses with logins given to the machine', () => {
const keys = generateSealingKeyPair();
let answer: SealedLoginResponse | null;
diff --git a/console/packages/agent-controller/src/status.ts b/console/packages/agent-controller/src/status.ts
index c7e958c83..af8eec43e 100644
--- a/console/packages/agent-controller/src/status.ts
+++ b/console/packages/agent-controller/src/status.ts
@@ -17,6 +17,7 @@ import {
type Assignment,
type Platform,
type ProcessState,
+ isProvider,
PROTOCOL_VERSION,
type Provider,
PROVIDERS,
@@ -216,6 +217,9 @@ export function providerStatusFrom(
* A provider as last checked: its status, its CLI, the login Switch gave the
* machine when that is what agents use, and why a given login is not used.
*/
+/** Provider checks made elsewhere, for {@link ProviderStatuses.seed}: each status and where its CLI was found. */
+export type ProviderSeed = { status: ProviderStatus; path: string | null }[];
+
type ProviderEntry = {
status: ProviderStatus;
path: string | null;
@@ -254,6 +258,44 @@ export class ProviderStatuses {
}
) {}
+ /**
+ * Takes provider checks made before this controller started (Switch
+ * Console's, as onboarding opens) as its own, so its first report already
+ * carries them rather than waiting on checks of its own.
+ *
+ * Only what no login given to the machine could change: a provider signed
+ * in on its own, or not installed. Any other is checked here as usual, and
+ * so is one already checked here or checked longer ago than the TTL.
+ */
+ seed(seeds: ProviderSeed): void {
+ let changed = false;
+ for (const { status, path } of seeds) {
+ if (!isProvider(status.provider) || this.entries.has(status.provider)) continue;
+ const own = status.auth === 'ok' && status.auth_source === 'local';
+ if (!own && status.installed) continue;
+ const at = Date.parse(status.checked_at);
+ if (!Number.isFinite(at) || this.deps.now() - at >= PROVIDER_TTL_MS) continue;
+ this.entries.set(status.provider, {
+ status,
+ path,
+ at,
+ login: null,
+ problem: null,
+ sequence: 0,
+ });
+ changed = true;
+ }
+ if (changed) this.deps.onChange();
+ }
+
+ /** Every check made so far, with where each provider's CLI was found: what `seed` takes. */
+ results(): ProviderSeed {
+ return PROVIDERS.flatMap((provider) => {
+ const entry = this.entries.get(provider);
+ return entry ? [{ status: entry.status, path: entry.path }] : [];
+ });
+ }
+
/** Checks one provider now, its own login first, then one given to the machine. */
async check(provider: Provider): Promise<ProviderStatus> {
const sequence = ++this.checks;
diff --git a/console/packages/agent-controller/src/systemd-runtime.e2e.test.ts b/console/packages/agent-controller/src/systemd-runtime.e2e.test.ts
index adc6e6679..7a2092e7c 100644
--- a/console/packages/agent-controller/src/systemd-runtime.e2e.test.ts
+++ b/console/packages/agent-controller/src/systemd-runtime.e2e.test.ts
@@ -136,6 +136,7 @@ describe.skipIf(!dataDir)('agents as users of their own, under systemd', () => {
},
rechecks: new ProviderRechecks(),
refreshPath: async () => {},
+ providerSeed: [],
tools: async () => [],
fetch,
openWebSocket: core.openWebSocket,