chat-js 1.0.0-alpha.8 → 1.0.0-beta.0

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 (84) hide show
  1. package/README.md +7 -5
  2. package/dist/index.js +7161 -6308
  3. package/package.json +2 -2
  4. package/templates/chat-app/agent/agent.ts +0 -2
  5. package/templates/chat-app/app/editor.css +0 -6
  6. package/templates/chat-app/app/layout.tsx +11 -18
  7. package/templates/chat-app/app/opengraph-image.png +0 -0
  8. package/templates/chat-app/chat.config.ts +0 -44
  9. package/templates/chat-app/chatjs/core/gateway/runtime.ts +0 -7
  10. package/templates/chat-app/chatjs/core/ui/slots.tsx +15 -5
  11. package/templates/chat-app/chatjs/generated/installed-chat-ui.ts +4 -0
  12. package/templates/chat-app/chatjs/generated/installed.ts +2 -0
  13. package/templates/chat-app/chatjs/plugins/guest-chat/signed-out.tsx +7 -4
  14. package/templates/chat-app/chatjs/plugins/mcp/routes/connectors-page.tsx +4 -1
  15. package/templates/chat-app/chatjs/plugins/mcp/ui/connectors-settings.tsx +1 -1
  16. package/templates/chat-app/chatjs/plugins/mcp/ui/mcp-connect-dialog.tsx +1 -1
  17. package/templates/chat-app/chatjs/plugins/mcp/ui/mcp-create-dialog.tsx +1 -1
  18. package/templates/chat-app/chatjs/plugins/model-preferences/model-row.tsx +3 -0
  19. package/templates/chat-app/chatjs/plugins/model-preferences/models-settings.tsx +1 -0
  20. package/templates/chat-app/chatjs/plugins/projects/routes/project-page.tsx +10 -1
  21. package/templates/chat-app/chatjs/plugins/projects/ui/delete-project-dialog.tsx +0 -3
  22. package/templates/chat-app/chatjs/plugins/projects/ui/project-icon-picker.tsx +1 -0
  23. package/templates/chat-app/chatjs/plugins/streamdown-math/chat-ui.ts +11 -0
  24. package/templates/chat-app/chatjs/plugins/streamdown-math/plugin.json +6 -0
  25. package/templates/chat-app/chatjs/plugins/streamdown-mermaid/chat-ui.ts +10 -0
  26. package/templates/chat-app/chatjs/plugins/streamdown-mermaid/plugin.json +6 -0
  27. package/templates/chat-app/chatjs/providers/gateway.ts +49 -55
  28. package/templates/chat-app/chatjs/tools/generate-image/tool.test.ts +3 -14
  29. package/templates/chat-app/components/ai-elements/response.tsx +16 -15
  30. package/templates/chat-app/components/auth-form-view.tsx +35 -43
  31. package/templates/chat-app/components/chat/chat-composer.tsx +55 -20
  32. package/templates/chat-app/components/chat/chat-sidebar.tsx +5 -3
  33. package/templates/chat-app/components/composer/prompt-form.tsx +7 -1
  34. package/templates/chat-app/components/eve/eve-chat-error.tsx +12 -2
  35. package/templates/chat-app/components/eve/eve-conversation.tsx +223 -154
  36. package/templates/chat-app/components/eve/eve-creation-recovery.tsx +32 -1
  37. package/templates/chat-app/components/eve/eve-history-list.tsx +1 -1
  38. package/templates/chat-app/components/model-selection-indicator.tsx +12 -10
  39. package/templates/chat-app/components/model-selector-view.tsx +211 -186
  40. package/templates/chat-app/components/new-chat-button.tsx +1 -1
  41. package/templates/chat-app/components/settings/settings-nav.tsx +1 -1
  42. package/templates/chat-app/components/settings/settings-navigation-link.tsx +1 -0
  43. package/templates/chat-app/components/sidebar-top-row.tsx +1 -1
  44. package/templates/chat-app/components/ui/sidebar.tsx +1 -1
  45. package/templates/chat-app/components/ui/trace.tsx +1 -1
  46. package/templates/chat-app/hooks/use-auto-focus.ts +12 -13
  47. package/templates/chat-app/lib/ai/active-gateway.ts +0 -9
  48. package/templates/chat-app/lib/ai/app-models.test.ts +0 -4
  49. package/templates/chat-app/lib/ai/app-models.ts +11 -6
  50. package/templates/chat-app/lib/ai/gateways/registry.ts +4 -31
  51. package/templates/chat-app/lib/ai/model-catalog.ts +50 -0
  52. package/templates/chat-app/lib/ai/models.ts +4 -39
  53. package/templates/chat-app/lib/ai/providers.ts +2 -16
  54. package/templates/chat-app/lib/config-schema.ts +0 -96
  55. package/templates/chat-app/lib/devtools-disabled.ts +1 -0
  56. package/templates/chat-app/lib/eve/model-selection.test.ts +47 -50
  57. package/templates/chat-app/lib/eve/model-selection.ts +5 -37
  58. package/templates/chat-app/lib/eve/tool-cost.test.ts +18 -6
  59. package/templates/chat-app/lib/eve/tool-cost.ts +10 -18
  60. package/templates/chat-app/oxfmt.config.ts +0 -2
  61. package/templates/chat-app/package.json +7 -9
  62. package/templates/chat-app/proxy.ts +2 -4
  63. package/templates/chat-app/scripts/build-eve.test.ts +56 -0
  64. package/templates/chat-app/scripts/build-eve.ts +12 -5
  65. package/templates/chat-app/scripts/check-env.ts +2 -17
  66. package/templates/chat-app/scripts/environment-validation-report.ts +1 -20
  67. package/templates/chat-app/trpc/react.tsx +2 -2
  68. package/templates/electron/forge.config.ts +1 -19
  69. package/templates/electron/scripts/write-branding.ts +1 -5
  70. package/templates/chat-app/app/privacy/page.tsx +0 -153
  71. package/templates/chat-app/app/terms/page.tsx +0 -270
  72. package/templates/chat-app/components/ai-elements/context-hover.radix.tsx +0 -15
  73. package/templates/chat-app/components/ai-elements/context-hover.tsx +0 -17
  74. package/templates/chat-app/components/ai-elements/context.tsx +0 -405
  75. package/templates/chat-app/components/composer/editor.css +0 -96
  76. package/templates/chat-app/components/lexical-chat-input.tsx +0 -276
  77. package/templates/chat-app/components/model-selection-indicator.radix.tsx +0 -17
  78. package/templates/chat-app/components/ui/resizable.tsx +0 -49
  79. package/templates/chat-app/lib/ai/gateways/fallback-models.ts +0 -29
  80. package/templates/chat-app/lib/ai/models.generated.ts +0 -4242
  81. package/templates/chat-app/lib/ai/usage-token-details.test.ts +0 -76
  82. package/templates/chat-app/lib/ai/usage-token-details.ts +0 -33
  83. package/templates/chat-app/scripts/fetch-models.ts +0 -30
  84. package/templates/chat-app/scripts/gateway-snapshot-warning.test.ts +0 -9
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chat-js",
3
- "version": "1.0.0-alpha.8",
3
+ "version": "1.0.0-beta.0",
4
4
  "private": false,
