From fb135424155348a347f223a483bd670b0b2dd5a5 Mon Sep 17 00:00:00 2001 From: Zack Jackson <25274700+ScriptedAlchemy@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:23:59 -0800 Subject: [PATCH 1/2] fix(inference): discover paired hosts and refresh routed models --- .../features/settings/InferenceAccounts.tsx | 271 +++++++++-- .../SettingsProviderAccountsRouteScreen.tsx | 2 +- .../features/settings/settings-search.test.ts | 1 + .../src/features/settings/settings-search.ts | 1 + .../src/inference/InferenceProxy.test.ts | 178 ++++++- apps/server/src/inference/InferenceProxy.ts | 440 +++++++++++------- apps/server/src/inference/http.test.ts | 11 + apps/server/src/inference/http.ts | 6 +- apps/server/src/inference/providerHealth.ts | 34 +- apps/server/src/inference/routes.test.ts | 18 +- apps/server/src/inference/routes.ts | 34 +- .../src/provider/Drivers/ClaudeDriver.ts | 6 +- .../src/provider/Drivers/CodexDriver.test.ts | 38 ++ .../src/provider/Drivers/CodexDriver.ts | 6 +- apps/server/src/provider/ProviderRegistry.ts | 2 + ...nstanceDialog.environment.browser.test.tsx | 58 +++ .../settings/AddProviderInstanceDialog.tsx | 116 ++++- ...InferenceProviderAccounts.browser.test.tsx | 32 +- .../settings/InferenceProviderAccounts.tsx | 45 +- .../components/settings/InferenceSettings.tsx | 39 +- .../settings/ProviderInstanceCard.tsx | 11 +- .../settings/ProviderModelsSection.tsx | 2 +- ...SettingsPanel.environment.browser.test.tsx | 77 ++- .../settings/ProviderSettingsPanel.tsx | 164 +++++-- .../src/components/settings/settingsSearch.ts | 2 +- .../settings/useEnableInferenceRouting.ts | 43 ++ apps/web/src/modelSelection.test.ts | 29 ++ apps/web/src/modelSelection.ts | 2 + apps/web/src/providerInstances.ts | 14 + docs/user/providers-claude.md | 23 +- docs/user/providers-codex.md | 2 +- docs/user/providers-opencode.md | 2 +- docs/user/providers-pi.md | 4 +- .../src/state/commandPermissions.test.ts | 120 ++++- .../src/state/inferenceProxy.ts | 253 +++++++--- packages/contracts/src/inferenceProxy.ts | 1 + packages/shared/src/serverSettings.ts | 14 + ...nce-routing-discovers-hosted-models.e2e.ts | 149 ++++++ .../inference-routing-without-a-host.e2e.ts | 20 + scripts/scenarios/second-server.ts | 15 +- scripts/scenarios/t3.ts | 2 +- 41 files changed, 1833 insertions(+), 454 deletions(-) create mode 100644 apps/web/src/components/settings/useEnableInferenceRouting.ts create mode 100644 scripts/scenarios/inference-routing-discovers-hosted-models.e2e.ts create mode 100644 scripts/scenarios/inference-routing-without-a-host.e2e.ts diff --git a/apps/mobile/src/features/settings/InferenceAccounts.tsx b/apps/mobile/src/features/settings/InferenceAccounts.tsx index e1a900f36d4ce..e3afee28db0d1 100644 --- a/apps/mobile/src/features/settings/InferenceAccounts.tsx +++ b/apps/mobile/src/features/settings/InferenceAccounts.tsx @@ -1,27 +1,31 @@ -import { - inferenceRouteIssue, - type InferenceRouting, - type InferenceProxyActionResult, -} from "@t3tools/contracts"; +import { type InferenceRouting, type InferenceProxyActionResult } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { inferenceAccountRetryAfter, inferenceAccountStatus, + inferenceHostRoutingIssue, } from "@t3tools/client-runtime/state/inference-proxy"; import { INFERENCE_DRIVERS, INFERENCE_HARNESSES, INFERENCE_UPSTREAMS, + defaultInstanceIdForDriver, inferenceHarness, + isCustomInferenceBackend, + isInferenceProviderConfig, + isManagedSettingPath, + type InferenceProxyStatus, + type ServerProvider, type InferenceDriver, type InferenceProxyAction, type InferenceUpstream, } from "@t3tools/contracts"; -import { useState } from "react"; +import { useRef, useState } from "react"; import { Linking, TextInput, View } from "react-native"; import { AppText } from "../../components/ui/AppText"; +import { ControlPill } from "../../components/ui/ControlPill"; import { ListActionRow } from "../../components/ui/ListActionRow"; import { useEnvironments, type EnvironmentPresentation } from "../../state/environments"; import { serverEnvironment } from "../../state/server"; @@ -39,7 +43,6 @@ function Route({ host, consumer }: { host: EnvironmentPresentation; consumer: Se const status = useEnvironmentQuery( inferenceProxy.inferenceStatus({ environmentId: host.environmentId, input: {} }), ); - const issue = inferenceRouteIssue(status.data, host.environmentId === consumer.environmentId); const route = useAtomCommand(inferenceProxy.routeInference, { reportFailure: false }); const [busy, setBusy] = useState(false); const [notice, setNotice] = useState(""); @@ -49,21 +52,24 @@ function Route({ host, consumer }: { host: EnvironmentPresentation; consumer: Se setBusy(false); setNotice( result._tag === "Success" - ? `Select ${INFERENCE_HARNESSES[driver].label}${host.environmentId === consumer.environmentId ? "" : ` via ${host.label}`} in the model picker.` + ? `${INFERENCE_HARNESSES[driver].label} now uses accounts on ${host.label}.` : String(squashAtomCommandFailure(result)), ); } return ( - {INFERENCE_DRIVERS.map((driver) => ( - void add(driver)} - /> - ))} + {INFERENCE_DRIVERS.map((driver) => { + const issue = inferenceHostRoutingIssue(status.data, { host, consumer, driver }); + return ( + void add(driver)} + /> + ); + })} {notice ? ( {notice} @@ -73,6 +79,112 @@ function Route({ host, consumer }: { host: EnvironmentPresentation; consumer: Se ); } +function ProviderRoutingSwitch({ + environment, + provider, + driver, + onSetup, +}: { + environment: SettingsTarget; + provider: ServerProvider; + driver: InferenceDriver; + onSetup: () => void; +}) { + const { environmentId } = environment; + const { environments } = useEnvironments(); + const canConnect = useAtomValue(inferenceProxy.canConnect(environmentId)); + const canManage = useAtomValue(inferenceProxy.manageInference.permissionAtom(environmentId)); + const enable = useAtomCommand(inferenceProxy.enableInferenceRouting, { reportFailure: false }); + const manage = useAtomCommand(inferenceProxy.manageInference, { reportFailure: false }); + const inFlight = useRef(false); + const [pending, setPending] = useState(false); + const [failure, setFailure] = useState<{ target: boolean; message: string } | null>(null); + const { instanceId } = provider; + const config = environment.serverConfig.settings.providerInstances[instanceId]?.config; + const route = isInferenceProviderConfig(config) ? config : null; + const enabled = route?.inferenceEnabled === true; + const error = failure && failure.target !== enabled ? failure.message : ""; + const locked = isManagedSettingPath( + environment.serverConfig.managedPolicy, + `providerInstances.${instanceId}`, + ); + async function change(value: boolean) { + if (inFlight.current) return; + inFlight.current = true; + setPending(true); + setFailure(null); + const result = value + ? await enable({ + consumer: { environmentId, label: environment.label }, + environments, + driver, + ...(route ? { preferredHostId: route.inferenceHostId } : {}), + }) + : await manage({ environmentId, input: { operation: "removeRoute", instanceId } }); + inFlight.current = false; + setPending(false); + if (result._tag === "Failure") { + const cause = squashAtomCommandFailure(result); + setFailure({ + target: value, + message: cause instanceof Error ? cause.message : String(cause), + }); + } + } + return ( + <> + void change(value)} + /> + {error && !enabled && canManage ? ( + + ) : null} + + ); +} + +function HostedAccountRow({ + account, + disabled, + onRemove, +}: { + account: InferenceProxyStatus["accounts"][number]; + disabled: boolean; + onRemove: () => void; +}) { + const [revealed, setRevealed] = useState(false); + const retryAfter = inferenceAccountRetryAfter(account); + return ( + + + setRevealed(!revealed)} + /> + + {revealed && ( + + )} + + ); +} + function InferenceRoutingControls({ routing, disabled, @@ -104,11 +216,22 @@ function InferenceRoutingControls({ ); } -function InferenceControls({ environment }: { environment: SettingsTarget }) { +function InferenceControls({ + environment, + setupDriver, + onConnected, +}: { + environment: SettingsTarget; + setupDriver: InferenceDriver | null; + onConnected: () => void; +}) { const { environmentId } = environment; const { environments } = useEnvironments(); const query = useEnvironmentQuery(inferenceProxy.inferenceStatus({ environmentId, input: {} })); const command = useAtomCommand(inferenceProxy.manageInference, { reportFailure: false }); + const enableRouting = useAtomCommand(inferenceProxy.enableInferenceRouting, { + reportFailure: false, + }); const permitted = useAtomValue(inferenceProxy.manageInference.permissionAtom(environmentId)); const [pending, setPending] = useState(false); const [login, setLogin] = useState<{ url: string; state: string } | null>(null); @@ -140,6 +263,22 @@ function InferenceControls({ environment }: { environment: SettingsTarget }) { setNotice("Sign-in failed or expired. Start a new sign-in."); if (result.value.status === "wait") setNotice("Waiting for the host to finish sign-in. Check status after a moment."); + if ( + setupDriver && + (result.value.status === "ok" || (input.operation === "configure" && input.enabled)) + ) { + const connected = await enableRouting({ + consumer: { environmentId, label: environment.label }, + environments, + driver: setupDriver, + preferredHostId: environmentId, + }); + if (connected._tag === "Success") onConnected(); + else { + const failure = squashAtomCommandFailure(connected); + setNotice(failure instanceof Error ? failure.message : String(failure)); + } + } return result.value; } const host = query.data; @@ -165,7 +304,12 @@ function InferenceControls({ environment }: { environment: SettingsTarget }) { disabled={disabled} value={host.enabled} onValueChange={(enabled) => - void run({ operation: "configure", enabled, sharing: false }) + void run({ + operation: "configure", + enabled, + sharing: false, + expectedEnabled: host.enabled, + }) } /> {host.enabled && ( @@ -191,7 +335,12 @@ function InferenceControls({ environment }: { environment: SettingsTarget }) { disabled={disabled} value={host.sharing} onValueChange={(sharing) => - void run({ operation: "configure", enabled: true, sharing }) + void run({ + operation: "configure", + enabled: true, + sharing, + expectedEnabled: true, + }) } /> {host.routing && ( @@ -205,18 +354,14 @@ function InferenceControls({ environment }: { environment: SettingsTarget }) { onPress={() => void run({ operation: "revoke", environmentId: c.environmentId })} /> ))} - {host.accounts.map((account) => { - const retryAfter = inferenceAccountRetryAfter(account); - return ( - void run({ operation: "removeAccount", name: account.name })} - /> - ); - })} + {host.accounts.map((account) => ( + void run({ operation: "removeAccount", name: account.name })} + /> + ))} {login ? ( <> ) : ( - upstreams.map((upstream) => ( - void run({ operation: "signIn", upstream })} - /> - )) + (setupDriver ? INFERENCE_HARNESSES[setupDriver].upstreams : upstreams).map( + (upstream) => ( + void run({ operation: "signIn", upstream })} + /> + ), + ) )} )} @@ -306,18 +453,52 @@ function InferenceControls({ environment }: { environment: SettingsTarget }) { ); } -export function InferenceAccounts({ environment }: { environment: SettingsTarget }) { - const [open, setOpen] = useState(false); +export function InferenceAccounts({ + environment, + providers, +}: { + environment: SettingsTarget; + providers: ReadonlyArray; +}) { + const [panel, setPanel] = useState<"all" | InferenceDriver | null>(null); return ( <> + {providers.map((provider) => { + const driver = INFERENCE_DRIVERS.find((candidate) => candidate === provider.driver); + const instance = environment.serverConfig.settings.providerInstances[provider.instanceId]; + if ( + !driver || + provider.instanceId !== defaultInstanceIdForDriver(provider.driver) || + (instance && isCustomInferenceBackend(instance)) + ) + return null; + return ( + setPanel(driver)} + /> + ); + })} setOpen((value) => !value)} + onPress={() => setPanel(panel ? null : "all")} /> - {open && } + {panel && ( + setPanel(null)} + /> + )} ); } diff --git a/apps/mobile/src/features/settings/SettingsProviderAccountsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProviderAccountsRouteScreen.tsx index 5ef31fab0e929..db937c4ca7c8b 100644 --- a/apps/mobile/src/features/settings/SettingsProviderAccountsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsProviderAccountsRouteScreen.tsx @@ -97,7 +97,7 @@ function EnvironmentProviders({ return ( <> {environment.serverConfig.environment.capabilities.inferenceProxy && ( - + )} {accounts.map((provider, index) => ( { expected: [["Server settings", ["Provider accounts"]]], }, { query: "inference accounts", expected: [["Server settings", ["Provider accounts"]]] }, + { query: "inference routing", expected: [["Server settings", ["Provider accounts"]]] }, { query: "CLIProxyAPI", expected: [["Server settings", ["Provider accounts"]]] }, { query: "usage", expected: [[null, ["Usage"]]] }, { query: "zzzz", expected: [] }, diff --git a/apps/mobile/src/features/settings/settings-search.ts b/apps/mobile/src/features/settings/settings-search.ts index f8edb24bc616f..448aa8614fa1a 100644 --- a/apps/mobile/src/features/settings/settings-search.ts +++ b/apps/mobile/src/features/settings/settings-search.ts @@ -84,6 +84,7 @@ const SETTINGS_SEARCH_TERMS = { SettingsProviderAccounts: [ "provider accounts", "inference accounts", + "inference routing", "CLIProxyAPI", "host accounts", "route requests", diff --git a/apps/server/src/inference/InferenceProxy.test.ts b/apps/server/src/inference/InferenceProxy.test.ts index 3f2d5a30ac4f6..fb6f88346d05d 100644 --- a/apps/server/src/inference/InferenceProxy.test.ts +++ b/apps/server/src/inference/InferenceProxy.test.ts @@ -5,9 +5,11 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { PeerLinkError, EnvironmentId, + ProjectId, ProviderInstanceId, ProviderDriverKind, isInferenceProviderConfig, + resolveProviderInstanceEnabled, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NetService from "@t3tools/shared/Net"; @@ -33,6 +35,8 @@ import * as ProviderInstanceRegistryMutator from "../provider/ProviderInstanceRe import { DirectEndpoints } from "../environment/DirectEndpoints.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as ProcessRunner from "../processRunner.ts"; +import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as InferenceProxy from "./InferenceProxy.ts"; import { proxyVersion } from "./install.ts"; @@ -83,6 +87,8 @@ it.effect( let linkedUrl = "http://127.0.0.1:23456"; let connectionOverride: string | undefined; let staleLinkedCatalog = false; + let remoteCatalogUnavailable = false; + let fallbackCatalog: typeof catalog | undefined; const link = { environmentId: hostId, label: "Host", @@ -176,6 +182,7 @@ it.effect( const importedCodexFiles: string[] = []; const importedClaudeFiles: string[] = []; let activeCodexConfig: unknown; + let activeCodexEnabled: boolean | undefined; const remoteCatalogKeys: (string | undefined)[] = []; const http = HttpClient.make((request) => { if (request.url.endsWith("/v0/management/api-call")) { @@ -288,6 +295,24 @@ it.effect( } if (!request.url.endsWith("/health")) remoteCatalogKeys.push(request.headers.authorization); + if (request.url.endsWith("/v1/models") && remoteCatalogUnavailable) + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(null, { status: 502 })), + ); + if ( + request.url.startsWith("https://fallback.example.ts.net/api/inference/") && + fallbackCatalog + ) + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json( + request.url.endsWith("/health") + ? { availableDrivers: ["codex"], models: fallbackCatalog.map(({ id }) => id) } + : { data: fallbackCatalog }, + ), + ), + ); if (staleLinkedCatalog && request.url.startsWith("http://127.0.0.1:34567/")) return Effect.succeed( HttpClientResponse.fromWeb(request, new Response(null, { status: 502 })), @@ -388,7 +413,9 @@ it.effect( Layer.succeed(ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator, { reconcile: (instances) => Effect.sync(() => { - activeCodexConfig = instances[ProviderInstanceId.make("codex")]?.config; + const activeCodex = instances[ProviderInstanceId.make("codex")]; + activeCodexConfig = activeCodex?.config; + activeCodexEnabled = activeCodex?.enabled; }), reloadSecrets: () => Effect.void, rebuild: () => Effect.void, @@ -966,6 +993,13 @@ it.effect( }); expect((yield* readConfig)["oauth"]).not.toHaveProperty("model-alias"); const issued = yield* proxy.grant(peer); + yield* proxy.manage({ + operation: "configure", + enabled: true, + sharing: false, + expectedEnabled: false, + }); + expect((yield* proxy.status).sharing).toBe(true); expect(issued.baseUrl).toBe("https://pool.example.ts.net/api/inference"); expect((yield* proxy.grant(peer)).key).toBe(issued.key); expect((yield* proxy.authorize(issued.key))?.key).not.toBe(issued.key); @@ -1112,6 +1146,46 @@ it.effect( expect(yield* proxy.routeHealth(configured.config, local.key, "codex")).toMatchObject({ availableDrivers: expect.arrayContaining(["codex"]), }); + const initialCatalog = catalog; + catalog = [...catalog, { id: "gpt-local-new", owned_by: "openai" }]; + yield* proxy.refreshModelCatalog(); + expect( + (yield* settings.getSettings).providerInstances[ProviderInstanceId.make("codex")] + ?.config, + ).toMatchObject({ inferenceModels: expect.arrayContaining(["gpt-local-new"]) }); + expect(activeCodexConfig).toMatchObject({ + customModels: expect.arrayContaining(["gpt-local-new"]), + }); + const piId = ProviderInstanceId.make("pi"); + yield* proxy.connect({ + ...connect, + driver: "pi", + grant: { + ...issued, + hostId: EnvironmentId.make("other-host"), + consumerId: hostId, + baseUrl: "https://fallback.example.ts.net/api/inference", + alternates: [], + }, + }); + const previousPiConfig = (yield* settings.getSettings).providerInstances[piId]?.config; + if (!isInferenceProviderConfig(previousPiConfig)) + throw new Error("Expected an independent Pi route"); + const unrelatedRequests = remoteCatalogKeys.length; + catalog = [...catalog, { id: "gpt-local-scoped", owned_by: "openai" }]; + yield* proxy.refreshModelCatalog(true, ProviderInstanceId.make("codex")); + expect(activeCodexConfig).toMatchObject({ + customModels: expect.arrayContaining(["gpt-local-scoped"]), + }); + const piConfig = (yield* settings.getSettings).providerInstances[piId]?.config; + expect(isInferenceProviderConfig(piConfig) ? piConfig.inferenceModels : null).toEqual( + previousPiConfig.inferenceModels, + ); + expect(remoteCatalogKeys.length).toBe(unrelatedRequests); + yield* proxy.manage({ operation: "removeRoute", instanceId: piId }); + remoteCatalogKeys.length = 0; + catalog = initialCatalog; + yield* proxy.manage({ operation: "check", state: "sign-in" }); yield* proxy.bindRoutes(45678); configured = (yield* settings.getSettings).providerInstances[ ProviderInstanceId.make("codex") @@ -1183,6 +1257,28 @@ it.effect( expect(yield* proxy.routeHealth(directConfig, issued.key, "codex")).toMatchObject({ availableDrivers: expect.arrayContaining(["codex"]), }); + const directCatalog = catalog; + catalog = [...catalog, { id: "gpt-remote-new", owned_by: "openai" }]; + yield* TestClock.adjust("15 seconds"); + yield* proxy.refreshModelCatalog(); + expect( + (yield* settings.getSettings).providerInstances[ProviderInstanceId.make("codex")] + ?.config, + ).toMatchObject({ + inferenceModels: expect.arrayContaining(["gpt-remote-new"]), + inferenceKey: issued.key, + }); + const requestsAfterRefresh = remoteCatalogKeys.length; + yield* proxy.refreshModelCatalog(); + expect(remoteCatalogKeys).toHaveLength(requestsAfterRefresh); + remoteCatalogUnavailable = true; + yield* proxy.refreshModelCatalog(true); + expect( + (yield* settings.getSettings).providerInstances[ProviderInstanceId.make("codex")] + ?.config, + ).toMatchObject({ inferenceModels: expect.arrayContaining(["gpt-remote-new"]) }); + remoteCatalogUnavailable = false; + catalog = directCatalog; tailnetCatalogDown = false; connectionDown = true; tailnetCatalogDown = true; @@ -1305,6 +1401,24 @@ it.effect( }, }); catalog = primaryCatalog; + fallbackCatalog = [ + { id: "codex-auto-review", owned_by: "openai" }, + { id: "fallback-only", owned_by: "openai" }, + { id: "gpt-fallback-new", owned_by: "openai" }, + ]; + yield* proxy.refreshModelCatalog(true); + expect( + (yield* settings.getSettings).providerInstances[ProviderInstanceId.make("codex")] + ?.config, + ).toMatchObject({ + inferenceHostId: hostId, + inferenceModels: expect.arrayContaining(["office-model", "gpt-fallback-new"]), + }); + expect( + (yield* proxy.routeCandidates(issued.key, hostId, "codex", "gpt-fallback-new"))?.map( + ({ hostId }) => hostId, + ), + ).toEqual([peerId]); expect( (yield* proxy.routeCandidates(issued.key, hostId, "codex", "codex-auto-review"))?.map( (candidate) => candidate.hostId, @@ -1325,6 +1439,60 @@ it.effect( peerId = hostId; yield* proxy.connect({ ...connect, grant: issued }); expect(yield* proxy.hasFallback(issued.key, hostId, "codex")).toBe(true); + expect(yield* fs.readFileString(config.settingsPath)).not.toContain(issued.key); + const setCodexConfigEnabled = (enabled: boolean) => + settings.reviseProviderInstance(ProviderInstanceId.make("codex"), (instance) => { + if (!instance || !isInferenceProviderConfig(instance.config)) + return Effect.die("Expected the connected Codex route"); + return Effect.succeed({ + instance: { + ...instance, + ...(enabled ? { enabled: true } : {}), + config: { ...instance.config, enabled }, + }, + result: undefined, + }); + }); + yield* setCodexConfigEnabled(false); + expect(yield* proxy.hasFallback(issued.key, hostId, "codex")).toBe(false); + expect(yield* proxy.routeCandidates(issued.key, hostId, "codex")).toBeNull(); + expect(yield* proxy.authorize(issued.key, hostId, "codex")).toBeNull(); + const inferenceProject = ProjectId.make("inference-project"); + const codexId = ProviderInstanceId.make("codex"); + yield* settings.updateSettings({ + projectSettingsOverrides: { + [inferenceProject]: { providerInstances: { [codexId]: { enabled: true } } }, + }, + }); + expect(yield* proxy.hasFallback(issued.key, hostId, "codex")).toBe(true); + expect(yield* proxy.routeCandidates(issued.key, hostId, "codex")).toHaveLength(1); + expect(yield* proxy.authorize(issued.key, hostId, "codex")).not.toBeNull(); + const oldCatalog = catalog; + catalog = [...catalog, { id: "gpt-project-catalog-refresh", owned_by: "openai" }]; + yield* proxy.refreshModelCatalog(true); + const projectOnlyCodex = (yield* settings.getSettings).providerInstances[codexId]!; + expect(resolveProviderInstanceEnabled(projectOnlyCodex)).toBe(false); + expect(projectOnlyCodex.config).toMatchObject({ + inferenceModels: expect.arrayContaining(["gpt-project-catalog-refresh"]), + }); + expect(activeCodexEnabled).toBe(true); + expect(activeCodexConfig).toMatchObject({ + setupMode: "inference", + customModels: expect.arrayContaining(["gpt-project-catalog-refresh"]), + }); + catalog = oldCatalog; + yield* proxy.manage({ + operation: "removeRoute", + instanceId: ProviderInstanceId.make("codex"), + }); + expect(yield* proxy.routeCandidates(issued.key, hostId, "codex")).toBeNull(); + expect(yield* proxy.authorize(issued.key, hostId, "codex")).toBeNull(); + yield* settings.updateSettings({ + projectSettingsOverrides: { [inferenceProject]: null }, + }); + yield* setCodexConfigEnabled(true); + yield* proxy.connect({ ...connect, grant: issued }); + expect(yield* proxy.hasFallback(issued.key, hostId, "codex")).toBe(true); expect( (yield* settings.getSettings).providerInstances[ProviderInstanceId.make("codex")] ?.config, @@ -1436,6 +1604,10 @@ it.effect( expect( yield* proxy.routeCandidates(issued.key, hostId, "codex", "codex-auto-review"), ).toHaveLength(2); + const reissued = { ...issued, key: "reissued-primary-key" }; + yield* proxy.connect({ ...connect, grant: reissued }); + expect(yield* proxy.hasFallback(reissued.key, hostId, "codex")).toBe(false); + expect(yield* proxy.authorize(issued.key, hostId, "codex")).toBeNull(); peerId = EnvironmentId.make("other-host"); yield* proxy.connect({ ...connect, @@ -1526,7 +1698,9 @@ it.effect( expect(stops).toBe(5); }).pipe( Effect.provide( - Layer.merge(ServerSettings.layerTest(), ServerSecretStore.layer).pipe( + ServerSettings.layer.pipe( + Layer.provideMerge(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layerTest())), + Layer.provideMerge(SqlitePersistence.layerMemory), Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { prefix: "t3-inference-test-" }), ), diff --git a/apps/server/src/inference/InferenceProxy.ts b/apps/server/src/inference/InferenceProxy.ts index da4b4c0007b9a..7963297a98760 100644 --- a/apps/server/src/inference/InferenceProxy.ts +++ b/apps/server/src/inference/InferenceProxy.ts @@ -29,6 +29,7 @@ import { import * as HostProcess from "@t3tools/shared/HostProcess"; import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; import { NetService } from "@t3tools/shared/Net"; +import { isProviderInstanceEnabledInAnyScope } from "@t3tools/shared/serverSettings"; import { readTailscaleServeRoutesTo } from "@t3tools/tailscale"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Cache from "effect/Cache"; @@ -41,6 +42,7 @@ import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"; import type * as HttpMethod from "effect/http/HttpMethod"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as Equal from "effect/Equal"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Fiber from "effect/Fiber"; @@ -60,6 +62,7 @@ import * as ServerConfig from "../config.ts"; import { DirectEndpoints } from "../environment/DirectEndpoints.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as ServerSettings from "../serverSettings.ts"; +import { SECRET_REDACTED } from "../settingsSecrets.ts"; import * as ManagedProviders from "../policy/managedProviders.ts"; import { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts"; import * as ProviderInstanceRegistryMutator from "../provider/ProviderInstanceRegistryMutator.ts"; @@ -68,6 +71,7 @@ import { claudeKeychainEntry } from "./claudeKeychain.ts"; import { install, proxyVersion, resolveRelease, Release } from "./install.ts"; import * as PeerLinks from "../peer/PeerLinks.ts"; import { + isRetryableInferenceStatus, modelsForDriver, needsAccountModelLookup, openCodeRouteProblem, @@ -373,6 +377,15 @@ const make = Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const store = yield* ServerSecretStore.ServerSecretStore; const settings = yield* ServerSettings.ServerSettingsService; + const matchesRouteKey = Effect.fn("InferenceProxy.matchesRouteKey")(function* ( + instanceId: ProviderInstanceId, + storedKey: InferenceProviderConfig["inferenceKey"], + expected: string, + ) { + if (storedKey !== SECRET_REDACTED) return storedKey === expected; + const current = (yield* settings.getSettings).providerInstances[instanceId]?.config; + return isInferenceProviderConfig(current) && current.inferenceKey === expected; + }); const registry = yield* ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator; const environment = yield* ServerEnvironment.ServerEnvironment; const links = yield* PeerLinks.PeerLinks; @@ -390,6 +403,7 @@ const make = Effect.gen(function* () { ); const mutex = yield* Semaphore.make(1); const updateMutex = yield* Semaphore.make(1); + const catalogMutex = yield* Semaphore.make(1); const children = yield* Queue.sliding(1); const directory = path.join(config.stateDir, "inference-proxy"); const localCodexHome = path.resolve( @@ -1163,6 +1177,8 @@ const make = Effect.gen(function* () { const manageHost = Effect.fn("InferenceProxy.manageHost")(function* (input: HostAction) { const state = yield* read; if (input.operation === "configure") { + // Another client may have started sharing while this client was still on the setup screen. + if (input.expectedEnabled !== undefined && state.enabled !== input.expectedEnabled) return {}; if (input.enabled && input.sharing && sharingDenial) return yield* failure(sharingDenial); if (!input.enabled) { yield* save({ ...state, enabled: false, sharing: false, grants: [] }).pipe( @@ -1225,13 +1241,6 @@ const make = Effect.gen(function* () { yield* registry.reconcile( deriveProviderInstanceConfigMap(revised.settings, providerEnvironment), ); - yield* save({ - ...state, - routePools: (state.routePools ?? []).filter( - (entry) => - defaultInstanceIdForDriver(ProviderDriverKind.make(entry.driver)) !== input.instanceId, - ), - }); return {}; } if (input.operation === "revoke") { @@ -1327,8 +1336,11 @@ const make = Effect.gen(function* () { switch (input.operation) { case "checkUpdate": return yield* updateRuntime("checkUpdate"); - case "update": - return yield* updateMutex.withPermit(updateRuntime("update")); + case "update": { + const result = yield* updateMutex.withPermit(updateRuntime("update")); + yield* refreshLocalProviders(); + return result; + } default: { const result = yield* manageHost(input); if (input.operation === "removeAccount" || ("status" in result && result.status === "ok")) @@ -1428,20 +1440,24 @@ const make = Effect.gen(function* () { for (const binding of bindings) { const url = `http://127.0.0.1:${port}/api/inference/linked/${binding.driver}/${encodeURIComponent(binding.hostId)}`; if (binding.baseUrl === url) continue; - yield* settings.reviseProviderInstance(ProviderInstanceId.make(binding.id), (current) => { - if ( - !current || - current.driver !== ProviderDriverKind.make(binding.driver) || - !isInferenceProviderConfig(current.config) || - current.config.inferenceHostId !== binding.hostId || - current.config.inferenceKey !== binding.key - ) - return failure("The inference route changed."); - return Effect.succeed({ - instance: { ...current, config: { ...current.config, inferenceBaseUrl: url } }, - result: undefined, - }); - }); + const instanceId = ProviderInstanceId.make(binding.id); + yield* settings.reviseProviderInstance( + instanceId, + Effect.fnUntraced(function* (current) { + if ( + !current || + current.driver !== ProviderDriverKind.make(binding.driver) || + !isInferenceProviderConfig(current.config) || + current.config.inferenceHostId !== binding.hostId || + !(yield* matchesRouteKey(instanceId, current.config.inferenceKey, binding.key)) + ) + return yield* failure("The inference route changed."); + return { + instance: { ...current, config: { ...current.config, inferenceBaseUrl: url } }, + result: undefined, + }; + }), + ); } yield* registry.reconcile( deriveProviderInstanceConfigMap(yield* settings.getSettings, providerEnvironment), @@ -1472,7 +1488,7 @@ const make = Effect.gen(function* () { }); const candidateAddress = Effect.fn("InferenceProxy.candidateAddress")(function* ( - candidate: SavedRouteCandidate, + candidate: Omit, ownId: EnvironmentId, ) { if (candidate.hostId === ownId) @@ -1515,9 +1531,11 @@ const make = Effect.gen(function* () { function* (key: string, hostId: EnvironmentId | undefined, driver: string | undefined) { if (!hostId || !driver) return false; const instanceId = defaultInstanceIdForDriver(ProviderDriverKind.make(driver)); - const instance = (yield* settings.getSettings).providerInstances[instanceId]; + const current = yield* settings.getSettings; + const instance = current.providerInstances[instanceId]; if ( !instance || + !isProviderInstanceEnabledInAnyScope(current, instanceId) || !isInferenceProviderConfig(instance.config) || !instance.config.inferenceEnabled || instance.config.inferenceHostId !== hostId || @@ -1549,16 +1567,20 @@ const make = Effect.gen(function* () { const target = yield* authorize(key); return target ? [{ ...target, models: [] }] : null; } - const { providerInstances } = yield* settings.getSettings; - const active = INFERENCE_DRIVERS.map((candidateDriver) => ({ - driver: candidateDriver, - instance: - providerInstances[defaultInstanceIdForDriver(ProviderDriverKind.make(candidateDriver))], - })).find( - ({ driver: candidateDriver, instance }) => + const current = yield* settings.getSettings; + const active = INFERENCE_DRIVERS.map((candidateDriver) => { + const instanceId = defaultInstanceIdForDriver(ProviderDriverKind.make(candidateDriver)); + return { + driver: candidateDriver, + instanceId, + instance: current.providerInstances[instanceId], + }; + }).find( + ({ driver: candidateDriver, instanceId, instance }) => (driver === undefined || candidateDriver === driver) && - instance?.enabled !== false && - isInferenceProviderConfig(instance?.config) && + instance !== undefined && + isProviderInstanceEnabledInAnyScope(current, instanceId) && + isInferenceProviderConfig(instance.config) && instance.config.inferenceEnabled && instance.config.inferenceHostId === hostId && instance.config.inferenceKey === key, @@ -1609,7 +1631,7 @@ const make = Effect.gen(function* () { routeFailures.delete(key); return; } - if (![401, 403, 429, 502, 503].includes(input.status)) return; + if (!isRetryableInferenceStatus(input.status)) return; const now = yield* Clock.currentTimeMillis; const numericDelay = (value: string | undefined, scale: number) => { if (!value?.trim()) return undefined; @@ -1631,7 +1653,7 @@ const make = Effect.gen(function* () { const duration = input.status === 429 && retryDelay !== undefined ? Math.max(5_000, Math.min(retryDelay, Number.MAX_SAFE_INTEGER - now)) - : input.status === 502 || input.status === 503 + : input.status === 502 || input.status === 503 || input.status === 529 ? 5_000 : 30_000; routeFailures.set(key, now + duration); @@ -1640,12 +1662,13 @@ const make = Effect.gen(function* () { const authorize = Effect.fn("InferenceProxy.authorize")( function* (key: string, hostId?: EnvironmentId, driver?: string) { if (hostId !== undefined) { - const { providerInstances } = yield* settings.getSettings; + const current = yield* settings.getSettings; const allowed = INFERENCE_DRIVERS.map((candidateDriver) => { - const instance = - providerInstances[defaultInstanceIdForDriver(ProviderDriverKind.make(candidateDriver))]; + const instanceId = defaultInstanceIdForDriver(ProviderDriverKind.make(candidateDriver)); + const instance = current.providerInstances[instanceId]; return (driver === undefined || candidateDriver === driver) && - instance?.enabled && + instance !== undefined && + isProviderInstanceEnabledInAnyScope(current, instanceId) && isInferenceProviderConfig(instance.config) && instance.config.inferenceEnabled && instance.config.inferenceHostId === hostId && @@ -1894,10 +1917,11 @@ const make = Effect.gen(function* () { if (fallback) { const revised = yield* mutex.withPermit( Effect.gen(function* () { - const configured = (yield* settings.getSettings).providerInstances[instanceId]; + const currentSettings = yield* settings.getSettings; + const configured = currentSettings.providerInstances[instanceId]; if ( !configured || - configured.enabled === false || + !isProviderInstanceEnabledInAnyScope(currentSettings, instanceId) || !isInferenceProviderConfig(configured.config) || !configured.config.inferenceEnabled ) @@ -1908,20 +1932,21 @@ const make = Effect.gen(function* () { return yield* failure("The primary inference credential is unavailable."); const primaryKey = primaryRoute.inferenceKey; const state = yield* read; - const existing = state.routePools?.find((entry) => entry.driver === driver); - const primary: SavedRouteCandidate = - existing?.primary.hostId === primaryRoute.inferenceHostId && - existing.primary.key === primaryKey - ? existing.primary - : { - hostId: primaryRoute.inferenceHostId, - baseUrl: primaryRoute.inferenceBaseUrl, - key: primaryKey, - models: [...primaryRoute.inferenceModels], - ...(primaryRoute.inferenceConnection - ? { connection: primaryRoute.inferenceConnection } - : {}), - }; + const existing = state.routePools?.find( + (entry) => + entry.driver === driver && + entry.primary.hostId === primaryRoute.inferenceHostId && + entry.primary.key === primaryKey, + ); + const primary: SavedRouteCandidate = existing?.primary ?? { + hostId: primaryRoute.inferenceHostId, + baseUrl: primaryRoute.inferenceBaseUrl, + key: primaryKey, + models: [...primaryRoute.inferenceModels], + ...(primaryRoute.inferenceConnection + ? { connection: primaryRoute.inferenceConnection } + : {}), + }; const alternates = [ ...(existing?.alternates ?? []).filter((entry) => entry.hostId !== grant.hostId), candidate, @@ -1934,30 +1959,33 @@ const make = Effect.gen(function* () { ], }); return yield* settings - .reviseProviderInstance(instanceId, (current) => { - if ( - !current || - current.enabled === false || - !isInferenceProviderConfig(current.config) || - !current.config.inferenceEnabled || - current.config.inferenceHostId !== primaryRoute.inferenceHostId || - current.config.inferenceKey !== primaryKey - ) - return failure("The inference route changed."); - return Effect.succeed({ - instance: { - ...current, - config: { - ...current.config, - inferenceBaseUrl: loopbackUrl(primary.hostId), - inferenceModels: [ - ...new Set([primary, ...alternates].flatMap((entry) => entry.models)), - ], + .reviseProviderInstance( + instanceId, + Effect.fnUntraced(function* (current, currentSettings) { + if ( + !current || + !isProviderInstanceEnabledInAnyScope(currentSettings, instanceId) || + !isInferenceProviderConfig(current.config) || + !current.config.inferenceEnabled || + current.config.inferenceHostId !== primaryRoute.inferenceHostId || + !(yield* matchesRouteKey(instanceId, current.config.inferenceKey, primaryKey)) + ) + return yield* failure("The inference route changed."); + return { + instance: { + ...current, + config: { + ...current.config, + inferenceBaseUrl: loopbackUrl(primary.hostId), + inferenceModels: [ + ...new Set([primary, ...alternates].flatMap((entry) => entry.models)), + ], + }, }, - }, - result: undefined, - }); - }) + result: undefined, + }; + }), + ) .pipe(Effect.onError(() => save(state).pipe(Effect.orDie))); }), ); @@ -1973,50 +2001,52 @@ const make = Effect.gen(function* () { Effect.gen(function* () { const state = yield* read; const existing = state.routePools?.find((entry) => entry.driver === driver); - const updated = yield* settings.reviseProviderInstance(instanceId, (current) => { - const problem = - driver === "opencode" - ? openCodeRouteProblem( - current?.environment, - providerEnvironment.OPENCODE_CONFIG_CONTENT, - ) - : null; - if (problem) return failure(problem); - const native = current ?? { driver: ProviderDriverKind.make(driver), config: {} }; - const { inferenceConnection: _previousConnection, ...nativeConfig } = providerConfig( - native.config, - ) - ? native.config - : {}; - const preserve = - existing?.primary.hostId === grant.hostId && - current?.enabled !== false && - isInferenceProviderConfig(current?.config) && - current.config.inferenceEnabled && - current.config.inferenceHostId === grant.hostId && - current.config.inferenceKey === existing.primary.key; - const alternates = preserve ? existing.alternates : []; - return Effect.succeed({ - instance: { - ...native, - enabled: true, - config: { - ...nativeConfig, - inferenceEnabled: true, - inferenceHostId: grant.hostId, - inferenceHostLabel: local ? "" : hostLabel, - inferenceBaseUrl: loopbackUrl(grant.hostId), - inferenceKey: grant.key, - inferenceModels: [ - ...new Set([...models, ...alternates.flatMap((entry) => entry.models)]), - ], - inferenceHomePath: home, - ...(linked && connection ? { inferenceConnection: connection } : {}), + const updated = yield* settings.reviseProviderInstance( + instanceId, + Effect.fnUntraced(function* (current) { + const problem = + driver === "opencode" + ? openCodeRouteProblem( + current?.environment, + providerEnvironment.OPENCODE_CONFIG_CONTENT, + ) + : null; + if (problem) return yield* failure(problem); + const native = current ?? { driver: ProviderDriverKind.make(driver), config: {} }; + const { inferenceConnection: _previousConnection, ...nativeConfig } = providerConfig( + native.config, + ) + ? native.config + : {}; + const preserve = + existing?.primary.hostId === grant.hostId && + existing.primary.key === grant.key && + isInferenceProviderConfig(current?.config) && + current.config.inferenceHostId === grant.hostId && + (yield* matchesRouteKey(instanceId, current.config.inferenceKey, grant.key)); + const alternates = preserve ? existing.alternates : []; + return { + instance: { + ...native, + enabled: true, + config: { + ...nativeConfig, + inferenceEnabled: true, + inferenceHostId: grant.hostId, + inferenceHostLabel: local ? "" : hostLabel, + inferenceBaseUrl: loopbackUrl(grant.hostId), + inferenceKey: grant.key, + inferenceModels: [ + ...new Set([...models, ...alternates.flatMap((entry) => entry.models)]), + ], + inferenceHomePath: home, + ...(linked && connection ? { inferenceConnection: connection } : {}), + }, }, - }, - result: preserve, - }); - }); + result: preserve, + }; + }), + ); yield* save({ ...state, routePools: [ @@ -2040,63 +2070,126 @@ const make = Effect.gen(function* () { const registerFallback = Effect.fn("InferenceProxy.registerFallback")( (input: InferenceRouteInput) => connect(input, true), ); - const refreshLocalProviders = Effect.fn("InferenceProxy.refreshLocalProviders")(function* () { - const state = yield* read; - if (!state.enabled) return; + const refreshRouteCatalogs = Effect.fn("InferenceProxy.refreshRouteCatalogs")(function* ( + localOnly: boolean, + targetInstanceId?: ProviderInstanceId, + ) { const hostId = yield* environment.getEnvironmentId; - const local = yield* grant({ environmentId: hostId, label: "Local" }); - const { data } = yield* jsonRequest(local.baseUrl + "/v1/models", local.key, Models); - const { providerInstances } = yield* settings.getSettings; - for (const driver of INFERENCE_DRIVERS) { - const instanceId = defaultInstanceIdForDriver(ProviderDriverKind.make(driver)); - const existing = providerInstances[instanceId]; + const { enabled, routePools = [] } = yield* read; + const currentSettings = yield* settings.getSettings; + const catalogs = yield* Cache.make({ + capacity: 64, + lookup: Effect.fn("InferenceProxy.fetchRouteCatalog")( + function* (candidate: Omit) { + const baseUrl = yield* candidateAddress(candidate, hostId); + const { data } = yield* jsonRequest(baseUrl + "/v1/models", candidate.key, Models); + return data; + }, + Effect.timeout("5 seconds"), + Effect.orElseSucceed(() => undefined), + ), + }); + const refreshCandidate = Effect.fn("InferenceProxy.refreshRouteCandidate")(function* ( + candidate: SavedRouteCandidate, + driver: InferenceDriver, + ) { + if (candidate.hostId === hostId ? !enabled : localOnly) return candidate; + const { models: _previous, ...connection } = candidate; + const catalog = yield* Cache.get(catalogs, connection); + if (catalog === undefined) return candidate; + const models = modelsForDriver(catalog, driver); + return Equal.equals(models, candidate.models) ? candidate : { ...candidate, models }; + }); + let changed = false; + for (const pool of routePools) { + const instanceId = defaultInstanceIdForDriver(ProviderDriverKind.make(pool.driver)); + if (targetInstanceId !== undefined && instanceId !== targetInstanceId) continue; + const active = currentSettings.providerInstances[instanceId]; if ( - !existing || - !isInferenceProviderConfig(existing.config) || - !existing.config.inferenceEnabled || - existing.config.inferenceHostId !== hostId + !active || + !isProviderInstanceEnabledInAnyScope(currentSettings, instanceId) || + !isInferenceProviderConfig(active.config) || + !active.config.inferenceEnabled || + active.config.inferenceHostId !== pool.primary.hostId || + active.config.inferenceKey !== pool.primary.key ) continue; - const localModels = modelsForDriver(data, driver); - const pool = (yield* read).routePools?.find( - (entry) => entry.driver === driver && entry.primary.hostId === hostId, + const [primary, ...alternates] = yield* Effect.forEach( + [pool.primary, ...pool.alternates] as const, + (candidate) => refreshCandidate(candidate, pool.driver), + { concurrency: 4 }, ); - const models = pool - ? [...new Set([...localModels, ...pool.alternates.flatMap((entry) => entry.models)])] - : localModels; - if (pool && pool.primary.models.join("\0") !== localModels.join("\0")) - yield* mutex.withPermit( - read.pipe( - Effect.flatMap((state) => - save({ - ...state, - routePools: (state.routePools ?? []).map((entry) => - entry.driver === driver - ? { ...entry, primary: { ...entry.primary, models: localModels } } - : entry, - ), + const poolChanged = primary !== pool.primary || !Equal.equals(alternates, pool.alternates); + const inferenceModels = [ + ...new Set([primary, ...alternates].flatMap((candidate) => candidate.models)), + ]; + if (!poolChanged && Equal.equals(inferenceModels, active.config.inferenceModels)) continue; + const applied = yield* mutex.withPermit( + Effect.gen(function* () { + const before = yield* read; + if ( + !before.routePools || + !Equal.equals( + before.routePools.find((entry) => entry.driver === pool.driver), + pool, + ) + ) + return false; + if (poolChanged) + yield* save({ + ...before, + routePools: before.routePools.map((entry) => + entry.driver === pool.driver ? { ...pool, primary, alternates } : entry, + ), + }); + const revised = yield* settings + .reviseProviderInstance( + instanceId, + Effect.fnUntraced(function* (current, currentSettings) { + if ( + !current || + !isProviderInstanceEnabledInAnyScope(currentSettings, instanceId) || + current.driver !== pool.driver || + !isInferenceProviderConfig(current.config) || + !current.config.inferenceEnabled || + current.config.inferenceHostId !== pool.primary.hostId || + !(yield* matchesRouteKey( + instanceId, + current.config.inferenceKey, + pool.primary.key, + )) + ) + return yield* failure("The inference route changed during catalog refresh."); + return { + instance: { ...current, config: { ...current.config, inferenceModels } }, + result: undefined, + }; }), - ), - ), - ); - const revised = yield* settings.reviseProviderInstance(instanceId, (current) => { - if (!current) return failure("The local inference provider was removed."); - return Effect.succeed({ - instance: - current.driver === driver && - isInferenceProviderConfig(current.config) && - current.config.inferenceEnabled && - current.config.inferenceHostId === hostId - ? { ...current, config: { ...current.config, inferenceModels: models } } - : current, - result: undefined, - }); - }); - yield* registry.reconcile( - deriveProviderInstanceConfigMap(revised.settings, providerEnvironment), + ) + .pipe( + Effect.onError(() => (poolChanged ? save(before).pipe(Effect.orDie) : Effect.void)), + Effect.result, + ); + return Result.isSuccess(revised); + }).pipe(Effect.uninterruptible), ); + changed ||= applied; } - }); + if (changed) + yield* registry.reconcile( + deriveProviderInstanceConfigMap(yield* settings.getSettings, providerEnvironment), + ); + }, catalogMutex.withPermit); + const refreshLocalProviders = () => refreshRouteCatalogs(true); + const [refreshCatalog, invalidateCatalog] = yield* Effect.cachedInvalidateWithTTL( + refreshRouteCatalogs(false).pipe(Effect.ignoreCause), + "15 seconds", + ); + const refreshModelCatalog = (fresh?: boolean, instanceId?: ProviderInstanceId) => { + if (instanceId !== undefined) + return refreshRouteCatalogs(false, instanceId).pipe(Effect.ignoreCause); + return fresh ? invalidateCatalog.pipe(Effect.andThen(refreshCatalog)) : refreshCatalog; + }; yield* watchLocalCodexAuth.pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped); yield* watchLocalClaudeAuth.pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped); yield* read.pipe( @@ -2122,6 +2215,7 @@ const make = Effect.gen(function* () { connect, registerFallback, bindRoutes, + refreshModelCatalog, }; }); @@ -2150,6 +2244,10 @@ export class InferenceProxy extends Context.Service< input: InferenceRouteInput, ) => Effect.Effect; readonly bindRoutes: (port: number) => Effect.Effect; + readonly refreshModelCatalog: ( + fresh?: boolean, + instanceId?: ProviderInstanceId, + ) => Effect.Effect; readonly authorize: ( key: string, hostId?: EnvironmentId, diff --git a/apps/server/src/inference/http.test.ts b/apps/server/src/inference/http.test.ts index efa6719a018a9..09c91158eb522 100644 --- a/apps/server/src/inference/http.test.ts +++ b/apps/server/src/inference/http.test.ts @@ -316,6 +316,17 @@ it("tries another authorized host for the same model after an upstream auth fail "http://primary.test/v1/models", "http://backup.test/v1/models", ]); + primaryStatus = 529; + const overload = await send(); + expect(overload.status).toBe(200); + expect(calls.slice(10)).toEqual([ + "http://primary.test/v1/messages", + "http://backup.test/v1/messages", + ]); + backupStatus = 400; + const invalid = await send(); + expect(invalid.status).toBe(400); + expect(calls.slice(12)).toEqual(["http://backup.test/v1/messages"]); } finally { await dispose(); } diff --git a/apps/server/src/inference/http.ts b/apps/server/src/inference/http.ts index 13905a9b712ea..2dec1739c193b 100644 --- a/apps/server/src/inference/http.ts +++ b/apps/server/src/inference/http.ts @@ -15,7 +15,7 @@ import { HttpServerResponse, } from "effect/http"; import { InferenceProxy } from "./InferenceProxy.ts"; -import { inferenceTarget } from "./routes.ts"; +import { inferenceTarget, isRetryableInferenceStatus } from "./routes.ts"; const MAX_REPLAY_BODY_BYTES = 8 * 1024 * 1024; const MAX_CATALOG_BODY_BYTES = 1024 * 1024; @@ -259,7 +259,7 @@ const handler = Effect.gen(function* () { if (affinityKey && target.hostId) { if (result.status < 400) rememberSessionRoute(affinityKey, target.hostId, yield* Clock.currentTimeMillis); - else if ([401, 403, 429, 502, 503].includes(result.status)) sessionRoutes.delete(affinityKey); + else if (isRetryableInferenceStatus(result.status)) sessionRoutes.delete(affinityKey); } if (target.hostId && targetPath.driver && model) yield* host.recordRouteOutcome({ @@ -303,7 +303,7 @@ const handler = Effect.gen(function* () { if (result.status >= 200 && result.status < 300) return HttpServerResponse.empty({ status: 502 }); } - if (index < targets.length - 1 && [401, 403, 429, 502, 503].includes(result.status)) continue; + if (index < targets.length - 1 && isRetryableInferenceStatus(result.status)) continue; break; } if (!result) return HttpServerResponse.empty({ status: 502 }); diff --git a/apps/server/src/inference/providerHealth.ts b/apps/server/src/inference/providerHealth.ts index f0226ae920da3..daa3a58e77705 100644 --- a/apps/server/src/inference/providerHealth.ts +++ b/apps/server/src/inference/providerHealth.ts @@ -4,6 +4,7 @@ import { type ServerProvider, type InferenceProviderConfig, } from "@t3tools/contracts"; +import { isProviderInstanceEnabledInAnyScope } from "@t3tools/shared/serverSettings"; import * as Cache from "effect/Cache"; import * as Effect from "effect/Effect"; import { InferenceProxy } from "./InferenceProxy.ts"; @@ -122,18 +123,31 @@ export const makeInferenceProviderHealth = Effect.fn("makeInferenceProviderHealt ), ); + const instanceIds = settings.getSettings.pipe( + Effect.map((settings) => + Object.entries(settings.providerInstances).flatMap(([id, instance]) => { + const instanceId = ProviderInstanceId.make(id); + return isProviderInstanceEnabledInAnyScope(settings, instanceId) && + isInferenceProviderConfig(instance.config) && + instance.config.inferenceEnabled + ? [instanceId] + : []; + }), + ), + Effect.orElseSucceed((): ProviderInstanceId[] => []), + ); + const refreshModelCatalog = Effect.fn("InferenceProviderHealth.refreshModelCatalog")(function* ( + fresh?: boolean, + instanceId?: ProviderInstanceId, + ) { + const ids = yield* instanceIds; + if (instanceId === undefined ? ids.length > 0 : ids.includes(instanceId)) + yield* proxy.refreshModelCatalog(fresh, instanceId); + }); return { apply, - instanceIds: settings.getSettings.pipe( - Effect.map(({ providerInstances }) => - Object.entries(providerInstances).flatMap(([id, instance]) => - isInferenceProviderConfig(instance.config) && instance.config.inferenceEnabled - ? [ProviderInstanceId.make(id)] - : [], - ), - ), - Effect.orElseSucceed(() => []), - ), + instanceIds, + refreshModelCatalog, invalidate: Cache.invalidateAll(catalogs), }; }); diff --git a/apps/server/src/inference/routes.test.ts b/apps/server/src/inference/routes.test.ts index 90e99ddf1045d..57f4dfde52ac8 100644 --- a/apps/server/src/inference/routes.test.ts +++ b/apps/server/src/inference/routes.test.ts @@ -76,7 +76,11 @@ describe("inference routes", () => { homePath: "/state/home", current: (name: string) => current[name], }); - const codex = routeProvider("codex", "Office", route(["gpt-fixture"])); + const codex = routeProvider( + "codex", + "Office", + route(["gpt-fixture", "gpt-image-2.6", "gpt-fixture"]), + ); const claude = routeProvider("claudeAgent", "Office", route(["claude-fixture"])); const pi = routeProvider("pi", "Office", route(["grok-fixture"])); const openCode = routeProvider( @@ -91,6 +95,7 @@ describe("inference routes", () => { }), ); expect(codex.config.launchArgs).toContain(baseUrl + "/v1"); + expect(codex.config.customModels).toEqual(["gpt-fixture"]); expect(codex.config.launchArgs).not.toContain("private"); expect(codex.environment).toContainEqual({ name: "T3_INFERENCE_KEY", @@ -149,14 +154,19 @@ describe("inference routes", () => { } }); - it("gives each harness its supported advertised models regardless of prefix", () => { - const models = [ + it("gives each harness its supported advertised chat models only once", () => { + const chatModels = [ { id: "gpt-fixture", owned_by: "openai" }, { id: "claude-fixture", owned_by: "anthropic" }, { id: "grok-fixture", owned_by: "xai" }, { id: "codex-pool-1", owned_by: "openai" }, { id: "claude-pool-1", owned_by: "anthropic" }, ]; + const models = [ + ...chatModels, + { id: "gpt-fixture", owned_by: "openai" }, + { id: "gpt-image-2.6", owned_by: "openai" }, + ]; expect(modelsForDriver(models, "codex")).toEqual(["gpt-fixture", "codex-pool-1"]); expect(modelsForDriver(models, "claudeAgent")).toEqual(["claude-fixture", "claude-pool-1"]); expect(modelsForDriver(models, "opencode")).toEqual([ @@ -166,7 +176,7 @@ describe("inference routes", () => { "codex-pool-1", "claude-pool-1", ]); - expect(modelsForDriver(models, "pi")).toEqual(models.map((model) => model.id)); + expect(modelsForDriver(models, "pi")).toEqual(chatModels.map((model) => model.id)); }); it("excludes an exhausted Claude account's models when only Codex remains available", () => { diff --git a/apps/server/src/inference/routes.ts b/apps/server/src/inference/routes.ts index af861457da850..0c1acd86171d1 100644 --- a/apps/server/src/inference/routes.ts +++ b/apps/server/src/inference/routes.ts @@ -4,6 +4,7 @@ import { INFERENCE_HARNESSES, ProviderDriverKind, type CustomModelSetting, + type ServerProviderModel, type SettingsSecretValue, type ProviderInstanceConfig, } from "@t3tools/contracts"; @@ -32,6 +33,9 @@ export function inferencePath(method: string, rawUrl: string): string | null { : null; } +export const isRetryableInferenceStatus = (status: number): boolean => + [401, 403, 429, 502, 503, 529].includes(status); + export function inferenceTarget(method: string, rawUrl: string) { const linked = /^\/api\/inference\/linked\/([^/]+)\/([^/]+)(\/.*)$/.exec(rawUrl); const driver = linked && isInferenceDriver(linked[1]) ? linked[1] : undefined; @@ -122,6 +126,8 @@ interface Route { const blank = (names: readonly string[], value = "") => names.map((name) => ({ name, value, sensitive: false })); const VENDORS = ["openai", "anthropic"]; +// GPT Image IDs are selected by the image tool or Images API, not as chat models. +const isGptImageModel = (id: string) => /^gpt-image(?:-|$)/i.test(id); const ownedBy = (vendor: string, pattern: RegExp) => (model: ProxyModel) => { const owner = model.owned_by?.toLowerCase(); return owner !== undefined && VENDORS.includes(owner) ? owner === vendor : pattern.test(model.id); @@ -249,12 +255,15 @@ export function modelsForDriver( driver: InferenceDriver, availability?: AccountModelAvailability, ) { - const models = data.filter((model) => harnesses[driver].serves(model)); + const models = data.filter( + (model) => !isGptImageModel(model.id) && harnesses[driver].serves(model), + ); + const modelIds = [...new Set(models.map((model) => model.id))]; if ( !availability || !needsAccountModelLookup(availability.accounts, availability.excludedNames, availability.now) ) - return models.map((model) => model.id); + return modelIds; const available = new Set(); for (const account of availability.accounts) { if (!usableAccount(account, availability.excludedNames)) continue; @@ -287,18 +296,22 @@ export function modelsForDriver( if (!blocked.has(model)) available.add(model); } } - return models.filter((model) => available.has(model.id)).map((model) => model.id); + return modelIds.filter((id) => available.has(id)); } export function routeProvider(driver: InferenceDriver, label: string | null, route: Route) { const harness = harnesses[driver]; const name = INFERENCE_HARNESSES[driver].label; + const chatRoute = { + ...route, + models: [...new Set(route.models.filter((id) => !isGptImageModel(id)))], + }; return { driver: ProviderDriverKind.make(driver), displayName: label === null ? name : `${name} via ${label}`, enabled: true, - config: harness.config(route), - environment: harness.environment(route), + config: harness.config(chatRoute), + environment: harness.environment(chatRoute), }; } @@ -310,3 +323,14 @@ export function inferenceModelSlugs(config: { ? new Set(config.customModels.map((entry) => (typeof entry === "string" ? entry : entry.slug))) : null; } + +export function withInferenceModelCatalog( + models: ReadonlyArray, + hostedSlugs: ReadonlySet | null, +): ReadonlyArray { + if (!hostedSlugs) return models; + // Codex and Claude ingest host discoveries through their custom model config. + return models + .filter((model) => hostedSlugs.has(model.slug)) + .map((model) => (model.isCustom ? { ...model, isCustom: false } : model)); +} diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index ccecbae8f1909..fb2aef58bfd51 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -1,4 +1,4 @@ -import { inferenceModelSlugs } from "../../inference/routes.ts"; +import { inferenceModelSlugs, withInferenceModelCatalog } from "../../inference/routes.ts"; import { ClaudeSettings, ProviderDriverKind, TextGenerationError } from "@t3tools/contracts"; import * as Cache from "effect/Cache"; import type * as Cause from "effect/Cause"; @@ -187,9 +187,7 @@ export const ClaudeDriver: ProviderDriver< const stampSnapshot = (draft: Parameters[0]) => stampIdentity({ ...draft, - ...(hostedModels - ? { models: draft.models.filter((model) => hostedModels.has(model.slug)) } - : {}), + models: withInferenceModelCatalog(draft.models, hostedModels), ...(auth ? { setup: { diff --git a/apps/server/src/provider/Drivers/CodexDriver.test.ts b/apps/server/src/provider/Drivers/CodexDriver.test.ts index b3325c3ed8326..c9ec9e8e6fff6 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.test.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.test.ts @@ -650,6 +650,44 @@ it.layer(layerTest)("CodexDriver", (it) => { }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)), ); + it.effect.each(["inference", "existing"] as const)( + "publishes models with the right provenance in %s mode", + (setupMode) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const homePath = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-models-" }); + const model = { + slug: "gpt-6.2-sol", + name: "GPT-6.2 Sol", + capabilities: { + optionDescriptors: [ + { + id: "reasoningEffort", + label: "Reasoning", + type: "select", + options: [{ id: "low", label: "Low", isDefault: true }], + }, + ], + }, + } as const; + const instance = yield* CodexDriver.create({ + instanceId: ProviderInstanceId.make("codex-catalog"), + displayName: "Codex", + enabled: false, + environment: [], + config: { + ...CodexDriver.defaultConfig(), + homePath, + setupMode, + customModels: [model, model.slug], + }, + }); + expect((yield* instance.snapshot.getSnapshot).models).toEqual([ + { ...model, isCustom: setupMode === "existing" }, + ]); + }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)), + ); + it.effect.skipIf(windowsHost)( "shares state from the environment CODEX_HOME in a shadow home", () => diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index 59fb22240a01e..70bb11143cc5d 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -1,4 +1,4 @@ -import { inferenceModelSlugs } from "../../inference/routes.ts"; +import { inferenceModelSlugs, withInferenceModelCatalog } from "../../inference/routes.ts"; import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe"; import { CodexSettings, ProviderDriverKind, TextGenerationError } from "@t3tools/contracts"; import { resolveCommandPath } from "@t3tools/shared/shell"; @@ -281,9 +281,7 @@ export const CodexDriver: ProviderDriver< const stampSnapshot = (draft: Parameters[0]) => stampIdentity({ ...draft, - ...(hostedModels - ? { models: draft.models.filter((model) => hostedModels.has(model.slug)) } - : {}), + models: withInferenceModelCatalog(draft.models, hostedModels), ...(cliAccount ? { setup: { diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts index 99d281d8a1ae0..4837554ada6ba 100644 --- a/apps/server/src/provider/ProviderRegistry.ts +++ b/apps/server/src/provider/ProviderRegistry.ts @@ -1351,6 +1351,7 @@ export const layer = Layer.effect( const invalidateModelCaches = Effect.fn("ProviderRegistry.invalidateModelCaches")(function* ( input: Parameters[0], ) { + yield* inferenceHealth.refreshModelCatalog(true, input.instanceId); yield* manifestService.forceRefresh; const instances = yield* instanceRegistry.listInstances; yield* Effect.forEach( @@ -1377,6 +1378,7 @@ export const layer = Layer.effect( }); const refreshModelCatalog = Effect.fn("ProviderRegistry.refreshModelCatalog")(function* () { + yield* inferenceHealth.refreshModelCatalog(); yield* refreshInferenceProviders(); const { updatedAt } = yield* manifestService.refreshOnDemand; // The first pass can be one that started before the fetch, so allow one more. diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx index 1f8729b3866b8..ac731bea154c2 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx @@ -1,4 +1,5 @@ import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "@t3tools/contracts"; +import { Atom, AsyncResult } from "effect/reactivity"; import { userEvent } from "vite-plus/test/browser"; import { describe, expect, it, vi } from "vite-plus/test"; @@ -8,6 +9,8 @@ const actions = vi.hoisted(() => ({ toast: vi.fn(), onOpenChange: vi.fn(), canManageProviders: true, + supportsInference: false, + enableInference: vi.fn(), })); const settingsHooks = vi.hoisted(() => ({ read: vi.fn(() => ({ providerInstances: {} })), @@ -46,6 +49,39 @@ vi.mock(import("../../state/session"), async (original) => { readEnvironmentScope: hasScope as never, }; }); +vi.mock(import("../../state/entities"), async (original) => ({ + ...(await original()), + useServerConfigs: (() => + new Map([ + [ + remoteEnvironmentId, + { environment: { capabilities: { inferenceProxy: actions.supportsInference } } }, + ], + ])) as never, +})); +vi.mock(import("../../state/server"), async (original) => { + const actual = await original(); + return { + ...actual, + serverEnvironment: { + ...actual.serverEnvironment, + inferenceProxy: { + ...actual.serverEnvironment.inferenceProxy, + canConnect: () => Atom.make(actions.canManageProviders), + }, + }, + }; +}); +vi.mock(import("../../state/use-atom-command"), async (original) => { + const actual = await original(); + return { + ...actual, + useAtomCommand: ((command: Parameters[0], options?: string) => { + const invoke = actual.useAtomCommand(command, options); + return command.label === "inference:enable-routing" ? actions.enableInference : invoke; + }) as never, + }; +}); vi.mock(import("../ui/toast"), async (original) => { const actual = await original(); return { ...actual, toastManager: { ...actual.toastManager, add: actions.toast } }; @@ -162,6 +198,8 @@ async function prepareCodexInstance() { function setup() { actions.canManageProviders = true; + actions.supportsInference = false; + actions.enableInference.mockReset(); actions.toast.mockReset(); actions.onOpenChange.mockReset(); settingsHooks.read.mockReset().mockReturnValue({ providerInstances: {} }); @@ -170,6 +208,26 @@ function setup() { } describe("AddProviderInstanceDialog environment routing", () => { + it("routes the default provider and opens the selected host's accounts before settings update", async () => { + setup(); + actions.supportsInference = true; + actions.enableInference.mockResolvedValue( + AsyncResult.success({ environmentId: EnvironmentId.make("studio"), label: "Studio" }), + ); + await using _screen = await render(dialog()); + await choose("Codex"); + await click("Next"); + await choose("Use inference accounts"); + await click("Continue"); + expect(actions.enableInference).toHaveBeenCalledExactlyOnceWith({ + consumer: { environmentId: remoteEnvironmentId, label: "Remote device" }, + driver: "codex", + environments: expect.any(Array), + }); + expect(document.body.textContent).toContain("Using Studio for inference."); + expect(settingsHooks.mutate).not.toHaveBeenCalled(); + }); + it.each([ { driver: "codex", label: "Codex" }, { driver: "opencode", label: "OpenCode" }, diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx index 8cd8d66f8b982..5ecb1d8fd9352 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx @@ -22,8 +22,12 @@ import { ProviderInstanceId, ProviderDriverKind, type EnvironmentId, + type InferenceConsumer, + type InferenceDriver, type ProviderInstanceConfig, type ProviderInstanceEnvironmentVariable, + isCustomInferenceBackend, + isInferenceProviderConfig, isManagedDriverAllowed, inferenceHarness, } from "@t3tools/contracts"; @@ -71,6 +75,7 @@ import { AddManagedCodexAccountDialog } from "./CodexSetupSection"; import { ProviderEnvironmentSection } from "./ProviderInstanceCard"; import { useSecretSources } from "./SecretSourceInput"; import { InferenceProviderAccounts } from "./InferenceProviderAccounts"; +import { useEnableInferenceRouting } from "./useEnableInferenceRouting"; const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex"); const TRAEX_BRIDGE_PRESET = "traexBridge"; @@ -194,6 +199,9 @@ export function AddProviderInstanceDialog({ const secretSources = useSecretSources(environmentId); const persistProviderInstance = usePersistEnvironmentProviderInstanceMutation(environmentId); const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope); + const inference = useEnableInferenceRouting(environmentId, environmentLabel); + const [routedHost, setRoutedHost] = useState(null); + const [localSetup, setLocalSetup] = useState(false); const [wizardStep, setWizardStep] = useState(0); const managedPolicy = useManagedPolicy(environmentId); @@ -241,13 +249,24 @@ export function AddProviderInstanceDialog({ const driverOption = providerClients.get(driver) ?? DEFAULT_DRIVER_OPTION; const isAcpRegistry = driver === ACP_REGISTRY_DRIVER_KIND; - const hasConnectionChoice = selection === "codex" || selection === "claudeAgent"; + const inferenceDriver = selection === "codex" || selection === "claudeAgent" ? selection : null; + const hasConnectionChoice = inferenceDriver !== null; const supportsInference = useServerConfigs().get(environmentId)?.environment.capabilities.inferenceProxy === true; + const defaultRoutingProvider = inferenceDriver + ? settings.providerInstances[ProviderInstanceId.make(inferenceDriver)] + : undefined; + const canUseInference = + supportsInference && + (!defaultRoutingProvider || !isCustomInferenceBackend(defaultRoutingProvider)); const accountHostId = inferenceHarness(selection)?.replacesAccounts ? inferenceAccountHostId(settings.providerInstances, selection, environmentId) : null; - const connectionChoice = connectionChoices[selection] ?? "existing"; + const storedConnectionChoice = connectionChoices[selection]; + const connectionChoice = + storedConnectionChoice === "inference" && !canUseInference + ? "existing" + : (storedConnectionChoice ?? "existing"); const connectionOptions = selection === "claudeAgent" ? CONNECTION_OPTIONS.claudeAgent : CONNECTION_OPTIONS.codex; const showRegistrySearch = @@ -336,6 +355,7 @@ export function AddProviderInstanceDialog({ })); }; const selectProvider = (value: string) => { + setLocalSetup(false); setSelection(value); setIsManualAcpConfiguration(false); setHasAttemptedSubmit(false); @@ -500,26 +520,43 @@ export function AddProviderInstanceDialog({ onOpenChange(false); }; - if ( - providerView === "accounts" && - accountHostId && - (driver === "codex" || driver === "claudeAgent") - ) { + async function routeProvider(driver: InferenceDriver, preferredHostId?: EnvironmentId) { + const host = await inference.run(driver, preferredHostId); + if (!host) return; + setLocalSetup(false); + setRoutedHost(host); + setProviderView("accounts"); + } + + const managedAccountHostId = routedHost?.environmentId ?? accountHostId; + if (providerView === "accounts" && managedAccountHostId && inferenceDriver) { return ( - + )} + onOpenChange(false)} + > + Choose another host + + + + )} + {localSetup && ( + void routeProvider(inferenceDriver, environmentId)} + /> + )} + + ) : null} {wizardStep === 0 && providerView === "catalog" && @@ -895,7 +970,7 @@ export function AddProviderInstanceDialog({ {wizardStep === 0 && providerView === "connection" && - connectionChoice === "inference" ? ( + connectionChoice === "inference" && + inferenceDriver ? ( ) : wizardStep === 0 ? ( + enableLocalHosting ? ( + + ) : ( + + ) } /> ); diff --git a/apps/web/src/components/settings/InferenceSettings.tsx b/apps/web/src/components/settings/InferenceSettings.tsx index be856be34b89f..82b4bc3689fa5 100644 --- a/apps/web/src/components/settings/InferenceSettings.tsx +++ b/apps/web/src/components/settings/InferenceSettings.tsx @@ -5,6 +5,10 @@ import { } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { + inferenceHostCandidates, + inferenceHostRoutingIssue, +} from "@t3tools/client-runtime/state/inference-proxy"; import { INFERENCE_DRIVERS, INFERENCE_HARNESSES, @@ -37,8 +41,6 @@ function InferenceRoute({ inferenceProxy.inferenceStatus({ environmentId: host.environmentId, input: {} }), ); const issue = inferenceRouteIssue(status.data, host.environmentId === consumer.environmentId); - const hasAccount = (driver: InferenceDriver) => - status.data?.availableDrivers.includes(driver) ?? false; const route = useAtomCommand(inferenceProxy.routeInference, { reportFailure: false }); const [busy, setBusy] = useState(false); const [notice, setNotice] = useState(""); @@ -70,7 +72,12 @@ function InferenceRoute({ key={driver} size="sm" variant="outline" - disabled={!canGrant || !canConnect || busy || !!issue || !hasAccount(driver)} + disabled={ + !canGrant || + !canConnect || + busy || + inferenceHostRoutingIssue(status.data, { host, consumer, driver }) !== null + } onClick={() => void add(driver)} > {INFERENCE_HARNESSES[driver].label} @@ -173,7 +180,12 @@ export function InferenceSettings({ environmentId }: { environmentId: Environmen checked={host.enabled} disabled={busy} onCheckedChange={(enabled) => - void run({ operation: "configure", enabled, sharing: false }) + void run({ + operation: "configure", + enabled, + sharing: false, + expectedEnabled: host.enabled, + }) } /> } @@ -210,7 +222,12 @@ export function InferenceSettings({ environmentId }: { environmentId: Environmen checked={host.sharing} disabled={busy} onCheckedChange={(sharing) => - void run({ operation: "configure", enabled: true, sharing }) + void run({ + operation: "configure", + enabled: true, + sharing, + expectedEnabled: true, + }) } /> } @@ -279,15 +296,9 @@ export function InferenceSettings({ environmentId }: { environmentId: Environmen } /> ))} - {environments - .filter( - (e) => - e.connection.phase === "connected" && - e.serverConfig?.environment.capabilities.inferenceProxy, - ) - .map((e) => ( - - ))} + {inferenceHostCandidates(environments, environmentId).map((e) => ( + + ))} )} diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx index cae8ac562c4d8..3ff351ec10635 100644 --- a/apps/web/src/components/settings/ProviderInstanceCard.tsx +++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx @@ -40,7 +40,7 @@ import { import { cn } from "../../lib/utils"; import { useCopyToClipboard } from "../../hooks/useCopyToClipboard"; import { useStableCallback } from "../../hooks/useStableCallback"; -import { normalizeProviderAccentColor } from "../../providerInstances"; +import { normalizeProviderAccentColor, usesHostedModelCatalog } from "../../providerInstances"; import { Badge } from "../ui/badge"; import { Button } from "../ui/button"; import { DraftInput } from "../ui/draft-input"; @@ -875,9 +875,12 @@ export function ProviderInstanceCard({ return onUpdate({ ...rest, config: nextConfig } as ProviderInstanceConfig); }, ); + const hostedModelCatalog = + driverKind !== null && usesHostedModelCatalog(instanceId, driverKind, instance.config); + const visibleCustomModels = hostedModelCatalog ? NO_CUSTOM_MODELS : customModels; const modelsForDisplay = deriveProviderModelsForDisplay({ liveModels: liveProvider?.models, - customModels, + customModels: visibleCustomModels, }); const updateDisplayName = (value: string) => { const trimmed = value.trim(); @@ -1450,12 +1453,12 @@ export function ProviderInstanceCard({ across connected devices.

0 ? ` · ${hiddenCount} hidden` : ""} - {driverKind !== "antigravity" && !isAdding ? ( + {canManageCustomModels && driverKind !== "antigravity" && !isAdding ? ( + )} + + Choose another host + + + + ) : usingProxy && disableError ? ( + {disableError} + ) : undefined + } + control={ + { + if (enabled) { + await run(driver, route?.inferenceHostId); + return; + } + setDisabling(true); + setDisableError(null); + const result = await manage({ + environmentId, + input: { operation: "removeRoute", instanceId }, + }); + setDisabling(false); + if (result._tag === "Failure") { + const failure = squashAtomCommandFailure(result); + setDisableError(failure instanceof Error ? failure.message : String(failure)); + } + }} + /> + } + /> + {!usingProxy && localSetup && ( + void run(driver, environmentId)} + /> + )} + + ); +} diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 38fc094fc580f..24424674738e0 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -1078,7 +1078,7 @@ export const SETTINGS_SEARCH_ITEMS = [ title: "Providers", to: "/settings/providers", searchTerms: [ - "agents cli codex claude cursor grok fx kiro opencode antigravity google sign in sign out install subscription instances authentication api key models configuration binary path config directory codex_home shadow home endpoint arguments environment variables display name accent color custom favorite hidden auto compact native sessions import resume", + "agents cli codex claude cursor grok fx kiro opencode antigravity google sign in sign out install subscription instances authentication api key models configuration binary path config directory codex_home shadow home endpoint arguments environment variables display name accent color custom favorite hidden auto compact native sessions import resume inference routing CLI proxy", ], }, { diff --git a/apps/web/src/components/settings/useEnableInferenceRouting.ts b/apps/web/src/components/settings/useEnableInferenceRouting.ts new file mode 100644 index 0000000000000..850cd3edac01e --- /dev/null +++ b/apps/web/src/components/settings/useEnableInferenceRouting.ts @@ -0,0 +1,43 @@ +import { useAtomValue } from "@effect/atom-react"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentId, InferenceConsumer, InferenceDriver } from "@t3tools/contracts"; +import { useRef, useState } from "react"; + +import { useEnvironments } from "../../state/environments"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; + +const { inferenceProxy } = serverEnvironment; + +export function useEnableInferenceRouting(environmentId: EnvironmentId, environmentLabel: string) { + const { environments } = useEnvironments(); + const canConnect = useAtomValue(inferenceProxy.canConnect(environmentId)); + const enable = useAtomCommand(inferenceProxy.enableInferenceRouting, { reportFailure: false }); + const inFlight = useRef(false); + const [pending, setPending] = useState(false); + const [error, setError] = useState(null); + + async function run( + driver: InferenceDriver, + preferredHostId?: EnvironmentId, + ): Promise { + if (!canConnect || inFlight.current) return null; + inFlight.current = true; + setPending(true); + setError(null); + const result = await enable({ + consumer: { environmentId, label: environmentLabel }, + driver, + environments, + ...(preferredHostId === undefined ? {} : { preferredHostId }), + }); + inFlight.current = false; + setPending(false); + if (result._tag === "Success") return result.value; + const failure = squashAtomCommandFailure(result); + setError(failure instanceof Error ? failure.message : String(failure)); + return null; + } + + return { canConnect, pending, error, run }; +} diff --git a/apps/web/src/modelSelection.test.ts b/apps/web/src/modelSelection.test.ts index 1de6d7cd52b22..7663b459c9d5e 100644 --- a/apps/web/src/modelSelection.test.ts +++ b/apps/web/src/modelSelection.test.ts @@ -219,6 +219,35 @@ describe("scoped default model selections", () => { }); describe("instance-scoped model selection", () => { + it.each([ + { driver: "codex", replacesAccounts: true }, + { driver: "claudeAgent", replacesAccounts: true }, + { driver: "opencode", replacesAccounts: false }, + { driver: "pi", replacesAccounts: false }, + ])( + "only keeps native custom models on additive $driver routes", + ({ driver, replacesAccounts }) => { + const instanceId = ProviderInstanceId.make(driver); + const driverKind = ProviderDriverKind.make(driver); + const settings: UnifiedSettings = { + ...DEFAULT_UNIFIED_SETTINGS, + providerInstances: { + [instanceId]: { + driver: driverKind, + config: { inferenceEnabled: true, customModels: ["native-model"] }, + }, + }, + }; + const [entry] = deriveProviderInstanceEntries([ + provider({ instanceId, provider: driverKind, models: ["hosted-model"] }), + ]); + + expect(getAppModelOptionsForInstance(settings, entry!).map((option) => option.slug)).toEqual( + replacesAccounts ? ["hosted-model"] : ["hosted-model", "native-model"], + ); + }, + ); + it("keeps custom models on the provider instance that declared them", () => { const providers = [ provider({ diff --git a/apps/web/src/modelSelection.ts b/apps/web/src/modelSelection.ts index 7cf73d9109d3e..46e7a8ff45dc7 100644 --- a/apps/web/src/modelSelection.ts +++ b/apps/web/src/modelSelection.ts @@ -39,6 +39,7 @@ import { NO_PROVIDER_MODEL_SELECTION, resolveDefaultProviderModelSelection, resolveProjectDefaultProviderModelSelection, + usesHostedModelCatalog, } from "./providerInstances"; import { sortModelsForProviderInstance } from "./modelOrdering"; import { resolveModelShortName } from "@t3tools/client-runtime/provider-clients"; @@ -55,6 +56,7 @@ export function readInstanceCustomModels( if (driverKind === "antigravity") return []; const instance = settings.providerInstances?.[instanceId]; const config = instance?.config; + if (usesHostedModelCatalog(instanceId, driverKind, config)) return []; if (config !== null && typeof config === "object") { const value = (config as Record).customModels; if (Array.isArray(value)) { diff --git a/apps/web/src/providerInstances.ts b/apps/web/src/providerInstances.ts index 3b889060346b9..371e49ab90ecd 100644 --- a/apps/web/src/providerInstances.ts +++ b/apps/web/src/providerInstances.ts @@ -2,7 +2,9 @@ import { pipe } from "effect/Function"; import { DEFAULT_MODEL_BY_PROVIDER, defaultInstanceIdForDriver, + inferenceHarness, isInferenceAccountReplaced, + isInferenceRoutingEnabled, providerLimitedUntilMs, resolveProjectProviderInstanceEnabled, type ModelSelection, @@ -22,6 +24,18 @@ import { export { normalizeProviderAccentColor, shouldShowInstanceBadge }; +export function usesHostedModelCatalog( + instanceId: ProviderInstanceId, + driver: ProviderDriverKind, + config: unknown, +): boolean { + return ( + instanceId === defaultInstanceIdForDriver(driver) && + inferenceHarness(driver)?.replacesAccounts === true && + isInferenceRoutingEnabled(config) + ); +} + type ProviderInstanceSettings = Pick< ServerSettings, "providerInstances" | "projectSettingsOverrides" diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index 244228628a719..4798be4f87e23 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -41,19 +41,28 @@ To let another machine use those accounts, turn on **Share inference with paired T3 reuses the selected host's existing connection, including SSH, LAN, Tailscale, or T3 Connect. You do not need an agent link or a separate proxy installation on the consuming machine. Connect your client to both T3 environments with provider management access. -Select the environment where you want to run agents in Settings. Under **Route -requests through an environment**, choose Codex, Claude, [OpenCode](./providers-opencode.md#shared-inference-accounts), -or [Pi](./providers-pi.md#shared-inference-accounts) beside the host name. +Select the environment where you want to run agents in **Settings > Providers**. +Turn on **Inference routing** for the provider. T3 tries its previous host first, then +accounts on the current environment, then paired hosts with sharing enabled. +The provider settings show which host it connects to. You can also choose +**Use inference accounts** when adding a Codex or Claude account on web or desktop. +If no host is ready, choose **Set up accounts here** to start hosting and add an account +from the same screen. + +To pick a host yourself, open **Inference accounts** and choose Codex, Claude, +[OpenCode](./providers-opencode.md#shared-inference-accounts), or +[Pi](./providers-pi.md#shared-inference-accounts) beside the host name. The environment running agents needs the corresponding CLI and must be able to reach the host through the selected connection. You can also choose the current host for local use. Use LAN HTTP only on a trusted network. Prompts, responses, and revocable route keys travel unencrypted on that connection. -Select **Codex via …** or **Claude via …** in a thread on web, desktop, or mobile. +Select a Codex or Claude model in the thread’s model picker on web, desktop, or mobile. +Remote routes appear as **Codex via [host]** or **Claude via [host]**. The host receives the model request, including its prompt and tool results. The agent runs tools and stores files and thread history on its executing environment. Choosing another host in Settings changes the same provider. Local inference is labeled **Claude** or **Codex**. -Choose the route again in Settings to refresh its model list after changing accounts. +Open the model picker or refresh provider status in Settings to update the model list. While a client is connected to the executing environment and other shared inference hosts, T3 discovers hosts that serve the same provider and saves them as fallback routes. If the selected host is unreachable, rejects authentication, or reaches a temporary limit, a new @@ -73,11 +82,11 @@ requests across eligible accounts, or leave it off to use the first available ac Session affinity keeps a conversation on its credential while available. The model picker always shows normal Claude and Codex models. Traex remains a separate backend. -Routing is optional. Turn off **Use CLI proxy** to return to this provider's normal +Routing is optional. Turn off **Inference routing** to return to this provider's normal T3 Code configuration. Standalone CLI configuration is unchanged. After an upgrade, threads, scheduled tasks, and saved model choices that named an older route or account pool use the normal Claude or Codex provider. They run through the proxy -only when **Use CLI proxy** is on for that provider. +only when **Inference routing** is on for that provider. Remove a provider login on its host, revoke one consuming environment, or turn off sharing to revoke all remote grants. Remove the route in **Inference accounts** on the executing machine. Stopping hosting keeps the host's accounts diff --git a/docs/user/providers-codex.md b/docs/user/providers-codex.md index d29877ea606d2..a85b94988ea83 100644 --- a/docs/user/providers-codex.md +++ b/docs/user/providers-codex.md @@ -72,7 +72,7 @@ image appears in the thread. ## Use multiple accounts -Add accounts on the inference host, then turn on **Use CLI proxy** for Codex on each environment that needs them. Threads keep using the normal Codex provider and model names. While the proxy is on, other Codex accounts on that environment are hidden; turn it off to use an individual CLI login again. [Host and share inference accounts](./providers-claude.md#host-and-share-inference-accounts) +Add accounts on the inference host, then turn on **Inference routing** for Codex on each environment that needs them. Threads keep using the normal Codex provider and model names. While the proxy is on, other Codex accounts on that environment are hidden; turn it off to use an individual CLI login again. [Host and share inference accounts](./providers-claude.md#host-and-share-inference-accounts) ## Answer questions while Codex works diff --git a/docs/user/providers-opencode.md b/docs/user/providers-opencode.md index bb86a0f625e9d..10bcef50f3127 100644 --- a/docs/user/providers-opencode.md +++ b/docs/user/providers-opencode.md @@ -79,7 +79,7 @@ can also return HTTP 429. OpenCode handles those retries itself. OpenCode can use the accounts on an [inference host](./providers-claude.md), next to its own logins. In **Settings > Inference accounts**, choose **OpenCode** beside the -host, or turn on **Use CLI proxy** in OpenCode's provider settings. The host's models +host, or turn on **Inference routing** in OpenCode's provider settings. The host's models then appear in the model picker under **T3 inference**. OpenCode and [Pi](./providers-pi.md#shared-inference-accounts) can run every model the host has diff --git a/docs/user/providers-pi.md b/docs/user/providers-pi.md index d2153b61dc1e4..9aed1a7e35bc8 100644 --- a/docs/user/providers-pi.md +++ b/docs/user/providers-pi.md @@ -37,7 +37,7 @@ update it through that manager instead. For example, a Nix profile installation Pi 1.4.0 or newer can use accounts on an [inference host](./providers-claude.md#host-and-share-inference-accounts) alongside its own logins. In **Settings > Inference accounts**, choose **Pi** beside the host, -or turn on **Use CLI proxy** in Pi's provider settings. Pi can use every model the host serves, +or turn on **Inference routing** in Pi's provider settings. Pi can use every model the host serves, including models from accounts other than Claude and Codex. Choose a `t3proxy/` model to send its requests through the host. Pi's native models, @@ -45,7 +45,7 @@ logins, extensions, and configuration remain available. Tools, files, and thread the environment running Pi; the host manages the accounts used for the model requests. Choose the route again in Settings to refresh the model list after changing the host's accounts. -Turn off **Use CLI proxy** to stop adding the host's models to Pi. +Turn off **Inference routing** to stop adding the host's models to Pi. In a terminal opened for the routed Pi provider in T3 Code, load the host's models with: diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index 429aa65cea180..ad5ed8e14b98e 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -18,7 +18,11 @@ import { AuthSourceControlWriteScope, ThreadId, EnvironmentId, + InferenceProxyError, + isInferenceProviderConfig, ORCHESTRATION_V2_WS_METHODS, + ProjectId, + ProviderInstanceId, ScheduledTaskId, WS_METHODS, type AuthSessionState, @@ -118,14 +122,16 @@ describe("command permissions", () => { }), ); it.effect.each([ - { via: "the connected SSH host", ssh: true, fallback: false }, + { via: "the connected SSH host", ssh: true, mode: "explicit" }, { via: "the grant when this client reaches the host over loopback", ssh: false, - fallback: false, + mode: "explicit", }, - { via: "a connected SSH fallback", ssh: true, fallback: true }, - ])("routes through $via without forwarding the client's bearer credential", ({ ssh, fallback }) => + { via: "a connected SSH fallback", ssh: true, mode: "fallback" }, + { via: "a paired host discovered at first enable", ssh: true, mode: "discovery" }, + { via: "a revoked host discovered at first enable", ssh: true, mode: "revoked" }, + ])("handles $via without forwarding the client's bearer credential", ({ ssh, mode }) => Effect.gen(function* () { const registry = yield* setup; registry.mount(sessions(other)); @@ -158,6 +164,20 @@ describe("command permissions", () => { let selected: InferenceRouteInput | undefined; let automaticGrant: boolean | undefined; let selectedMethod: string | undefined; + const discovery = mode === "discovery" || mode === "revoked"; + const fallback = mode === "fallback"; + const checkedHosts: EnvironmentId[] = []; + const hostStatus = { + running: true, + enabled: true, + sharing: true, + version: "8.0.76", + problem: null, + accounts: [], + availableDrivers: ["codex"], + consumers: [], + routes: [], + } as const; const host = { target, prepared: yield* SubscriptionRef.make( @@ -173,9 +193,15 @@ describe("command permissions", () => { session: yield* SubscriptionRef.make( Option.some({ client: { + [WS_METHODS.inferenceStatus]: () => { + checkedHosts.push(env); + return Effect.succeed(hostStatus); + }, [WS_METHODS.inferenceGrant]: (input: { automatic?: boolean }) => { automaticGrant = input.automatic; - return Effect.succeed(issued); + return mode === "revoked" && input.automatic + ? Effect.fail(new InferenceProxyError({ message: "Sharing was revoked." })) + : Effect.succeed(issued); }, }, } as unknown as RpcSession), @@ -190,6 +216,14 @@ describe("command permissions", () => { session: yield* SubscriptionRef.make( Option.some({ client: { + [WS_METHODS.inferenceStatus]: () => { + checkedHosts.push(other); + return Effect.succeed({ + ...hostStatus, + sharing: false, + availableDrivers: ["claudeAgent"], + }); + }, [WS_METHODS.inferenceConnect]: (input: InferenceRouteInput) => Effect.sync(() => { selected = input; @@ -223,17 +257,45 @@ describe("command permissions", () => { Effect.provideService(effect, EnvironmentSupervisor, id === env ? host : consumer), }), ); - const { routeInference } = createInferenceProxyAtoms(routeRuntime); - const result = yield* Effect.promise(() => - routeInference.run(registry, { - host: { environmentId: env, label: "Host" }, - consumer: { environmentId: other, label: "Consumer" }, - driver: "codex", - fallback, - }), - ); + const { routeInference, enableInferenceRouting } = createInferenceProxyAtoms(routeRuntime); + const hostIdentity = { environmentId: env, label: "Host" }; + const consumerIdentity = { environmentId: other, label: "Consumer" }; + const serverConfig = { + environment: { capabilities: { inferenceProxy: true } }, + } as InferenceFleetEnvironment["serverConfig"]; + const result = discovery + ? yield* Effect.promise(() => + enableInferenceRouting.run(registry, { + consumer: consumerIdentity, + driver: "codex", + environments: [ + { ...hostIdentity, connection: { phase: "offline" }, serverConfig }, + { ...hostIdentity, connection: { phase: "connected" }, serverConfig }, + { ...consumerIdentity, connection: { phase: "connected" }, serverConfig }, + ], + }), + ) + : yield* Effect.promise(() => + routeInference.run(registry, { + host: hostIdentity, + consumer: consumerIdentity, + driver: "codex", + fallback, + }), + ); + expect(automaticGrant).toBe(fallback || discovery || undefined); + expect(checkedHosts).toEqual(discovery ? [other, env] : []); + if (mode === "revoked") { + expect(result._tag).toBe("Failure"); + if (result._tag === "Failure") + expect(Cause.squash(result.cause)).toMatchObject({ + message: expect.stringContaining("Sharing was revoked."), + }); + expect(selected).toBeUndefined(); + return; + } expect(result._tag).toBe("Success"); - expect(automaticGrant).toBe(fallback || undefined); + if (discovery && result._tag === "Success") expect(result.value).toEqual(hostIdentity); expect(selectedMethod).toBe( fallback ? WS_METHODS.inferenceRegisterFallback : WS_METHODS.inferenceConnect, ); @@ -295,6 +357,34 @@ describe("command permissions", () => { }, ]); expect(planInferenceFallbacks(host, { ...status, sharing: false }, [consumer])).toEqual([]); + const config = consumer.serverConfig!; + const instanceId = ProviderInstanceId.make("claudeAgent"); + const instance = config.settings.providerInstances[instanceId]!; + if (!isInferenceProviderConfig(instance.config)) throw new Error("Expected a configured route"); + const disabledSettings = { + ...config.settings, + projectSettingsOverrides: {}, + providerInstances: { + [instanceId]: { ...instance, config: { ...instance.config, enabled: false } }, + }, + }; + const disabled = { ...consumer, serverConfig: { ...config, settings: disabledSettings } }; + expect(planInferenceFallbacks(host, status, [disabled])).toEqual([]); + const enabledInProject = { + ...disabled, + serverConfig: { + ...config, + settings: { + ...disabledSettings, + projectSettingsOverrides: { + [ProjectId.make("inference-project")]: { + providerInstances: { [instanceId]: { enabled: true } }, + }, + }, + }, + }, + }; + expect(planInferenceFallbacks(host, status, [enabledInProject])).toHaveLength(1); expect( planInferenceFallbacks({ ...host, connection: { phase: "offline" } }, status, [consumer]), ).toEqual([]); diff --git a/packages/client-runtime/src/state/inferenceProxy.ts b/packages/client-runtime/src/state/inferenceProxy.ts index 18f1df840b5c8..580a018221e2a 100644 --- a/packages/client-runtime/src/state/inferenceProxy.ts +++ b/packages/client-runtime/src/state/inferenceProxy.ts @@ -1,15 +1,21 @@ import { defaultInstanceIdForDriver, INFERENCE_DRIVERS, + INFERENCE_HARNESSES, + InferenceProxyError, + inferenceRouteIssue, isInferenceProviderConfig, ProviderDriverKind, + type EnvironmentId, type InferenceConsumer, type InferenceDriver, type InferenceProxyStatus, WS_METHODS, } from "@t3tools/contracts"; +import { isProviderInstanceEnabledInAnyScope } from "@t3tools/shared/serverSettings"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; +import * as Result from "effect/Result"; import * as SubscriptionRef from "effect/SubscriptionRef"; import { EnvironmentSupervisor } from "../connection/supervisor.ts"; import { connectionRoutes } from "../connection/routes.ts"; @@ -31,6 +37,51 @@ export interface InferenceFleetEnvironment extends InferenceConsumer { readonly serverConfig: EnvironmentServerConfig | null; } +interface EnableInferenceRoutingInput { + readonly consumer: InferenceConsumer; + readonly driver: InferenceDriver; + readonly environments: ReadonlyArray; + readonly preferredHostId?: EnvironmentId; +} + +export function inferenceHostRoutingIssue( + status: InferenceProxyStatus | null, + input: { + readonly host: InferenceConsumer; + readonly consumer: InferenceConsumer; + readonly driver: InferenceDriver; + }, +): string | null { + const issue = inferenceRouteIssue( + status, + input.host.environmentId === input.consumer.environmentId, + ); + if (issue !== null) return issue; + return status?.availableDrivers.includes(input.driver) + ? null + : `This host has no available ${INFERENCE_HARNESSES[input.driver].label} accounts.`; +} + +export function inferenceHostCandidates( + environments: ReadonlyArray, + consumerId: EnvironmentId, + preferredHostId?: EnvironmentId, +): ReadonlyArray { + const priority = (id: EnvironmentId) => (id === preferredHostId ? 0 : id === consumerId ? 1 : 2); + return environments + .filter( + (environment) => + environment.connection.phase === "connected" && + environment.serverConfig?.environment.capabilities.inferenceProxy === true, + ) + .sort( + (left, right) => + priority(left.environmentId) - priority(right.environmentId) || + left.label.localeCompare(right.label) || + left.environmentId.localeCompare(right.environmentId), + ); +} + type InferenceAccount = InferenceProxyStatus["accounts"][number]; const accountAvailabilityLabels = { @@ -66,12 +117,10 @@ export function planInferenceFallbacks( if (host.environmentId !== consumer.environmentId && !status.sharing) return []; return INFERENCE_DRIVERS.flatMap((driver) => { if (!status.availableDrivers.includes(driver)) return []; - const instance = - config.settings.providerInstances[ - defaultInstanceIdForDriver(ProviderDriverKind.make(driver)) - ]; + const instanceId = defaultInstanceIdForDriver(ProviderDriverKind.make(driver)); + const instance = config.settings.providerInstances[instanceId]; const route = instance?.config; - return instance?.enabled !== false && + return isProviderInstanceEnabledInAnyScope(config.settings, instanceId) && isInferenceProviderConfig(route) && route.inferenceEnabled && route.inferenceHostId !== host.environmentId @@ -152,83 +201,136 @@ export function createInferenceProxyAtoms( runtime, WS_METHODS.inferenceRegisterFallback, ); + const routeThroughHost = Effect.fn("InferenceProxy.route")( + function* ( + input: { + host: InferenceConsumer; + consumer: InferenceConsumer; + driver: InferenceDriver; + fallback?: boolean; + automatic?: boolean; + }, + registry: AtomRegistry.AtomRegistry, + ) { + yield* (input.fallback ? fallbackPermission : consumerPermission).authorize( + registry, + input.consumer.environmentId, + ); + const connections = yield* EnvironmentRegistry; + const { grant, prepared } = yield* connections.run( + input.host.environmentId, + Effect.gen(function* () { + const grant = yield* requestGuarded(WS_METHODS.inferenceGrant, { + environmentId: input.consumer.environmentId, + label: input.consumer.label, + ...(input.fallback || input.automatic ? { automatic: true } : {}), + }); + const supervisor = yield* EnvironmentSupervisor; + return { grant, prepared: yield* SubscriptionRef.get(supervisor.prepared) }; + }), + ); + const entries = yield* SubscriptionRef.get(connections.entries); + const entry = entries.get(input.host.environmentId); + const active = Option.getOrUndefined(prepared); + const target = active?.target; + const profile = + entry && target?._tag === "SshConnectionTarget" + ? connectionRoutes(entry).find( + (route) => + route.target._tag === "SshConnectionTarget" && + route.target.connectionId === target.connectionId, + )?.profile + : undefined; + const ssh = + profile && Option.isSome(profile) && profile.value._tag === "SshConnectionProfile" + ? profile.value.target + : undefined; + // Without SSH, the consumer cannot reach this client's loopback address for the host. + const reachable = + ssh !== undefined || + !["127.0.0.1", "localhost", "[::1]"].includes( + URL.parse(active?.httpBaseUrl ?? "")?.hostname ?? "", + ); + const connection = + active && reachable ? { url: active.httpBaseUrl, ...(ssh ? { ssh } : {}) } : undefined; + if (!input.fallback) + registry.refresh(inferenceStatus({ environmentId: input.host.environmentId, input: {} })); + yield* connections.run( + input.consumer.environmentId, + requestGuarded( + input.fallback ? WS_METHODS.inferenceRegisterFallback : WS_METHODS.inferenceConnect, + { + grant, + driver: input.driver, + hostLabel: input.host.label, + ...(connection ? { connection } : {}), + }, + ), + ); + if (!input.fallback) + registry.refresh( + inferenceStatus({ environmentId: input.consumer.environmentId, input: {} }), + ); + }, + (effect, _input, registry) => + effect.pipe( + withEnvironmentRpcPermissions(runtime, registry), + Effect.withTracerEnabled(false), + ), + ); const routeInference = createRuntimeCommand(runtime, { label: "inference:route", - execute: Effect.fn("InferenceProxy.route")( - function* ( - input: { - host: InferenceConsumer; - consumer: InferenceConsumer; - driver: InferenceDriver; - fallback?: boolean; - }, - registry: AtomRegistry.AtomRegistry, - ) { - yield* (input.fallback ? fallbackPermission : consumerPermission).authorize( - registry, - input.consumer.environmentId, - ); + execute: ( + input: { + readonly host: InferenceConsumer; + readonly consumer: InferenceConsumer; + readonly driver: InferenceDriver; + readonly fallback?: boolean; + }, + registry, + ) => routeThroughHost(input, registry), + }); + const enableInferenceRouting = createRuntimeCommand(runtime, { + label: "inference:enable-routing", + concurrency: { + mode: "singleFlight", + key: (input: EnableInferenceRoutingInput) => + JSON.stringify([input.consumer.environmentId, input.driver]), + }, + execute: Effect.fn("InferenceProxy.enableRouting")( + function* (input: EnableInferenceRoutingInput, registry: AtomRegistry.AtomRegistry) { + yield* consumerPermission.authorize(registry, input.consumer.environmentId); const connections = yield* EnvironmentRegistry; - const { grant, prepared } = yield* connections.run( - input.host.environmentId, - Effect.gen(function* () { - const grant = yield* requestGuarded(WS_METHODS.inferenceGrant, { - environmentId: input.consumer.environmentId, - label: input.consumer.label, - ...(input.fallback ? { automatic: true } : {}), - }); - const supervisor = yield* EnvironmentSupervisor; - return { grant, prepared: yield* SubscriptionRef.get(supervisor.prepared) }; - }), - ); - const entries = yield* SubscriptionRef.get(connections.entries); - const entry = entries.get(input.host.environmentId); - const active = Option.getOrUndefined(prepared); - const target = active?.target; - const profile = - entry && target?._tag === "SshConnectionTarget" - ? connectionRoutes(entry).find( - (route) => - route.target._tag === "SshConnectionTarget" && - route.target.connectionId === target.connectionId, - )?.profile - : undefined; - const ssh = - profile && Option.isSome(profile) && profile.value._tag === "SshConnectionProfile" - ? profile.value.target - : undefined; - // Without SSH, the consumer cannot reach this client's loopback address for the host. - const reachable = - ssh !== undefined || - !["127.0.0.1", "localhost", "[::1]"].includes( - URL.parse(active?.httpBaseUrl ?? "")?.hostname ?? "", - ); - const connection = - active && reachable ? { url: active.httpBaseUrl, ...(ssh ? { ssh } : {}) } : undefined; - if (!input.fallback) - registry.refresh(inferenceStatus({ environmentId: input.host.environmentId, input: {} })); - yield* connections.run( + const candidates = inferenceHostCandidates( + input.environments, input.consumer.environmentId, - requestGuarded( - input.fallback ? WS_METHODS.inferenceRegisterFallback : WS_METHODS.inferenceConnect, - { - grant, - driver: input.driver, - hostLabel: input.host.label, - ...(connection ? { connection } : {}), - }, - ), + input.preferredHostId, ); - if (!input.fallback) - registry.refresh( - inferenceStatus({ environmentId: input.consumer.environmentId, input: {} }), + const problems: string[] = []; + for (const candidate of candidates) { + const { environmentId, label } = candidate; + const host = { environmentId, label }; + const result = yield* Effect.result( + Effect.gen(function* () { + yield* hostPermission.authorize(registry, environmentId); + const status = yield* connections.run( + environmentId, + requestGuarded(WS_METHODS.inferenceStatus, {}), + ); + const issue = inferenceHostRoutingIssue(status, { host, ...input }); + if (issue) return yield* new InferenceProxyError({ message: issue }); + yield* routeThroughHost({ ...input, host, automatic: true }, registry); + return host; + }), ); + if (Result.isSuccess(result)) return result.success; + problems.push(`${label}: ${result.failure.message}`); + } + return yield* new InferenceProxyError({ + message: problems.join(" ") || "Connect to an environment that hosts inference accounts.", + }); }, - (effect, _input, registry) => - effect.pipe( - withEnvironmentRpcPermissions(runtime, registry), - Effect.withTracerEnabled(false), - ), + (effect, _input, registry) => withEnvironmentRpcPermissions(runtime, registry)(effect), ), }); return { @@ -236,6 +338,7 @@ export function createInferenceProxyAtoms( updates, manageInference, routeInference, + enableInferenceRouting, canGrant: hostPermission.permissionAtom, canConnect: consumerPermission.permissionAtom, canRegisterFallback: fallbackPermission.permissionAtom, diff --git a/packages/contracts/src/inferenceProxy.ts b/packages/contracts/src/inferenceProxy.ts index 30db397365c52..a7b467215970a 100644 --- a/packages/contracts/src/inferenceProxy.ts +++ b/packages/contracts/src/inferenceProxy.ts @@ -132,6 +132,7 @@ export const InferenceProxyAction = Schema.Union([ operation: Schema.Literal("configure"), enabled: Schema.Boolean, sharing: Schema.Boolean, + expectedEnabled: Schema.optionalKey(Schema.Boolean), }), Schema.Struct({ operation: Schema.Literal("signIn"), upstream: InferenceUpstream }), Schema.Struct({ diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts index 56934c29c0fab..405f0d0eec85a 100644 --- a/packages/shared/src/serverSettings.ts +++ b/packages/shared/src/serverSettings.ts @@ -45,6 +45,20 @@ const decodeServerObservabilitySettingsJson = Schema.decodeUnknownOption( ServerObservabilitySettingsJson, ); +export function isProviderInstanceEnabledInAnyScope( + settings: Pick, + instanceId: ProviderInstanceId, +): boolean { + const instance = settings.providerInstances[instanceId]; + return ( + instance !== undefined && + (resolveProviderInstanceEnabled(instance) || + Object.values(settings.projectSettingsOverrides).some( + (project) => project?.providerInstances?.[instanceId]?.enabled === true, + )) + ); +} + export function isModelSelectionProviderEnabled( settings: ServerSettings, selection: ModelSelection, diff --git a/scripts/scenarios/inference-routing-discovers-hosted-models.e2e.ts b/scripts/scenarios/inference-routing-discovers-hosted-models.e2e.ts new file mode 100644 index 0000000000000..ce5396128b0c9 --- /dev/null +++ b/scripts/scenarios/inference-routing-discovers-hosted-models.e2e.ts @@ -0,0 +1,149 @@ +// @effect-diagnostics nodeBuiltinImport:off - prepares an isolated server and fake CLI binaries. +import * as NodeFSP from "node:fs/promises"; +import * as NodePath from "node:path"; +import * as NodeURL from "node:url"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; + +import { APP_DIR } from "../e2e.config.ts"; +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { environmentId, runPromise, test, WEB } from "./t3.ts"; + +const fakeProxy = `#!/usr/bin/env node +const { createServer } = require("node:http"); +const { readFileSync } = require("node:fs"); +const config = JSON.parse(readFileSync(process.argv[process.argv.indexOf("-config") + 1], "utf8")); +createServer((request, response) => { + const { url, headers, method } = request; + const key = url === "/v0/management/auth-files" + ? config.management["secret-key"] + : config.access["api-keys"][0]; + let body; + if (method === "GET" && headers.authorization === "Bearer " + key) { + if (url === "/v0/management/auth-files") + body = { files: [{ name: "codex-fixture@example.invalid.json", provider: "codex", status: "active" }] }; + else if (url === "/v1/models") + body = { data: JSON.parse(readFileSync("./scenario-models.json", "utf8")).map((id) => ({ id, owned_by: "openai" })) }; + } + response.writeHead(body ? 200 : 404, { "content-type": "application/json" }); + response.end(JSON.stringify(body ?? {})); +}).listen(config.server.port, "127.0.0.1"); +`; + +const fakeCodex = `#!/usr/bin/env node +if (process.argv.includes("--version")) { + console.log("codex-cli 0.167.0"); + process.exit(0); +} +const replies = { + initialize: { userAgent: "codex-cli/0.167.0", codexHome: process.env.CODEX_HOME, platformFamily: "unix", platformOs: process.platform }, + "account/read": { account: null, requiresOpenaiAuth: false }, + "config/read": { config: {}, origins: {}, layers: null }, + "model/list": { data: [], nextCursor: null }, + "skills/list": { data: [] }, +}; +require("node:readline").createInterface({ input: process.stdin }).on("line", (line) => { + const { id, method } = JSON.parse(line); + if (id !== undefined) console.log(JSON.stringify(replies[method] + ? { id, result: replies[method] } + : { id, error: { code: -32601, message: "Fixture does not execute turns." } })); +}); +`; + +const loopbackFetch = ` +const fetchLoopback = globalThis.fetch; +globalThis.fetch = (input, init) => { + const url = new URL(input instanceof Request ? input.url : input); + if (!["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)) + return Promise.reject(new Error("Scenario fixture allows loopback requests only.")); + return fetchLoopback(input, init); +}; +`; + +const modelsFile = NodePath.join(SECOND_HOME, "userdata/inference-proxy/scenario-models.json"); +const sol = "gpt-6.2-sol"; +const astra = "gpt-6.2-astra"; + +async function prepare(home: string) { + const [platform, architecture] = await runPromise( + Effect.all([HostProcess.Platform, HostProcess.Architecture]), + ); + const installer = await NodeFSP.readFile( + NodePath.join(APP_DIR, "apps/server/src/inference/install.ts"), + "utf8", + ); + const version = /^export const proxyVersion = "(\d+\.\d+\.\d+)";$/m.exec(installer)?.[1]; + if (!version) throw new Error("The fixture could not find the pinned proxy version."); + const runtime = NodePath.join( + home, + "userdata/inference-proxy/runtime", + `${version}-${platform}-${architecture}`, + ); + const codex = NodePath.join(home, "bin/codex-fixture"); + const settings = NodePath.join(home, "userdata/settings.json"); + const offlineModule = NodePath.join(home, "loopback-fetch.mjs"); + + await NodeFSP.mkdir(runtime, { recursive: true }); + await NodeFSP.writeFile( + NodePath.join(home, "package.json"), + JSON.stringify({ type: "commonjs" }), + ); + await NodeFSP.writeFile(NodePath.join(runtime, "cli-proxy-api"), fakeProxy, { mode: 0o755 }); + await NodeFSP.writeFile(codex, fakeCodex, { mode: 0o755 }); + await NodeFSP.writeFile(offlineModule, loopbackFetch); + await NodeFSP.writeFile(modelsFile, JSON.stringify([sol])); + const config: { + enableProviderUpdateChecks: boolean; + providerInstances: { codex: { config: { binaryPath: string } } }; + } = JSON.parse(await NodeFSP.readFile(settings, "utf8")); + config.enableProviderUpdateChecks = false; + config.providerInstances.codex.config.binaryPath = codex; + await NodeFSP.writeFile(settings, JSON.stringify(config)); + + return { + HOME: home, + USERPROFILE: home, + CODEX_HOME: NodePath.join(home, "codex"), + CLAUDE_CONFIG_DIR: NodePath.join(home, "claude"), + NODE_OPTIONS: `--import=${NodeURL.pathToFileURL(offlineModule).href}`, + }; +} + +test( + "The Codex switch connects to a hosted catalog and provider refresh adds newly advertised models", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("demo"); + const server = startSecondServer(app.baseUrl ?? "", prepare); + try { + const { host, token } = await server.ready; + const machine = `machine=${encodeURIComponent(await runPromise(environmentId(host)))}`; + await t3.open("/settings/connections"); + await screen.getByRole("button", "Add environment").tap(); + const dialog = screen.getByRole("dialog"); + await dialog.getByPlaceholder("backend.example.com").fill(host); + await dialog.getByPlaceholder("PAIRCODE").fill(token); + await dialog.getByRole("button", "Add environment").tap(); + await screen.getByRole("button", /^More actions for (?!this machine)/).waitFor(); + await app.open(`/settings/inference?${machine}`); + const hosting = screen.getByRole("switch", "Host inference accounts"); + await hosting.tap(); + await expect(hosting).toBeChecked(); + + await app.open(`/settings/providers?${machine}&instanceId=codex`); + const routing = screen.getByRole("switch", /^(Use CLI proxy|Inference routing)$/i); + await routing.tap(); + await expect(routing).toBeChecked(); + await expect(browser.locator(`[data-model-slug="${sol}"]`)).toBeVisible(); + + await NodeFSP.writeFile(modelsFile, JSON.stringify([sol, astra])); + await screen.getByRole("button", /refresh provider status|checked just now/i).tap(); + await expect(browser.locator(`[data-model-slug="${astra}"]`)).toBeVisible(); + await expect(browser.locator(`[data-model-slug="${sol}"]`)).toBeVisible(); + await app.screenshot("hosted-models-after-refresh"); + } finally { + await server.stop(); + } + }, +); diff --git a/scripts/scenarios/inference-routing-without-a-host.e2e.ts b/scripts/scenarios/inference-routing-without-a-host.e2e.ts new file mode 100644 index 0000000000000..b3d19158cae25 --- /dev/null +++ b/scripts/scenarios/inference-routing-without-a-host.e2e.ts @@ -0,0 +1,20 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "Enabling inference routing without a host explains how to set one up in Providers", + WEB, + async ({ t3, app, screen }) => { + await t3.project("demo"); + await t3.open("/settings/providers?instanceId=codex"); + const routing = screen.getByRole("switch", /^(Use CLI proxy|Inference routing)$/i); + await routing.tap(); + const setup = screen.getByRole("button", "Set up accounts here"); + await expect(setup).toBeVisible(); + await setup.tap(); + await app.screenshot("routing-needs-host"); + await expect(screen.getByRole("button", "Start hosting here")).toBeVisible(); + await expect(routing).not.toBeChecked(); + }, +); diff --git a/scripts/scenarios/second-server.ts b/scripts/scenarios/second-server.ts index 190cc800e2bca..44a1a1d346a97 100644 --- a/scripts/scenarios/second-server.ts +++ b/scripts/scenarios/second-server.ts @@ -21,12 +21,19 @@ export const SECOND_HOME = `${T3_HOME}-second-environment`; const runSecondServer = Effect.fn("scenario.secondServer")(function* ( devUrl: string, paired: (target: { readonly host: string; readonly token: string }) => void, + prepare?: (home: string) => Promise, ) { const path = yield* Path.Path; const node = yield* HostProcess.ExecutablePath; const hostEnvironment = yield* HostProcess.Environment; const port = yield* (yield* NetService.NetService).reserveLoopbackPort(); yield* prepareHome(SECOND_HOME); + const extraEnvironment = prepare + ? yield* Effect.tryPromise({ + try: () => prepare(SECOND_HOME), + catch: () => new ScenarioError({ message: "Could not prepare the second server fixture." }), + }) + : {}; const token = yield* Deferred.make(); const server = yield* start({ cwd: APP_DIR, @@ -47,6 +54,7 @@ const runSecondServer = Effect.fn("scenario.secondServer")(function* ( PATH: `${path.join(SECOND_HOME, "bin")}:${hostEnvironment.PATH ?? ""}`, HOME: hostEnvironment.HOME, T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0", + ...extraEnvironment, }, onLine: (line) => { const value = /^Token:\s*(\S+)/.exec(line)?.[1]; @@ -68,10 +76,13 @@ const runSecondServer = Effect.fn("scenario.secondServer")(function* ( }); /** Starts the second server for the web app at `devUrl`. `ready` settles with its pairing input. */ -export function startSecondServer(devUrl: string) { +export function startSecondServer( + devUrl: string, + prepare?: (home: string) => Promise, +) { const pairing = Promise.withResolvers<{ readonly host: string; readonly token: string }>(); const server = Effect.runFork( - runSecondServer(devUrl, pairing.resolve).pipe( + runSecondServer(devUrl, pairing.resolve, prepare).pipe( Effect.scoped, Effect.provide([NodeServices.layer, NetService.layer]), ), diff --git a/scripts/scenarios/t3.ts b/scripts/scenarios/t3.ts index 132322ef4f216..7ff732d883f6f 100644 --- a/scripts/scenarios/t3.ts +++ b/scripts/scenarios/t3.ts @@ -224,7 +224,7 @@ const readPairingPath = Effect.gen(function* () { }); /** The id every thread link starts with, asked of the server the app talks to. */ -const environmentId = (baseUrl: string) => +export const environmentId = (baseUrl: string) => HttpClient.get(`${baseUrl}/.well-known/t3/environment`).pipe( Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.flatMap( From f67cd6a966adee8e8034b4c4a8ba4567b0db5a24 Mon Sep 17 00:00:00 2001 From: Zack Jackson <25274700+ScriptedAlchemy@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:31:27 -0800 Subject: [PATCH 2/2] fix(inference): clear stale setup state and simplify route lookup --- .../features/settings/InferenceAccounts.tsx | 26 +++++----- apps/server/src/inference/InferenceProxy.ts | 47 +++++++++---------- apps/server/src/inference/routes.ts | 3 -- ...nstanceDialog.environment.browser.test.tsx | 21 +++++++-- .../settings/AddProviderInstanceDialog.tsx | 1 + ...SettingsPanel.environment.browser.test.tsx | 23 +++++++-- .../settings/ProviderSettingsPanel.tsx | 9 +++- .../settings/useEnableInferenceRouting.ts | 2 +- ...nce-routing-discovers-hosted-models.e2e.ts | 17 ++++--- 9 files changed, 93 insertions(+), 56 deletions(-) diff --git a/apps/mobile/src/features/settings/InferenceAccounts.tsx b/apps/mobile/src/features/settings/InferenceAccounts.tsx index e3afee28db0d1..7d3bbc5cf8a25 100644 --- a/apps/mobile/src/features/settings/InferenceAccounts.tsx +++ b/apps/mobile/src/features/settings/InferenceAccounts.tsx @@ -4,6 +4,7 @@ import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime" import { inferenceAccountRetryAfter, inferenceAccountStatus, + inferenceHostCandidates, inferenceHostRoutingIssue, } from "@t3tools/client-runtime/state/inference-proxy"; import { @@ -84,11 +85,13 @@ function ProviderRoutingSwitch({ provider, driver, onSetup, + onRouteChange, }: { environment: SettingsTarget; provider: ServerProvider; driver: InferenceDriver; onSetup: () => void; + onRouteChange: () => void; }) { const { environmentId } = environment; const { environments } = useEnvironments(); @@ -123,7 +126,9 @@ function ProviderRoutingSwitch({ : await manage({ environmentId, input: { operation: "removeRoute", instanceId } }); inFlight.current = false; setPending(false); - if (result._tag === "Failure") { + if (result._tag === "Success") { + onRouteChange(); + } else { const cause = squashAtomCommandFailure(result); setFailure({ target: value, @@ -241,8 +246,8 @@ function InferenceControls({ setPending(true); setNotice(""); const result = await command({ environmentId, input }); - setPending(false); if (result._tag === "Failure") { + setPending(false); setNotice(String(squashAtomCommandFailure(result))); return; } @@ -265,7 +270,8 @@ function InferenceControls({ setNotice("Waiting for the host to finish sign-in. Check status after a moment."); if ( setupDriver && - (result.value.status === "ok" || (input.operation === "configure" && input.enabled)) + (result.value.status === "ok" || + (input.operation === "configure" && input.enabled && input.expectedEnabled === false)) ) { const connected = await enableRouting({ consumer: { environmentId, label: environment.label }, @@ -279,6 +285,7 @@ function InferenceControls({ setNotice(failure instanceof Error ? failure.message : String(failure)); } } + setPending(false); return result.value; } const host = query.data; @@ -440,15 +447,9 @@ function InferenceControls({ onPress={() => void run({ operation: "removeRoute", instanceId: route.instanceId })} /> ))} - {environments - .filter( - (e) => - e.connection.phase === "connected" && - e.serverConfig?.environment.capabilities.inferenceProxy, - ) - .map((host) => ( - - ))} + {inferenceHostCandidates(environments, environmentId).map((host) => ( + + ))}
); } @@ -479,6 +480,7 @@ export function InferenceAccounts({ provider={provider} driver={driver} onSetup={() => setPanel(driver)} + onRouteChange={() => setPanel((current) => (current === driver ? null : current))} /> ); })} diff --git a/apps/server/src/inference/InferenceProxy.ts b/apps/server/src/inference/InferenceProxy.ts index 7963297a98760..d5184cf08c691 100644 --- a/apps/server/src/inference/InferenceProxy.ts +++ b/apps/server/src/inference/InferenceProxy.ts @@ -31,6 +31,7 @@ import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; import { NetService } from "@t3tools/shared/Net"; import { isProviderInstanceEnabledInAnyScope } from "@t3tools/shared/serverSettings"; import { readTailscaleServeRoutesTo } from "@t3tools/tailscale"; +import * as Arr from "effect/Array"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Cache from "effect/Cache"; import * as Digest from "effect/crypto/Digest"; @@ -1568,26 +1569,21 @@ const make = Effect.gen(function* () { return target ? [{ ...target, models: [] }] : null; } const current = yield* settings.getSettings; - const active = INFERENCE_DRIVERS.map((candidateDriver) => { + const active = Arr.findFirst(INFERENCE_DRIVERS, (candidateDriver) => { + if (driver !== undefined && candidateDriver !== driver) return Option.none(); const instanceId = defaultInstanceIdForDriver(ProviderDriverKind.make(candidateDriver)); - return { - driver: candidateDriver, - instanceId, - instance: current.providerInstances[instanceId], - }; - }).find( - ({ driver: candidateDriver, instanceId, instance }) => - (driver === undefined || candidateDriver === driver) && - instance !== undefined && - isProviderInstanceEnabledInAnyScope(current, instanceId) && - isInferenceProviderConfig(instance.config) && - instance.config.inferenceEnabled && - instance.config.inferenceHostId === hostId && - instance.config.inferenceKey === key, - ); - if (!active || !isInferenceProviderConfig(active.instance?.config)) return null; - const route = active.instance.config; - const pool = (yield* read).routePools?.find((entry) => entry.driver === active.driver); + const route = current.providerInstances[instanceId]?.config; + return isInferenceProviderConfig(route) && + route.inferenceEnabled && + route.inferenceHostId === hostId && + route.inferenceKey === key && + isProviderInstanceEnabledInAnyScope(current, instanceId) + ? Option.some({ driver: candidateDriver, route }) + : Option.none(); + }); + if (Option.isNone(active)) return null; + const { driver: activeDriver, route } = active.value; + const pool = (yield* read).routePools?.find((entry) => entry.driver === activeDriver); if (!pool || pool.primary.hostId !== hostId || pool.primary.key !== key) { const target = yield* authorize(key, hostId, driver); return target ? [{ ...target, models: route.inferenceModels }] : null; @@ -1597,17 +1593,18 @@ const make = Effect.gen(function* () { : includeAll ? [pool.primary, ...pool.alternates] : [pool.primary]; + if (matching.length === 0) return []; const candidates = yield* Effect.forEach( - matching.length ? matching : [pool.primary], - (candidate) => Cache.get(routeProbes, { candidate, driver: active.driver }), + matching, + (candidate) => Cache.get(routeProbes, { candidate, driver: activeDriver }), { concurrency: "unbounded" }, ); const now = yield* Clock.currentTimeMillis; const available = candidates.flatMap((candidate, index) => { if (!candidate) return []; - const host = (matching.length ? matching : [pool.primary])[index]!; + const host = matching[index]!; const models = candidate.models.filter( - (slug) => (routeFailures.get(`${active.driver}\0${host.hostId}\0${slug}`) ?? 0) <= now, + (slug) => (routeFailures.get(`${activeDriver}\0${host.hostId}\0${slug}`) ?? 0) <= now, ); return models.length && (model === undefined || models.includes(model)) ? [{ ...candidate, hostId: host.hostId, models }] @@ -2043,7 +2040,7 @@ const make = Effect.gen(function* () { ...(linked && connection ? { inferenceConnection: connection } : {}), }, }, - result: preserve, + result: alternates, }; }), ); @@ -2054,7 +2051,7 @@ const make = Effect.gen(function* () { { driver, primary: candidate, - alternates: updated.result ? (existing?.alternates ?? []) : [], + alternates: updated.result, }, ], }); diff --git a/apps/server/src/inference/routes.ts b/apps/server/src/inference/routes.ts index 0c1acd86171d1..16b163a6be9fc 100644 --- a/apps/server/src/inference/routes.ts +++ b/apps/server/src/inference/routes.ts @@ -2,7 +2,6 @@ import { EnvironmentId, InferenceDriver, INFERENCE_HARNESSES, - ProviderDriverKind, type CustomModelSetting, type ServerProviderModel, type SettingsSecretValue, @@ -307,9 +306,7 @@ export function routeProvider(driver: InferenceDriver, label: string | null, rou models: [...new Set(route.models.filter((id) => !isGptImageModel(id)))], }; return { - driver: ProviderDriverKind.make(driver), displayName: label === null ? name : `${name} via ${label}`, - enabled: true, config: harness.config(chatRoute), environment: harness.environment(chatRoute), }; diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx index ac731bea154c2..f87b923e3b994 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx @@ -1,5 +1,6 @@ import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "@t3tools/contracts"; import { Atom, AsyncResult } from "effect/reactivity"; +import * as Cause from "effect/Cause"; import { userEvent } from "vite-plus/test/browser"; import { describe, expect, it, vi } from "vite-plus/test"; @@ -211,9 +212,11 @@ describe("AddProviderInstanceDialog environment routing", () => { it("routes the default provider and opens the selected host's accounts before settings update", async () => { setup(); actions.supportsInference = true; - actions.enableInference.mockResolvedValue( - AsyncResult.success({ environmentId: EnvironmentId.make("studio"), label: "Studio" }), - ); + actions.enableInference + .mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("No Codex accounts.")))) + .mockResolvedValueOnce( + AsyncResult.success({ environmentId: EnvironmentId.make("studio"), label: "Studio" }), + ); await using _screen = await render(dialog()); await choose("Codex"); await click("Next"); @@ -224,6 +227,18 @@ describe("AddProviderInstanceDialog environment routing", () => { driver: "codex", environments: expect.any(Array), }); + expect(queryButton("Set up accounts here")).toBeDefined(); + await click("Back"); + await choose("Claude"); + await click("Next"); + await choose("Use inference accounts"); + expect(queryButton("Set up accounts here")).toBeUndefined(); + await click("Continue"); + expect(actions.enableInference).toHaveBeenLastCalledWith({ + consumer: { environmentId: remoteEnvironmentId, label: "Remote device" }, + driver: "claudeAgent", + environments: expect.any(Array), + }); expect(document.body.textContent).toContain("Using Studio for inference."); expect(settingsHooks.mutate).not.toHaveBeenCalled(); }); diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx index 5ecb1d8fd9352..76c0cf92d2235 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx @@ -356,6 +356,7 @@ export function AddProviderInstanceDialog({ }; const selectProvider = (value: string) => { setLocalSetup(false); + inference.clearError(); setSelection(value); setIsManualAcpConfiguration(false); setHasAttemptedSubmit(false); diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx index 22bec7c7e8138..c0d6e0c589986 100644 --- a/apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx +++ b/apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx @@ -328,11 +328,28 @@ describe("EnvironmentProviderSettings routing", () => { .element(screen.getByRole("status")) .toHaveTextContent("No connected inference host."); await userEvent.click(screen.getByRole("button", { name: "Set up accounts here" })); - await expect - .element(screen.getByText("Connect to Remote device to manage its accounts")) - .toBeVisible(); + const localSetup = screen.getByText("Connect to Remote device to manage its accounts"); + await expect.element(localSetup).toBeVisible(); await expect.element(proxySwitch).toBeEnabled(); await expect.element(proxySwitch).not.toBeChecked(); + + await userEvent.click(proxySwitch); + state.settings = { + ...DEFAULT_UNIFIED_SETTINGS, + providerInstances: { + [codexId]: { + driver: ProviderDriverKind.make("codex"), + config: { inferenceEnabled: true, inferenceHostId: environmentId }, + }, + }, + }; + await screen.rerender(panel({ targetInstanceId: codexId })); + await expect.element(proxySwitch).toBeChecked(); + await userEvent.click(proxySwitch); + state.settings = DEFAULT_UNIFIED_SETTINGS; + await screen.rerender(panel({ targetInstanceId: codexId })); + await expect.element(proxySwitch).not.toBeChecked(); + await expect.element(localSetup).not.toBeInTheDocument(); }); it.each(["codex", "opencode", "pi"] as const)( diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsx index ba9b317f8d975..b09f1fa83b9ea 100644 --- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx @@ -1598,6 +1598,9 @@ function InferenceProxySetting({ environmentLabel, ); const usingProxy = accountHostId !== null; + async function enable(preferredHostId?: EnvironmentId) { + if (await run(driver, preferredHostId)) setLocalSetup(false); + } const host = accountHostId === environmentId ? environmentLabel : route?.inferenceHostLabel; const accountBehavior = !INFERENCE_HARNESSES[driver].replacesAccounts ? "Its own logins keep working." @@ -1646,7 +1649,7 @@ function InferenceProxySetting({ disabled={disabled || !canConnect || pending || disabling} onCheckedChange={async (enabled) => { if (enabled) { - await run(driver, route?.inferenceHostId); + await enable(route?.inferenceHostId); return; } setDisabling(true); @@ -1659,6 +1662,8 @@ function InferenceProxySetting({ if (result._tag === "Failure") { const failure = squashAtomCommandFailure(result); setDisableError(failure instanceof Error ? failure.message : String(failure)); + } else { + setLocalSetup(false); } }} /> @@ -1670,7 +1675,7 @@ function InferenceProxySetting({ driver={driver} hostLabel={environmentLabel} enableLocalHosting - onAccountsChanged={() => void run(driver, environmentId)} + onAccountsChanged={() => void enable(environmentId)} /> )} diff --git a/apps/web/src/components/settings/useEnableInferenceRouting.ts b/apps/web/src/components/settings/useEnableInferenceRouting.ts index 850cd3edac01e..29f33690667d1 100644 --- a/apps/web/src/components/settings/useEnableInferenceRouting.ts +++ b/apps/web/src/components/settings/useEnableInferenceRouting.ts @@ -39,5 +39,5 @@ export function useEnableInferenceRouting(environmentId: EnvironmentId, environm return null; } - return { canConnect, pending, error, run }; + return { canConnect, pending, error, run, clearError: () => setError(null) }; } diff --git a/scripts/scenarios/inference-routing-discovers-hosted-models.e2e.ts b/scripts/scenarios/inference-routing-discovers-hosted-models.e2e.ts index ce5396128b0c9..e432a53dad100 100644 --- a/scripts/scenarios/inference-routing-discovers-hosted-models.e2e.ts +++ b/scripts/scenarios/inference-routing-discovers-hosted-models.e2e.ts @@ -32,10 +32,7 @@ createServer((request, response) => { `; const fakeCodex = `#!/usr/bin/env node -if (process.argv.includes("--version")) { - console.log("codex-cli 0.167.0"); - process.exit(0); -} +if (!process.argv.includes("app-server")) process.exit(1); const replies = { initialize: { userAgent: "codex-cli/0.167.0", codexHome: process.env.CODEX_HOME, platformFamily: "unix", platformOs: process.platform }, "account/read": { account: null, requiresOpenaiAuth: false }, @@ -135,12 +132,18 @@ test( const routing = screen.getByRole("switch", /^(Use CLI proxy|Inference routing)$/i); await routing.tap(); await expect(routing).toBeChecked(); - await expect(browser.locator(`[data-model-slug="${sol}"]`)).toBeVisible(); + const details = browser.locator("[data-provider-detail]"); + const solRow = browser.locator(`[data-model-slug="${sol}"]`); + const astraRow = browser.locator(`[data-model-slug="${astra}"]`); + await expect(details.getByText("v0.167.0", { exact: true })).toBeVisible(); + await expect(details.getByText("Available", { exact: true })).toBeVisible(); + await expect(solRow).toBeVisible(); await NodeFSP.writeFile(modelsFile, JSON.stringify([sol, astra])); await screen.getByRole("button", /refresh provider status|checked just now/i).tap(); - await expect(browser.locator(`[data-model-slug="${astra}"]`)).toBeVisible(); - await expect(browser.locator(`[data-model-slug="${sol}"]`)).toBeVisible(); + await expect(astraRow).toBeVisible(); + await expect(solRow).toBeVisible(); + await astraRow.scrollIntoView(); await app.screenshot("hosted-models-after-refresh"); } finally { await server.stop();