@hanzo/browser-extension 1.9.49 → 1.9.53

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.
@@ -0,0 +1,385 @@
1
+ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+ import { createAiClient, type AiClient, type SearchEvent, type SearchSource } from '@hanzo/ai';
3
+ import { fetchNews, type NewsItem } from './news.js';
4
+ import { AUTO_MODEL, fetchModelCatalog, type ChatModel, type ModelGroup } from './model-catalog.js';
5
+ import { renderMarkdown } from './markdown.js';
6
+ import { capture, contributeTrainingSample } from '../shared/consent.js';
7
+ import { Composer, type Mode } from './Composer.js';
8
+ import { Rail } from './Rail.js';
9
+ import { Source } from './Source.js';
10
+ import { Stories } from './Stories.js';
11
+ import { Widgets } from './WidgetView.js';
12
+ import { extractWidgets } from './widget.js';
13
+ import { DEFAULT_PROVIDER_ID, fallbackUrl, loadProviderId, providerById } from './websearch.js';
14
+
15
+ /**
16
+ * Hanzo Answer Engine — the shared AI-answer surface (query → streamed answer +
17
+ * inline citations + sources + live news). Backend = api.hanzo.ai ONLY, reached
18
+ * through @hanzo/ai: `search` for the grounded modes, `chat.completions` for
19
+ * Chat (each capability defined in exactly one place). Strict monochrome per
20
+ * the Hanzo brand.
21
+ *
22
+ * This file holds the state and the wire. Everything it draws with is a
23
+ * presentational sibling — Rail, Composer (Models), Source, Stories — each one
24
+ * a component whose data and effects arrive as props, so the same parts can be
25
+ * lifted into @hanzo/ui and mounted by chat and app without dragging the
26
+ * extension's transport along.
27
+ */
28
+
29
+ /**
30
+ * Chat mode — the same question, ungrounded, straight to the model. It yields
31
+ * `SearchEvent`s so the surface keeps ONE stream to consume and ONE way to
32
+ * render an answer; a mode is a value the wire takes, never a second UI.
33
+ */
34
+ async function* converse(
35
+ client: AiClient,
36
+ question: string,
37
+ model: string,
38
+ signal: AbortSignal,
39
+ ): AsyncGenerator<SearchEvent> {
40
+ const stream = await client.chat.completions.create(
41
+ { model, messages: [{ role: 'user', content: question }], stream: true },
42
+ { signal },
43
+ );
44
+ let answer = '';
45
+ for await (const chunk of stream) {
46
+ const delta = chunk.choices?.[0]?.delta?.content;
47
+ if (!delta) continue;
48
+ answer += delta;
49
+ yield { type: 'text', delta };
50
+ }
51
+ yield { type: 'done', answer, sources: [] };
52
+ }
53
+
54
+ export interface AnswerEngineProps {
55
+ apiBase: string;
56
+ /** Resolves the current IAM bearer, or null when signed out. */
57
+ getToken: () => Promise<string | null>;
58
+ /** Kicks off IAM sign-in (opens the OAuth tab). */
59
+ signIn: () => void;
60
+ /** Optional initial query (from the omnibox / address bar `?q=`). */
61
+ initialQuery?: string;
62
+ }
63
+
64
+ export function AnswerEngine({ apiBase, getToken, signIn, initialQuery }: AnswerEngineProps) {
65
+ // Sidebar hidden by default — the answer surface should read like hanzo.chat:
66
+ // a single centered column. A fixed toggle (below) brings the rail back.
67
+ const [collapsed, setCollapsed] = useState(true);
68
+ const [query, setQuery] = useState('');
69
+ const [submitted, setSubmitted] = useState('');
70
+ const [mode, setMode] = useState<Mode>('search');
71
+ const [sources, setSources] = useState<Set<string>>(new Set());
72
+ const [modelGroups, setModelGroups] = useState<ModelGroup[]>([]);
73
+ const [model, setModel] = useState<ChatModel>(AUTO_MODEL);
74
+ const [news, setNews] = useState<NewsItem[]>([]);
75
+ // True once the user picks a model themselves, so the catalog's default-to-Enso
76
+ // never overwrites a deliberate choice made while the fetch was still in flight.
77
+ const picked = useRef(false);
78
+ const chooseModel = useCallback((m: ChatModel) => {
79
+ picked.current = true;
80
+ setModel(m);
81
+ }, []);
82
+
83
+ const [phase, setPhase] = useState<'idle' | 'running' | 'done'>('idle');
84
+ const [status, setStatus] = useState('');
85
+ const [answer, setAnswer] = useState('');
86
+ const [answerSources, setAnswerSources] = useState<SearchSource[]>([]);
87
+ const [followUps, setFollowUps] = useState<string[]>([]);
88
+ const [error, setError] = useState('');
89
+ const [needAuth, setNeedAuth] = useState(false);
90
+ // The engine an unauthenticated query falls back to. Read once; the default
91
+ // stands until storage answers, so a query typed in the first moments after a
92
+ // new tab opens still has somewhere to go.
93
+ const [providerId, setProviderId] = useState<string>(DEFAULT_PROVIDER_ID);
94
+ const abortRef = useRef<AbortController | null>(null);
95
+
96
+ // Load real model catalog + live news (both public — work signed out).
97
+ //
98
+ // Enso is the default, selected once the catalog lands. It cannot be the
99
+ // useState seed: the catalog is fetched at runtime, so naming a model before
100
+ // it arrives would hardcode an id the server may not serve — the whole point
101
+ // of model-catalog.ts is that the list is never fabricated. AUTO_MODEL is the
102
+ // seed and the fallback, so a failed/slow fetch degrades to "routes to the
103
+ // best model" instead of a dead selection. Only the initial pick is
104
+ // overridden: `picked` guards a user's choice against a late catalog resolve.
105
+ useEffect(() => {
106
+ fetchModelCatalog()
107
+ .then(({ groups }) => {
108
+ setModelGroups(groups);
109
+ if (picked.current) return;
110
+ const enso = groups.find((g) => g.family === 'enso')?.models[0];
111
+ if (enso) setModel(enso);
112
+ })
113
+ .catch(() => {});
114
+ fetchNews().then(setNews).catch(() => {});
115
+ loadProviderId().then(setProviderId).catch(() => {});
116
+ }, [apiBase]);
117
+
118
+ const client = useMemo(
119
+ () =>
120
+ createAiClient({
121
+ baseUrl: apiBase,
122
+ getToken: async () => {
123
+ const t = await getToken();
124
+ if (!t) throw new Error('__NO_TOKEN__');
125
+ return t;
126
+ },
127
+ }),
128
+ [apiBase, getToken],
129
+ );
130
+
131
+ const run = useCallback(
132
+ async (q: string) => {
133
+ const question = q.trim();
134
+ if (!question) return;
135
+ abortRef.current?.abort();
136
+ const ctrl = new AbortController();
137
+ abortRef.current = ctrl;
138
+
139
+ // NO IDENTITY, NO DEAD END. /v1/ask is metered and answers 401 to a
140
+ // signed-out caller, but this surface IS the browser's search box: a query
141
+ // that returns a sign-in card has broken the address bar rather than shown a
142
+ // paywall. Hand it to the configured engine instead, before any spinner —
143
+ // checking first is what makes the handoff instant rather than a flash of
144
+ // "Searching the web" followed by a navigation.
145
+ //
146
+ // The fallback is not a Hanzo call: no token, no proxy, no telemetry. The
147
+ // query goes from this browser straight to the engine the user chose.
148
+ let identified = false;
149
+ try {
150
+ identified = Boolean(await getToken());
151
+ } catch {
152
+ identified = false;
153
+ }
154
+ if (!identified) {
155
+ const url = fallbackUrl(providerId, question);
156
+ if (url) {
157
+ void capture('answer_search_fallback', { provider: providerId, mode });
158
+ window.location.assign(url);
159
+ return;
160
+ }
161
+ }
162
+
163
+ setSubmitted(question);
164
+ setPhase('running');
165
+ setStatus(mode === 'chat' ? 'Thinking' : 'Searching the web');
166
+ setAnswer('');
167
+ setAnswerSources([]);
168
+ setFollowUps([]);
169
+ setError('');
170
+ setNeedAuth(false);
171
+ void capture('answer_search', { mode, model: model.id });
172
+ let fullAnswer = '';
173
+
174
+ const stream =
175
+ mode === 'chat'
176
+ ? converse(client, question, model.id, ctrl.signal)
177
+ : (client.search(question, {
178
+ mode,
179
+ model: model.id,
180
+ sources: [...sources],
181
+ signal: ctrl.signal,
182
+ }) as AsyncGenerator<SearchEvent>);
183
+ try {
184
+ for await (const ev of stream) {
185
+ switch (ev.type) {
186
+ case 'status':
187
+ setStatus(
188
+ ev.stage === 'planning'
189
+ ? 'Planning research' + (ev.detail ? `: ${ev.detail}` : '')
190
+ : ev.stage === 'searching'
191
+ ? 'Searching the web' + (ev.detail ? `: ${ev.detail}` : '')
192
+ : ev.stage === 'reading'
193
+ ? 'Reading sources' + (ev.detail ? `: ${ev.detail}` : '')
194
+ : 'Writing the answer',
195
+ );
196
+ break;
197
+ case 'sources':
198
+ setAnswerSources(ev.sources);
199
+ break;
200
+ case 'text':
201
+ fullAnswer += ev.delta;
202
+ setAnswer((a) => a + ev.delta);
203
+ break;
204
+ case 'follow_ups':
205
+ setFollowUps(ev.questions);
206
+ break;
207
+ case 'done':
208
+ setPhase('done');
209
+ void capture('answer_shown', { mode, model: model.id });
210
+ // Opt-in only: no-ops unless the user turned on training
211
+ // contribution (the consent module gates the send).
212
+ void contributeTrainingSample({ query: question, answer: fullAnswer, model: model.id });
213
+ break;
214
+ case 'error':
215
+ if (ev.error.includes('__NO_TOKEN__') || /401|invalid api key/i.test(ev.error)) {
216
+ setNeedAuth(true);
217
+ } else {
218
+ setError(ev.error);
219
+ }
220
+ setPhase('done');
221
+ break;
222
+ }
223
+ }
224
+ } catch (e) {
225
+ const msg = e instanceof Error ? e.message : String(e);
226
+ if (msg.includes('__NO_TOKEN__') || /401|invalid api key/i.test(msg)) setNeedAuth(true);
227
+ else setError(msg);
228
+ setPhase('done');
229
+ }
230
+ },
231
+ [client, mode, model, sources, getToken, providerId],
232
+ );
233
+
234
+ // Fire the initial (address-bar) query once models are ready enough.
235
+ const didInit = useRef(false);
236
+ useEffect(() => {
237
+ if (didInit.current || !initialQuery) return;
238
+ didInit.current = true;
239
+ setQuery(initialQuery);
240
+ void run(initialQuery);
241
+ }, [initialQuery, run]);
242
+
243
+ const submit = useCallback(() => void run(query), [query, run]);
244
+ const toggleSource = useCallback((s: string) => {
245
+ setSources((prev) => {
246
+ const next = new Set(prev);
247
+ next.has(s) ? next.delete(s) : next.add(s);
248
+ return next;
249
+ });
250
+ }, []);
251
+
252
+ const newThread = useCallback(() => {
253
+ abortRef.current?.abort();
254
+ setPhase('idle');
255
+ setQuery('');
256
+ setSubmitted('');
257
+ setAnswer('');
258
+ setAnswerSources([]);
259
+ setFollowUps([]);
260
+ setError('');
261
+ setNeedAuth(false);
262
+ }, []);
263
+
264
+ const composer = (busy: boolean) => (
265
+ <Composer
266
+ value={query}
267
+ onChange={setQuery}
268
+ onSubmit={submit}
269
+ mode={mode}
270
+ setMode={setMode}
271
+ sources={sources}
272
+ toggleSource={toggleSource}
273
+ models={modelGroups}
274
+ model={model}
275
+ setModel={chooseModel}
276
+ busy={busy}
277
+ />
278
+ );
279
+
280
+ return (
281
+ <div className={'ae-root' + (collapsed ? ' collapsed' : '')}>
282
+ {/* No fixed reveal button: the rail itself is always present now, and it
283
+ carries its own expand control. A floating toggle only existed because
284
+ the collapsed rail rendered nothing to click. */}
285
+ <Rail
286
+ collapsed={collapsed}
287
+ toggle={() => setCollapsed((v) => !v)}
288
+ newThread={newThread}
289
+ signIn={signIn}
290
+ />
291
+
292
+ <main className="ae-main">
293
+ {phase === 'idle' ? (
294
+ <div className="ae-hero">
295
+ <div className="ae-hero-card">{composer(false)}</div>
296
+ <Stories items={news} />
297
+ </div>
298
+ ) : (
299
+ <div className="ae-answer-wrap">
300
+ <div className="ae-answer-scroll">
301
+ <h1 className="ae-question">{submitted}</h1>
302
+
303
+ {answerSources.length > 0 && (
304
+ <div className="ae-sources">
305
+ {answerSources.map((s, i) => (
306
+ <Source key={s.url} source={s} index={i} />
307
+ ))}
308
+ </div>
309
+ )}
310
+
311
+ {phase === 'running' && !answer && (
312
+ <div className="ae-status">
313
+ <span className="ae-spinner" /> {status}…
314
+ </div>
315
+ )}
316
+
317
+ {needAuth ? (
318
+ /* Reached only when a token EXISTED and the call still came back
319
+ 401 — an expired or revoked session, since a signed-out query
320
+ never gets here (run() hands it to the fallback engine first).
321
+ Both doors are offered: renew the session for an AI answer, or
322
+ take the same query to the configured engine. A dead end here
323
+ would strand someone who simply needs to sign in again. */
324
+ <div className="ae-auth">
325
+ <p>Your Hanzo session expired. Sign in again for AI answers.</p>
326
+ <button className="ae-signin big" onClick={signIn}>
327
+ Sign in
328
+ </button>
329
+ <a
330
+ className="ae-fallback-link"
331
+ href={fallbackUrl(providerId, submitted) || undefined}
332
+ >
333
+ Search {providerById(providerId).label} instead
334
+ </a>
335
+ </div>
336
+ ) : error ? (
337
+ <div className="ae-error">{error}</div>
338
+ ) : (
339
+ /* The answer picks its own presentation: any widget blocks it
340
+ emitted render as real components, and the prose is what is
341
+ left after they are removed — so a widget is never also shown
342
+ as raw JSON. Extraction runs per frame against a STREAMING,
343
+ half-written document, which is why an unterminated fence is
344
+ left alone until it closes. */
345
+ (() => {
346
+ const { prose, widgets } = extractWidgets(answer);
347
+ return (
348
+ <>
349
+ <Widgets widgets={widgets} />
350
+ <div
351
+ className="ae-answer markdown"
352
+ dangerouslySetInnerHTML={{ __html: renderMarkdown(prose) }}
353
+ />
354
+ </>
355
+ );
356
+ })()
357
+ )}
358
+
359
+ {followUps.length > 0 && (
360
+ <div className="ae-followups">
361
+ <div className="ae-followups-head">Follow-up</div>
362
+ {followUps.map((f) => (
363
+ <button
364
+ key={f}
365
+ className="ae-followup"
366
+ onClick={() => {
367
+ setQuery(f);
368
+ void run(f);
369
+ }}
370
+ >
371
+ {f}
372
+ <span className="ae-followup-arrow">→</span>
373
+ </button>
374
+ ))}
375
+ </div>
376
+ )}
377
+ </div>
378
+
379
+ <div className="ae-answer-composer">{composer(phase === 'running')}</div>
380
+ </div>
381
+ )}
382
+ </main>
383
+ </div>
384
+ );
385
+ }
@@ -0,0 +1,147 @@
1
+ import React from 'react';
2
+ import type { SearchMode } from '@hanzo/ai';
3
+ import { Button, Textarea } from '@hanzo/ui';
4
+ import { Models } from './Models.js';
5
+ import type { ChatModel, ModelGroup } from './model-catalog.js';
6
+
7
+ /**
8
+ * The composer: an auto-growing field over one toolbar row — source pills on the
9
+ * left, mode tabs + model picker + a single send control on the right.
10
+ *
11
+ * Enter sends; Shift+Enter writes a newline. The send control is also the busy
12
+ * indicator, so there is exactly one control for "go" and one signal for "running".
13
+ *
14
+ * Presentational: every value and every effect is injected. It owns no query
15
+ * state and never calls a backend — mount it wherever the answer surface lives.
16
+ */
17
+
18
+ /** What the composer sends. `chat` goes straight to the model; the rest ground
19
+ * the question on the live web (`SearchMode` is the wire's own vocabulary).
20
+ *
21
+ * `deep` is EXCLUDED rather than absent. The wire still names it — dropping it
22
+ * from `MODES` only stopped it being offered, it stayed a legal `Mode`, so any
23
+ * call site could still hold one and put the retired name back on the surface.
24
+ * Excluding it makes the collapse structural. Derived from `SearchMode` and not
25
+ * restated, so a mode this surface invents is still a type error, and the day
26
+ * the wire drops `deep` this narrows to nothing on its own. */
27
+ export type Mode = Exclude<SearchMode, 'deep'> | 'chat';
28
+
29
+ /** The modes, in the order they read as escalating effort. */
30
+ export const MODES: { id: Mode; label: string; hint: string }[] = [
31
+ { id: 'chat', label: 'Chat', hint: 'Straight to the model' },
32
+ { id: 'search', label: 'Search', hint: 'Fast grounded answer' },
33
+ { id: 'news', label: 'News', hint: 'Recency-biased' },
34
+ // No 'deep'. It was research with the dials up — same system prompt, same
35
+ // models, same gate — so two names offered a choice that was really an
36
+ // intensity, and hid a 2x price behind an adjective. Cloud folded them into
37
+ // one research mode (apps/answer/mode.go) that always does the deeper pass;
38
+ // 'deep' still RESOLVES there, so a client that has not shipped this does not
39
+ // 400 — which is why dropping the tab is safe on its own.
40
+ { id: 'research', label: 'Research', hint: 'Plans, reads sources, synthesizes' },
41
+ ];
42
+
43
+ export const SOURCES = ['web', 'news', 'academic', 'github', 'reddit', 'x'];
44
+
45
+ export interface ComposerProps {
46
+ value: string;
47
+ onChange: (value: string) => void;
48
+ onSubmit: () => void;
49
+ mode: Mode;
50
+ setMode: (mode: Mode) => void;
51
+ sources: Set<string>;
52
+ toggleSource: (source: string) => void;
53
+ models: ModelGroup[];
54
+ model: ChatModel;
55
+ setModel: (model: ChatModel) => void;
56
+ busy: boolean;
57
+ }
58
+
59
+ export function Composer({
60
+ value,
61
+ onChange,
62
+ onSubmit,
63
+ mode,
64
+ setMode,
65
+ sources,
66
+ toggleSource,
67
+ models,
68
+ model,
69
+ setModel,
70
+ busy,
71
+ }: ComposerProps) {
72
+ return (
73
+ <div className="ae-card">
74
+ {/* @hanzo/ui field — auto-grows by line count (rows is the floor), so the
75
+ DOM-measured resize effect the raw <textarea> needed is gone. Blends
76
+ into .ae-card with transparent bg / no border, matching .ae-input. */}
77
+ <Textarea
78
+ placeholder={mode === 'chat' ? 'Ask anything' : 'Type @ for sources or / for modes'}
79
+ value={value}
80
+ rows={1}
81
+ maxH={200}
82
+ bg="transparent"
83
+ borderWidth={0}
84
+ px={18}
85
+ fontSize={15}
86
+ onChangeText={onChange}
87
+ onKeyDown={(e) => {
88
+ if (e.key === 'Enter' && !e.shiftKey) {
89
+ e.preventDefault();
90
+ onSubmit();
91
+ }
92
+ }}
93
+ />
94
+ <div className="ae-card-row">
95
+ {/* The container stays in the row whatever the mode: it is the left half
96
+ of a space-between, so dropping it would slide the toolbar left.
97
+ Chat is ungrounded, so it offers no sources to pick. */}
98
+ <div className="ae-chips">
99
+ {mode !== 'chat' &&
100
+ SOURCES.map((s) => (
101
+ <button
102
+ key={s}
103
+ className={'ae-chip' + (sources.has(s) ? ' on' : '')}
104
+ onClick={() => toggleSource(s)}
105
+ title={`@${s}`}
106
+ >
107
+ @{s}
108
+ </button>
109
+ ))}
110
+ </div>
111
+ <div className="ae-card-right">
112
+ <div className="ae-modes">
113
+ {MODES.map((m) => (
114
+ <button
115
+ key={m.id}
116
+ className={'ae-mode' + (mode === m.id ? ' on' : '')}
117
+ onClick={() => setMode(m.id)}
118
+ title={m.hint}
119
+ >
120
+ {m.label}
121
+ </button>
122
+ ))}
123
+ </div>
124
+ <Models groups={models} current={model} onPick={setModel} />
125
+ {/* @hanzo/ui send control — `isLoading` is the built-in busy signal,
126
+ so the hand-rolled .ae-spinner is gone with the raw <button>. */}
127
+ <Button
128
+ size="icon"
129
+ rounded={999}
130
+ width={34}
131
+ height={34}
132
+ onPress={onSubmit}
133
+ disabled={busy || !value.trim()}
134
+ isLoading={busy}
135
+ aria-label="Search (Enter)"
136
+ >
137
+ {busy ? null : (
138
+ <svg viewBox="0 0 16 16" width="15" height="15" aria-hidden="true">
139
+ <path d="M3 13V3l10 5-10 5z" fill="currentColor" />
140
+ </svg>
141
+ )}
142
+ </Button>
143
+ </div>
144
+ </div>
145
+ </div>
146
+ );
147
+ }
@@ -0,0 +1,14 @@
1
+ import React from 'react';
2
+
3
+ /** The Hanzo mark. Monochrome — it inherits colour from its parent. */
4
+ export function Mark({ size = 28 }: { size?: number }) {
5
+ return (
6
+ <svg viewBox="0 0 67 67" width={size} height={size} xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
7
+ <path d="M22.21 67V44.6369H0V67H22.21Z" fill="currentColor" />
8
+ <path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z" fill="currentColor" />
9
+ <path d="M22.21 0H0V22.3184H22.21V0Z" fill="currentColor" />
10
+ <path d="M66.7198 0H44.5098V22.3184H66.7198V0Z" fill="currentColor" />
11
+ <path d="M66.7198 67V44.6369H44.5098V67H66.7198Z" fill="currentColor" />
12
+ </svg>
13
+ );
14
+ }
@@ -0,0 +1,118 @@
1
+ import React, { useEffect, useMemo, useRef, useState } from 'react';
2
+ import { AUTO_MODEL, type ChatModel, type ModelGroup } from './model-catalog.js';
3
+
4
+ /**
5
+ * The model picker: a filterable menu over the grouped catalog, with Auto — the
6
+ * router — pinned at the top as the one entry that is always valid.
7
+ *
8
+ * Presentational: the catalog and the choice are both injected. It never fetches.
9
+ */
10
+
11
+ // Tiers mirror @hanzo/plans (the pricing SoT); shown in the upgrade banner.
12
+ // Full plan detail lives at console.hanzo.ai/pricing.
13
+ const TIERS = [
14
+ { name: 'Pro', price: '$20' },
15
+ { name: 'Max', price: '$100' },
16
+ { name: 'Ultra', price: '$200' },
17
+ ];
18
+
19
+ export interface ModelsProps {
20
+ groups: ModelGroup[];
21
+ current: ChatModel;
22
+ onPick: (model: ChatModel) => void;
23
+ }
24
+
25
+ export function Models({ groups, current, onPick }: ModelsProps) {
26
+ const [open, setOpen] = useState(false);
27
+ const [filter, setFilter] = useState('');
28
+ const ref = useRef<HTMLDivElement>(null);
29
+
30
+ useEffect(() => {
31
+ if (!open) return;
32
+ const onDoc = (e: MouseEvent) => {
33
+ if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
34
+ };
35
+ document.addEventListener('mousedown', onDoc);
36
+ return () => document.removeEventListener('mousedown', onDoc);
37
+ }, [open]);
38
+
39
+ const q = filter.trim().toLowerCase();
40
+ const shown = useMemo(
41
+ () =>
42
+ groups
43
+ .map((g) => ({
44
+ ...g,
45
+ models: g.models.filter(
46
+ (m) => !q || m.name.toLowerCase().includes(q) || m.id.toLowerCase().includes(q),
47
+ ),
48
+ }))
49
+ .filter((g) => g.models.length),
50
+ [groups, q],
51
+ );
52
+
53
+ return (
54
+ <div className="ae-picker" ref={ref}>
55
+ <button className="ae-picker-btn" onClick={() => setOpen((v) => !v)} title="Choose model">
56
+ <span className="ae-dot" />
57
+ {current.name}
58
+ <svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">
59
+ <path d="M4 6l4 4 4-4" fill="none" stroke="currentColor" strokeWidth="1.5" />
60
+ </svg>
61
+ </button>
62
+ {open && (
63
+ <div className="ae-picker-menu">
64
+ <input
65
+ className="ae-picker-filter"
66
+ placeholder="Search models…"
67
+ value={filter}
68
+ autoFocus
69
+ onChange={(e) => setFilter(e.target.value)}
70
+ />
71
+ <div className="ae-picker-list">
72
+ <button
73
+ className={'ae-model-row' + (current.id === AUTO_MODEL.id ? ' active' : '')}
74
+ onClick={() => {
75
+ onPick(AUTO_MODEL);
76
+ setOpen(false);
77
+ }}
78
+ >
79
+ <span className="ae-model-name">Auto</span>
80
+ <span className="ae-model-desc">Routes to the best model</span>
81
+ </button>
82
+ {shown.map((g) => (
83
+ <div key={g.family} className="ae-model-group">
84
+ <div className="ae-model-group-label">{g.label}</div>
85
+ {g.models.map((m) => (
86
+ <button
87
+ key={m.id}
88
+ className={'ae-model-row' + (current.id === m.id ? ' active' : '')}
89
+ onClick={() => {
90
+ onPick(m);
91
+ setOpen(false);
92
+ }}
93
+ >
94
+ <span className="ae-model-name">
95
+ {m.name}
96
+ {m.tier && <span className="ae-badge">{m.tier}</span>}
97
+ </span>
98
+ {m.description && <span className="ae-model-desc">{m.description}</span>}
99
+ </button>
100
+ ))}
101
+ </div>
102
+ ))}
103
+ </div>
104
+ <a className="ae-plan-banner" href="https://console.hanzo.ai/pricing" target="_blank" rel="noreferrer">
105
+ <span>Unlock every model</span>
106
+ <span className="ae-plan-tiers">
107
+ {TIERS.map((t) => (
108
+ <span key={t.name} className="ae-plan-tier">
109
+ {t.name} <b>{t.price}</b>
110
+ </span>
111
+ ))}
112
+ </span>
113
+ </a>
114
+ </div>
115
+ )}
116
+ </div>
117
+ );
118
+ }