chat-js 1.0.0-alpha.6 → 1.0.0-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/README.md +2 -2
  2. package/dist/index.js +14 -16
  3. package/package.json +1 -1
  4. package/templates/chat-app/app/(chat)/layout.tsx +8 -20
  5. package/templates/chat-app/chatjs/plugins/guest-chat/guest-policy.ts +1 -0
  6. package/templates/chat-app/chatjs/plugins/guest-chat/signed-out.tsx +14 -2
  7. package/templates/chat-app/chatjs/plugins/mcp/routes/oauth-callback.ts +27 -26
  8. package/templates/chat-app/chatjs/plugins/model-preferences/settings-link.tsx +1 -2
  9. package/templates/chat-app/chatjs/providers/gateway.ts +34 -16
  10. package/templates/chat-app/chatjs/tools/attach-workspace-file/schemas.ts +13 -2
  11. package/templates/chat-app/components/eve/eve-model-picker.tsx +3 -0
  12. package/templates/chat-app/components/model-selector-view.tsx +8 -15
  13. package/templates/chat-app/components/model-selector.tsx +1 -0
  14. package/templates/chat-app/integrations/chat/models.ts +3 -8
  15. package/templates/chat-app/lib/ai/app-models.test.ts +41 -46
  16. package/templates/chat-app/lib/ai/app-models.ts +4 -154
  17. package/templates/chat-app/lib/ai/web-chat-models.ts +70 -0
  18. package/templates/chat-app/lib/config-schema.ts +1 -1
  19. package/templates/chat-app/lib/eve/application-model.ts +17 -5
  20. package/templates/chat-app/lib/eve/model-selection.test.ts +6 -0
  21. package/templates/chat-app/lib/eve/model-selection.ts +40 -6
  22. package/templates/chat-app/providers/chat-models-provider.tsx +1 -2
  23. package/templates/electron/src/config.ts +7 -23
  24. package/templates/electron/src/lib/auth-client.ts +3 -4
  25. package/templates/electron/src/startup-config.test.ts +133 -0
package/README.md CHANGED
@@ -34,7 +34,7 @@ After publication, run `bun --filter chat-js test:published` to create an app us
34
34
 
35
35
  ## Installation and migration
36
36
 
37
- The `1.0.0-alpha.6` release continues the ChatJS 1.0 alpha series under the `chat-js` package name. Apps are usable, but APIs and generated source may change substantially before 1.0. Use `npx chat-js@alpha` for the examples below. This CLI supports Base UI and Radix with registry `0.2.0-beta.7`.
37
+ The `1.0.0-alpha.7` release continues the ChatJS 1.0 alpha series under the `chat-js` package name. Apps are usable, but APIs and generated source may change substantially before 1.0. Use `npx chat-js@alpha` for the examples below. This CLI supports Base UI and Radix with registry `0.2.0-beta.8`.
38
38
 
39
39
  Pass native shadcn visual options after `--`:
40
40
 
@@ -75,7 +75,7 @@ Existing ChatJS applications need a source migration; upgrading the CLI does not
75
75
 
76
76
  Migrate callers together with primitives. Base UI menu actions use `onClick` and custom triggers use `render`; Radix uses `onSelect` and `asChild`. Passing Radix `onSelect` to a Base UI menu may compile without running the action. Use each library's native composition and ordinary links styled with `buttonVariants` for navigation. Preserve EVE message IDs, scroll anchoring, draft/IME behavior, approval dispatch before specialized renderers, and document revision actions. Verify these flows in your app before removing the old wrappers. Markdown still uses Streamdown; tool-specific renderers remain installed source.
77
77
 
78
- This CLI candidate pins new apps to `@chat-js/registry@0.2.0-beta.7`. Matching registry builds preserve the root Base namespace and add complete `/base/{name}.json` and `/radix/{name}.json` namespaces. Fresh Radix generation selects `/radix/`; item IDs and installation targets remain the same. Subsequent `add` and `sync` retain the configured namespace and check the host's native `base-*` or `radix-*` style before writing source or registrations.
78
+ This CLI candidate pins new apps to `@chat-js/registry@0.2.0-beta.8`. Matching registry builds preserve the root Base namespace and add complete `/base/{name}.json` and `/radix/{name}.json` namespaces. Fresh Radix generation selects `/radix/`; item IDs and installation targets remain the same. Subsequent `add` and `sync` retain the configured namespace and check the host's native `base-*` or `radix-*` style before writing source or registrations.
79
79
 
80
80
  UI-specific plugins and tools declare descriptor `contractVersion: 2` with matching `uiBase: "base"` or `uiBase: "radix"`. A mismatch stops installation; v2 descriptor versions do not prescribe npm major versions. Legacy v1 descriptors remain supported. Existing applications are not automatically migrated between libraries: changing `components.json` or a registry URL alone is insufficient. Keep the compatible registry namespace until migrating primitives and callers together. Publish the matching registry candidate under `beta` before publishing the CLI under `alpha`. The CLI’s `latest` tag also points to the explicitly approved `1.0.0-alpha.2` as an explicit default-install policy; the version remains an alpha until the stable 1.0 launch.
81
81
 
package/dist/index.js CHANGED
@@ -22764,7 +22764,7 @@ import { registrySchema } from "shadcn/schema";
22764
22764
  // ../registry/package.json
