Skip to content

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

Split switch-buddy's provider card into what it does and what it draws

Simon Flackb6cb317246cb
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-modal.tsx
index 9146c0c00..5dce178e0 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-modal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-modal.tsx
@@ -7,6 +7,7 @@ import {
DialogTitle,
} from '@renderer/lib/ui/dialog';
import { ProviderSetup } from './provider-setup';
+import { useThisComputer } from './use-this-computer';
type Args = { serverId: string; workspaceId: string };
@@ -17,6 +18,7 @@ export function BuddySetupModal({
onSuccess,
onClose,
}: Args & BaseModalProps<{ agentId: string; name: string }>) {
+ const thisComputer = useThisComputer(serverId, workspaceId);
return (
<>
<DialogHeader>
@@ -28,6 +30,7 @@ export function BuddySetupModal({
workspaceId={workspaceId}
entryPoint="switch_buddy"
onCreated={onSuccess}
+ thisComputer={thisComputer}
/>
</DialogContentArea>
<DialogFooter>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/install-failure.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/install-failure.test.ts
new file mode 100644
index 000000000..fd311f089
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/install-failure.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+import { installFailure } from './install-failure';
+
+describe('installFailure', () => {
+ it('says to open a new terminal when the CLI was installed but is not found', () => {
+ expect(installFailure('Codex', { type: 'not-detected-after-install' } as never)).toContain(
+ 'Codex was installed, but this computer can’t find it yet.'
+ );
+ });
+
+ it('says to install it by hand when Console cannot', () => {
+ for (const type of ['no-install-command', 'unknown-dependency'])
+ expect(installFailure('Codex', { type } as never)).toBe(
+ 'Switch Console can’t install Codex on this computer. Install it yourself, then press Check again.'
+ );
+ });
+
+ it('quotes the end of the output when the install command failed', () => {
+ const said = installFailure('Codex', {
+ type: 'command-failed',
+ message: 'npm exited with 1.',
+ output: 'lots of noise\nEACCES: permission denied',
+ } as never);
+ expect(said).toMatch(/^Installing Codex failed: npm exited with 1\. Output: /);
+ expect(said).toContain('EACCES');
+ });
+
+ it('gives the reason for anything else', () => {
+ expect(
+ installFailure('Codex', { type: 'permission-denied', message: 'Not allowed.' } as never)
+ ).toBe('Installing Codex failed: Not allowed.');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/install-failure.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/install-failure.ts
new file mode 100644
index 000000000..ca0482e55
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/install-failure.ts
@@ -0,0 +1,22 @@
+import type { AgentInstallError } from '@shared/core/providers/agent-payload';
+import { installOutputSummary } from './install-output-summary';
+
+/** What the card says when installing a provider's CLI failed, by why. */
+export function installFailure(name: string, error: AgentInstallError): string {
+ switch (error.type) {
+ case 'not-detected-after-install':
+ return `${name} was installed, but this computer can’t find it yet. Open a new terminal and check it runs, then press Check again.`;
+ case 'no-install-command':
+ case 'unknown-dependency':
+ return `Switch Console can’t install ${name} on this computer. Install it yourself, then press Check again.`;
+ case 'command-failed': {
+ const last = installOutputSummary(error.output);
+ return last
+ ? `Installing ${name} failed: ${error.message} Output: ${last}`
+ : `Installing ${name} failed: ${error.message}`;
+ }
+ case 'permission-denied':
+ case 'process-open-failed':
+ return `Installing ${name} failed: ${error.message}`;
+ }
+}
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 f83639037..23f22a263 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
@@ -52,7 +52,8 @@ export const MeetBuddyPage = observer(function MeetBuddyPage({
}) {
const exit = useWizardExit();
const [settingUp, setSettingUp] = useState(false);
- const { state: computer, earlyProviders } = useThisComputer(serverId, workspaceId);
+ const thisComputer = useThisComputer(serverId, workspaceId);
+ const { state: computer, earlyProviders } = thisComputer;
// What this computer's controller reports, or until it does, what Console
// found checking the providers as onboarding opened.
const reported = useMemo(
@@ -137,6 +138,7 @@ export const MeetBuddyPage = observer(function MeetBuddyPage({
workspaceId={workspaceId}
entryPoint="onboarding"
onCreated={onCreated}
+ thisComputer={thisComputer}
/>
</OnboardingSurface>
);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/provider-cards.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/provider-cards.tsx
new file mode 100644
index 000000000..5dda6de52
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/provider-cards.tsx
@@ -0,0 +1,216 @@
+import { CircleAlert, ExternalLink } from 'lucide-react';
+import { LogTail } from '@renderer/features/switch-servers/log-tail';
+import { AgentIcon } from '@renderer/lib/components/agent-icon';
+import { openExternalUrl } from '@renderer/lib/open-external';
+import { Button } from '@renderer/lib/ui/button';
+import { Spinner } from '@renderer/lib/ui/spinner';
+import { cn } from '@renderer/utils/utils';
+import { requireProvider } from '@shared/core/providers/agent-provider-registry';
+import { linksIn } from '@shared/core/providers/provider-login';
+import type { BuddyProvider } from './buddy-providers';
+import type { Login, SetupBusy } from './use-provider-setup';
+import type { ThisComputer } from './use-this-computer';
+
+/*
+ * What the provider card draws: this computer's state, a card per provider,
+ * and what the selected one needs next. Nothing here acts; `ProviderSetup`
+ * hands each its state and handlers from `useProviderSetup`.
+ */
+
+export function ComputerNote({ computer }: { computer: ThisComputer }) {
+ if (computer.kind === 'ready') return null;
+ if (computer.kind === 'failed')
+ return (
+ <p role="alert" className="flex items-start gap-2 text-sm text-destructive">
+ <CircleAlert className="mt-0.5 size-4 shrink-0" />
+ <span>{computer.error}</span>
+ </p>
+ );
+ return (
+ <p className="flex items-center gap-2 text-sm text-foreground-muted">
+ <Spinner className="size-3.5" />
+ Getting this computer ready to run switch-buddy…
+ </p>
+ );
+}
+
+const TAG: Record<BuddyProvider['state'], string> = {
+ ready: 'Signed in locally',
+ 'sign-in': 'Not signed in',
+ install: 'Not installed',
+ checking: 'Checking…',
+};
+
+export function ProviderCard({
+ provider,
+ selected,
+ disabled,
+ onSelect,
+}: {
+ provider: BuddyProvider;
+ selected: boolean;
+ disabled: boolean;
+ onSelect: () => void;
+}) {
+ return (
+ <li className="list-none">
+ <button
+ type="button"
+ aria-pressed={selected}
+ disabled={disabled || provider.state === 'checking'}
+ onClick={onSelect}
+ className={cn(
+ 'flex h-full w-full flex-col items-start gap-3 rounded-xl border bg-background/80 p-4 text-left disabled:opacity-60',
+ selected ? 'border-foreground' : 'border-border hover:bg-[var(--sel-soft)]'
+ )}
+ >
+ <AgentIcon id={provider.id} size={28} />
+ <span className="space-y-0.5">
+ <span className="block text-sm font-medium text-foreground">{provider.name}</span>
+ <span
+ className={cn(
+ 'flex items-center gap-1.5 text-xs',
+ provider.state === 'ready' ? 'text-emerald-600' : 'text-foreground-muted'
+ )}
+ >
+ {provider.state === 'checking' && <Spinner className="size-3" />}
+ {TAG[provider.state]}
+ </span>
+ </span>
+ </button>
+ </li>
+ );
+}
+
+export function SelectedPanel({
+ provider,
+ login,
+ busy,
+ onStart,
+ onSignIn,
+ onCancelSignIn,
+ onInstall,
+ onCheckAgain,
+ checked,
+}: {
+ provider: BuddyProvider;
+ login: Login | null;
+ /** What the last Check again found, or null. */
+ checked: string | null;
+ busy: SetupBusy;
+ onStart: () => void;
+ onSignIn: () => void;
+ onCancelSignIn: () => void;
+ onInstall: () => void;
+ onCheckAgain: () => void;
+}) {
+ const loginCommand = requireProvider(provider.id).loginCommand;
+ switch (provider.state) {
+ case 'ready':
+ return (
+ <>
+ <div className="space-y-1">
+ <p className="text-sm font-medium text-foreground">Use the account signed in here</p>
+ <p className="text-xs text-foreground-muted">
+ switch-buddy runs on this computer with your {provider.name} sign-in. Nothing is
+ uploaded.
+ </p>
+ </div>
+ <div>
+ <Button onClick={onStart} disabled={busy !== null}>
+ {busy === 'create' && <Spinner className="size-3.5" />}
+ {busy === 'create' ? 'Creating switch-buddy…' : `Start with ${provider.name}`}
+ </Button>
+ </div>
+ </>
+ );
+ case 'install':
+ return (
+ <>
+ <div className="space-y-1">
+ <p className="text-sm font-medium text-foreground">
+ {provider.name} isn’t installed on this computer
+ </p>
+ <p className="text-xs text-foreground-muted">
+ Switch Console can install it for you. You’ll sign in to it next.
+ </p>
+ </div>
+ <div>
+ <Button onClick={onInstall} disabled={busy !== null}>
+ {busy === 'install' && <Spinner className="size-3.5" />}
+ {busy === 'install' ? `Installing ${provider.name}…` : `Install ${provider.name}`}
+ </Button>
+ </div>
+ </>
+ );
+ case 'sign-in': {
+ const running = login !== null && login.ended === null;
+ const links = login ? linksIn(login.lines) : [];
+ return (
+ <>
+ <div className="space-y-1">
+ <p className="text-sm font-medium text-foreground">
+ Sign in to {provider.name} on this computer
+ </p>
+ <p className="text-xs text-foreground-muted">
+ {running
+ ? 'Finish signing in in your browser. This page moves on by itself once it’s done.'
+ : 'It opens your browser to sign in with your own account.'}
+ </p>
+ {provider.detail && !running && (
+ <p className="text-xs text-foreground-warning">{provider.detail}</p>
+ )}
+ </div>
+ {login && <LogTail lines={login.lines} placeholder="Starting the sign-in…" />}
+ {links.length > 0 && (
+ <div className="flex flex-wrap gap-2">
+ {links.map((link) => (
+ <Button
+ key={link}
+ variant="outline"
+ size="sm"
+ onClick={() => void openExternalUrl(link, 'Could not open the sign-in page')}
+ >
+ <ExternalLink className="size-3.5" />
+ Open sign-in page
+ </Button>
+ ))}
+ </div>
+ )}
+ {login?.ended && !login.ended.ok && (
+ <p className="text-xs text-destructive">
+ {login.ended.error ?? `${loginCommand} ended without signing in.`}
+ </p>
+ )}
+ <div className="flex flex-wrap items-center gap-2">
+ {running ? (
+ <Button variant="outline" onClick={onCancelSignIn}>
+ Cancel
+ </Button>
+ ) : (
+ <Button onClick={onSignIn} disabled={busy !== null}>
+ Sign in
+ </Button>
+ )}
+ <Button variant="ghost" onClick={onCheckAgain} disabled={busy !== null || running}>
+ {busy === 'check' && <Spinner className="size-3.5" />}
+ Check again
+ </Button>
+ </div>
+ {checked && !running && <p className="text-xs text-foreground-muted">{checked}</p>}
+ <p className="text-xs text-foreground-muted">
+ Or run <code className="rounded bg-background-tertiary px-1">{loginCommand}</code> in a
+ terminal, then press Check again.
+ </p>
+ </>
+ );
+ }
+ case 'checking':
+ return (
+ <p className="flex items-center gap-2 text-sm text-foreground-muted">
+ <Spinner className="size-3.5" />
+ Checking {provider.name} on this computer…
+ </p>
+ );
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/provider-setup.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/provider-setup.tsx
index 2f45e89b5..850ddb671 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/provider-setup.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/provider-setup.tsx
@@ -1,419 +1,79 @@
-import { CircleAlert, ExternalLink } from 'lucide-react';
+import { CircleAlert } from 'lucide-react';
import { observer } from 'mobx-react-lite';
-import { useCallback, useEffect, useMemo, useState } from 'react';
-import { LogTail } from '@renderer/features/switch-servers/log-tail';
-import { AgentIcon } from '@renderer/lib/components/agent-icon';
-import { failureText } from '@renderer/lib/errors/describe-failure';
-import { events, rpc } from '@renderer/lib/ipc';
-import { openExternalUrl } from '@renderer/lib/open-external';
-import { Button } from '@renderer/lib/ui/button';
-import { Spinner } from '@renderer/lib/ui/spinner';
-import { cn } from '@renderer/utils/utils';
-import type { AgentInstallError } from '@shared/core/providers/agent-payload';
-import { agentProviders, requireProvider } from '@shared/core/providers/agent-provider-registry';
-import { linksIn } from '@shared/core/providers/provider-login';
import type { UiEntryPoint } from '@shared/core/telemetry/reporting';
-import { providerLoginExitChannel, providerLoginLineChannel } from '@shared/events/appEvents';
-import { type BuddyProvider, buddyProviders } from './buddy-providers';
-import { reportBuddyStep } from './buddy-telemetry';
-import { installOutputSummary } from './install-output-summary';
-import { useStartBuddy } from './use-start-buddy';
-import { type ThisComputer, useThisComputer } from './use-this-computer';
-
-/** How many lines of a sign-in command's output are kept on screen. */
-const KEPT_LINES = 40;
-
-type Login = {
- attemptId: string;
- providerId: string;
- lines: string[];
- /** Null while it runs; then how it ended. */
- ended: { ok: boolean; error: string | null } | null;
-};
+import { ComputerNote, ProviderCard, SelectedPanel } from './provider-cards';
+import { useProviderSetup } from './use-provider-setup';
+import type { ThisComputer } from './use-this-computer';
/**
* Pick the AI provider switch-buddy runs on, get it ready on this computer,
- * and create the buddy with it.
+ * and create the buddy with it (see `useProviderSetup`).
*
- * What a provider needs is read from what this computer's agent controller
- * reports to Switch, which is what Switch checks before creating an agent.
- * Installing a CLI or signing it in is followed by asking the controller to
- * check again straight away, so the card moves on as soon as it is true
- * rather than at the controller's next check.
+ * `thisComputer` is the page's own `useThisComputer`, so a page that already
+ * follows this computer does not set it up a second time.
*/
export const ProviderSetup = observer(function ProviderSetup({
serverId,
workspaceId,
entryPoint,
onCreated,
+ thisComputer,
}: {
serverId: string;
workspaceId: string;
/** Where this card is shown: the first run, or the buddy's chat later. */
entryPoint: UiEntryPoint;
onCreated: (agent: { agentId: string; name: string }) => void;
+ thisComputer: { state: ThisComputer; recheck: () => Promise<string | null> };
}) {
- const { state: computer, recheck } = useThisComputer(serverId, workspaceId);
- const providers = useMemo(
- () => buddyProviders(agentProviders(), computer.kind === 'ready' ? computer.machine : null),
- [computer]
- );
- const [picked, setPicked] = useState<string | null>(null);
- const selected =
- providers.find((p) => p.id === picked) ??
- providers.find((p) => p.state === 'ready') ??
- providers.find((p) => p.state === 'sign-in') ??
- null;
-
- const [working, setWorking] = useState<'install' | 'check' | null>(null);
- const [actionError, setActionError] = useState<string | null>(null);
- const started = useStartBuddy({ serverId, workspaceId, computer, entryPoint, onCreated });
- const busy = working ?? (started.starting !== null ? 'create' : null);
- // One error at a time, as each action clears what the last one said.
- const error = actionError ?? started.error;
- const { clearError } = started;
- const setError = useCallback(
- (message: string | null) => {
- setActionError(message);
- clearError();
- },
- [clearError]
- );
-
- const [login, setLogin] = useState<Login | null>(null);
- /** What the last Check again found, when it found nothing new: said, not left blank. */
- const [checked, setChecked] = useState<string | null>(null);
-
- const checkAgain = useCallback(async () => {
- reportBuddyStep('check_again', null);
- setWorking('check');
- setError(null);
- setChecked(null);
- try {
- setChecked(await recheck());
- } catch (cause) {
- setError(failureText(cause, 'Could not check this computer again.'));
- } finally {
- setWorking(null);
- }
- }, [recheck, setError]);
-
- useEffect(() => {
- const offLine = events.on(providerLoginLineChannel, ({ attemptId, line }) =>
- setLogin((current) =>
- current?.attemptId === attemptId
- ? { ...current, lines: [...current.lines, line].slice(-KEPT_LINES) }
- : current
- )
- );
- const offExit = events.on(providerLoginExitChannel, ({ attemptId, exitCode, error: why }) => {
- let ours = false;
- setLogin((current) => {
- if (current?.attemptId !== attemptId) return current;
- ours = true;
- return { ...current, ended: { ok: exitCode === 0 && why === null, error: why } };
- });
- if (ours) void checkAgain();
- });
- return () => {
- offLine();
- offExit();
- };
- }, [checkAgain]);
-
- useEffect(() => () => void rpc.providers.cancelLogin(), []);
-
- const signIn = async (provider: BuddyProvider) => {
- reportBuddyStep('sign_in', provider.id);
- setError(null);
- try {
- const { attemptId } = await rpc.providers.startLogin(provider.id);
- setLogin({ attemptId, providerId: provider.id, lines: [], ended: null });
- } catch (cause) {
- setError(failureText(cause, `Could not start signing in to ${provider.name}.`));
- }
- };
-
- const install = async (provider: BuddyProvider) => {
- reportBuddyStep('install', provider.id);
- setWorking('install');
- setError(null);
- try {
- const result = await rpc.providers.install(provider.id);
- if (!result.success) setError(installFailure(provider.name, result.error));
- await recheck();
- } catch (cause) {
- setError(failureText(cause, `Could not install ${provider.name}.`));
- } finally {
- setWorking(null);
- }
- };
-
- const start = (provider: BuddyProvider) => {
- if (computer.kind !== 'ready') return;
- setActionError(null);
- started.start(provider.id);
- };
+ const computer = thisComputer.state;
+ const setup = useProviderSetup({
+ serverId,
+ workspaceId,
+ entryPoint,
+ onCreated,
+ computer,
+ recheck: thisComputer.recheck,
+ });
return (
<div className="flex flex-col gap-4">
<ComputerNote computer={computer} />
<p className="text-sm text-foreground">Pick an AI provider to power switch-buddy:</p>
<ul className="grid gap-3 sm:grid-cols-3">
- {providers.map((provider) => (
+ {setup.providers.map((provider) => (
<ProviderCard
key={provider.id}
provider={provider}
- selected={selected?.id === provider.id}
- disabled={busy !== null || (login !== null && login.ended === null)}
- onSelect={() => setPicked(provider.id)}
+ selected={setup.selected?.id === provider.id}
+ disabled={setup.busy !== null || (setup.login !== null && setup.login.ended === null)}
+ onSelect={() => setup.pick(provider.id)}
/>
))}
</ul>
- {selected && computer.kind === 'ready' && (
+ {setup.selected && computer.kind === 'ready' && (
<div className="flex flex-col gap-3 rounded-xl border border-border bg-background/80 p-4">
<SelectedPanel
- provider={selected}
- login={login?.providerId === selected.id ? login : null}
- busy={busy}
- onStart={() => start(selected)}
- onSignIn={() => void signIn(selected)}
- onCancelSignIn={() => {
- void rpc.providers.cancelLogin();
- setLogin(null);
- setChecked(null);
- }}
- checked={checked}
- onInstall={() => void install(selected)}
- onCheckAgain={() => void checkAgain()}
+ provider={setup.selected}
+ login={setup.login?.providerId === setup.selected.id ? setup.login : null}
+ busy={setup.busy}
+ onStart={() => setup.start(setup.selected!)}
+ onSignIn={() => void setup.signIn(setup.selected!)}
+ onCancelSignIn={setup.cancelSignIn}
+ checked={setup.checked}
+ onInstall={() => void setup.install(setup.selected!)}
+ onCheckAgain={() => void setup.checkAgain()}
/>
</div>
)}
- {error && (
+ {setup.error && (
<p role="alert" className="flex items-start gap-2 text-sm text-destructive">
<CircleAlert className="mt-0.5 size-4 shrink-0" />
- <span>{error}</span>
+ <span>{setup.error}</span>
</p>
)}
</div>
);
});
-
-function ComputerNote({ computer }: { computer: ThisComputer }) {
- if (computer.kind === 'ready') return null;
- if (computer.kind === 'failed')
- return (
- <p role="alert" className="flex items-start gap-2 text-sm text-destructive">
- <CircleAlert className="mt-0.5 size-4 shrink-0" />
- <span>{computer.error}</span>
- </p>
- );
- return (
- <p className="flex items-center gap-2 text-sm text-foreground-muted">
- <Spinner className="size-3.5" />
- Getting this computer ready to run switch-buddy…
- </p>
- );
-}
-
-const TAG: Record<BuddyProvider['state'], string> = {
- ready: 'Signed in locally',
- 'sign-in': 'Not signed in',
- install: 'Not installed',
- checking: 'Checking…',
-};
-
-function ProviderCard({
- provider,
- selected,
- disabled,
- onSelect,
-}: {
- provider: BuddyProvider;
- selected: boolean;
- disabled: boolean;
- onSelect: () => void;
-}) {
- return (
- <li className="list-none">
- <button
- type="button"
- aria-pressed={selected}
- disabled={disabled || provider.state === 'checking'}
- onClick={onSelect}
- className={cn(
- 'flex h-full w-full flex-col items-start gap-3 rounded-xl border bg-background/80 p-4 text-left disabled:opacity-60',
- selected ? 'border-foreground' : 'border-border hover:bg-[var(--sel-soft)]'
- )}
- >
- <AgentIcon id={provider.id} size={28} />
- <span className="space-y-0.5">
- <span className="block text-sm font-medium text-foreground">{provider.name}</span>
- <span
- className={cn(
- 'flex items-center gap-1.5 text-xs',
- provider.state === 'ready' ? 'text-emerald-600' : 'text-foreground-muted'
- )}
- >
- {provider.state === 'checking' && <Spinner className="size-3" />}
- {TAG[provider.state]}
- </span>
- </span>
- </button>
- </li>
- );
-}
-
-function SelectedPanel({
- provider,
- login,
- busy,
- onStart,
- onSignIn,
- onCancelSignIn,
- onInstall,
- onCheckAgain,
- checked,
-}: {
- provider: BuddyProvider;
- login: Login | null;
- /** What the last Check again found, or null. */
- checked: string | null;
- busy: 'install' | 'check' | 'create' | null;
- onStart: () => void;
- onSignIn: () => void;
- onCancelSignIn: () => void;
- onInstall: () => void;
- onCheckAgain: () => void;
-}) {
- const loginCommand = requireProvider(provider.id).loginCommand;
- switch (provider.state) {
- case 'ready':
- return (
- <>
- <div className="space-y-1">
- <p className="text-sm font-medium text-foreground">Use the account signed in here</p>
- <p className="text-xs text-foreground-muted">
- switch-buddy runs on this computer with your {provider.name} sign-in. Nothing is
- uploaded.
- </p>
- </div>
- <div>
- <Button onClick={onStart} disabled={busy !== null}>
- {busy === 'create' && <Spinner className="size-3.5" />}
- {busy === 'create' ? 'Creating switch-buddy…' : `Start with ${provider.name}`}
- </Button>
- </div>
- </>
- );
- case 'install':
- return (
- <>
- <div className="space-y-1">
- <p className="text-sm font-medium text-foreground">
- {provider.name} isn’t installed on this computer
- </p>
- <p className="text-xs text-foreground-muted">
- Switch Console can install it for you. You’ll sign in to it next.
- </p>
- </div>
- <div>
- <Button onClick={onInstall} disabled={busy !== null}>
- {busy === 'install' && <Spinner className="size-3.5" />}
- {busy === 'install' ? `Installing ${provider.name}…` : `Install ${provider.name}`}
- </Button>
- </div>
- </>
- );
- case 'sign-in': {
- const running = login !== null && login.ended === null;
- const links = login ? linksIn(login.lines) : [];
- return (
- <>
- <div className="space-y-1">
- <p className="text-sm font-medium text-foreground">
- Sign in to {provider.name} on this computer
- </p>
- <p className="text-xs text-foreground-muted">
- {running
- ? 'Finish signing in in your browser. This page moves on by itself once it’s done.'
- : 'It opens your browser to sign in with your own account.'}
- </p>
- {provider.detail && !running && (
- <p className="text-xs text-foreground-warning">{provider.detail}</p>
- )}
- </div>
- {login && <LogTail lines={login.lines} placeholder="Starting the sign-in…" />}
- {links.length > 0 && (
- <div className="flex flex-wrap gap-2">
- {links.map((link) => (
- <Button
- key={link}
- variant="outline"
- size="sm"
- onClick={() => void openExternalUrl(link, 'Could not open the sign-in page')}
- >
- <ExternalLink className="size-3.5" />
- Open sign-in page
- </Button>
- ))}
- </div>
- )}
- {login?.ended && !login.ended.ok && (
- <p className="text-xs text-destructive">
- {login.ended.error ?? `${loginCommand} ended without signing in.`}
- </p>
- )}
- <div className="flex flex-wrap items-center gap-2">
- {running ? (
- <Button variant="outline" onClick={onCancelSignIn}>
- Cancel
- </Button>
- ) : (
- <Button onClick={onSignIn} disabled={busy !== null}>
- Sign in
- </Button>
- )}
- <Button variant="ghost" onClick={onCheckAgain} disabled={busy !== null || running}>
- {busy === 'check' && <Spinner className="size-3.5" />}
- Check again
- </Button>
- </div>
- {checked && !running && <p className="text-xs text-foreground-muted">{checked}</p>}
- <p className="text-xs text-foreground-muted">
- Or run <code className="rounded bg-background-tertiary px-1">{loginCommand}</code> in a
- terminal, then press Check again.
- </p>
- </>
- );
- }
- case 'checking':
- return (
- <p className="flex items-center gap-2 text-sm text-foreground-muted">
- <Spinner className="size-3.5" />
- Checking {provider.name} on this computer…
- </p>
- );
- }
-}
-
-function installFailure(name: string, error: AgentInstallError): string {
- switch (error.type) {
- case 'not-detected-after-install':
- return `${name} was installed, but this computer can’t find it yet. Open a new terminal and check it runs, then press Check again.`;
- case 'no-install-command':
- case 'unknown-dependency':
- return `Switch Console can’t install ${name} on this computer. Install it yourself, then press Check again.`;
- case 'command-failed': {
- const last = installOutputSummary(error.output);
- return last
- ? `Installing ${name} failed: ${error.message} Output: ${last}`
- : `Installing ${name} failed: ${error.message}`;
- }
- case 'permission-denied':
- case 'process-open-failed':
- return `Installing ${name} failed: ${error.message}`;
- }
-}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/use-provider-setup.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/use-provider-setup.ts
new file mode 100644
index 000000000..044669ffd
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/use-provider-setup.ts
@@ -0,0 +1,174 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { events, rpc } from '@renderer/lib/ipc';
+import { agentProviders } from '@shared/core/providers/agent-provider-registry';
+import type { UiEntryPoint } from '@shared/core/telemetry/reporting';
+import { providerLoginExitChannel, providerLoginLineChannel } from '@shared/events/appEvents';
+import { type BuddyProvider, buddyProviders } from './buddy-providers';
+import { reportBuddyStep } from './buddy-telemetry';
+import { installFailure } from './install-failure';
+import { useStartBuddy } from './use-start-buddy';
+import type { ThisComputer } from './use-this-computer';
+
+/** How many lines of a sign-in command's output are kept on screen. */
+const KEPT_LINES = 40;
+
+export type Login = {
+ attemptId: string;
+ providerId: string;
+ lines: string[];
+ /** Null while it runs; then how it ended. */
+ ended: { ok: boolean; error: string | null } | null;
+};
+
+/** What the card is busy with, which disables the rest. */
+export type SetupBusy = 'install' | 'check' | 'create' | null;
+
+/**
+ * Getting a provider ready on this computer and starting switch-buddy with
+ * it: everything the provider card does, without drawing it.
+ *
+ * What a provider needs is read from what this computer's agent controller
+ * reports to Switch, which is what Switch checks before creating an agent.
+ * Installing a CLI or signing it in is followed by asking the controller to
+ * check again straight away, so the card moves on as soon as it is true
+ * rather than at the controller's next check.
+ */
+export function useProviderSetup({
+ serverId,
+ workspaceId,
+ entryPoint,
+ onCreated,
+ computer,
+ recheck,
+}: {
+ serverId: string;
+ workspaceId: string;
+ entryPoint: UiEntryPoint;
+ onCreated: (agent: { agentId: string; name: string }) => void;
+ computer: ThisComputer;
+ /** Has this computer check its providers again; a line when nothing new was found. */
+ recheck: () => Promise<string | null>;
+}) {
+ const providers = useMemo(
+ () => buddyProviders(agentProviders(), computer.kind === 'ready' ? computer.machine : null),
+ [computer]
+ );
+ const [picked, setPicked] = useState<string | null>(null);
+ const selected =
+ providers.find((p) => p.id === picked) ??
+ providers.find((p) => p.state === 'ready') ??
+ providers.find((p) => p.state === 'sign-in') ??
+ null;
+
+ const [working, setWorking] = useState<'install' | 'check' | null>(null);
+ const [actionError, setActionError] = useState<string | null>(null);
+ const started = useStartBuddy({ serverId, workspaceId, computer, entryPoint, onCreated });
+ const busy = working ?? (started.starting !== null ? 'create' : null);
+ // One error at a time, as each action clears what the last one said.
+ const error = actionError ?? started.error;
+ const { clearError } = started;
+ const setError = useCallback(
+ (message: string | null) => {
+ setActionError(message);
+ clearError();
+ },
+ [clearError]
+ );
+
+ const [login, setLogin] = useState<Login | null>(null);
+ /** What the last Check again found, when it found nothing new: said, not left blank. */
+ const [checked, setChecked] = useState<string | null>(null);
+
+ const checkAgain = useCallback(async () => {
+ reportBuddyStep('check_again', null);
+ setWorking('check');
+ setError(null);
+ setChecked(null);
+ try {
+ setChecked(await recheck());
+ } catch (cause) {
+ setError(failureText(cause, 'Could not check this computer again.'));
+ } finally {
+ setWorking(null);
+ }
+ }, [recheck, setError]);
+
+ useEffect(() => {
+ const offLine = events.on(providerLoginLineChannel, ({ attemptId, line }) =>
+ setLogin((current) =>
+ current?.attemptId === attemptId
+ ? { ...current, lines: [...current.lines, line].slice(-KEPT_LINES) }
+ : current
+ )
+ );
+ const offExit = events.on(providerLoginExitChannel, ({ attemptId, exitCode, error: why }) => {
+ let ours = false;
+ setLogin((current) => {
+ if (current?.attemptId !== attemptId) return current;
+ ours = true;
+ return { ...current, ended: { ok: exitCode === 0 && why === null, error: why } };
+ });
+ if (ours) void checkAgain();
+ });
+ return () => {
+ offLine();
+ offExit();
+ };
+ }, [checkAgain]);
+
+ useEffect(() => () => void rpc.providers.cancelLogin(), []);
+
+ const signIn = async (provider: BuddyProvider) => {
+ reportBuddyStep('sign_in', provider.id);
+ setError(null);
+ try {
+ const { attemptId } = await rpc.providers.startLogin(provider.id);
+ setLogin({ attemptId, providerId: provider.id, lines: [], ended: null });
+ } catch (cause) {
+ setError(failureText(cause, `Could not start signing in to ${provider.name}.`));
+ }
+ };
+
+ const install = async (provider: BuddyProvider) => {
+ reportBuddyStep('install', provider.id);
+ setWorking('install');
+ setError(null);
+ try {
+ const result = await rpc.providers.install(provider.id);
+ if (!result.success) setError(installFailure(provider.name, result.error));
+ await recheck();
+ } catch (cause) {
+ setError(failureText(cause, `Could not install ${provider.name}.`));
+ } finally {
+ setWorking(null);
+ }
+ };
+
+ const start = (provider: BuddyProvider) => {
+ if (computer.kind !== 'ready') return;
+ setActionError(null);
+ started.start(provider.id);
+ };
+
+ const cancelSignIn = () => {
+ void rpc.providers.cancelLogin();
+ setLogin(null);
+ setChecked(null);
+ };
+
+ return {
+ providers,
+ selected,
+ pick: setPicked,
+ busy: busy as SetupBusy,
+ error,
+ login,
+ checked,
+ checkAgain,
+ signIn,
+ cancelSignIn,
+ install,
+ start,
+ };
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/use-this-computer.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/use-this-computer.test.ts
new file mode 100644
index 000000000..46e6390e1
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/use-this-computer.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { OwnedMachine } from '@shared/core/managed-agents/managed-agents';
+
+vi.mock('@renderer/lib/ipc', () => ({ rpc: {} }));
+vi.mock('@renderer/features/managed-agents/use-managed-agents', () => ({
+ MANAGED_AGENTS_KEY: 'managed-agents',
+}));
+
+const { thisComputerIn, thisComputerState } = await import('./use-this-computer');
+
+function machine(kind: string | null, providers: number): OwnedMachine {
+ return {
+ id: `m-${kind}`,
+ local: kind === null ? null : { kind },
+ providers: Array.from({ length: providers }, (_, i) => ({ provider: `p${i}`, ready: true })),
+ } as unknown as OwnedMachine;
+}
+
+describe('thisComputerState', () => {
+ it('has failed, with why, when setting this computer up failed', () => {
+ expect(thisComputerState('No Docker.', [machine('this-computer', 2)])).toEqual({
+ kind: 'failed',
+ error: 'No Docker.',
+ });
+ });
+
+ it('has failed when the server runs no managed agents', () => {
+ expect(thisComputerState(null, null)).toMatchObject({ kind: 'failed' });
+ });
+
+ it('is starting until this computer is a machine of the workspace and has reported', () => {
+ expect(thisComputerState(null, undefined)).toEqual({ kind: 'starting' });
+ expect(thisComputerState(null, [])).toEqual({ kind: 'starting' });
+ expect(thisComputerState(null, [machine('remote', 3)])).toEqual({ kind: 'starting' });
+ expect(thisComputerState(null, [machine('this-computer', 0)])).toEqual({ kind: 'starting' });
+ });
+
+ it('is ready once this computer has reported its providers', () => {
+ const mine = machine('this-computer', 2);
+ expect(thisComputerState(null, [machine(null, 1), mine])).toEqual({
+ kind: 'ready',
+ machine: mine,
+ });
+ });
+});
+
+describe('thisComputerIn', () => {
+ it('finds this computer among the machines, or nothing', () => {
+ const mine = machine('this-computer', 0);
+ expect(thisComputerIn([machine('remote', 1), mine])).toBe(mine);
+ expect(thisComputerIn([machine('remote', 1)])).toBeNull();
+ expect(thisComputerIn(undefined)).toBeNull();
+ });
+});
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 bc52d2ed5..c0c2c7f5f 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
@@ -69,9 +69,7 @@ export function useThisComputer(serverId: string, workspaceId: string) {
queryFn: () => rpc.managedAgents.machines(serverId),
// Quick while this computer has not reported yet, then at an easy pace.
refetchInterval: (query) =>
- query.state.data?.some((m) => m.local?.kind === 'this-computer' && m.providers.length > 0)
- ? 10_000
- : 2_000,
+ (thisComputerIn(query.state.data)?.providers.length ?? 0) > 0 ? 10_000 : 2_000,
});
/**
@@ -88,7 +86,7 @@ export function useThisComputer(serverId: string, workspaceId: string) {
: 'Checked just now: nothing new is signed in yet. Finish signing in, then check again.';
}, [serverId, machines]);
- const machine = machines.data?.find((m) => m.local?.kind === 'this-computer') ?? null;
+ const machine = thisComputerIn(machines.data);
const reported = machine !== null && machine.providers.length > 0;
// Console's own check of the providers, made as onboarding opened: what
@@ -99,22 +97,40 @@ export function useThisComputer(serverId: string, workspaceId: string) {
enabled: !reported,
refetchInterval: 1_000,
});
- const state: ThisComputer = setupError
- ? { kind: 'failed', error: setupError }
- : machines.data === null
- ? {
- kind: 'failed',
- error: 'This server does not run managed agents, so switch-buddy cannot be set up here.',
- }
- : machine && machine.providers.length > 0
- ? { kind: 'ready', machine }
- : { kind: 'starting' };
+ const state = thisComputerState(setupError, machines.data);
const earlyProviders = !reported && early.data && early.data.length > 0 ? early.data : null;
return { state, recheck, earlyProviders };
}
+/**
+ * Where this computer stands, from why setting it up failed (null when it
+ * did not) and the workspace's machines as last read: null when the server
+ * runs no managed agents, undefined before the first read. Ready once this
+ * computer is among them and has reported its providers.
+ */
+export function thisComputerState(
+ setupError: string | null,
+ machines: OwnedMachine[] | null | undefined
+): ThisComputer {
+ if (setupError) return { kind: 'failed', error: setupError };
+ if (machines === null)
+ return {
+ kind: 'failed',
+ error: 'This server does not run managed agents, so switch-buddy cannot be set up here.',
+ };
+ const machine = thisComputerIn(machines);
+ return machine && machine.providers.length > 0
+ ? { kind: 'ready', machine }
+ : { kind: 'starting' };
+}
+
/** How many providers this computer last reported ready. */
function readyOn(machines: OwnedMachine[] | null | undefined): number {
- const machine = machines?.find((m) => m.local?.kind === 'this-computer');
+ const machine = thisComputerIn(machines);
return machine?.providers.filter((provider) => provider.ready).length ?? 0;
}
+
+/** This computer among the workspace's machines, once it is one. */
+export function thisComputerIn(machines: OwnedMachine[] | null | undefined): OwnedMachine | null {
+ return machines?.find((m) => m.local?.kind === 'this-computer') ?? null;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/buddy-provider-setup.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/buddy-provider-setup.test.tsx
index 05d14a67d..518fc2357 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/buddy-provider-setup.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/buddy-provider-setup.test.tsx
@@ -25,13 +25,6 @@ const state = vi.hoisted(() => ({
onCreated: vi.fn(),
}));
-vi.mock('@renderer/features/switch-buddy/use-this-computer', () => ({
- useThisComputer: () => ({
- state: { kind: 'ready', machine: { id: 'm-1', providers: state.providers } },
- recheck: state.recheck,
- earlyProviders: null,
- }),
-}));
vi.mock('@renderer/features/switch-buddy/create-buddy', () => ({
createBuddy: state.createBuddy,
}));
@@ -95,6 +88,10 @@ async function render() {
workspaceId="ws-1"
entryPoint="switch_buddy"
onCreated={state.onCreated}
+ thisComputer={{
+ state: { kind: 'ready', machine: { id: 'm-1', providers: state.providers } as never },
+ recheck: state.recheck,
+ }}
/>
)
);