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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions apps/mobile/src/lib/modelOptions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,18 +328,20 @@ describe("mobile model options", () => {
).toEqual([true, true]);
});

it.each(["disabled", "unavailable", "missing"] as const)(
it.each(["disabled", "unavailable", "missing", "offline", "limited"] as const)(
"retains the selected %s provider's fallback in a filtered catalog",
(state) => {
const selection = {
instanceId: ProviderInstanceId.make("google_work"),
instanceId: ProviderInstanceId.make("claude_work"),
model: "saved-model",
options: [{ id: "native-option", value: "saved-choice" }],
};
const provider = {
instanceId: selection.instanceId,
driver: "antigravity",
displayName: "Google Work",
driver: "claudeAgent",
status: state === "offline" ? "error" : "ready",
...(state === "limited" ? { limitedUntil: "2099-01-01T00:00:00.000Z" } : {}),
displayName: "Claude Work",
enabled: state !== "disabled",
installed: true,
availability: state === "unavailable" ? "unavailable" : "available",
Expand All @@ -348,10 +350,15 @@ describe("mobile model options", () => {
};
const config = {
providers: state === "missing" ? [] : [provider],
settings: { providerInstances: { google_work: { driver: "antigravity" } } },
settings: {
providerInstances: {
claude_work: { driver: "claudeAgent", enabled: state !== "disabled" },
},
},
} as unknown as ServerConfig;
const options = buildModelOptions(config, selection, selection.instanceId, null);
expect(options).toEqual(buildModelOptions(config, selection, undefined, null));
expect(buildModelOptions(config, null, undefined, null)).toEqual([]);
expect(options).toHaveLength(1);
expect(options[0]).toMatchObject({ selection, isUnavailable: true });
},
Expand Down Expand Up @@ -396,7 +403,7 @@ describe("mobile model options", () => {
expect(resolveSelectableModelSelection(config, disabled, null)).toBeNull();
expect(resolveSelectableModelSelection(config, removed, null)).toBeNull();
expect(isModelSelectionUnavailable(config, disabled, null)).toBe(true);
expect(isModelSelectionUnavailable(config, removed, null)).toBe(false);
expect(isModelSelectionUnavailable(config, removed, null)).toBe(true);
expect(resolveSelectableModelSelection(null, disabled, null)).toBe(disabled);
});

Expand Down Expand Up @@ -532,14 +539,14 @@ describe("mobile model options", () => {
]);
});

it("keeps offline selections without assuming that an unknown instance is Antigravity", () => {
it("keeps the saved label but blocks an instance missing from the available catalog", () => {
const unknownConfig = { ...config, providers: [] };

expect(resolveDefaultableModelSelection(null, selection, null)).toBe(selection);
expect(isModelSelectionUnavailable(null, selection, null)).toBe(false);
expect(buildModelOptions(null, selection, undefined, null)[0]?.selection).toBe(selection);
expect(buildModelOptions(null, selection, undefined, null)[0]?.isUnavailable).not.toBe(true);
expect(isModelSelectionUnavailable(unknownConfig, selection, null)).toBe(false);
expect(isModelSelectionUnavailable(unknownConfig, selection, null)).toBe(true);
expect(resolveSelectableModelSelection(unknownConfig, selection, null)).toBeNull();
});
});
Expand Down
31 changes: 22 additions & 9 deletions apps/mobile/src/lib/modelOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
disallowedProviderMessage,
isManagedDriverAllowed,
isInferenceAccountReplaced,
providerLimitedUntilMs,
isProviderDriverKind,
resolveProjectProviderInstanceEnabled,
} from "@t3tools/contracts";
Expand Down Expand Up @@ -201,12 +202,14 @@ function modelOptionProviderContext(
!config?.settings ||
!isInferenceAccountReplaced(provider.instanceId, config.settings.providerInstances)) &&
isProviderEnabledForProject(config, provider, projectId) &&
provider.availability !== "unavailable" &&
provider.status !== "error" &&
provider.status !== "disabled" &&
providerLimitedUntilMs(provider, Date.now()) === null &&
// Antigravity's catalog only exists once it is set up; other providers stay
// listed as unavailable so a pending or failed probe cannot erase them.
(provider.driver !== "antigravity" ||
(provider.installed &&
provider.auth.status !== "unauthenticated" &&
provider.availability !== "unavailable")),
(provider.installed && provider.auth.status !== "unauthenticated")),
),
};
}
Expand Down Expand Up @@ -235,12 +238,18 @@ export function isModelSelectionUnavailable(
if (isDriverDisallowed(config, driver)) {
return true;
}
if (
!provider ||
provider.availability === "unavailable" ||
provider.status === "error" ||
provider.status === "disabled" ||
providerLimitedUntilMs(provider, Date.now()) !== null
)
return true;
return (
driver === "antigravity" &&
(!provider ||
!provider.installed ||
(!provider.installed ||
provider.auth.status === "unauthenticated" ||
provider.availability === "unavailable" ||
!provider.models.some((model) => model.slug === selection.model))
);
}
Expand Down Expand Up @@ -273,8 +282,11 @@ export function describeUnavailableModelSelection(
detail: "Turn it back on from web or desktop, or choose another model.",
}
: {
title: "Antigravity model unavailable",
detail: "Set up Antigravity on web or desktop, or choose another model.",
title: "Provider unavailable",
detail:
provider?.unavailableReason ??
provider?.message ??
"Check the provider on web or desktop, or choose another model.",
};
}

