Skip to content

Commit e895512

Browse files
fix(inference): preserve active sessions and routing state
1 parent 99252fb commit e895512

31 files changed

Lines changed: 877 additions & 216 deletions

‎apps/mobile/src/features/settings/InferenceAccounts.tsx‎

Lines changed: 66 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,16 @@ import {
1515
inferenceHarness,
1616
isCustomInferenceBackend,
1717
isInferenceProviderConfig,
18+
isInferenceRoutingEnabled,
1819
isManagedSettingPath,
20+
ProviderDriverKind,
1921
type InferenceProxyStatus,
2022
type ServerProvider,
2123
type InferenceDriver,
2224
type InferenceProxyAction,
2325
type InferenceUpstream,
2426
} from "@t3tools/contracts";
25-
import { useRef, useState } from "react";
27+
import { useEffect, useRef, useState } from "react";
2628
import { Linking, TextInput, View } from "react-native";
2729

2830
import { AppText } from "../../components/ui/AppText";
@@ -105,11 +107,11 @@ function ProviderRoutingSwitch({
105107
const { instanceId } = provider;
106108
const config = environment.serverConfig.settings.providerInstances[instanceId]?.config;
107109
const route = isInferenceProviderConfig(config) ? config : null;
108-
const enabled = route?.inferenceEnabled === true;
110+
const enabled = isInferenceRoutingEnabled(config);
109111
const error = failure && failure.target !== enabled ? failure.message : "";
110112
const locked = isManagedSettingPath(
111113
environment.serverConfig.managedPolicy,
112-
`providerInstances.${instanceId}`,
114+
`providerInstances.${instanceId}.config.inferenceEnabled`,
113115
);
114116
async function change(value: boolean) {
115117
if (inFlight.current) return;
@@ -121,7 +123,9 @@ function ProviderRoutingSwitch({
121123
consumer: { environmentId, label: environment.label },
122124
environments,
123125
driver,
124-
...(route ? { preferredHostId: route.inferenceHostId } : {}),
126+
...(route
127+
? { preferredHostId: route.inferenceHostId, preserveProviderEnabled: true }
128+
: {}),
125129
})
126130
: await manage({ environmentId, input: { operation: "removeRoute", instanceId } });
127131
inFlight.current = false;
@@ -143,7 +147,9 @@ function ProviderRoutingSwitch({
143147
subtitle={
144148
error ||
145149
(enabled
146-
? `Using accounts on ${route.inferenceHostLabel || environment.label}.`
150+
? route
151+
? `Using accounts on ${route.inferenceHostLabel || environment.label}.`
152+
: "This inference route is incomplete. Turn it off to use the native provider."
147153
: "Use accounts on this environment or a paired inference host.")
148154
}
149155
value={enabled}
@@ -225,10 +231,12 @@ function InferenceControls({
225231
environment,
226232
setupDriver,
227233
onConnected,
234+
onOpenHostingSettings,
228235
}: {
229236
environment: SettingsTarget;
230237
setupDriver: InferenceDriver | null;
231238
onConnected: () => void;
239+
onOpenHostingSettings: () => void;
232240
}) {
233241
const { environmentId } = environment;
234242
const { environments } = useEnvironments();
@@ -242,10 +250,21 @@ function InferenceControls({
242250
const [login, setLogin] = useState<{ url: string; state: string } | null>(null);
243251
const [callback, setCallback] = useState("");
244252
const [notice, setNotice] = useState("");
253+
const accountSetup = useRef({ active: false });
254+
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- prevents an account operation from routing after its setup panel closes
255+
useEffect(() => {
256+
const setup = { active: true };
257+
accountSetup.current = setup;
258+
return () => {
259+
setup.active = false;
260+
};
261+
}, []);
245262
async function run(input: InferenceProxyAction) {
263+
const setup = accountSetup.current;
246264
setPending(true);
247265
setNotice("");
248266
const result = await command({ environmentId, input });
267+
if (!setup.active) return;
249268
if (result._tag === "Failure") {
250269
setPending(false);
251270
setNotice(String(squashAtomCommandFailure(result)));
@@ -273,12 +292,19 @@ function InferenceControls({
273292
(result.value.status === "ok" ||
274293
(input.operation === "configure" && input.enabled && input.expectedEnabled === false))
275294
) {
295+
const instanceId = defaultInstanceIdForDriver(ProviderDriverKind.make(setupDriver));
276296
const connected = await enableRouting({
277297
consumer: { environmentId, label: environment.label },
278298
environments,
279299
driver: setupDriver,
280-
preferredHostId: environmentId,
300+
onlyHostId: environmentId,
301+
...(isInferenceProviderConfig(
302+
environment.serverConfig.settings.providerInstances[instanceId]?.config,
303+
)
304+
? { preserveProviderEnabled: true }
305+
: {}),
281306
});
307+
if (!setup.active) return;
282308
if (connected._tag === "Success") onConnected();
283309
else {
284310
const failure = squashAtomCommandFailure(connected);
@@ -296,29 +322,42 @@ function InferenceControls({
296322
);
297323
const available = updateQuery.data?.update?.available;
298324
const disabled = pending || !permitted;
325+
const requiresHostingSettings =
326+
setupDriver !== null &&
327+
host?.enabled === false &&
328+
environment.serverConfig.environment.capabilities.inferenceConfigureGuard !== true;
299329
return (
300330
<View className="gap-1">
301331
{host ? (
302332
<>
303-
<SettingsSwitchRow
304-
label="Host accounts here"
305-
subtitle={
306-
host.problem ??
307-
(host.running
308-
? `CLIProxyAPI ${host.version} is running.`
309-
: `Enable to install and start CLIProxyAPI ${host.version}.`)
310-
}
311-
disabled={disabled}
312-
value={host.enabled}
313-
onValueChange={(enabled) =>
314-
void run({
315-
operation: "configure",
316-
enabled,
317-
sharing: false,
318-
expectedEnabled: host.enabled,
319-
})
320-
}
321-
/>
333+
{requiresHostingSettings ? (
334+
<ListActionRow
335+
label="Manage inference hosting"
336+
description="Start hosting in Inference accounts, then turn on routing."
337+
disabled={disabled}
338+
onPress={onOpenHostingSettings}
339+
/>
340+
) : (
341+
<SettingsSwitchRow
342+
label="Host accounts here"
343+
subtitle={
344+
host.problem ??
345+
(host.running
346+
? `CLIProxyAPI ${host.version} is running.`
347+
: `Enable to install and start CLIProxyAPI ${host.version}.`)
348+
}
349+
disabled={disabled}
350+
value={host.enabled}
351+
onValueChange={(enabled) =>
352+
void run({
353+
operation: "configure",
354+
enabled,
355+
sharing: false,
356+
expectedEnabled: host.enabled,
357+
})
358+
}
359+
/>
360+
)}
322361
{host.enabled && (
323362
<>
324363
<ListActionRow
@@ -498,7 +537,8 @@ export function InferenceAccounts({
498537
key={panel}
499538
environment={environment}
500539
setupDriver={panel === "all" ? null : panel}
501-
onConnected={() => setPanel(null)}
540+
onConnected={() => setPanel((current) => (current === panel ? null : current))}
541+
onOpenHostingSettings={() => setPanel("all")}
502542
/>
503543
)}
504544
</>

‎apps/server/src/environment/ServerEnvironment.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("ServerEnvironmen
288288
expect(second.capabilities.requiredWorktreeBootstrap).toBe(true);
289289
expect(second.capabilities.usagePriceOverrides).toBe(true);
290290
expect(second.capabilities.inferenceProxy).toBe(true);
291+
expect(second.capabilities.inferenceConfigureGuard).toBe(true);
292+
expect(second.capabilities.inferenceRoutePreservesEnablement).toBe(true);
291293
expect(second.capabilities.threadActiveReorder).toBe(true);
292294
expect(second.capabilities.threadTitleRegeneration).toBe(true);
293295
expect(second.capabilities.threadPullRequests).toBe(true);

‎apps/server/src/environment/ServerEnvironment.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,8 @@ export const make = Effect.gen(function* () {
274274
usagePriceOverrides: true,
275275
usageModelAliases: true,
276276
inferenceProxy: true,
277+
inferenceConfigureGuard: true,
278+
inferenceRoutePreservesEnablement: true,
277279
threadPinning: true,
278280
threadPinReorder: true,
279281
threadActiveReorder: true,

‎apps/server/src/inference/InferenceProxy.test.ts‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -574,6 +574,21 @@ it.effect(
574574
operation: "removeRoute",
575575
instanceId: ProviderInstanceId.make(route.driver),
576576
});
577+
const incomplete = ProviderInstanceId.make("claudeAgent");
578+
yield* settings.updateProviderInstance({
579+
operation: "upsert",
580+
instanceId: incomplete,
581+
instance: {
582+
driver: ProviderDriverKind.make("claudeAgent"),
583+
enabled: false,
584+
config: { inferenceEnabled: true },
585+
},
586+
});
587+
yield* proxy.manage({ operation: "removeRoute", instanceId: incomplete });
588+
expect((yield* settings.getSettings).providerInstances[incomplete]).toMatchObject({
589+
enabled: false,
590+
config: { inferenceEnabled: false },
591+
});
577592
const startSharing = proxy.manage({
578593
operation: "configure",
579594
enabled: true,
@@ -1447,7 +1462,7 @@ it.effect(
14471462
return Effect.succeed({
14481463
instance: {
14491464
...instance,
1450-
...(enabled ? { enabled: true } : {}),
1465+
enabled,
14511466
config: { ...instance.config, enabled },
14521467
},
14531468
result: undefined,
@@ -1457,6 +1472,9 @@ it.effect(
14571472
expect(yield* proxy.hasFallback(issued.key, hostId, "codex")).toBe(false);
14581473
expect(yield* proxy.routeCandidates(issued.key, hostId, "codex")).toBeNull();
14591474
expect(yield* proxy.authorize(issued.key, hostId, "codex")).toBeNull();
1475+
expect((yield* proxy.status).routes.map((route) => route.instanceId)).not.toContain(
1476+
ProviderInstanceId.make("codex"),
1477+
);
14601478
const inferenceProject = ProjectId.make("inference-project");
14611479
const codexId = ProviderInstanceId.make("codex");
14621480
yield* settings.updateSettings({
@@ -1467,6 +1485,9 @@ it.effect(
14671485
expect(yield* proxy.hasFallback(issued.key, hostId, "codex")).toBe(true);
14681486
expect(yield* proxy.routeCandidates(issued.key, hostId, "codex")).toHaveLength(1);
14691487
expect(yield* proxy.authorize(issued.key, hostId, "codex")).not.toBeNull();
1488+
expect((yield* proxy.status).routes.map((route) => route.instanceId)).toContain(
1489+
codexId,
1490+
);
14701491
const oldCatalog = catalog;
14711492
catalog = [...catalog, { id: "gpt-project-catalog-refresh", owned_by: "openai" }];
14721493
yield* proxy.refreshModelCatalog(true);
@@ -1487,6 +1508,11 @@ it.effect(
14871508
});
14881509
expect(yield* proxy.routeCandidates(issued.key, hostId, "codex")).toBeNull();
14891510
expect(yield* proxy.authorize(issued.key, hostId, "codex")).toBeNull();
1511+
yield* proxy.connect({ ...connect, grant: issued, preserveProviderEnabled: true });
1512+
const resumed = (yield* settings.getSettings).providerInstances[codexId]!;
1513+
expect(resumed.enabled).toBe(false);
1514+
expect(resumed.config).toMatchObject({ inferenceEnabled: true });
1515+
expect(yield* proxy.hasFallback(issued.key, hostId, "codex")).toBe(true);
14901516
yield* settings.updateSettings({
14911517
projectSettingsOverrides: { [inferenceProject]: null },
14921518
});

‎apps/server/src/inference/InferenceProxy.ts‎

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
type InferenceProviderConfig,
1515
InferenceHostConnection,
1616
isInferenceProviderConfig,
17+
isInferenceRoutingEnabled,
1718
InferenceRouting,
1819
defaultInferenceRouting,
1920
InferenceProxyError,
@@ -987,14 +988,15 @@ const make = Effect.gen(function* () {
987988
.withPermit(
988989
Effect.gen(function* () {
989990
const state = yield* read;
990-
const { providerInstances } = yield* settings.getSettings;
991+
const current = yield* settings.getSettings;
991992
let routeProblem: string | null = null;
992993
const summary = {
993-
routes: Object.entries(providerInstances).flatMap(([id, instance]) => {
994+
routes: Object.entries(current.providerInstances).flatMap(([id, instance]) => {
995+
const instanceId = ProviderInstanceId.make(id);
994996
if (
995997
!isInferenceProviderConfig(instance.config) ||
996998
!instance.config.inferenceEnabled ||
997-
instance.enabled === false
999+
!isProviderInstanceEnabledInAnyScope(current, instanceId)
9981000
)
9991001
return [];
10001002
const problem =
@@ -1010,7 +1012,7 @@ const make = Effect.gen(function* () {
10101012
}
10111013
return [
10121014
{
1013-
instanceId: ProviderInstanceId.make(id),
1015+
instanceId,
10141016
label: `${inferenceHarness(instance.driver)?.label ?? instance.driver}${instance.config.inferenceHostLabel ? ` via ${instance.config.inferenceHostLabel}` : ""}`,
10151017
},
10161018
];
@@ -1228,11 +1230,7 @@ const make = Effect.gen(function* () {
12281230
}
12291231
if (input.operation === "removeRoute") {
12301232
const revised = yield* settings.reviseProviderInstance(input.instanceId, (current) => {
1231-
if (
1232-
!current ||
1233-
!isInferenceProviderConfig(current.config) ||
1234-
!current.config.inferenceEnabled
1235-
)
1233+
if (!current || !isInferenceRoutingEnabled(current.config))
12361234
return failure("This provider is not using inference routing.");
12371235
return Effect.succeed({
12381236
instance: { ...current, config: { ...current.config, inferenceEnabled: false } },
@@ -1842,7 +1840,10 @@ const make = Effect.gen(function* () {
18421840
);
18431841

18441842
const connect = Effect.fn("InferenceProxy.connect")(
1845-
function* ({ grant, driver, hostLabel, connection }: InferenceRouteInput, fallback = false) {
1843+
function* (
1844+
{ grant, driver, hostLabel, connection, preserveProviderEnabled }: InferenceRouteInput,
1845+
fallback = false,
1846+
) {
18461847
const id = yield* environment.getEnvironmentId;
18471848
if (id !== grant.consumerId)
18481849
return yield* failure("Invalid inference route for this environment.");
@@ -2025,7 +2026,7 @@ const make = Effect.gen(function* () {
20252026
return {
20262027
instance: {
20272028
...native,
2028-
enabled: true,
2029+
...(preserveProviderEnabled && current ? {} : { enabled: true }),
20292030
config: {
20302031
...nativeConfig,
20312032
inferenceEnabled: true,

‎apps/server/src/inference/routes.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@ import {
22
EnvironmentId,
33
InferenceDriver,
44
INFERENCE_HARNESSES,
5+
isInferenceProviderConfig,
56
type CustomModelSetting,
67
type ServerProviderModel,
78
type SettingsSecretValue,
89
type ProviderInstanceConfig,
910
} from "@t3tools/contracts";
1011
import { fromLenientJson } from "@t3tools/shared/schemaJson";
12+
import * as Equal from "effect/Equal";
1113
import * as Option from "effect/Option";
1214
import * as Schema from "effect/Schema";
1315

@@ -312,6 +314,41 @@ export function routeProvider(driver: InferenceDriver, label: string | null, rou
312314
};
313315
}
314316

317+
export function isOpenCodeInferenceCatalogChange(
318+
previous: ProviderInstanceConfig,
319+
next: ProviderInstanceConfig,
320+
): boolean {
321+
const current = previous.config;
322+
const updated = next.config;
323+
if (
324+
previous.driver !== "opencode" ||
325+
!isInferenceProviderConfig(current) ||
326+
!current.inferenceEnabled ||
327+
!isInferenceProviderConfig(updated) ||
328+
Equal.equals(current.inferenceModels, updated.inferenceModels)
329+
)
330+
return false;
331+
const environment = previous.environment;
332+
const content = environment?.find(({ name }) => name === "OPENCODE_CONFIG_CONTENT");
333+
const nativeContent = content?.value;
334+
if (environment === undefined || typeof nativeContent !== "string") return false;
335+
const generated = routeProvider("opencode", null, {
336+
baseUrl: current.inferenceBaseUrl,
337+
key: current.inferenceKey,
338+
models: updated.inferenceModels,
339+
homePath: current.inferenceHomePath,
340+
current: () => nativeContent,
341+
}).environment.find(({ name }) => name === "OPENCODE_CONFIG_CONTENT");
342+
return Equal.equals(
343+
{
344+
...previous,
345+
config: { ...current, inferenceModels: updated.inferenceModels },
346+
environment: environment.map((entry) => (entry === content ? generated : entry)),
347+
},
348+
next,
349+
);
350+
}
351+
315352
export function inferenceModelSlugs(config: {
316353
setupMode?: string;
317354
customModels: readonly CustomModelSetting[];

0 commit comments

Comments
 (0)