Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 148 additions & 4 deletions apps/web/src/aldo/AldoAgentConnections.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import { useState } from "react";
import { useEffect, useState } from "react";
import type { AuthConnectorMethod } from "@t3tools/contracts";

import { AuthConnectorDialog } from "../components/settings/AuthConnectorDialog";
import { AGENT_AUTH_METHODS } from "../components/settings/authConnectorMethods";
import { SettingsRow, SettingsSection } from "../components/settings/settingsLayout";
import { Button } from "../components/ui/button";
import { AldoBrandTile } from "./AldoBrandTile";
import { AldoPolicyRuleRow, useAldoPolicy } from "./AldoPolicy";
import { disconnectAldoAccount } from "./accountApi";
import { Input } from "../components/ui/input";
import {
disconnectAldoAccount,
fetchOpenCodeProviders,
type AldoOpenCodeProvider,
} from "./accountApi";
import { useAldoAccounts } from "./useAldoAccounts";

const GO = {
Expand All @@ -25,6 +31,136 @@ const GOOGLE = {
returnInstruction: "After you sign in, paste the code or full address from Antigravity here.",
};

/** How many matches the provider search shows at once. */
const SHOWN = 8;

/** A key for one provider OpenCode knows, as the connect dialog offers it. */
function otherProviderMethod(provider: AldoOpenCodeProvider) {
return {
// Aldo takes any provider's "<id>-api-key"; the contract lists only T3's own.
method: `${provider.id}-api-key` as AuthConnectorMethod,
label: provider.name,
description: `Use ${provider.name} models with your own API key.`,
...(provider.doc
? { externalHelpUrl: provider.doc, externalHelpLabel: `${provider.name} documentation` }
: {}),
};
}

/** Another provider than the four OpenCode offers by name: search OpenCode's list, then connect its key. */
function OtherOpenCodeProvider(props: {
/** The four named above and the keys already connected: not offered again. */
readonly listed: ReadonlySet<string>;
readonly onConnected: () => void;
}) {
const [open, setOpen] = useState(false);
const [providers, setProviders] = useState<ReadonlyArray<AldoOpenCodeProvider> | null>(null);
const [failed, setFailed] = useState(false);
const [query, setQuery] = useState("");
const [chosen, setChosen] = useState<AldoOpenCodeProvider | null>(null);
useEffect(() => {
if (!open || providers) return;
let cancelled = false;
fetchOpenCodeProviders()
.then((list) => !cancelled && setProviders(list))
.catch(() => !cancelled && setFailed(true));
Comment on lines +64 to +66

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear the provider-load error when retrying succeeds

If the initial provider request fails, closing and reopening the search retries it, but a successful response only updates providers and never resets failed. Since the render checks failed before displaying the results, the error remains visible and no providers can be selected even after the retry succeeds. Clear the error when starting a retry or accepting its successful response so a transient network failure does not block this flow until the component remounts.

Useful? React with 👍 / 👎.

return () => {
cancelled = true;
};
}, [open, providers]);
const words = query.toLowerCase().split(/\s+/).filter(Boolean);
const matches = (providers ?? []).filter(
(p) =>
!props.listed.has(`${p.id}-api-key`) &&
words.every((w) => `${p.name} ${p.id}`.toLowerCase().includes(w)),
);
return (
<SettingsRow
title="Another provider"
description="Any provider OpenCode supports with an API key, such as Groq, DeepSeek or Mistral. Your provider may bill you for usage."
inline
control={
chosen ? (
<div className="flex items-center gap-2">
<Button size="sm" variant="ghost" onClick={() => setChosen(null)}>
Change
</Button>
<AuthConnectorDialog
connector="opencode"
serviceName={chosen.name}
methods={[otherProviderMethod(chosen)]}
isAuthenticated={false}
accountScoped
triggerLabel={`Connect ${chosen.name}`}
onConnected={() => {
setChosen(null);
setOpen(false);
setQuery("");
props.onConnected();
}}
/>
</div>
) : (
<Button size="sm" variant="outline" onClick={() => setOpen((was) => !was)}>
{open ? "Close" : "Choose a provider"}
</Button>
)
}
>
{open && !chosen ? (
<div className="mt-3 space-y-2">
<Input
type="search"
aria-label="Search providers"
placeholder="Search providers"
value={query}
onChange={(event) => setQuery(event.currentTarget.value)}
autoFocus
/>
{failed ? (
<p role="alert" className="text-sm text-destructive-foreground">
Couldn't load the providers. Try again in a moment.
</p>
) : !providers ? (
<p className="text-sm text-muted-foreground">Loading providers…</p>
) : matches.length === 0 ? (
<p className="text-sm text-muted-foreground">
{words.length
? `No provider matches “${query}”.`
: "No other providers are available right now. Try again later."}
</p>
) : (
<ul
className="divide-y overflow-hidden rounded-xl border bg-card"
aria-label="Providers"
>
{matches.slice(0, SHOWN).map((provider) => (
<li key={provider.id}>
<button
type="button"
className="flex min-h-11 w-full items-center justify-between gap-4 px-4 py-2.5 text-left text-sm transition-colors hover:bg-muted/45"
onClick={() => setChosen(provider)}
>
<span className="min-w-0 truncate font-medium text-foreground">
{provider.name}
</span>
<span className="shrink-0 text-xs text-muted-foreground">{provider.id}</span>
</button>
</li>
))}
</ul>
)}
{matches.length > SHOWN ? (
<p className="text-xs text-muted-foreground">
{matches.length - SHOWN} more. Type to narrow the list.
</p>
) : null}
</div>
) : null}
</SettingsRow>
);
}

export function AldoAgentConnections() {
const { accounts, refresh } = useAldoAccounts();
const policy = useAldoPolicy();
Expand Down Expand Up @@ -72,10 +208,12 @@ export function AldoAgentConnections() {
) : null}
{methods
.filter((method) => method.connected)
.map(({ method, kind }) => (
.map(({ method, kind, label }) => (
<SettingsRow
key={kind}
title={offered.find((option) => option.method === method)?.label ?? "OpenCode key"}
title={
offered.find((option) => option.method === method)?.label ?? label ?? "OpenCode key"
}
status="Connected"
inline
control={
Expand All @@ -92,6 +230,12 @@ export function AldoAgentConnections() {
}
/>
))}
{accounts.opencode?.otherProviders ? (
<OtherOpenCodeProvider
listed={new Set(methods.map((m) => m.method))}
onConnected={refresh}
/>
) : null}
{accounts.antigravity ? (
<SettingsRow
id="aldo-account-antigravity"
Expand Down
19 changes: 18 additions & 1 deletion apps/web/src/aldo/accountApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ export interface AldoAccount {

export type AldoAgentAccounts = {
opencode?: AldoAccount & {
methods: ReadonlyArray<{ method: string; kind: string; connected: boolean }>;
/** A key for another provider than the four Settings names carries its name (`label`). */
methods: ReadonlyArray<{ method: string; kind: string; connected: boolean; label?: string }>;
/** Whether Aldo takes a key for any provider in fetchOpenCodeProviders. */
otherProviders?: boolean;
};
antigravity?: AldoAccount & { instanceId: string | null };
};
Expand Down Expand Up @@ -74,6 +77,20 @@ export async function connectAldoGitHost(
await api(`/api/hosts/${kind}`, { method: "POST", body: JSON.stringify(values) });
}

/** A provider OpenCode knows that takes one API key (OpenCode's registry, as Aldo reads it). */
export interface AldoOpenCodeProvider {
readonly id: string;
readonly name: string;
readonly doc: string | null;
}

export async function fetchOpenCodeProviders(): Promise<ReadonlyArray<AldoOpenCodeProvider>> {
const { providers } = await api<{ providers: AldoOpenCodeProvider[] }>(
"/api/connections/opencode/providers",
);
return providers;
}

export async function disconnectAldoAccount(
kind: AldoAccountKind | AldoGitHostKind | "antigravity" | `opencode:${string}`,
): Promise<void> {
Expand Down
26 changes: 26 additions & 0 deletions apps/web/src/aldo/serverConfig.logic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test";
import {
missingProviders,
mergeProviderSnapshots,
withSavedBackends,
providerInstances,
providerKinds,
withAldoTemplate,
Expand Down Expand Up @@ -150,3 +151,28 @@ it("refreshes existing sleeping providers independently, without replacing a new
expect(JSON.parse(refreshed!).config.providers).toEqual([future, claude]);
expect(withAldoTemplate(refreshed, { providers: reported }, {})).toBeNull();
});

it("keeps the saved OpenCode backends a machine without their keys doesn't list", () => {
const model = (slug: string) => ({ slug, name: slug });
const opencode = (slugs: string[]) => ({
instanceId: "opencode",
driver: "opencode",
checkedAt: "2026-11-28T01:00:00Z",
models: slugs.map(model),
});
const codex = { instanceId: "codex", driver: "codex", models: [model("gpt")] };
const saved = [opencode(["aldo/a", "openrouter/x", "openrouter/y"]), codex];
// A machine started before the OpenRouter key: Aldo's saved models of it stay, after the machine's own.
expect(withSavedBackends([opencode(["aldo/a", "aldo/b"]), codex], saved)).toEqual([
opencode(["aldo/a", "aldo/b", "openrouter/x", "openrouter/y"]),
codex,
]);
// A backend the machine lists is its own; other agents and an empty save are as reported.
expect(withSavedBackends([opencode(["openrouter/z"])], saved)).toEqual([
opencode(["openrouter/z", "aldo/a"]),
]);
expect(withSavedBackends([opencode(["aldo/a"]), codex], [])).toEqual([
opencode(["aldo/a"]),
codex,
]);
});
27 changes: 27 additions & 0 deletions apps/web/src/aldo/serverConfig.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,30 @@ export function mergeProviderSnapshots<P extends Provider>(
...reported.filter((p) => !previous.some((old) => old.instanceId === p.instanceId)),
];
}

/** An OpenCode model's backend: its slug's first segment (openrouter, opencode-go, aldo…). */
function backendOf(model: unknown): string {
const slug = (model as { slug?: unknown } | null)?.slug;
return typeof slug === "string" && slug.includes("/") ? slug.slice(0, slug.indexOf("/")) : "";
}

/**
* A machine's OpenCode lists the backends of the keys it had when it started,
* so a machine started before a key was added lists fewer than the account
* has. Aldo's saved catalog keeps each backend a machine reported, and drops a
* disconnected one at once: a report gets the saved models of the backends it
* doesn't list, after its own.
*/
export function withSavedBackends<
P extends Provider & { readonly models?: ReadonlyArray<unknown> },
>(reported: ReadonlyArray<P>, saved: ReadonlyArray<P>): P[] {
return reported.map((provider) => {
if (provider.driver !== "opencode" || !Array.isArray(provider.models)) return provider;
const own = saved.find(
(p) => p.instanceId === provider.instanceId && p.driver === provider.driver,
);
const listed = new Set(provider.models.map(backendOf));
const kept = (own?.models ?? []).filter((model) => !listed.has(backendOf(model)));
return kept.length > 0 ? { ...provider, models: [...provider.models, ...kept] } : provider;
});
}
10 changes: 8 additions & 2 deletions apps/web/src/aldo/serverConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { fetchAldoServerConfig, reportAldoServerConfig } from "./threadApi";
import { isAldoCloud, isAldoEnvironmentId } from "./api";
import { settingsAccounts } from "./settingsData";
import { loadAldoMachineSettings } from "./machineSettings";
import { providerKinds, mergeProviderSnapshots } from "./serverConfig.logic";
import { providerKinds, mergeProviderSnapshots, withSavedBackends } from "./serverConfig.logic";

type EncodedConfig = {
environment: Record<string, unknown>;
Expand All @@ -34,6 +34,8 @@ const ACCOUNT_FOR_DRIVER: Record<string, "claude" | "codex" | "grok" | "muse" |
};

let latest: EncodedConfig | null = null;
/** The providers of the catalog Aldo last returned (withSavedBackends). */
let saved: EncodedConfig["providers"] = [];
let reportedProviders: string | null = null;
let fetchedFromAldo: Promise<void> | null = null;
let fetchedAt = 0;
Expand Down Expand Up @@ -99,7 +101,10 @@ function capture(): void {
const encoded = encodeServerConfig(config) as unknown as EncodedConfig;
latest = {
...encoded,
providers: mergeProviderSnapshots(latest?.providers ?? [], encoded.providers),
providers: mergeProviderSnapshots(
latest?.providers ?? [],
withSavedBackends(encoded.providers, saved),
),
};
// Save when the models (or their availability) change, not on every check.
const providers = JSON.stringify(
Expand Down Expand Up @@ -129,6 +134,7 @@ async function template(): Promise<EncodedConfig | null> {
.then((config) => {
if (!config) return;
const reported = config as EncodedConfig;
if (Array.isArray(reported.providers)) saved = reported.providers;
latest = {
...reported,
providers: mergeProviderSnapshots(latest?.providers ?? [], reported.providers),
Expand Down