Expand All @@ -297,7 +309,8 @@ export function resolveSelectableModelSelection(
return provider &&
isProviderEnabledForProject(config, provider, projectId) &&
provider.installed &&
provider.auth.status !== "unauthenticated"
provider.auth.status !== "unauthenticated" &&
!isModelSelectionUnavailable(config, selection, projectId)
? selection
: null;
}
Expand Down
14 changes: 14 additions & 0 deletions apps/server/src/inference/InferenceProxy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ it.effect(
lastError: null,
};
let serving = false;
let poolUnavailable = false;
let lan = false;
let rejectNextLaunch = false;
let currentExit: Deferred.Deferred<void> | undefined;
Expand Down Expand Up @@ -248,12 +249,14 @@ it.effect(
name: "codex:api-key:fixture",
provider: "codex",
status: "active",
unavailable: poolUnavailable,
runtime_only: true,
},
{
name: "one.json",
provider: "codex",
status: "active",
unavailable: poolUnavailable,
refresh_token: "must stay local",
},
],
Expand Down Expand Up @@ -663,6 +666,16 @@ it.effect(
expect((yield* proxy.grant(peer)).key).toBe(issued.key);
expect((yield* proxy.authorize(issued.key))?.key).not.toBe(issued.key);
const local = yield* proxy.grant({ environmentId: hostId, label: "Host" });
expect(yield* proxy.health("wrong-key")).toBeNull();
expect((yield* proxy.health(issued.key))?.availableDrivers).toEqual([
"codex",
"opencode",
"pi",
]);
poolUnavailable = true;
expect((yield* proxy.health(issued.key))?.availableDrivers).toEqual([]);
poolUnavailable = false;
expect((yield* proxy.health(issued.key))?.availableDrivers).toContain("codex");
const connect = { grant: local, driver: "codex" as const, hostLabel: "Host" };
expect(yield* proxy.connect(connect).pipe(Effect.flip)).toHaveProperty(
"_tag",
Expand Down Expand Up @@ -974,6 +987,7 @@ it.effect(
expect((yield* proxy.authorize(grant.key))?.baseUrl).toMatch(/^http:\/\/127\.0\.0\.1:/);
yield* proxy.manage({ operation: "revoke", environmentId: peer.environmentId });
expect(yield* proxy.authorize(grant.key)).toBeNull();
expect(yield* proxy.health(grant.key)).toBeNull();
expect((yield* proxy.grant(peer)).key).not.toBe(grant.key);
expectRecovery = true;
yield* Deferred.succeed(currentExit!, undefined);
Expand Down
78 changes: 77 additions & 1 deletion apps/server/src/inference/InferenceProxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
INFERENCE_HARNESSES,
inferenceHarness,
InferenceConsumer,
InferenceRouteHealth,
type InferenceProviderConfig,
InferenceHostConnection,
isInferenceProviderConfig,
InferenceRouting,
Expand Down Expand Up @@ -83,6 +85,8 @@ const Files = Schema.Struct({
name: Schema.String,
provider: Schema.String,
status: Schema.String,
disabled: Schema.optionalKey(Schema.Boolean),
unavailable: Schema.optionalKey(Schema.Boolean),
runtime_only: Schema.optionalKey(Schema.Boolean),
}),
),
Expand Down Expand Up @@ -1223,6 +1227,70 @@ const make = Effect.gen(function* () {
Effect.mapError(safeFailure("Inference host unavailable.")),
);

const localHealth = Effect.fn("InferenceProxy.localHealth")(function* () {
const state = yield* read;
if (!state.enabled) return yield* failure("Inference hosting is disabled.");
const runtime = yield* ensureWatched(state);
const [{ files }, { data }] = yield* Effect.all(
[
jsonRequest(runtime.baseUrl + "/v0/management/auth-files", runtime.management, Files),
jsonRequest(runtime.baseUrl + "/v1/models", runtime.key, Models),
],
{ concurrency: "unbounded" },
);
const available = files.filter(
(account) => account.status === "active" && !account.disabled && !account.unavailable,
);
return {
availableDrivers: INFERENCE_DRIVERS.filter((driver) =>
available.some(
(account) => INFERENCE_HARNESSES[driver].accounts?.includes(account.provider) ?? true,
),
),
models: data.map((model) => model.id),
};
});

const health = Effect.fn("InferenceProxy.health")(
function* (key: string, hostId?: EnvironmentId) {
const target = yield* authorize(key, hostId);
if (!target) return null;
return hostId === undefined
? yield* mutex.withPermit(localHealth())
: yield* jsonRequest(target.baseUrl + "/health", target.key, InferenceRouteHealth);
},
Effect.mapError(safeFailure("Could not check inference host health.")),
);

const routeHealth = Effect.fn("InferenceProxy.routeHealth")(
function* (route: InferenceProviderConfig, key: string) {
const ownId = yield* environment.getEnvironmentId;
if (route.inferenceHostId === ownId) {
return yield* mutex.withPermit(
Effect.gen(function* () {
const state = yield* read;
if (!state.enabled) return yield* failure("Inference hosting is disabled.");
const runtime = yield* ensureWatched(state);
if (runtime.baseUrl !== route.inferenceBaseUrl || runtime.key !== key)
return yield* failure(
"Inference route credentials have changed. Connect the route again.",
);
return yield* localHealth();
}),
);
}
const address =
route.inferenceConnection || route.inferenceBaseUrl.includes("/api/inference/linked/")
? new URL(
"/api/inference",
yield* peerAddress(route.inferenceHostId, route.inferenceConnection),
).href
: route.inferenceBaseUrl;
return yield* jsonRequest(address + "/health", key, InferenceRouteHealth);
},
Effect.mapError(safeFailure("Could not check inference route health.")),
);

const connect = Effect.fn("InferenceProxy.connect")(
function* ({ grant, driver, hostLabel, connection }: InferenceRouteInput) {
const id = yield* environment.getEnvironmentId;
Expand Down Expand Up @@ -1368,13 +1436,21 @@ const make = Effect.gen(function* () {
Effect.ignore,
Effect.forkScoped,
);
return { status, manage, authorize, grant, connect, bindRoutes };
return { status, manage, authorize, health, routeHealth, grant, connect, bindRoutes };
});

export class InferenceProxy extends Context.Service<
InferenceProxy,
{
readonly status: Effect.Effect<InferenceProxyStatus, InferenceProxyError>;
readonly health: (
key: string,
hostId?: EnvironmentId,
) => Effect.Effect<InferenceRouteHealth | null, InferenceProxyError>;
readonly routeHealth: (
route: InferenceProviderConfig,
key: string,
) => Effect.Effect<InferenceRouteHealth, InferenceProxyError>;
readonly manage: (
input: InferenceProxyAction,
) => Effect.Effect<InferenceProxyActionResult, InferenceProxyError>;
Expand Down
26 changes: 26 additions & 0 deletions apps/server/src/inference/http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,14 @@ it("streams an authorized request with a host key, then denies the revoked consu
InferenceHttp.layer.pipe(
Layer.provide(
Layer.mock(InferenceProxy)({
health: (key, hostId) => {
linkedHost = hostId;
return Effect.succeed(
active && key === "consumer"
? { availableDrivers: ["codex"], models: ["gpt-fixture"] }
: null,
);
},
authorize: (key, hostId) => {
linkedHost = hostId;
return Effect.succeed(
Expand Down Expand Up @@ -110,8 +118,26 @@ it("streams an authorized request with a host key, then denies the revoked consu
expect(limited.status).toBe(429);
expect(limited.headers.get("retry-after")).toBe("60");
expect(await limited.text()).toBe("quota");
const health = await handler(
new Request("http://t3.test/api/inference/linked/host/health", {
headers: { authorization: "Bearer consumer" },
}),
);
expect(health.status).toBe(200);
expect(health.headers.get("cache-control")).toBe("no-store");
expect(await health.json()).toEqual({ availableDrivers: ["codex"], models: ["gpt-fixture"] });
expect(linkedHost).toBe("host");
active = false;
expect((await handler(request("v1/messages", "consumer"))).status).toBe(403);
expect(
(
await handler(
new Request("http://t3.test/api/inference/health", {
headers: { authorization: "Bearer consumer" },
}),
)
).status,
).toBe(403);
expect(upstreamCalls).toBe(4);
} finally {
await dispose();
Expand Down
6 changes: 6 additions & 0 deletions apps/server/src/inference/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ const handler = Effect.gen(function* () {
request.headers.authorization?.match(/^Bearer ([^ ]+)$/i)?.[1] ?? request.headers["x-api-key"];
if (!key) return HttpServerResponse.empty({ status: 401 });
const host = yield* InferenceProxy;
if (targetPath.path === "/health") {
const health = yield* host.health(key, targetPath.environmentId);
return health === null
? HttpServerResponse.empty({ status: 403 })
: HttpServerResponse.jsonUnsafe(health, { headers: { "cache-control": "no-store" } });
}
const target = yield* host.authorize(key, targetPath.environmentId);
if (!target) return HttpServerResponse.empty({ status: 403 });
const client = HttpClient.withScope(yield* HttpClient.HttpClient);
Expand Down
Loading
Loading