22765
22765
  var package_default = {
22766
22766
  name: "@chat-js/registry",
22767
- version: "0.2.0-beta.7",
22767
+ version: "0.2.0-beta.8",
22768
22768
  private: false,
22769
22769
  description: "ChatJS tool and gateway registry items",
22770
22770
  keywords: [
@@ -23169,7 +23169,7 @@ var schemaDependencies = {
23169
23169
  openai: ["zod"],
23170
23170
  "openai-compatible": ["zod"],
23171
23171
  openrouter: ["zod"],
23172
- vercel: ["zod"]
23172
+ vercel: ["@vercel/oidc@3.2.0", "zod"]
23173
23173
  };
23174
23174
  var isGatewayType = (id) => Object.hasOwn(environment, id);
23175
23175
  var builtInGateways = Object.entries(gatewayMetadata).map(([id, metadata]) => {
@@ -24046,7 +24046,6 @@ var researchItem = {
24046
24046
  })
24047
24047
  },
24048
24048
  name: "deep-research",
24049
- registryDependencies: ["trace", "badge"],
24050
24049
  type: "registry:item"
24051
24050
  };
24052
24051
 
@@ -46449,7 +46448,7 @@ var withRegistryTransport = async (operation) => {
46449
46448
  };
46450
46449
 
46451
46450
  // src/registry/shadcn.ts
46452
- var registryUrl = "https://unpkg.com/@chat-js/registry@0.2.0-beta.7/dist/r/{name}.json";
46451
+ var registryUrl = "https://unpkg.com/@chat-js/registry@0.2.0-beta.8/dist/r/{name}.json";
46453
46452
  var registryConfig = async (cwd) => {
46454
46453
  const config3 = await getRegistriesConfig(cwd);
46455
46454
  const source = await optionalFile(path14.join(cwd, "components.json"));
@@ -49864,6 +49863,7 @@ var eveCatalogItemsSchema = exports_external.array(exports_external.object({
49864
49863
 
49865
49864
  // ../registry/agent-configuration.ts
49866
49865
  var modelId = exports_external.string().trim().min(1).max(200);
49866
+ var modelIds = exports_external.array(exports_external.string().trim().max(200)).transform((models) => [...new Set(models.filter(Boolean))]).pipe(exports_external.array(modelId).max(30)).optional();
49867
49867
  var agentReasoningLevels = [
49868
49868
  "provider-default",
49869
49869
  "none",
@@ -49884,7 +49884,7 @@ var eveDefaultToolIds = [
49884
49884
  ];
49885
49885
  var agentConfigurationSchema = exports_external.strictObject({
49886
49886
  model: modelId.optional(),
49887
- allowedModels: exports_external.array(exports_external.string().trim().max(200)).transform((models) => [...new Set(models.filter(Boolean))]).pipe(exports_external.array(modelId).max(30)).default([]),
49887
+ modelIds,
49888
49888
  reasoning: exports_external.enum(agentReasoningLevels).default("provider-default"),
49889
49889
  defaultTools: exports_external.boolean().default(true),
49890
49890
  disabledDefaultTools: exports_external.array(exports_external.enum(eveDefaultToolIds)).max(eveDefaultToolIds.length).transform((ids) => [...new Set(ids)]).optional(),
@@ -50702,7 +50702,7 @@ import path29 from "node:path";
50702
50702
  // package.json
50703
50703
  var package_default2 = {
50704
50704
  name: "chat-js",
50705
- version: "1.0.0-alpha.6",
50705
+ version: "1.0.0-alpha.7",
50706
50706
  private: false,
50707
50707
  description: "CLI for creating and extending ChatJS apps",
50708
50708
  keywords: [
@@ -51115,14 +51115,12 @@ import { mkdir as mkdir11, writeFile as writeFile16 } from "node:fs/promises";
51115
51115
  import path30 from "node:path";
51116
51116
  var writeAgentConfiguration = async (cwd, input3) => {
51117
51117
  const configuration = agentConfigurationSchema.parse(input3 ?? {});
51118
- const {
51119
- approval,
51120
- allowedModels,
51121
- disabledDefaultTools,
51122
- model: model2,
51123
- ...nativeOptions
51124
- } = configuration;
51118
+ const { approval, disabledDefaultTools, model: model2, modelIds: modelIds2, ...nativeOptions } = configuration;
51125
51119
  const modelExpression = model2 === undefined ? "config.ai.workflows.chat" : JSON.stringify(model2);
51120
+ const webModelSettings = [
51121
+ ...model2 === undefined ? [] : [`model: ${modelExpression}`],
51122
+ ...modelIds2 === undefined || modelIds2.length === 0 ? [] : [`modelIds: ${JSON.stringify(modelIds2)}`]
51123
+ ];
51126
51124
  const approvalExpressions = {
51127
51125
  never: "undefined",
51128
51126
  always: '() => "user-approval"',
@@ -51132,8 +51130,8 @@ var writeAgentConfiguration = async (cwd, input3) => {
51132
51130
  await mkdir11(path30.join(cwd, "agent"), { recursive: true });
51133
51131
  await mkdir11(path30.join(cwd, "integrations/chat"), { recursive: true });
51134
51132
  await writeFile16(path30.join(cwd, "integrations/chat/models.ts"), [
51135
- ...model2 === undefined ? ['import { config } from "@/lib/config";', ""] : [],
51136
- `export const webModels: { readonly model?: string; readonly allowedModels: readonly string[] } = { model: ${modelExpression}, allowedModels: ${JSON.stringify(allowedModels)} };`,
51133
+ "/** Optional web chat overrides. Omit modelIds to use the gateway catalog. */",
51134
+ `export const webModels: { readonly model?: string; readonly modelIds?: readonly string[] } = {${webModelSettings.join(", ")}};`,
51137
51135
  ""
51138
51136
  ].join(`
51139
51137
  `));
@@ -51648,7 +51646,7 @@ var aiToolsSchema = exports_external.strictObject({
51648
51646
  ...toolConfig
51649
51647
  }).prefault({});
51650
51648
  var createAiSchema = (gateway) => exports_external.object({
51651
- curatedDefaults: exports_external.array(gatewayModelId()).describe("Default models enabled for new users"),
51649
+ curatedDefaults: exports_external.array(gatewayModelId()).describe("Recommended models shown first in the chat catalog"),
51652
51650
  disabledModels: exports_external.array(gatewayModelId()).describe("Models to hide from all users"),
51653
51651
  gateway: exports_external.literal(gateway),
51654
51652
  providerOrder: exports_external.array(exports_external.string()).describe("Provider sort order in model selector"),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chat-js",
3
- "version": "1.0.0-alpha.6",
3
+ "version": "1.0.0-alpha.7",
4
4
  "private": false,
5
5
  "description": "CLI for creating and extending ChatJS apps",
6
6
  "keywords": [
@@ -1,4 +1,3 @@
1
- import { webModels } from "@/integrations/chat/models";
2
1
  import { cookies, headers } from "next/headers";
3
2
  import React, { Suspense } from "react";
4
3
 
@@ -12,8 +11,10 @@ import {
12
11
  ChatWorkspace,
13
12
  ChatWorkspaceContent,
14
13
  } from "@/components/chat/chat-workspace";
15
- import type { AppModelId } from "@/lib/ai/app-model-id";
16
- import { config } from "@/lib/config";
14
+ import {
15
+ getConfiguredWebChatModel,
16
+ getDefaultWebChatModelId,
17
+ } from "@/lib/ai/web-chat-models";
17
18
  import { isPlaywrightTestEnvironment } from "@/lib/constants";
18
19
  import { resolveEvePrincipal } from "@/lib/eve/principal";
19
20
  import type { ReadonlyReactNode } from "@/lib/readonly-react-node";
@@ -26,22 +27,6 @@ import { HydrateClient } from "@/trpc/server";
26
27
 
27
28
  import { auth } from "@/lib/auth";
28
29
 
29
- const resolveDefaultModel = (
30
- cookieModel: string | undefined,
31
- chatModels: readonly { readonly id: string }[]
32
- ): AppModelId => {
33
- const configuredModel = webModels.model ?? config.ai.workflows.chat;
34
- let defaultModel: AppModelId = cookieModel ?? configuredModel;
35
-
36
- if (typeof cookieModel === "string" && cookieModel !== "") {
37
- const modelExists = chatModels.some((model) => model.id === cookieModel);
38
- if (!modelExists) {
39
- defaultModel = configuredModel;
40
- }
41
- }
42
- return defaultModel;
43
- };
44
-
45
30
  const ChatLayoutDynamic = async ({
46
31
  children,
47
32
  }: {
@@ -61,7 +46,10 @@ const ChatLayoutDynamic = async ({
61
46
 
62
47
  const cookieModel = cookieStore.get("chat-model")?.value;
63
48
 
64
- const defaultModel = resolveDefaultModel(cookieModel, chatModels);
49
+ const defaultModel =
50
+ chatModels.find((model) => model.id === cookieModel)?.id ??
51
+ getDefaultWebChatModelId(chatModels) ??
52
+ getConfiguredWebChatModel();
65
53
 
66
54
  return (
67
55
  <HydrateClient>
@@ -7,6 +7,7 @@ export const guestModelIdForGateway = (gateway: string): string =>
7
7
  export const GUEST_POLICY = {
8
8
  version: "1",
9
9
  modelId: guestModelIdForGateway(config.ai.gateway),
10
+ modelName: "GPT-5 nano",
10
11
  requestsPerMinute: 5,
11
12
  sessionsPerHour: 5,
12
13
  credentialDurationMs: 3_600_000,
@@ -133,7 +133,13 @@ const GuestConversationView = ({
133
133
  <EveComposer
134
134
  autoFocus
135
135
 
136
- modelPicker={<EveModelPicker disabled modelId={modelId} />}
136
+ modelPicker={
137
+ <EveModelPicker
138
+ disabled
139
+ modelId={modelId}
140
+ fallbackModelName={GUEST_POLICY.modelName}
141
+ />
142
+ }
137
143
  status={busy ? "streaming" : "ready"}
138
144
  disabled={busy || expired}
139
145
  draft={draft}
@@ -293,7 +299,13 @@ const GuestWelcomeView = ({
293
299
  )}
294
300
  <EveComposer
295
301
  autoFocus
296
- modelPicker={<EveModelPicker disabled modelId={modelId} />}
302
+ modelPicker={
303
+ <EveModelPicker
304
+ disabled
305
+ modelId={modelId}
306
+ fallbackModelName={GUEST_POLICY.modelName}
307
+ />
308
+ }
297
309
  status={busy ? "submitted" : "ready"}
298
310
  disabled={busy || !modelId}
299
311
  draft={draft}
@@ -21,34 +21,35 @@ const hasNonEmptyValue = (value: string | null | undefined): value is string =>
21
21
  typeof value === "string" && value !== "";
22
22
 
23
23
  const log = createModuleLogger("mcp-oauth-callback");
24
-
25
- const redirectToConnector = (
26
- request: ReadonlyNativeSurface<Pick<NextRequest, "nextUrl">>,
27
- {
28
- connectorId,
29
- connected,
30
- errorMessage,
31
- }: {
32
- readonly connectorId?: string;
33
- readonly connected?: boolean;
34
- readonly errorMessage?: string;
35
- }
36
- ): NextResponse => {
24
+ const TEMPORARY_REDIRECT = 307;
25
+
26
+ const redirectToConnector = ({
27
+ connectorId,
28
+ connected,
29
+ errorMessage,
30
+ }: {
31
+ readonly connectorId?: string;
32
+ readonly connected?: boolean;
33
+ readonly errorMessage?: string;
34
+ }): NextResponse => {
37
35
  const path = hasNonEmptyValue(connectorId)
38
36
  ? `/settings/connectors/${connectorId}`
39
37
  : "/settings/connectors";
40
- const url = new URL(path, request.nextUrl.origin);
38
+ const searchParams = new URLSearchParams();
41
39
  if (connected === true) {
42
- url.searchParams.set("connected", "1");
40
+ searchParams.set("connected", "1");
43
41
  }
44
42
  if (hasNonEmptyValue(errorMessage)) {
45
- url.searchParams.set("error", errorMessage);
43
+ searchParams.set("error", errorMessage);
46
44
  }
47
- return NextResponse.redirect(url);
45
+ // Keep the browser on the callback origin when a proxy supplies a different host to Next.
46
+ return new NextResponse(null, {
47
+ headers: { Location: `${path}?${searchParams}` },
48
+ status: TEMPORARY_REDIRECT,
49
+ });
48
50
  };
49
51
 
50
52
  const oauthFailureResponse = (
51
- request: ReadonlyNativeSurface<Pick<NextRequest, "nextUrl">>,
52
53
  connector: Readonly<
53
54
  Pick<NonNullable<Awaited<ReturnType<typeof getMcpConnectorById>>>, "id">
54
55
  >,
@@ -66,7 +67,7 @@ const oauthFailureResponse = (
66
67
  "OAuth token exchange failed"
67
68
  );
68
69
 
69
- return redirectToConnector(request, {
70
+ return redirectToConnector({
70
71
  connectorId: connector.id,
71
72
  errorMessage:
72
73
  "Could not complete connector authorization. Please try again.",
@@ -92,7 +93,7 @@ export const GET = async (
92
93
  requireMcpCredentials();
93
94
  } catch (setupError) {
94
95
  if (setupError instanceof MissingCredentialsError) {
95
- return redirectToConnector(request, { errorMessage: setupError.message });
96
+ return redirectToConnector({ errorMessage: setupError.message });
96
97
  }
97
98
  throw setupError;
98
99
  }
@@ -109,7 +110,7 @@ export const GET = async (
109
110
  invalidateAllMcpCaches(deleted.mcpConnectorId);
110
111
  }
111
112
  }
112
- return redirectToConnector(request, {
113
+ return redirectToConnector({
113
114
  connectorId: pending?.mcpConnectorId,
114
115
  errorMessage:
115
116
  "Authorization was not completed. Please try connecting again.",
@@ -120,7 +121,7 @@ export const GET = async (
120
121
  { code: Boolean(code), state: Boolean(state) },
121
122
  "Missing code or state"
122
123
  );
123
- return redirectToConnector(request, {
124
+ return redirectToConnector({
124
125
  errorMessage: "Missing authorization code or state parameter",
125
126
  });
126
127
  }
@@ -130,7 +131,7 @@ export const GET = async (
130
131
 
131
132
  if (!session) {
132
133
  log.error({ state }, "Session not found for state");
133
- return redirectToConnector(request, {
134
+ return redirectToConnector({
134
135
  errorMessage: "Invalid or expired session. Please try again.",
135
136
  });
136
137
  }
@@ -139,7 +140,7 @@ export const GET = async (
139
140
  const connector = await getMcpConnectorById({ id: session.mcpConnectorId });
140
141
  if (!connector) {
141
142
  log.error({ connectorId: session.mcpConnectorId }, "Connector not found");
142
- return redirectToConnector(request, {
143
+ return redirectToConnector({
143
144
  errorMessage: "MCP connector not found",
144
145
  });
145
146
  }
@@ -170,11 +171,11 @@ export const GET = async (
170
171
  // cached clients may still keep an authorization URL in memory.
171
172
  await removeMcpClient(connector.id);
172
173
 
173
- return redirectToConnector(request, {
174
+ return redirectToConnector({
174
175
  connected: true,
175
176
  connectorId: connector.id,
176
177
  });
177
178
  } catch (oauthError) {
178
- return oauthFailureResponse(request, connector, oauthError);
179
+ return oauthFailureResponse(connector, oauthError);
179
180
  }
180
181
  };
@@ -36,7 +36,6 @@ export const ModelPreferencesLink = ({
36
36
  return (
37
37
  <div className="border-t p-2">
38
38
  <InternalLink
39
- aria-label="Add Models"
40
39
  href="/settings/models"
41
40
  className={buttonVariants({
42
41
  className: "w-full justify-between",
@@ -44,7 +43,7 @@ export const ModelPreferencesLink = ({
44
43
  variant: "ghost",
45
44
  })}
46
45
  >
47
- Add Models
46
+ Manage models
48
47
  <ChevronRightIcon className="h-4 w-4" />
49
48
  </InternalLink>
50
49
  </div>
@@ -13,6 +13,7 @@ import type { ImageModel } from "ai";
13
13
 
14
14
  import { createGateway } from "@ai-sdk/gateway";
15
15
  import type { gateway } from "@ai-sdk/gateway";
16
+ import { getVercelOidcToken } from "@vercel/oidc";
16
17
  import { z } from "zod";
17
18
 
18
19
  const MODEL_ID_PARAMETER_INDEX = 0;
@@ -29,6 +30,14 @@ const modelsEnvelopeSchema = z.object({
29
30
  data: z.array(z.unknown()),
30
31
  object: z.literal("list"),
31
32
  });
33
+ const modelAvailability = z.object({
34
+ model_eligibility: z
35
+ .object({
36
+ status: z.string(),
37
+ category: z.string().optional(),
38
+ })
39
+ .optional(),
40
+ });
32
41
 
33
42
  class VercelGateway
34
43
  extends GatewayRuntime
@@ -61,33 +70,33 @@ class VercelGateway
61
70
  return this.provider;
62
71
  }
63
72
 
64
- private getApiKey(): string | undefined {
73
+ private async getApiKey(): Promise<string | null> {
65
74
  const apiKey = this.env.AI_GATEWAY_API_KEY;
66
75
 
67
76
  if (typeof apiKey === "string" && apiKey !== "") {
68
77
  return apiKey;
69
78
  }
70
- return this.env.VERCEL_OIDC_TOKEN;
79
+ const oidcToken = this.env.VERCEL_OIDC_TOKEN;
80
+ if (typeof oidcToken === "string" && oidcToken !== "") {
81
+ return oidcToken;
82
+ }
83
+ return await getVercelOidcToken().catch(() => null);
71
84
  }
72
85
 
73
86
  public async fetchModels(): Promise<AiGatewayModel[]> {
74
- const apiKey = this.getApiKey();
75
-
76
- if (!(typeof apiKey === "string" && apiKey !== "")) {
77
- this.log.warn("No AI gateway API key found, using fallback models");
78
- return [...this.getFallbackModels(this.type)];
79
- }
80
-
81
- const url = "https://ai-gateway.vercel.sh/v1/models";
87
+ const apiKey = await this.getApiKey();
88
+ const catalogUrl = "https://ai-gateway.vercel.sh/v1/models";
89
+ const url =
90
+ apiKey === null ? catalogUrl : `${catalogUrl}?include_availability`;
82
91
  this.log.debug({ url }, "Fetching models from Vercel AI Gateway");
83
92
 
84
93
  try {
85
- const response = await this.fetch(url, {
86
- headers: {
87
- Authorization: `Bearer ${apiKey}`,
88
- "Content-Type": "application/json",
89
- },
90
- });
94
+ const response = await this.fetch(
95
+ url,
96
+ apiKey === null
97
+ ? undefined
98
+ : { headers: { Authorization: `Bearer ${apiKey}` } }
99
+ );
91
100
 
92
101
  if (!response.ok) {
93
102
  this.log.error(
@@ -105,6 +114,15 @@ class VercelGateway
105
114
  for (const candidate of body.data) {
106
115
  const { type } = modelDiscriminatorSchema.parse(candidate);
107
116
  if (isAiGatewayModelType(type)) {
117
+ const availability = modelAvailability.safeParse(candidate);
118
+ const eligibility = availability.data?.model_eligibility;
119
+ if (
120
+ eligibility?.status === "ineligible" &&
121
+ (eligibility.category === "policy" ||
122
+ eligibility.category === "configuration")
123
+ ) {
124
+ continue;
125
+ }
108
126
  models.push(aiGatewayModelSchema.parse(candidate));
109
127
  } else {
110
128
  unsupportedTypes.add(type);
@@ -3,12 +3,20 @@ import { isFileStorageKey } from "@/lib/file-url";
3
3
 
4
4
  export const maximumWorkspaceFileBytes = 32 * 1024 * 1024;
5
5
 
6
+ // Keep Unicode character validation at runtime so model providers do not have
7
+ // to compile JavaScript Unicode property escapes from the tool's JSON Schema.
8
+ const controlCharacter = /\p{Cc}/u;
9
+ const invalidFilenameCharacter = /[/\\\p{Cc}]/u;
10
+
6
11
  export const attachWorkspaceFileInput = z.object({
7
12
  path: z
8
13
  .string()
9
14
  .min(1)
10
15
  .max(4096)
11
- .regex(/^[^\p{Cc}]+$/u)
16
+ .refine(
17
+ (path) => !controlCharacter.test(path),
18
+ "Path contains a control character."
19
+ )
12
20
  .describe(
13
21
  "File in the current EVE sandbox workspace, e.g. /workspace/report.xlsx."
14
22
  ),
@@ -17,7 +25,10 @@ export const attachWorkspaceFileInput = z.object({
17
25
  .trim()
18
26
  .min(1)
19
27
  .max(180)
20
- .regex(/^[^/\\\p{Cc}]+$/u)
28
+ .refine(
29
+ (name) => !invalidFilenameCharacter.test(name),
30
+ "Filename contains a separator or control character."
31
+ )
21
32
  .optional()
22
33
  .describe("Optional download filename, including its extension."),
23
34
  });
@@ -10,9 +10,11 @@ import {
10
10
  /** The default composer chooses one model. Other selection modes supply a slot. */
11
11
  export const EveModelPicker = ({
12
12
  disabled = false,
13
+ fallbackModelName,
13
14
  modelId,
14
15
  }: {
15
16
  readonly disabled?: boolean;
17
+ readonly fallbackModelName?: string;
16
18
  readonly modelId?: string;
17
19
  }): React.JSX.Element => {
18
20
  const defaultModel = useDefaultModel();
@@ -22,6 +24,7 @@ export const EveModelPicker = ({
22
24
  <fieldset disabled={disabled}>
23
25
  <ModelSelector
24
26
  className="h-8 w-fit max-w-none shrink justify-start truncate px-2 text-xs @[500px]:h-10 @[500px]:px-3 @[500px]:text-sm"
27
+ fallbackModelName={fallbackModelName}
25
28
  selectedModelId={selected}
26
29
  selectedModelSelection={selected}
27
30
  onModelSelectionChangeAction={async (selection) => {
@@ -5,6 +5,7 @@ import type { getEnabledFeatures } from "@/lib/features-config";
5
5
  import { Checkbox } from "@/components/ui/checkbox";
6
6
  import { ModelSelectionIndicator } from "@/components/model-selection-indicator";
7
7
  import { PopoverButton } from "@/components/popover-button";
8
+ import { nonEmptyText } from "@/components/text-value";
8
9
  import type { AppModelDefinition, AppModelId } from "@/lib/ai/app-models";
9
10
  import {
10
11
  CheckIcon,
@@ -260,6 +261,7 @@ const PureModelSelector = ({
260
261
  allowMultiple = true,
261
262
  selectedModelId,
262
263
  selectedModelSelection,
264
+ fallbackModelName,
263
265
  className,
264
266
  onModelSelectionChangeAction,
265
267
  chatModels,
@@ -278,6 +280,7 @@ const PureModelSelector = ({
278
280
  readonly allowMultiple?: boolean;
279
281
  readonly selectedModelId: AppModelId;
280
282
  readonly selectedModelSelection: SelectedModelValue;
283
+ readonly fallbackModelName?: string;
281
284
  readonly onModelSelectionChangeAction?: (
282
285
  selection: SelectedModelValue
283
286
  ) => void | Promise<void>;
@@ -451,21 +454,11 @@ const PureModelSelector = ({
451
454
  () => getSelectionCount(optimisticSelection),
452
455
  [optimisticSelection]
453
456
  );
454
- const triggerLabel = useMemo(() => {
455
- if (useMultipleModels && selectedModelCount > 1) {
456
- const modelName = selectedItem?.model.name;
457
- if (modelName !== undefined && modelName !== "") {
458
- return `${modelName} +${selectedModelCount - 1}`;
459
- }
460
- return `Selected model +${selectedModelCount - 1}`;
461
- }
462
-
463
- const modelName = selectedItem?.model.name;
464
- if (modelName !== undefined && modelName !== "") {
465
- return modelName;
466
- }
467
- return "Select model";
468
- }, [selectedItem?.model.name, selectedModelCount, useMultipleModels]);
457
+ const modelName = nonEmptyText(selectedItem?.model.name) ?? fallbackModelName;
458
+ const triggerLabel =
459
+ useMultipleModels && selectedModelCount > 1
460
+ ? `${modelName ?? "Selected model"} +${selectedModelCount - 1}`
461
+ : (modelName ?? "Select model");
469
462
 
470
463
  const dispatchSelection = useCallback(
471
464
  (selection: SelectedModelValue): void => {
@@ -15,6 +15,7 @@ const ConnectedModelSelector = (
15
15
  props: Pick<
16
16
  ComponentProps<typeof ModelSelectorView>,
17
17
  | "allowMultiple"
18
+ | "fallbackModelName"
18
19
  | "selectedModelId"
19
20
  | "selectedModelSelection"
20
21
  | "onModelSelectionChangeAction"
@@ -1,10 +1,5 @@
1
- import { config } from "@/lib/config";
2
-
3
- /** Application model picker choices. Native EVE agents configure their own model. */
1
+ /** Optional web chat overrides. Omit modelIds to use the gateway catalog. */
4
2
  export const webModels: {
5
3
  readonly model?: string;
6
- readonly allowedModels: readonly string[];
7
- } = {
8
- model: config.ai.workflows.chat,
9
- allowedModels: [],
10
- };
4
+ readonly modelIds?: readonly string[];
5
+ } = {};
@@ -1,8 +1,11 @@
1
1
  import { beforeEach, expect, test, vi } from "vitest";
2
2
 
3
- import { fetchChatModels, getDefaultEnabledModels } from "./app-models";
3
+ import { fetchChatModels } from "./app-models";
4
4
  import type { ModelData } from "./model-data";
5
5
  import { fetchModels } from "./models";
6
+ import { getDefaultWebChatModelId } from "./web-chat-models";
7
+
8
+ const modelSettings = vi.hoisted((): { modelIds?: string[] } => ({}));
6
9
 
7
10
  vi.mock("next/cache", () => ({
8
11
  unstable_cache: <Result>(operation: () => Result): (() => Result) =>
@@ -20,18 +23,7 @@ vi.mock("@/lib/config", () => ({
20
23
  },
21
24
  }));
22
25
  vi.mock("@/integrations/chat/models", () => ({
23
- webModels: {
24
- allowedModels: [
25
- "openai/gpt-5-mini-reasoning",
26
- "fixture/known",
27
- "fixture/new",
28
- "fixture/last",
29
- ],
30
- },
31
- }));
32
- vi.mock("./models.generated", () => ({
33
- generatedForGateway: "vercel",
34
- models: [{ id: "openai/gpt-5-mini" }, { id: "fixture/known" }],
26
+ webModels: modelSettings,
35
27
  }));
36
28
  vi.mock("./models", () => ({
37
29
  fetchModels: vi.fn(),
@@ -66,39 +58,42 @@ const catalog: ModelData[] = [
66
58
  { ...baseModel, id: "fixture/last" },
67
59
  ];
68
60
 
69
- beforeEach(() => vi.mocked(fetchModels).mockResolvedValue(catalog));
61
+ beforeEach(() => {
62
+ modelSettings.modelIds = undefined;
63
+ vi.mocked(fetchModels).mockResolvedValue(catalog);
64
+ });
70
65
 
71
- test("chat catalogs preserve reasoning variants, disabled filtering, and provider order", async () => {
66
+ test.each([undefined, []])(
67
+ "discovers chat models with modelIds %j",
68
+ async (modelIds) => {
69
+ modelSettings.modelIds = modelIds;
70
+ const models = await fetchChatModels();
71
+ expect(models.map((model: { readonly id: string }) => model.id)).toEqual([
72
+ "openai/gpt-5-mini-reasoning",
73
+ "openai/gpt-5-mini",
74
+ "fixture/known",
75
+ "fixture/new",
76
+ "fixture/last",
77
+ ]);
78
+ expect(
79
+ models.find(
80
+ (model: { readonly id: string }) => model.id === "openai/gpt-5-mini"
81
+ )
82
+ ).toMatchObject({
83
+ apiModelId: "openai/gpt-5-mini",
84
+ reasoning: false,
85
+ });
86
+ expect(
87
+ catalog.find(
88
+ (model: { readonly id: string }) => model.id === "openai/gpt-5-mini"
89
+ )
90
+ ).toMatchObject({ reasoning: true });
91
+ }
92
+ );
93
+
94
+ test("a populated modelIds list restricts the catalog and supplies a usable default", async () => {
95
+ modelSettings.modelIds = ["fixture/new", "fixture/disabled", "fixture/image"];
72
96
  const models = await fetchChatModels();
73
- expect(models.map((model: { readonly id: string }) => model.id)).toEqual([
74
- "openai/gpt-5-mini-reasoning",
75
- "openai/gpt-5-mini",
76
- "fixture/known",
77
- "fixture/new",
78
- "fixture/last",
79
- ]);
80
- expect(
81
- models.find(
82
- (model: { readonly id: string }) => model.id === "openai/gpt-5-mini"
83
- )
84
- ).toMatchObject({
85
- apiModelId: "openai/gpt-5-mini",
86
- reasoning: false,
87
- });
88
- expect(
89
- catalog.find(
90
- (model: { readonly id: string }) => model.id === "openai/gpt-5-mini"
91
- )
92
- ).toMatchObject({ reasoning: true });
93
- });
94
- test("readonly catalogs enable configured alternatives alongside curated defaults", async () => {
95
- const models = Object.freeze(await fetchChatModels());
96
- const enabled = getDefaultEnabledModels(models);
97
- expect([...enabled]).toEqual([
98
- "openai/gpt-5-mini",
99
- "openai/gpt-5-mini-reasoning",
100
- "fixture/known",
101
- "fixture/new",
102
- "fixture/last",
103
- ]);
97
+ expect(models.map((model) => model.id)).toEqual(["fixture/new"]);
98
+ expect(getDefaultWebChatModelId(models)).toBe("fixture/new");
104
99
  });
@@ -1,163 +1,13 @@
1
- import { webModels } from "@/integrations/chat/models";
2
- import {
3
- generatedForGateway,
4
- models as generatedModels,
5
- } from "./models.generated";
6
- import type { AppModelId } from "./app-model-id";
7
- import type { ModelData } from "./model-data";
8
-
9
1
  import { unstable_cache as cache } from "next/cache";
10
- import { config } from "@/lib/config";
11
2
  import { fetchModels } from "./models";
3
+ import { buildWebChatModels } from "./web-chat-models";
12
4
 
13
- type AppModelDefinition = Omit<ModelData, "id"> & {
14
- readonly id: AppModelId;
15
- readonly apiModelId: string;
16
- };
17
-
18
- const DISABLED_MODELS = new Set<string>(config.ai.disabledModels);
19
- const PROVIDER_ORDER = config.ai.providerOrder;
20
-
21
- const buildAppModels = (models: readonly ModelData[]): AppModelDefinition[] =>
22
- models
23
- .flatMap((model): (AppModelDefinition & { disabled: boolean })[] => {
24
- const modelId = model.id;
25
- // If the model supports reasoning, return two variants:
26
- // - Non-reasoning (original id, reasoning=false)
27
- // - Reasoning (id with -reasoning suffix, reasoning=true)
28
- if (model.reasoning) {
29
- const reasoningId = `${modelId}-reasoning`;
30
-
31
- return [
32
- {
33
- ...model,
34
- apiModelId: modelId,
35
- disabled: DISABLED_MODELS.has(modelId),
36
- id: reasoningId,
37
- },
38
- {
39
- ...model,
40
- apiModelId: modelId,
41
- disabled: DISABLED_MODELS.has(modelId),
42
- id: modelId,
43
- reasoning: false,
44
- },
45
- ];
46
- }
47
-
48
- // Models without reasoning stay as-is
49
- return [
50
- {
51
- ...model,
52
- apiModelId: modelId,
53
- disabled: DISABLED_MODELS.has(modelId),
54
- id: modelId,
55
- },
56
- ];
57
- })
58
- .filter(
59
- (model: {
60
- readonly type: ModelData["type"];
61
- readonly disabled: boolean;
62
- }) => model.type === "language" && !model.disabled
63
- );
64
-
65
- const buildChatModels = (
66
- appModels: readonly AppModelDefinition[]
67
- ): AppModelDefinition[] =>
68
- appModels
69
- .filter(
70
- (model: {
71
- readonly id: string;
72
- readonly output: { readonly text: boolean };
73
- }) =>
74
- model.output.text &&
75
- (model.id === (webModels.model ?? config.ai.workflows.chat) ||
76
- webModels.allowedModels.includes(model.id))
77
- )
78
- .toSorted(
79
- (
80
- leftModel: { readonly owned_by: string },
81
- rightModel: { readonly owned_by: string }
82
- ) => {
83
- const leftProviderIndex = PROVIDER_ORDER.indexOf(leftModel.owned_by);
84
- const rightProviderIndex = PROVIDER_ORDER.indexOf(rightModel.owned_by);
85
-
86
- const leftIndex =
87
- leftProviderIndex === -1 ? PROVIDER_ORDER.length : leftProviderIndex;
88
- const rightIndex =
89
- rightProviderIndex === -1
90
- ? PROVIDER_ORDER.length
91
- : rightProviderIndex;
92
-
93
- return leftIndex - rightIndex;
94
- }
95
- );
96
-
97
- const fetchAllAppModels = cache(
98
- async (): Promise<AppModelDefinition[]> => {
99
- const models = await fetchModels();
100
- return buildAppModels(models);
101
- },
102
- ["all-app-models"],
103
- { revalidate: 3600, tags: ["ai-gateway-models"] }
104
- );
105
5
  const fetchChatModels = cache(
106
- async (): Promise<AppModelDefinition[]> => {
107
- const appModels = await fetchAllAppModels();
108
- return buildChatModels(appModels);
109
- },
6
+ async () => buildWebChatModels(await fetchModels()),
110
7
  ["chat-models"],
111
8
  { revalidate: 3600, tags: ["ai-gateway-models"] }
112
9
  );
113
- /**
114
- * Whether the generated catalog belongs to the selected gateway.
115
- * @param {string} gateway - Gateway identity from application configuration.
116
- * @returns {boolean} True when generated IDs can be used to identify previously known models.
117
- */
118
- const snapshotMatchesGateway = (gateway: string): boolean =>
119
- generatedForGateway === gateway;
120
-
121
- const KNOWN_MODEL_IDS = new Set<string>(
122
- snapshotMatchesGateway(config.ai.gateway)
123
- ? generatedModels.map((model: { readonly id: string }) => model.id)
124
- : []
125
- );
126
-
127
- /**
128
- * Returns the default enabled models for a given list of app models.
129
- * Includes curated defaults + any new models from the API not in models.generated.ts
130
- * @param {readonly { readonly id: AppModelId; readonly apiModelId: string }[]} appModels - Available application variants and their provider IDs.
131
- * @returns {Set<AppModelId>} Curated IDs, their available reasoning variants, and IDs absent from the matching generated catalog.
132
- */
133
- const getDefaultEnabledModels = (
134
- appModels: readonly {
135
- readonly id: AppModelId;
136
- readonly apiModelId: string;
137
- }[]
138
- ): Set<AppModelId> => {
139
- const enabled = new Set<AppModelId>([
140
- ...config.ai.curatedDefaults,
141
- webModels.model ?? config.ai.workflows.chat,
142
- ...webModels.allowedModels,
143
- ]);
144
-
145
- // If a curated default has a -reasoning variant, enable it too
146
- for (const model of appModels) {
147
- if (model.id.endsWith("-reasoning") && enabled.has(model.apiModelId)) {
148
- enabled.add(model.id);
149
- }
150
- }
151
-
152
- // Add any new models from the API that aren't in our generated snapshot
153
- for (const model of appModels) {
154
- if (!KNOWN_MODEL_IDS.has(model.apiModelId)) {
155
- enabled.add(model.id);
156
- }
157
- }
158
10
 
159
- return enabled;
160
- };
161
- export { fetchChatModels, getDefaultEnabledModels };
162
- export type { AppModelDefinition };
11
+ export { fetchChatModels };
12
+ export type { AppModelDefinition } from "./web-chat-models";
163
13
  export type { AppModelId } from "./app-model-id";
@@ -0,0 +1,70 @@
1
+ import { webModels } from "@/integrations/chat/models";
2
+ import { config } from "@/lib/config";
3
+ import type { ModelData } from "./model-data";
4
+
5
+ type AppModelDefinition = ModelData & { readonly apiModelId: string };
6
+
7
+ const getConfiguredWebChatModel = (
8
+ defaultModelId: string = config.ai.workflows.chat
9
+ ): string => webModels.model ?? defaultModelId;
10
+
11
+ const isWebChatModelAllowed = (modelId: string): boolean => {
12
+ const { modelIds } = webModels;
13
+ return (
14
+ modelIds === undefined ||
15
+ modelIds.length === 0 ||
16
+ modelIds.includes(modelId)
17
+ );
18
+ };
19
+
20
+ const providerRank = (provider: string): number => {
21
+ const index = config.ai.providerOrder.indexOf(provider);
22
+ return index === -1 ? config.ai.providerOrder.length : index;
23
+ };
24
+
25
+ const recommendedIds = new Set<string>(config.ai.curatedDefaults);
26
+ const disabledIds = new Set<string>(config.ai.disabledModels);
27
+
28
+ const buildWebChatModels = (
29
+ models: readonly ModelData[]
30
+ ): AppModelDefinition[] =>
31
+ models
32
+ .flatMap((model: Readonly<ModelData>): AppModelDefinition[] => {
33
+ if (
34
+ model.type !== "language" ||
35
+ !model.output.text ||
36
+ disabledIds.has(model.id)
37
+ ) {
38
+ return [];
39
+ }
40
+ const standard = { ...model, apiModelId: model.id, reasoning: false };
41
+ return model.reasoning
42
+ ? [
43
+ { ...model, apiModelId: model.id, id: `${model.id}-reasoning` },
44
+ standard,
45
+ ]
46
+ : [standard];
47
+ })
48
+ .filter((model) => isWebChatModelAllowed(model.id))
49
+ .toSorted(
50
+ (left, right) =>
51
+ Number(recommendedIds.has(right.apiModelId)) -
52
+ Number(recommendedIds.has(left.apiModelId)) ||
53
+ providerRank(left.owned_by) - providerRank(right.owned_by)
54
+ );
55
+
56
+ const getDefaultWebChatModelId = (
57
+ models: readonly Pick<AppModelDefinition, "apiModelId" | "id">[],
58
+ preferredModelId = getConfiguredWebChatModel()
59
+ ): string | undefined =>
60
+ models.find((model) => model.id === preferredModelId)?.id ??
61
+ models.find((model) => model.id === model.apiModelId)?.id ??
62
+ models[0]?.id;
63
+
64
+ export {
65
+ buildWebChatModels,
66
+ getConfiguredWebChatModel,
67
+ getDefaultWebChatModelId,
68
+ isWebChatModelAllowed,
69
+ };
70
+ export type { AppModelDefinition };
@@ -63,7 +63,7 @@ const createAiSchema = <Gateway extends GatewayType>(
63
63
  z.object({
64
64
  curatedDefaults: z
65
65
  .array(gatewayModelId<Gateway>())
66
- .describe("Default models enabled for new users"),
66
+ .describe("Recommended models shown first in the chat catalog"),
67
67
  disabledModels: z
68
68
  .array(gatewayModelId<Gateway>())
69
69
  .describe("Models to hide from all users"),
@@ -1,7 +1,10 @@
1
1
  import { defineDynamic } from "eve/models";
2
2
  import { defineState } from "eve/context";
3
3
  import { wrapLanguageModel } from "ai";
4
- import { webModels } from "@/integrations/chat/models";
4
+ import {
5
+ getConfiguredWebChatModel,
6
+ isWebChatModelAllowed,
7
+ } from "@/lib/ai/web-chat-models";
5
8
  import { isAccountSession } from "./session-identity";
6
9
  import { installedToolAvailabilityMiddleware } from "./tool-availability";
7
10
 
@@ -30,15 +33,24 @@ export const applicationModel = (model: string, allowWebSelection = true) =>
30
33
  ? context.session.auth.current?.attributes.modelId
31
34
  : undefined;
32
35
  if (typeof requested === "string") {
33
- if (requested !== model && !webModels.allowedModels.includes(requested)) {
36
+ if (!isWebChatModelAllowed(requested)) {
34
37
  throw new Error("This model is not enabled for web chat.");
35
38
  }
36
39
  selectedModel.update(() => ({ modelId: requested }));
37
40
  }
38
- const modelId =
39
- (allowWebSelection ? selectedModel.get().modelId : undefined) ?? model;
40
41
  const { billing } = await import("@/integrations/billing");
41
- const { resolveEveModel } = await import("./model-selection");
42
+ const { loadDefaultEveWebModelId, resolveEveModel } =
43
+ await import("./model-selection");
44
+ const retainedModel = allowWebSelection
45
+ ? selectedModel.get().modelId
46
+ : undefined;
47
+ let modelId = model;
48
+ if (allowWebSelection) {
49
+ modelId =
50
+ retainedModel !== undefined && isWebChatModelAllowed(retainedModel)
51
+ ? retainedModel
52
+ : await loadDefaultEveWebModelId(getConfiguredWebChatModel(model));
53
+ }
42
54
  let resolved;
43
55
  if (billing.debit === undefined) {
44
56
  resolved = await resolveEveModel(modelId);
@@ -31,6 +31,7 @@ vi.mock("../config", () => ({
31
31
  config: {
32
32
  ai: {
33
33
  disabledModels: ["disabled"],
34
+ providerOrder: [],
34
35
  gateway: "test",
35
36
  workflows: { chat: "plain" },
36
37
  },
@@ -137,3 +138,8 @@ test("accepts live catalog models absent from the snapshot", async () => {
137
138
  id: "live-only",
138
139
  });
139
140
  });
141
+
142
+ test("chooses a discovered chat model when the gateway's preferred ID is missing", async () => {
143
+ const { loadDefaultEveWebModelId } = await import("./model-selection");
144
+ expect(await loadDefaultEveWebModelId("missing-default")).toBe("plain");
145
+ });
@@ -8,12 +8,17 @@ import { getFallbackModels } from "@/lib/ai/gateways/fallback-models";
8
8
  import type { ModelData } from "@/lib/ai/model-data";
9
9
  import type { ReadonlyAiGatewayModel } from "@/lib/ai/to-model-data";
10
10
  import { toModelData } from "@/lib/ai/to-model-data";
11
+ import {
12
+ buildWebChatModels,
13
+ getDefaultWebChatModelId,
14
+ } from "@/lib/ai/web-chat-models";
11
15
  import { config } from "@/lib/config";
12
16
 
13
17
  const serializedOptions = z.record(z.string(), z.record(z.string(), z.json()));
14
18
  const MODEL_CATALOG_TTL_MS = 3_600_000;
15
19
  type EveModelDefinition = ModelData & {
16
20
  apiModelId: string;
21
+ selectedModelId: string;
17
22
  };
18
23
 
19
24
  class EveModelUnavailableError extends Error {
@@ -47,15 +52,14 @@ const getEveModelDefinition = (
47
52
  // The active gateway catalog above validates this ID at the runtime boundary.
48
53
  apiModelId: model.id,
49
54
  reasoning: model.reasoning && id.endsWith("-reasoning"),
55
+ selectedModelId: id,
50
56
  };
51
57
  };
52
58
 
53
59
  let catalog: { expires: number; models: ModelData[] } | undefined;
54
60
  let loading: Promise<ModelData[]> | undefined;
55
61
 
56
- const loadEveModelDefinition = async (
57
- requestedId?: string
58
- ): Promise<EveModelDefinition> => {
62
+ const loadEveModelCatalog = async (): Promise<readonly ModelData[]> => {
59
63
  if (!catalog || catalog.expires < Date.now()) {
60
64
  loading ??= (async (): Promise<ModelData[]> => {
61
65
  try {
@@ -72,9 +76,38 @@ const loadEveModelDefinition = async (
72
76
  loading = undefined;
73
77
  }
74
78
  })();
75
- return getEveModelDefinition(requestedId, await loading);
79
+ return await loading;
80
+ }
81
+ return catalog.models;
82
+ };
83
+
84
+ const defaultEveWebModelId = (
85
+ models: readonly ModelData[],
86
+ preferredModelId?: string
87
+ ): string => {
88
+ const id = getDefaultWebChatModelId(
89
+ buildWebChatModels(models),
90
+ preferredModelId
91
+ );
92
+ if (id === undefined) {
93
+ throw new EveModelUnavailableError("No models are available for chat.");
76
94
  }
77
- return getEveModelDefinition(requestedId, catalog.models);
95
+ return id;
96
+ };
97
+
98
+ const loadDefaultEveWebModelId = async (
99
+ preferredModelId: string
100
+ ): Promise<string> =>
101
+ defaultEveWebModelId(await loadEveModelCatalog(), preferredModelId);
102
+
103
+ const loadEveModelDefinition = async (
104
+ requestedId?: string
105
+ ): Promise<EveModelDefinition> => {
106
+ const models = await loadEveModelCatalog();
107
+ return getEveModelDefinition(
108
+ requestedId ?? defaultEveWebModelId(models),
109
+ models
110
+ );
78
111
  };
79
112
 
80
113
  const resolveEveModel = async (requestedId?: string): Promise<SessionModel> => {
@@ -83,7 +116,7 @@ const resolveEveModel = async (requestedId?: string): Promise<SessionModel> => {
83
116
  model: wrapLanguageModel({
84
117
  middleware: { specificationVersion: "v4" },
85
118
  model: getActiveGateway().createLanguageModel(model.apiModelId),
86
- modelId: requestedId ?? config.ai.workflows.chat,
119
+ modelId: model.selectedModelId,
87
120
  }),
88
121
  modelContextWindowTokens: model.context_window,
89
122
  modelOptions: {
@@ -94,6 +127,7 @@ const resolveEveModel = async (requestedId?: string): Promise<SessionModel> => {
94
127
  export {
95
128
  EveModelUnavailableError,
96
129
  getEveModelDefinition,
130
+ loadDefaultEveWebModelId,
97
131
  loadEveModelDefinition,
98
132
  resolveEveModel,
99
133
  };
@@ -5,7 +5,6 @@ import type { AppModelDefinition } from "@/lib/ai/app-models";
5
5
  import type { ReadonlyNativeSurface } from "@/lib/readonly-native-surface";
6
6
  import type { ReadonlyReactNode } from "@/lib/readonly-react-node";
7
7
  import { useModelVisibility } from "@/integrations/chat/model-visibility";
8
- import { getDefaultEnabledModels } from "@/lib/ai/app-models";
9
8
 
10
9
  interface ChatModelsContextType {
11
10
  readonly allModels: readonly ReadonlyNativeSurface<AppModelDefinition>[];
@@ -35,7 +34,7 @@ const ChatModelsProvider = ({
35
34
  }, [models]);
36
35
 
37
36
  const defaultEnabledIds = useMemo(
38
- () => getDefaultEnabledModels(models),
37
+ () => new Set(models.map((model) => model.id)),
39
38
  [models]
40
39
  );
41
40
  const enabledModelsSet = useModelVisibility(defaultEnabledIds);
@@ -1,4 +1,5 @@
1
1
  import branding from "../branding.json";
2
+ import { app } from "electron";
2
3
 
3
4
  const ELECTRON_AUTH_CLIENT_ID = branding.auth.clientId;
4
5
  const ELECTRON_AUTH_CALLBACK_PATH = branding.auth.callbackPath;
@@ -9,29 +10,12 @@ const APP_NAME = branding.appName;
9
10
  const APP_SCHEME = branding.appPrefix;
10
11
 
11
12
  const DEFAULT_DEV_APP_URL = "http://localhost:3000";
12
- const EMPTY_URL_LENGTH = 0;
13
-
14
- const resolveAppUrl = (
15
- environment: Readonly<
16
- Partial<Pick<NodeJS.ProcessEnv, "ELECTRON_APP_URL" | "NODE_ENV">>
17
- >
18
- ): string => {
19
- const configuredUrl = environment.ELECTRON_APP_URL;
20
- if (
21
- typeof configuredUrl === "string" &&
22
- configuredUrl.length > EMPTY_URL_LENGTH
23
- ) {
24
- return configuredUrl;
25
- }
26
-
27
- if (environment.NODE_ENV === "production") {
28
- return branding.appUrl;
29
- }
30
- return DEFAULT_DEV_APP_URL;
31
- };
32
-
33
- // Passing the process environment here preserves lazy NODE_ENV access in the fallback.
34
- const APP_URL = resolveAppUrl(process.env);
13
+ const defaultAppUrl = app.isPackaged ? branding.appUrl : DEFAULT_DEV_APP_URL;
14
+ const configuredAppUrl = process.env.ELECTRON_APP_URL;
15
+ const APP_URL =
16
+ configuredAppUrl !== undefined && configuredAppUrl !== ""
17
+ ? configuredAppUrl
18
+ : defaultAppUrl;
35
19
 
36
20
  const WINDOW_DEFAULTS = {
37
21
  height: 800,
@@ -7,10 +7,10 @@ import {
7
7
  } from "../config";
8
8
  import { createAuthClient } from "better-auth/client";
9
9
  import { electronClient } from "@better-auth/electron/client";
10
- import { safeStorage } from "electron";
10
+ import { app, safeStorage } from "electron";
11
11
  import { storage } from "@better-auth/electron/storage";
12
12
 
13
- if (process.env.NODE_ENV !== "production") {
13
+ if (!app.isPackaged) {
14
14
  Object.defineProperty(safeStorage, "isEncryptionAvailable", {
15
15
  configurable: true,
16
16
  value: (): boolean => false,
@@ -30,8 +30,7 @@ const memoryStorage = (): {
30
30
  };
31
31
  };
32
32
 
33
- const electronAuthStorage =
34
- process.env.NODE_ENV === "production" ? storage() : memoryStorage();
33
+ const electronAuthStorage = app.isPackaged ? storage() : memoryStorage();
35
34
 
36
35
  const electronAuthClient = createAuthClient({
37
36
  baseURL: APP_URL,
@@ -0,0 +1,133 @@
1
+ import { beforeAll, expect, mock, test } from "bun:test";
2
+ import path from "node:path";
3
+ import { Script } from "node:vm";
4
+
5
+ const branding = {
6
+ appName: "ChatJS",
7
+ appPrefix: "chatjs",
8
+ appUrl: "https://chat.example.test",
9
+ auth: {
10
+ callbackPath: "/electron/callback",
11
+ clientId: "chatjs-desktop",
12
+ cookiePrefix: "chatjs",
13
+ },
14
+ };
15
+ const devUrl = "http://localhost:3000";
16
+ const overrideUrl = "https://override.example.test";
17
+ let startup: Script;
18
+
19
+ beforeAll(async () => {
20
+ const result = await Bun.build({
21
+ entrypoints: [path.join(import.meta.dir, "lib/auth-client.ts")],
22
+ external: [
23
+ "@better-auth/electron/client",
24
+ "@better-auth/electron/storage",
25
+ "better-auth/client",
26
+ "electron",
27
+ ],
28
+ plugins: [
29
+ {
30
+ name: "startup-test-branding",
31
+ setup(build) {
32
+ build.onResolve(
33
+ { filter: /^\.\.\/branding\.json$/u },
34
+ ({ path: request }) => ({ external: true, path: request })
35
+ );
36
+ },
37
+ },
38
+ ],
39
+ format: "cjs",
40
+ target: "node",
41
+ });
42
+ expect(result.success).toBe(true);
43
+ startup = new Script(await result.outputs[0].text());
44
+ });
45
+
46
+ test.each([
47
+ {
48
+ name: "packaged launch without NODE_ENV uses the branded host",
49
+ isPackaged: true,
50
+ nodeEnv: undefined,
51
+ configuredUrl: undefined,
52
+ expectedUrl: branding.appUrl,
53
+ },
54
+ {
55
+ name: "packaged launch with an empty override uses the branded host",
56
+ isPackaged: true,
57
+ nodeEnv: "development",
58
+ configuredUrl: "",
59
+ expectedUrl: branding.appUrl,
60
+ },
61
+ {
62
+ name: "unpackaged launch with production NODE_ENV uses localhost",
63
+ isPackaged: false,
64
+ nodeEnv: "production",
65
+ configuredUrl: undefined,
66
+ expectedUrl: devUrl,
67
+ },
68
+ {
69
+ name: "packaged launch honors the configured URL",
70
+ isPackaged: true,
71
+ nodeEnv: "development",
72
+ configuredUrl: overrideUrl,
73
+ expectedUrl: overrideUrl,
74
+ },
75
+ {
76
+ name: "unpackaged launch honors the configured URL",
77
+ isPackaged: false,
78
+ nodeEnv: "production",
79
+ configuredUrl: overrideUrl,
80
+ expectedUrl: overrideUrl,
81
+ },
82
+ ])("$name", ({ isPackaged, nodeEnv, configuredUrl, expectedUrl }) => {
83
+ const protectedStorage = { getItem: mock(() => null), setItem: mock() };
84
+ const storage = mock(() => protectedStorage);
85
+ const safeStorage = { isEncryptionAvailable: () => true };
86
+ const createAuthClient = mock(
87
+ (_options: Readonly<{ baseURL: string }>) => ({})
88
+ );
89
+ const electronClient = mock(
90
+ (
91
+ options: Readonly<{
92
+ signInURL: string;
93
+ storage: Readonly<{
94
+ getItem: (key: string) => unknown;
95
+ setItem: (key: string, value: unknown) => void;
96
+ }>;
97
+ }>
98
+ ) => options
99
+ );
100
+ const modules = new Map<string, unknown>([
101
+ ["../branding.json", branding],
102
+ ["better-auth/client", { createAuthClient }],
103
+ ["@better-auth/electron/client", { electronClient }],
104
+ ["@better-auth/electron/storage", { storage }],
105
+ ["electron", { app: { isPackaged }, safeStorage }],
106
+ ]);
107
+
108
+ startup.runInNewContext({
109
+ module: { exports: {} },
110
+ process: { env: { ELECTRON_APP_URL: configuredUrl, NODE_ENV: nodeEnv } },
111
+ require: (request: string) => {
112
+ if (!modules.has(request)) {
113
+ throw new Error(`Unexpected startup dependency: ${request}`);
114
+ }
115
+ return modules.get(request);
116
+ },
117
+ });
118
+
119
+ const [[{ baseURL }]] = createAuthClient.mock.calls;
120
+ const [[plugin]] = electronClient.mock.calls;
121
+ expect(baseURL).toBe(expectedUrl);
122
+ expect(plugin.signInURL).toBe(`${expectedUrl}/device-login`);
123
+ expect(safeStorage.isEncryptionAvailable()).toBe(isPackaged);
124
+ if (isPackaged) {
125
+ expect(storage).toHaveBeenCalledTimes(1);
126
+ expect(plugin.storage).toBe(protectedStorage);
127
+ } else {
128
+ expect(storage).not.toHaveBeenCalled();
129
+ expect(plugin.storage.getItem("session")).toBeNull();
130
+ plugin.storage.setItem("session", "local-session");
131
+ expect(plugin.storage.getItem("session")).toBe("local-session");
132
+ }
133
+ });