5
5
  "description": "CLI for creating and extending ChatJS apps",
6
6
  "keywords": [
@@ -33,7 +33,7 @@
33
33
  },
34
34
  "publishConfig": {
35
35
  "access": "public",
36
- "tag": "alpha"
36
+ "tag": "beta"
37
37
  },
38
38
  "scripts": {
39
39
  "start": "bun src/index.ts",
@@ -10,8 +10,6 @@ export default defineAgent({
10
10
  model: applicationModel(config.ai.workflows.chat),
11
11
  reasoning: "provider-default",
12
12
  defaultTools: true,
13
- approval: ({ toolAnnotations }) =>
14
- toolAnnotations?.readOnlyHint === true ? "approved" : "user-approval",
15
13
  build: {
16
14
  externalDependencies: [
17
15
  "pino",
@@ -1,9 +1,3 @@
1
- @import "../components/composer/editor.css";
2
-
3
- .lexical-editor {
4
- outline: none;
5
- }
6
-
7
1
  .cm-editor,
8
2
  .cm-gutters {
9
3
  @apply bg-card! outline-hidden! selection:bg-zinc-900!;
@@ -2,7 +2,6 @@ import { Geist, Geist_Mono } from "next/font/google";
2
2
  import type { Metadata, Viewport } from "next";
3
3
  import type { ReadonlyReactNode } from "@/lib/readonly-react-node";
4
4
  import Script from "next/script";
5
- import { NuqsAdapter } from "nuqs/adapters/next/app";
6
5
 
7
6
  import "./globals.css";
8
7
  import components from "@/components.json";
@@ -93,24 +92,18 @@ const RootLayout = ({
93
92
  ) : null}
94
93
  </head>
95
94
  <body className="antialiased">
96
- <Script
97
- src="https://cdn.jsdelivr.net/pyodide/v0.23.4/full/pyodide.js"
98
- strategy="afterInteractive"
99
- />
100
95
  <UiDirection direction={components.rtl ? "rtl" : "ltr"}>
101
- <NuqsAdapter>
102
- <ThemeProvider
103
- attribute="class"
104
- defaultTheme="system"
105
- disableTransitionOnChange
106
- enableSystem
107
- >
108
- <TooltipProvider>
109
- <Toaster position="top-center" />
110
- {children}
111
- </TooltipProvider>
112
- </ThemeProvider>
113
- </NuqsAdapter>
96
+ <ThemeProvider
97
+ attribute="class"
98
+ defaultTheme="system"
99
+ disableTransitionOnChange
100
+ enableSystem
101
+ >
102
+ <TooltipProvider>
103
+ <Toaster position="top-center" />
104
+ {children}
105
+ </TooltipProvider>
106
+ </ThemeProvider>
114
107
  </UiDirection>
115
108
  <LayoutPlugins />
116
109
  </body>
@@ -68,49 +68,5 @@ const config = defineConfig({
68
68
  features: {
69
69
  parallelResponses: true,
70
70
  },
71
- legal: {
72
- governingLaw: "United States",
73
- minimumAge: 13,
74
- refundPolicy: "no-refunds",
75
- },
76
- organization: {
77
- contact: {
78
- legalEmail: "legal@chatjs.dev",
79
- privacyEmail: "privacy@chatjs.dev",
80
- },
81
- name: "ChatJS",
82
- },
83
- policies: {
84
- privacy: {
85
- lastUpdated: "July 24, 2025",
86
- title: "Privacy Policy",
87
- },
88
- terms: {
89
- lastUpdated: "July 24, 2025",
90
- title: "Terms of Service",
91
- },
92
- },
93
- services: {
94
- aiProviders: [
95
- "OpenAI",
96
- "Anthropic",
97
- "xAI",
98
- "Google",
99
- "Meta",
100
- "Mistral",
101
- "Alibaba",
102
- "Amazon",
103
- "Cohere",
104
- "DeepSeek",
105
- "Perplexity",
106
- "Vercel",
107
- "Inception",
108
- "Moonshot",
109
- "Morph",
110
- "ZAI",
111
- ],
112
- hosting: "Vercel",
113
- paymentProcessors: [],
114
- },
115
71
  });
116
72
  export default config;
@@ -1,5 +1,3 @@
1
- import type { AiGatewayModel } from "./models.ts";
2
-
3
1
  interface GatewayLogger {
4
2
  debug: (data: unknown, message?: string) => void;
5
3
  info: (data: unknown, message?: string) => void;
@@ -12,7 +10,6 @@ interface GatewayOptions {
12
10
  fetch?: (
13
11
  ...args: Parameters<typeof globalThis.fetch>
14
12
  ) => ReturnType<typeof globalThis.fetch>;
15
- getFallbackModels?: (gateway: string) => readonly AiGatewayModel[];
16
13
  logger?: GatewayLogger;
17
14
  }
18
15
 
@@ -39,9 +36,6 @@ const silentLogger: GatewayLogger = {
39
36
  class GatewayRuntime {
40
37
  protected readonly env: NonNullable<GatewayOptions["env"]>;
41
38
  protected readonly fetch: NonNullable<GatewayOptions["fetch"]>;
42
- protected readonly getFallbackModels: NonNullable<
43
- GatewayOptions["getFallbackModels"]
44
- >;
45
39
  protected readonly log: GatewayLogger;
46
40
 
47
41
  public constructor(options: GatewayReaderOptions = {}) {
@@ -52,7 +46,6 @@ class GatewayRuntime {
52
46
  ...args: Parameters<typeof globalThis.fetch>
53
47
  ): ReturnType<typeof globalThis.fetch> =>
54
48
  await globalThis.fetch(...args));
55
- this.getFallbackModels = options.getFallbackModels ?? ((): never[] => []);
56
49
  this.log = options.logger ?? silentLogger;
57
50
  }
58
51
  }
@@ -3,20 +3,28 @@
3
3
  import { createContext, createElement, useContext, useMemo } from "react";
4
4
  import type { ComponentType, ReactNode } from "react";
5
5
 
6
+ import type { PluginConfig } from "streamdown";
7
+
8
+ type MarkdownPlugins = Pick<PluginConfig, "math" | "mermaid">;
9
+
6
10
  interface SlotBinding {
7
11
  readonly slot: object;
8
12
  readonly View: ComponentType;
9
13
  }
10
14
  export interface UiPlugin {
11
15
  readonly id: string;
16
+ readonly streamdown?: MarkdownPlugins;
12
17
  readonly slots: readonly SlotBinding[];
13
18
  }
14
19
  interface InstalledSlotBinding extends SlotBinding {
15
20
  readonly key: string;
16
21
  }
17
- const Bindings = createContext<
18
- ReadonlyMap<object, readonly InstalledSlotBinding[]>
19
- >(new Map());
22
+ const Bindings = createContext<{
23
+ readonly slots: ReadonlyMap<object, readonly InstalledSlotBinding[]>;
24
+ readonly streamdown: MarkdownPlugins;
25
+ }>({ slots: new Map(), streamdown: {} });
26
+
27
+ export const useMarkdownPlugins = () => useContext(Bindings).streamdown;
20
28
 
21
29
  const bindSlot = Symbol("bindSlot");
22
30
 
@@ -26,7 +34,7 @@ export const defineSlot = <Props extends object = Record<string, never>>() => {
26
34
  const SlotProps = createContext<Props | null>(null);
27
35
  const useBindings = () => {
28
36
  const installed = useContext(Bindings);
29
- return installed.get(identity) ?? [];
37
+ return installed.slots.get(identity) ?? [];
30
38
  };
31
39
  const Slot = (props: Props) => {
32
40
  const entries = useBindings();
@@ -73,19 +81,21 @@ export const Plugins = ({
73
81
  }) => {
74
82
  const registry = useMemo(() => {
75
83
  const resolved = new Map<object, InstalledSlotBinding[]>();
84
+ const streamdown: MarkdownPlugins = {};
76
85
  const seen = new Set<string>();
77
86
  for (const plugin of plugins) {
78
87
  if (seen.has(plugin.id)) {
79
88
  throw new Error(`Duplicate UI plugin: ${plugin.id}`);
80
89
  }
81
90
  seen.add(plugin.id);
91
+ Object.assign(streamdown, plugin.streamdown);
82
92
  for (const [index, binding] of plugin.slots.entries()) {
83
93
  const entries = resolved.get(binding.slot) ?? [];
84
94
  entries.push({ ...binding, key: `${plugin.id}:${index}` });
85
95
  resolved.set(binding.slot, entries);
86
96
  }
87
97
  }
88
- return resolved;
98
+ return { slots: resolved, streamdown };
89
99
  }, [plugins]);
90
100
  return <Bindings value={registry}>{children}</Bindings>;
91
101
  };
@@ -11,6 +11,8 @@ import { chatUi as projectsClient } from "@/chatjs/plugins/projects/chat-ui";
11
11
  import { chatUi as searchClient } from "@/chatjs/plugins/search/chat-ui";
12
12
  import { chatUi as sharingClient } from "@/chatjs/plugins/sharing/chat-ui";
13
13
  import { chatUi as spreadsheetViewerClient } from "@/chatjs/plugins/spreadsheet-viewer/chat-ui";
14
+ import { chatUi as streamdownMathClient } from "@/chatjs/plugins/streamdown-math/chat-ui";
15
+ import { chatUi as streamdownMermaidClient } from "@/chatjs/plugins/streamdown-mermaid/chat-ui";
14
16
  import { chatUi as videoViewerClient } from "@/chatjs/plugins/video-viewer/chat-ui";
15
17
  import type { UiPlugin } from "@/chatjs/core/ui/slots";
16
18
  export const installedChatPlugins: readonly UiPlugin[] = [
@@ -25,5 +27,7 @@ export const installedChatPlugins: readonly UiPlugin[] = [
25
27
  searchClient,
26
28
  sharingClient,
27
29
  spreadsheetViewerClient,
30
+ streamdownMathClient,
31
+ streamdownMermaidClient,
28
32
  videoViewerClient,
29
33
  ];
@@ -14,5 +14,7 @@ export const installedPlugins: ReadonlySet<string> = new Set([
14
14
  "search",
15
15
  "sharing",
16
16
  "spreadsheet-viewer",
17
+ "streamdown-math",
18
+ "streamdown-mermaid",
17
19
  "video-viewer",
18
20
  ]);
@@ -125,17 +125,20 @@ const GuestConversationView = ({
125
125
  </p>
126
126
  )}
127
127
  {expired && (
128
- <output className="text-muted-foreground mb-3 text-sm">
129
- This chat has expired. Start a new chat to continue.
128
+ <div className="mb-3 flex items-center justify-between gap-3 rounded-2xl border px-3 py-2">
129
+ <output className="text-muted-foreground text-sm">
130
+ This chat has expired.
131
+ </output>
130
132
  <Button
131
- variant="link"
133
+ variant="outline"
134
+ size="sm"
132
135
  onClick={() => {
133
136
  globalThis.dispatchEvent(new Event("chatjs:new-chat"));
134
137
  }}
135
138
  >
136
139
  New chat
137
140
  </Button>
138
- </output>
141
+ </div>
139
142
  )}
140
143
  <EveComposer
141
144
  autoFocus
@@ -1,4 +1,5 @@
1
1
  import { HydrationBoundary, dehydrate } from "@tanstack/react-query";
2
+ import { NuqsAdapter } from "nuqs/adapters/next/app";
2
3
  import { connection } from "next/server";
3
4
  import React, { Suspense } from "react";
4
5
 
@@ -32,7 +33,9 @@ const ConnectorsSettingsContent = async (): Promise<React.JSX.Element> => {
32
33
  <HydrationBoundary state={dehydrate(queryClient)}>
33
34
  <SettingsPage>
34
35
  <ConnectorsSettingsHeader />
35
- <ConnectorsSettings />
36
+ <NuqsAdapter>
37
+ <ConnectorsSettings />
38
+ </NuqsAdapter>
36
39
  </SettingsPage>
37
40
  </HydrationBoundary>
38
41
  );
@@ -163,7 +163,7 @@ const CustomConnectorRow = ({
163
163
  ) : null}
164
164
  <DropdownMenu>
165
165
  <MenuButton
166
- aria-label="More connector actions"
166
+ aria-label={`More actions for ${connector.name}`}
167
167
  size="icon"
168
168
  variant="ghost"
169
169
  >
@@ -123,7 +123,7 @@ export const McpConnectDialog = ({
123
123
  }}
124
124
  open={open}
125
125
  >
126
- <DialogContent className="sm:max-w-md">
126
+ <DialogContent className="max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-md">
127
127
  <DialogHeader className="overflow-hidden">
128
128
  <div className="flex items-center gap-3 overflow-hidden">
129
129
  <div className="bg-muted flex size-10 shrink-0 items-center justify-center rounded-md">
@@ -169,7 +169,7 @@ export const McpCreateDialog = ({
169
169
  }}
170
170
  open={open}
171
171
  >
172
- <DialogContent className="sm:max-w-md">
172
+ <DialogContent className="max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-md">
173
173
  <DialogHeader>
174
174
  <DialogTitle className="flex items-center gap-2">
175
175
  Add custom connector
@@ -44,6 +44,9 @@ const ModelRowComponent = ({
44
44
  </TableCell>
45
45
  <TableCell className="py-2.5 pr-0">
46
46
  <Switch
47
+ aria-label={
48
+ model.reasoning === true ? `${model.name} (reasoning)` : model.name
49
+ }
47
50
  checked={isEnabled}
48
51
  onCheckedChange={() => {
49
52
  onToggle(model.id, isEnabled);
@@ -40,6 +40,7 @@ export const ModelsSettings = (): ReactJSX.Element => {
40
40
  value={search}
41
41
  />
42
42
  <Button
43
+ aria-label="Refresh model preferences"
43
44
  onClick={() => {
44
45
  void queryClient.invalidateQueries({
45
46
  queryKey: trpc.modelPreferences.getModelPreferences.queryKey(),
@@ -3,6 +3,8 @@ import { notFound, redirect } from "next/navigation";
3
3
  import React, { Suspense } from "react";
4
4
  import { z } from "zod";
5
5
 
6
+ import { InternalLink } from "@/components/internal-link";
7
+ import { buttonVariants } from "@/components/ui/button";
6
8
  import { EveCreationRecovery } from "@/components/eve/eve-creation-recovery";
7
9
  import { EveProjectHome } from "@/chatjs/plugins/projects/ui/eve-project-home";
8
10
  import { auth } from "@/lib/auth";
@@ -29,9 +31,10 @@ const ProjectContent = async ({
29
31
  const project = await getProjectById({ id: projectId });
30
32
  if (project === undefined || project.userId !== session.user.id) {
31
33
  return (
32
- <div className="p-4">
34
+ <div className="space-y-4 p-4">
33
35
  <h1 className="text-xl font-semibold">Project unavailable</h1>
34
36
  <EveCreationRecovery
37
+ missingRequestMessage="This project may have been deleted, or your account may not have access."
35
38
  firstMessage=""
36
39
  ownerId={session.user.id}
37
40
  scope={{
@@ -41,6 +44,12 @@ const ProjectContent = async ({
41
44
  },
42
45
  }}
43
46
  />
47
+ <InternalLink
48
+ className={buttonVariants({ variant: "outline" })}
49
+ href="/"
50
+ >
51
+ Back to chats
52
+ </InternalLink>
44
53
  </div>
45
54
  );
46
55
  }
@@ -40,9 +40,6 @@ export const DeleteProjectDialog = ({
40
40
 
41
41
  const deleteMutation = useMutation(
42
42
  trpc.project.remove.mutationOptions({
43
- onError: () => {
44
- toast.error("Failed to delete project");
45
- },
46
43
  onSuccess: async () => {
47
44
  await Promise.all([
48
45
  queryClient.invalidateQueries({
@@ -44,6 +44,7 @@ export const ProjectIconPicker = ({
44
44
  return (
45
45
  <Popover>
46
46
  <PopoverButton
47
+ aria-label="Choose project icon and color"
47
48
  className={cn("size-9 p-0", className)}
48
49
  type="button"
49
50
  variant="outline"
@@ -0,0 +1,11 @@
1
+ "use client";
2
+
3
+ import "katex/dist/katex.min.css";
4
+ import { math } from "@streamdown/math";
5
+ import { definePlugin } from "@/chatjs/core/ui/slots";
6
+
7
+ export const chatUi = definePlugin({
8
+ id: "streamdown-math",
9
+ slots: [],
10
+ streamdown: { math },
11
+ });
@@ -0,0 +1,6 @@
1
+ {
2
+ "contractVersion": 3,
3
+ "id": "streamdown-math",
4
+ "kind": "plugin",
5
+ "files": ["chatjs/plugins/streamdown-math/chat-ui.ts"]
6
+ }
@@ -0,0 +1,10 @@
1
+ "use client";
2
+
3
+ import { mermaid } from "@streamdown/mermaid";
4
+ import { definePlugin } from "@/chatjs/core/ui/slots";
5
+
6
+ export const chatUi = definePlugin({
7
+ id: "streamdown-mermaid",
8
+ slots: [],
9
+ streamdown: { mermaid },
10
+ });
@@ -0,0 +1,6 @@
1
+ {
2
+ "contractVersion": 3,
3
+ "id": "streamdown-mermaid",
4
+ "kind": "plugin",
5
+ "files": ["chatjs/plugins/streamdown-mermaid/chat-ui.ts"]
6
+ }
@@ -16,6 +16,7 @@ import type { gateway } from "@ai-sdk/gateway";
16
16
  import { getVercelOidcToken } from "@vercel/oidc";
17
17
  import { z } from "zod";
18
18
 
19
+ const MODEL_DISCOVERY_TIMEOUT_MS = 10_000;
19
20
  const MODEL_ID_PARAMETER_INDEX = 0;
20
21
  type VercelImageModelId = Parameters<
21
22
  (typeof gateway)["imageModel"]
@@ -90,68 +91,61 @@ class VercelGateway
90
91
  apiKey === null ? catalogUrl : `${catalogUrl}?include_availability`;
91
92
  this.log.debug({ url }, "Fetching models from Vercel AI Gateway");
92
93
 
93
- try {
94
- const response = await this.fetch(
95
- url,
96
- apiKey === null
97
- ? undefined
98
- : { headers: { Authorization: `Bearer ${apiKey}` } }
99
- );
94
+ const response = await this.fetch(url, {
95
+ headers:
96
+ apiKey === null ? undefined : { Authorization: `Bearer ${apiKey}` },
97
+ signal: AbortSignal.timeout(MODEL_DISCOVERY_TIMEOUT_MS),
98
+ });
100
99
 
101
- if (!response.ok) {
102
- this.log.error(
103
- { status: response.status, statusText: response.statusText, url },
104
- "Vercel AI Gateway returned non-OK response"
105
- );
106
- throw new Error(`Failed to fetch models: ${response.statusText}`);
107
- }
100
+ if (!response.ok) {
101
+ this.log.error(
102
+ { status: response.status, statusText: response.statusText, url },
103
+ "Vercel AI Gateway returned non-OK response"
104
+ );
105
+ throw new Error(
106
+ `Failed to fetch models: ${response.status} ${response.statusText}`
107
+ );
108
+ }
108
109
 
109
- const bodyRaw: unknown = await response.json();
110
- const body = modelsEnvelopeSchema.parse(bodyRaw);
111
- const unsupportedTypes = new Set<string>();
112
- const models: AiGatewayModel[] = [];
113
-
114
- for (const candidate of body.data) {
115
- const { type } = modelDiscriminatorSchema.parse(candidate);
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
- }
126
- models.push(aiGatewayModelSchema.parse(candidate));
127
- } else {
128
- unsupportedTypes.add(type);
110
+ const bodyRaw: unknown = await response.json();
111
+ const body = modelsEnvelopeSchema.parse(bodyRaw);
112
+ const unsupportedTypes = new Set<string>();
113
+ const models: AiGatewayModel[] = [];
114
+
115
+ for (const candidate of body.data) {
116
+ const { type } = modelDiscriminatorSchema.parse(candidate);
117
+ if (isAiGatewayModelType(type)) {
118
+ const availability = modelAvailability.safeParse(candidate);
119
+ const eligibility = availability.data?.model_eligibility;
120
+ if (
121
+ eligibility?.status === "ineligible" &&
122
+ (eligibility.category === "policy" ||
123
+ eligibility.category === "configuration")
124
+ ) {
125
+ continue;
129
126
  }
127
+ models.push(aiGatewayModelSchema.parse(candidate));
128
+ } else {
129
+ unsupportedTypes.add(type);
130
130
  }
131
+ }
131
132
 
132
- if (unsupportedTypes.size > EMPTY_MODEL_TYPE_COUNT) {
133
- this.log.warn(
134
- {
135
- modelCount: body.data.length,
136
- skippedModelCount: body.data.length - models.length,
137
- unsupportedTypes: [...unsupportedTypes],
138
- },
139
- "Skipping models with unsupported types from Vercel AI Gateway"
140
- );
141
- }
142
-
143
- this.log.info(
144
- { modelCount: models.length },
145
- "Successfully fetched models from Vercel AI Gateway"
133
+ if (unsupportedTypes.size > EMPTY_MODEL_TYPE_COUNT) {
134
+ this.log.warn(
135
+ {
136
+ modelCount: body.data.length,
137
+ skippedModelCount: body.data.length - models.length,
138
+ unsupportedTypes: [...unsupportedTypes],
139
+ },
140
+ "Skipping models with unsupported types from Vercel AI Gateway"
146
141
  );
147
- return models;
148
- } catch (error) {
149
- this.log.error(
150
- { err: error, url },
151
- "Error fetching models from Vercel AI Gateway, falling back to generated models"
152
- );
153
- return [...this.getFallbackModels(this.type)];
154
142
  }
143
+
144
+ this.log.info(
145
+ { modelCount: models.length },
146
+ "Successfully fetched models from Vercel AI Gateway"
147
+ );
148
+ return models;
155
149
  }
156
150
  }
157
151
  export { VercelGateway as Gateway, VercelGateway };
@@ -39,20 +39,9 @@ vi.mock(
39
39
  vi.mock("@/lib/eve/tool-image-context", () => ({
40
40
  eveToolImageContext: { get: mocks.images },
41
41
  }));
42
- vi.mock(
43
- "@/lib/ai/active-gateway",
44
- (): { getActiveGateway: () => { fetchModels: typeof mocks.catalog } } => ({
45
- getActiveGateway: (): { fetchModels: typeof mocks.catalog } => ({
46
- fetchModels: mocks.catalog,
47
- }),
48
- })
49
- );
50
- vi.mock(
51
- "@/lib/ai/to-model-data",
52
- (): { toModelData: (value: unknown) => unknown } => ({
53
- toModelData: (value: unknown) => value,
54
- })
55
- );
42
+ vi.mock("@/lib/ai/model-catalog", () => ({
43
+ loadModelCatalog: mocks.catalog,
44
+ }));
56
45
  vi.mock("@/lib/config", () => ({
57
46
  config: {
58
47
  ai: { tools: { image: { default: "test-image" } } },
@@ -2,31 +2,32 @@
2
2
 
3
3
  import "streamdown/styles.css";
4
4
 
5
- import React, { memo } from "react";
5
+ import React, { memo, useMemo } from "react";
6
6
  import type { ComponentProps } from "react";
7
7
  import { Streamdown } from "streamdown";
8
8
  import { cn } from "@/lib/utils";
9
9
  import { code } from "@streamdown/code";
10
- import { math } from "@streamdown/math";
11
- import { mermaid } from "@streamdown/mermaid";
12
-
13
- const plugins = { code, math, mermaid };
10
+ import { useMarkdownPlugins } from "@/chatjs/core/ui/slots";
14
11
 
15
12
  type ResponseProps = ComponentProps<typeof Streamdown>;
16
13
 
17
14
  const ResponseComponent = ({
18
15
  className,
19
16
  ...props
20
- }: ResponseProps): React.JSX.Element => (
21
- <Streamdown
22
- className={cn(
23
- "w-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",
24
- className
25
- )}
26
- plugins={plugins}
27
- {...props}
28
- />
29
- );
17
+ }: ResponseProps): React.JSX.Element => {
18
+ const markdown = useMarkdownPlugins();
19
+ const plugins = useMemo(() => ({ code, ...markdown }), [markdown]);
20
+ return (
21
+ <Streamdown
22
+ className={cn(
23
+ "w-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",
24
+ className
25
+ )}
26
+ plugins={plugins}
27
+ {...props}
28
+ />
29
+ );
30
+ };
30
31
 
31
32
  const Response = memo(
32
33
  ResponseComponent,