@shellui/core 0.5.3 → 0.6.0-beta.1

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 (113) hide show
  1. package/README.md +2 -0
  2. package/package.json +6 -4
  3. package/schemas/shellui.config.schema.json +104 -64
  4. package/src/app.tsx +5 -3
  5. package/src/components/ContentView.tsx +14 -23
  6. package/src/components/LoadingOverlay.tsx +1 -1
  7. package/src/components/ui/sonner.spec.tsx +138 -0
  8. package/src/components/ui/sonner.tsx +5 -5
  9. package/src/components/ui/switch.tsx +1 -1
  10. package/src/features/admin/AdminView.tsx +14 -3
  11. package/src/features/ai/AiBridge.tsx +106 -0
  12. package/src/features/ai/AiUnavailableResponder.tsx +39 -0
  13. package/src/features/ai/README.md +52 -0
  14. package/src/features/ai/ShellAiHost.tsx +24 -0
  15. package/src/features/ai/adapters/ollama.ts +170 -0
  16. package/src/features/ai/adapters/promptApi.spec.ts +135 -0
  17. package/src/features/ai/adapters/promptApi.ts +222 -0
  18. package/src/features/ai/adapters/webllm.experimental.spec.ts +69 -0
  19. package/src/features/ai/adapters/webllm.spec.ts +527 -0
  20. package/src/features/ai/adapters/webllm.ts +142 -0
  21. package/src/features/ai/aiDisabledResponses.spec.ts +29 -0
  22. package/src/features/ai/aiDisabledResponses.ts +32 -0
  23. package/src/features/ai/browserInstallStore.spec.ts +58 -0
  24. package/src/features/ai/browserInstallStore.ts +76 -0
  25. package/src/features/ai/catalog.ts +31 -0
  26. package/src/features/ai/createRegistry.ts +83 -0
  27. package/src/features/ai/developHarness.spec.ts +108 -0
  28. package/src/features/ai/developHarness.ts +161 -0
  29. package/src/features/ai/engine/formatAiError.spec.ts +85 -0
  30. package/src/features/ai/engine/formatAiError.ts +132 -0
  31. package/src/features/ai/engine/mapInitProgress.ts +9 -0
  32. package/src/features/ai/engine/normalizeWebLlmModule.spec.ts +47 -0
  33. package/src/features/ai/engine/vite-worker.d.ts +6 -0
  34. package/src/features/ai/engine/webllm.worker.ts +51 -0
  35. package/src/features/ai/engine/webllmEngine.ts +1011 -0
  36. package/src/features/ai/handleRequest.spec.ts +288 -0
  37. package/src/features/ai/handleRequest.ts +325 -0
  38. package/src/features/ai/isAiFeatureEnabled.spec.ts +15 -0
  39. package/src/features/ai/isAiFeatureEnabled.ts +9 -0
  40. package/src/features/ai/promptApiSupport.spec.ts +64 -0
  41. package/src/features/ai/promptApiSupport.ts +117 -0
  42. package/src/features/ai/registry.spec.ts +100 -0
  43. package/src/features/ai/registry.ts +131 -0
  44. package/src/features/ai/status.spec.ts +92 -0
  45. package/src/features/ai/status.ts +85 -0
  46. package/src/features/ai/types.ts +100 -0
  47. package/src/features/ai/webLlmBrowserSupport.spec.ts +86 -0
  48. package/src/features/ai/webLlmBrowserSupport.ts +92 -0
  49. package/src/features/alertDialog/DialogContext.tsx +3 -1
  50. package/src/features/auth/AuthProvider.tsx +254 -39
  51. package/src/features/auth/backends/index.ts +8 -0
  52. package/src/features/auth/backends/shellui.spec.ts +201 -0
  53. package/src/features/auth/backends/shellui.ts +93 -16
  54. package/src/features/auth/backends/supabase.ts +8 -0
  55. package/src/features/auth/backends/types.ts +16 -1
  56. package/src/features/auth/components/LoginButton.tsx +26 -2
  57. package/src/features/auth/components/LoginView.tsx +114 -133
  58. package/src/features/auth/components/SessionLoadingView.tsx +21 -0
  59. package/src/features/auth/hooks/useAuth.tsx +12 -0
  60. package/src/features/auth/shellAccountRequests.ts +76 -0
  61. package/src/features/auth/utils/authRequestError.ts +4 -1
  62. package/src/features/auth/utils/authSessionPersistence.spec.ts +11 -0
  63. package/src/features/auth/utils/authSessionPersistence.ts +12 -0
  64. package/src/features/auth/utils/index.ts +4 -0
  65. package/src/features/auth/utils/resolveLoginSettings.spec.ts +33 -0
  66. package/src/features/auth/utils/resolveLoginSettings.ts +33 -0
  67. package/src/features/auth/utils/shareInFlight.spec.ts +41 -0
  68. package/src/features/auth/utils/shareInFlight.ts +14 -0
  69. package/src/features/config/ConfigProvider.ts +9 -1
  70. package/src/features/config/types.ts +43 -0
  71. package/src/features/layouts/appbar/AppBarLayout.tsx +8 -3
  72. package/src/features/layouts/filterNavigationForAuthState.spec.ts +41 -0
  73. package/src/features/layouts/floating/FloatingLayout.tsx +9 -4
  74. package/src/features/layouts/floating/layoutChromeStore.ts +3 -1
  75. package/src/features/layouts/sidebar/SidebarLayout.tsx +9 -4
  76. package/src/features/layouts/utils.ts +6 -2
  77. package/src/features/layouts/windows/WindowsLayout.tsx +8 -3
  78. package/src/features/messaging/MessagingSecurityBootstrap.tsx +6 -6
  79. package/src/features/security/trustedFrames.spec.ts +65 -0
  80. package/src/features/security/trustedFrames.ts +52 -0
  81. package/src/features/settings/SettingsIcons.tsx +17 -0
  82. package/src/features/settings/SettingsProvider.tsx +29 -4
  83. package/src/features/settings/SettingsRoutes.tsx +8 -0
  84. package/src/features/settings/SettingsView.tsx +21 -4
  85. package/src/features/settings/components/Ai.tsx +830 -0
  86. package/src/features/settings/components/Develop.tsx +4 -0
  87. package/src/features/settings/components/Storage.tsx +197 -32
  88. package/src/features/settings/components/UserSettingsPanel.tsx +160 -12
  89. package/src/features/settings/components/createUserSettingsRoute.tsx +4 -0
  90. package/src/features/settings/components/develop/AiTestTools.tsx +231 -0
  91. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +54 -1
  92. package/src/features/settings/utils/buildSettingsForPropagation.ts +15 -1
  93. package/src/features/settings/utils/mergePreferencesIntoSettings.spec.ts +6 -0
  94. package/src/features/settings/utils/shouldShowStorageSettings.spec.ts +49 -0
  95. package/src/features/settings/utils/shouldShowStorageSettings.ts +19 -0
  96. package/src/features/storage/uploads/UploadToastCard.tsx +2 -442
  97. package/src/features/storage/uploads/UploadToaster.tsx +2 -44
  98. package/src/features/storage/uploads/uploadQueue.ts +128 -308
  99. package/src/features/storage/uploads/useUploadQueue.ts +7 -3
  100. package/src/features/transfers/TransferToastCard.tsx +467 -0
  101. package/src/features/transfers/TransferToaster.tsx +50 -0
  102. package/src/features/transfers/index.ts +33 -0
  103. package/src/features/transfers/transferQueue.spec.ts +97 -0
  104. package/src/features/transfers/transferQueue.ts +442 -0
  105. package/src/features/transfers/types.ts +38 -0
  106. package/src/features/transfers/useTransferQueue.ts +30 -0
  107. package/src/i18n/translations/en/common.json +46 -2
  108. package/src/i18n/translations/en/settings.json +151 -2
  109. package/src/i18n/translations/fr/common.json +46 -2
  110. package/src/i18n/translations/fr/settings.json +151 -2
  111. package/src/index.css +57 -4
  112. package/src/index.ts +1 -0
  113. package/src/routes/components/NavigationItemRoute.tsx +2 -1
@@ -0,0 +1,830 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+ import { useTranslation } from 'react-i18next';
3
+ import { Button } from '../../../components/ui/button';
4
+ import { Select } from '../../../components/ui/select';
5
+ import { Switch } from '../../../components/ui/switch';
6
+ import { cn } from '../../../lib/utils';
7
+ import { isBrowserModelInstalled } from '../../ai/browserInstallStore';
8
+ import { BROWSER_MODEL_CATALOG } from '../../ai/catalog';
9
+ import {
10
+ createDefaultAiRegistry,
11
+ getSharedPromptApiAdapter,
12
+ getSharedWebLLMAdapter,
13
+ isPromptApiPresent,
14
+ } from '../../ai/createRegistry';
15
+ import { DEFAULT_OLLAMA_BASE_URL, probeOllama, probeWebGpu } from '../../ai/status';
16
+ import type { AiModel } from '../../ai/types';
17
+ import { formatUnknownError, logAiError } from '../../ai/engine/formatAiError';
18
+ import { probeWebLlmBrowserSupport } from '../../ai/webLlmBrowserSupport';
19
+ import { RefreshCwIcon } from '../SettingsIcons';
20
+ import { useSettings } from '../hooks/useSettings';
21
+
22
+ const BROWSER_MODEL_LOCAL_IDS = BROWSER_MODEL_CATALOG.map((model) =>
23
+ model.id.replace(/^webllm:/, ''),
24
+ );
25
+
26
+ type AiPanelStatus = {
27
+ webGpu: { available: boolean; detail?: string };
28
+ ollama: { reachable: boolean; baseUrl: string; detail?: string; latencyMs?: number };
29
+ storage: { available: boolean; detail?: string };
30
+ /** Whether the Chrome built-in Prompt API global is present (Chromium only). */
31
+ promptApiPresent: boolean;
32
+ models: AiModel[];
33
+ };
34
+
35
+ type DownloadState = {
36
+ modelId: string;
37
+ progress: number;
38
+ error?: string;
39
+ };
40
+
41
+ /** Prompt API setup (not a weight download — Chrome often reports no transferable progress). */
42
+ type PromptApiSetupState = {
43
+ modelId: string;
44
+ /**
45
+ * Real 0–1 progress only after Chrome fires `downloadprogress` with `loaded` > 0.
46
+ * `null` means indeterminate (“Setting up…”), never a stuck 0% bar.
47
+ */
48
+ progress: number | null;
49
+ error?: string;
50
+ };
51
+
52
+ function formatBytes(bytes: number | undefined, locale: string): string | null {
53
+ if (bytes === undefined || !Number.isFinite(bytes)) return null;
54
+ const units = ['B', 'KB', 'MB', 'GB'];
55
+ let value = bytes;
56
+ let unit = 0;
57
+ while (value >= 1024 && unit < units.length - 1) {
58
+ value /= 1024;
59
+ unit += 1;
60
+ }
61
+ return `${new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(value)} ${units[unit]}`;
62
+ }
63
+
64
+ async function probeBrowserStorage(): Promise<{ available: boolean; detail?: string }> {
65
+ const storage = (
66
+ globalThis as {
67
+ navigator?: { storage?: { estimate?: () => Promise<{ quota?: number; usage?: number }> } };
68
+ }
69
+ ).navigator?.storage;
70
+ if (!storage?.estimate) {
71
+ return { available: false, detail: 'Browser storage estimate is unavailable.' };
72
+ }
73
+ try {
74
+ const estimate = await storage.estimate();
75
+ const quota = estimate.quota ?? 0;
76
+ if (quota <= 0) {
77
+ return { available: false, detail: 'No durable storage quota reported.' };
78
+ }
79
+ return {
80
+ available: true,
81
+ detail: `${formatBytes(estimate.usage ?? 0, 'en') ?? '0 B'} / ${formatBytes(quota, 'en')}`,
82
+ };
83
+ } catch (error) {
84
+ return {
85
+ available: false,
86
+ detail: error instanceof Error ? error.message : 'Storage probe failed.',
87
+ };
88
+ }
89
+ }
90
+
91
+ function StatusBadge({
92
+ ok,
93
+ okLabel,
94
+ badLabel,
95
+ }: {
96
+ ok: boolean;
97
+ okLabel: string;
98
+ badLabel: string;
99
+ }) {
100
+ return (
101
+ <span
102
+ className={cn(
103
+ 'inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium',
104
+ ok
105
+ ? 'bg-emerald-500/15 text-emerald-800 dark:text-emerald-200'
106
+ : 'bg-muted text-muted-foreground',
107
+ )}
108
+ >
109
+ {ok ? okLabel : badLabel}
110
+ </span>
111
+ );
112
+ }
113
+
114
+ function ModelStatusBadge({
115
+ status,
116
+ t,
117
+ }: {
118
+ status: AiModel['status'];
119
+ t: (key: string) => string;
120
+ }) {
121
+ const label =
122
+ status === 'ready'
123
+ ? t('ai.models.status.ready')
124
+ : status === 'downloadable'
125
+ ? t('ai.models.status.downloadable')
126
+ : status === 'downloading'
127
+ ? t('ai.models.status.downloading')
128
+ : status === 'needs-webgpu'
129
+ ? t('ai.models.status.needsWebGpu')
130
+ : status === 'unsupported'
131
+ ? t('ai.models.status.unsupported')
132
+ : t('ai.models.status.unavailable');
133
+ const tone =
134
+ status === 'ready'
135
+ ? 'bg-emerald-500/15 text-emerald-800 dark:text-emerald-200'
136
+ : status === 'downloading'
137
+ ? 'bg-amber-500/15 text-amber-900 dark:text-amber-100'
138
+ : status === 'unsupported'
139
+ ? 'bg-amber-500/15 text-amber-900 dark:text-amber-100'
140
+ : 'bg-muted text-muted-foreground';
141
+ return (
142
+ <span className={cn('inline-flex rounded-full px-2 py-0.5 text-[11px] font-medium', tone)}>
143
+ {label}
144
+ </span>
145
+ );
146
+ }
147
+
148
+ export const Ai = () => {
149
+ const { t, i18n } = useTranslation('settings');
150
+ const { settings, updateSetting } = useSettings();
151
+ const locale = i18n.language || 'en';
152
+ const ai = settings.ai ?? {
153
+ enabled: true,
154
+ defaultModelId: null,
155
+ ollamaEnabled: true,
156
+ browserEnabled: true,
157
+ };
158
+
159
+ const webllm = useMemo(() => getSharedWebLLMAdapter(), []);
160
+ const promptApi = useMemo(() => getSharedPromptApiAdapter(), []);
161
+ const [status, setStatus] = useState<AiPanelStatus | null>(null);
162
+ const [loading, setLoading] = useState(false);
163
+ const [error, setError] = useState(false);
164
+ const [download, setDownload] = useState<DownloadState | null>(null);
165
+ const [promptApiSetup, setPromptApiSetup] = useState<PromptApiSetupState | null>(null);
166
+ const downloadAbortRef = useRef<AbortController | null>(null);
167
+ const promptApiAbortRef = useRef<AbortController | null>(null);
168
+
169
+ const load = useCallback(async () => {
170
+ setLoading(true);
171
+ setError(false);
172
+ try {
173
+ const registry = createDefaultAiRegistry({
174
+ ollama: { baseUrl: ai.ollamaBaseUrl ?? DEFAULT_OLLAMA_BASE_URL },
175
+ includeWebLLM: ai.browserEnabled,
176
+ webllmAdapter: webllm,
177
+ promptApiAdapter: promptApi,
178
+ defaultModelId: ai.defaultModelId,
179
+ });
180
+ const promptApiPresent = isPromptApiPresent();
181
+ const [webGpu, ollama, storage, models] = await Promise.all([
182
+ probeWebGpu(),
183
+ ai.ollamaEnabled
184
+ ? probeOllama({ baseUrl: ai.ollamaBaseUrl ?? DEFAULT_OLLAMA_BASE_URL })
185
+ : Promise.resolve({
186
+ reachable: false,
187
+ baseUrl: ai.ollamaBaseUrl ?? DEFAULT_OLLAMA_BASE_URL,
188
+ detail: 'disabled',
189
+ }),
190
+ probeBrowserStorage(),
191
+ registry.listModels(),
192
+ ]);
193
+ const filtered = models.filter((model) => {
194
+ if (model.provider === 'ollama') return ai.ollamaEnabled;
195
+ if (model.provider === 'webllm') return ai.browserEnabled;
196
+ if (model.provider === 'prompt-api') return ai.promptApiEnabled !== false;
197
+ return true;
198
+ });
199
+ setStatus({ webGpu, ollama, storage, promptApiPresent, models: filtered });
200
+ } catch {
201
+ setStatus(null);
202
+ setError(true);
203
+ } finally {
204
+ setLoading(false);
205
+ }
206
+ }, [
207
+ ai.browserEnabled,
208
+ ai.ollamaBaseUrl,
209
+ ai.ollamaEnabled,
210
+ ai.promptApiEnabled,
211
+ ai.defaultModelId,
212
+ webllm,
213
+ promptApi,
214
+ ]);
215
+
216
+ // Keep in-panel progress in sync when Settings remounts mid-download (toaster owns the job).
217
+ useEffect(() => {
218
+ if (!ai.enabled) return;
219
+ const engine = webllm.getEngine();
220
+ const syncFromEngine = () => {
221
+ for (const localId of BROWSER_MODEL_LOCAL_IDS) {
222
+ const progress = engine.getDownloadProgress(localId);
223
+ if (progress !== null) {
224
+ setDownload({ modelId: `webllm:${localId}`, progress });
225
+ return;
226
+ }
227
+ }
228
+ };
229
+ syncFromEngine();
230
+ return engine.subscribeProgress((localId, progress) => {
231
+ setDownload({ modelId: `webllm:${localId}`, progress });
232
+ if (progress >= 1) {
233
+ setDownload(null);
234
+ void load();
235
+ }
236
+ });
237
+ }, [ai.enabled, load, webllm]);
238
+
239
+ useEffect(() => {
240
+ if (!ai.enabled) {
241
+ setStatus(null);
242
+ setError(false);
243
+ setLoading(false);
244
+ setDownload(null);
245
+ setPromptApiSetup(null);
246
+ return;
247
+ }
248
+ void load();
249
+ }, [ai.enabled, load]);
250
+
251
+ useEffect(() => {
252
+ if (ai.defaultModelId || !status) return;
253
+ const ready = status.models.filter((model) => model.status === 'ready');
254
+ if (ready.length === 1) {
255
+ updateSetting('ai', { defaultModelId: ready[0].id });
256
+ }
257
+ }, [ai.defaultModelId, status, updateSetting]);
258
+
259
+ const readyModels = (status?.models ?? []).filter((m) => m.status === 'ready');
260
+ const ollamaModels = (status?.models ?? []).filter((m) => m.provider === 'ollama');
261
+ const browserModels = (status?.models ?? []).filter((m) => m.provider === 'webllm');
262
+ const promptApiModels = (status?.models ?? []).filter((m) => m.provider === 'prompt-api');
263
+
264
+ const startDownload = async (model: AiModel) => {
265
+ // Firefox is experimental, not blocked: attempt Install and let the real
266
+ // error surface (mapped) rather than pre-emptively refusing.
267
+ setDownload({ modelId: model.id, progress: 0 });
268
+ const controller = new AbortController();
269
+ downloadAbortRef.current = controller;
270
+ try {
271
+ await webllm.download(model.id, {
272
+ signal: controller.signal,
273
+ onProgress: (progress) => setDownload({ modelId: model.id, progress }),
274
+ });
275
+ setDownload(null);
276
+ await load();
277
+ } catch (err) {
278
+ if (err instanceof Error && err.name === 'AbortError') {
279
+ setDownload(null);
280
+ await load();
281
+ return;
282
+ }
283
+ logAiError('settings.install', err, { modelId: model.id, stage: 'settings.startDownload' });
284
+ setDownload({
285
+ modelId: model.id,
286
+ progress: 0,
287
+ error: formatUnknownError(err) || t('ai.unknownError'),
288
+ });
289
+ await load();
290
+ } finally {
291
+ downloadAbortRef.current = null;
292
+ }
293
+ };
294
+
295
+ const cancelDownload = (modelId: string) => {
296
+ webllm.cancelDownload(modelId);
297
+ downloadAbortRef.current?.abort();
298
+ setDownload(null);
299
+ };
300
+
301
+ const startPromptApiEnable = useCallback(
302
+ async (model: AiModel) => {
303
+ // Indeterminate until Chrome fires a real downloadprogress with loaded > 0.
304
+ setPromptApiSetup({ modelId: model.id, progress: null });
305
+ const controller = new AbortController();
306
+ promptApiAbortRef.current = controller;
307
+ try {
308
+ await promptApi.download(model.id, {
309
+ signal: controller.signal,
310
+ onProgress: (progress) => {
311
+ // Only promote to a determinate bar once progress actually advances.
312
+ if (progress > 0) {
313
+ setPromptApiSetup({ modelId: model.id, progress });
314
+ }
315
+ },
316
+ });
317
+ setPromptApiSetup(null);
318
+ await load();
319
+ } catch (err) {
320
+ if (err instanceof Error && err.name === 'AbortError') {
321
+ setPromptApiSetup(null);
322
+ await load();
323
+ return;
324
+ }
325
+ logAiError('settings.promptApi.enable', err, {
326
+ modelId: model.id,
327
+ stage: 'settings.startPromptApiEnable',
328
+ });
329
+ setPromptApiSetup({
330
+ modelId: model.id,
331
+ progress: null,
332
+ error: formatUnknownError(err) || t('ai.unknownError'),
333
+ });
334
+ await load();
335
+ } finally {
336
+ promptApiAbortRef.current = null;
337
+ }
338
+ },
339
+ [load, promptApi, t],
340
+ );
341
+
342
+ const onPromptApiEnabledChange = (checked: boolean) => {
343
+ updateSetting('ai', { promptApiEnabled: checked });
344
+ if (!checked) {
345
+ promptApiAbortRef.current?.abort();
346
+ setPromptApiSetup(null);
347
+ return;
348
+ }
349
+ // Turning the switch on: if the built-in model still needs a one-shot create()
350
+ // warm, run Enable automatically (no separate “Install” step).
351
+ void (async () => {
352
+ const models = await promptApi.listModels();
353
+ const needsSetup = models.find(
354
+ (model) => model.status === 'downloadable' || model.status === 'downloading',
355
+ );
356
+ if (needsSetup) {
357
+ await startPromptApiEnable(needsSetup);
358
+ } else {
359
+ await load();
360
+ }
361
+ })();
362
+ };
363
+
364
+ const deleteModel = async (modelId: string) => {
365
+ await webllm.deleteInstalled(modelId);
366
+ if (ai.defaultModelId === modelId) {
367
+ updateSetting('ai', { defaultModelId: null });
368
+ }
369
+ await load();
370
+ };
371
+
372
+ return (
373
+ <div className="w-full shrink-0 space-y-5">
374
+ <p className="text-sm text-muted-foreground">{t('ai.description')}</p>
375
+
376
+ <div className="flex items-center justify-between gap-4">
377
+ <div className="space-y-0.5">
378
+ <label
379
+ htmlFor="ai-enabled"
380
+ className="text-sm font-medium leading-none"
381
+ style={{ fontFamily: 'var(--heading-font-family, inherit)' }}
382
+ >
383
+ {t('ai.enabled.title')}
384
+ </label>
385
+ <p className="text-sm text-muted-foreground">{t('ai.enabled.description')}</p>
386
+ </div>
387
+ <Switch
388
+ id="ai-enabled"
389
+ checked={ai.enabled}
390
+ onCheckedChange={(checked) => updateSetting('ai', { enabled: checked })}
391
+ />
392
+ </div>
393
+
394
+ <div
395
+ data-shellui-ai-details={ai.enabled ? 'open' : 'closed'}
396
+ className="w-full shrink-0 self-start"
397
+ aria-hidden={!ai.enabled}
398
+ >
399
+ <div
400
+ data-shellui-ai-details-inner
401
+ className="space-y-5"
402
+ inert={!ai.enabled ? true : undefined}
403
+ >
404
+ <div className="space-y-2.5">
405
+ <div className="flex items-center justify-between gap-3">
406
+ <h2
407
+ className="text-sm font-medium leading-none"
408
+ style={{ fontFamily: 'var(--heading-font-family, inherit)' }}
409
+ >
410
+ {t('ai.status.title')}
411
+ </h2>
412
+ <Button
413
+ variant="ghost"
414
+ size="sm"
415
+ className="h-8 gap-1.5 text-xs"
416
+ disabled={loading}
417
+ onClick={() => void load()}
418
+ aria-label={t('ai.status.refresh')}
419
+ >
420
+ <RefreshCwIcon />
421
+ {t('ai.status.refresh')}
422
+ </Button>
423
+ </div>
424
+
425
+ {loading && !status ? (
426
+ <p className="text-sm text-muted-foreground">{t('ai.status.loading')}</p>
427
+ ) : null}
428
+ {error ? (
429
+ <div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2.5">
430
+ <p className="text-sm text-destructive">{t('ai.status.error')}</p>
431
+ <Button
432
+ variant="outline"
433
+ size="sm"
434
+ onClick={() => void load()}
435
+ >
436
+ {t('ai.status.retry')}
437
+ </Button>
438
+ </div>
439
+ ) : null}
440
+
441
+ {status ? (
442
+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-3">
443
+ {(
444
+ [
445
+ {
446
+ key: 'webGpu',
447
+ title: t('ai.status.webGpu'),
448
+ hint: t('ai.status.webGpuHint'),
449
+ ok: status.webGpu.available,
450
+ okLabel: t('ai.status.available'),
451
+ badLabel: t('ai.status.unavailable'),
452
+ },
453
+ {
454
+ key: 'ollama',
455
+ title: t('ai.status.ollama'),
456
+ hint: status.ollama.reachable
457
+ ? t('ai.status.ollamaOnlineHint')
458
+ : t('ai.status.ollamaOffline'),
459
+ ok: status.ollama.reachable,
460
+ okLabel: t('ai.status.connected'),
461
+ badLabel: t('ai.status.offline'),
462
+ },
463
+ {
464
+ key: 'storage',
465
+ title: t('ai.status.storage'),
466
+ hint: t('ai.status.storageHint'),
467
+ ok: status.storage.available,
468
+ okLabel: t('ai.status.available'),
469
+ badLabel: t('ai.status.unavailable'),
470
+ },
471
+ ] as const
472
+ ).map((item) => (
473
+ <div
474
+ key={item.key}
475
+ className="rounded-lg border border-border/60 px-3 py-2.5"
476
+ >
477
+ <div className="flex items-start justify-between gap-2">
478
+ <div className="min-w-0 space-y-1">
479
+ <p className="text-sm font-medium">{item.title}</p>
480
+ <p className="text-xs text-muted-foreground">{item.hint}</p>
481
+ </div>
482
+ <StatusBadge
483
+ ok={item.ok}
484
+ okLabel={item.okLabel}
485
+ badLabel={item.badLabel}
486
+ />
487
+ </div>
488
+ </div>
489
+ ))}
490
+ </div>
491
+ ) : null}
492
+ </div>
493
+
494
+ <div className="space-y-2">
495
+ <label
496
+ htmlFor="ai-default-model"
497
+ className="text-sm font-medium leading-none"
498
+ style={{ fontFamily: 'var(--heading-font-family, inherit)' }}
499
+ >
500
+ {t('ai.defaultModel.title')}
501
+ </label>
502
+ <p className="text-sm text-muted-foreground">{t('ai.defaultModel.description')}</p>
503
+ <Select
504
+ id="ai-default-model"
505
+ value={ai.defaultModelId ?? ''}
506
+ disabled={readyModels.length === 0}
507
+ onChange={(event) =>
508
+ updateSetting('ai', {
509
+ defaultModelId: event.target.value || null,
510
+ })
511
+ }
512
+ >
513
+ <option value="">{t('ai.defaultModel.none')}</option>
514
+ {readyModels.map((model) => (
515
+ <option
516
+ key={model.id}
517
+ value={model.id}
518
+ >
519
+ {model.name} ({model.provider})
520
+ </option>
521
+ ))}
522
+ </Select>
523
+ {readyModels.length === 0 ? (
524
+ <p className="text-sm text-muted-foreground">{t('ai.defaultModel.empty')}</p>
525
+ ) : null}
526
+ </div>
527
+
528
+ <div className="space-y-3">
529
+ <h2
530
+ className="text-sm font-medium leading-none"
531
+ style={{ fontFamily: 'var(--heading-font-family, inherit)' }}
532
+ >
533
+ {t('ai.providers.title')}
534
+ </h2>
535
+
536
+ <section className="space-y-3 rounded-lg border border-border/60 p-3">
537
+ <div className="flex items-start justify-between gap-4">
538
+ <div className="space-y-1">
539
+ <label
540
+ htmlFor="ai-ollama-enabled"
541
+ className="text-sm font-medium leading-none"
542
+ style={{ fontFamily: 'var(--heading-font-family, inherit)' }}
543
+ >
544
+ {t('ai.providers.ollama')}
545
+ </label>
546
+ <p className="text-sm text-muted-foreground">{t('ai.providers.ollamaHint')}</p>
547
+ </div>
548
+ <Switch
549
+ id="ai-ollama-enabled"
550
+ checked={ai.ollamaEnabled}
551
+ onCheckedChange={(checked) => updateSetting('ai', { ollamaEnabled: checked })}
552
+ />
553
+ </div>
554
+ {ai.ollamaEnabled ? (
555
+ ollamaModels.length === 0 ? (
556
+ <p className="text-sm text-muted-foreground">
557
+ {status?.ollama.reachable
558
+ ? t('ai.models.ollamaEmptyReady')
559
+ : t('ai.models.ollamaEmpty')}
560
+ </p>
561
+ ) : (
562
+ <ul className="divide-y divide-border/60 overflow-hidden rounded-md border border-border/60">
563
+ {ollamaModels.map((model) => (
564
+ <li
565
+ key={model.id}
566
+ className="flex flex-wrap items-center justify-between gap-3 px-3 py-2.5"
567
+ >
568
+ <p className="min-w-0 truncate text-sm font-medium">{model.name}</p>
569
+ <div className="flex items-center gap-2">
570
+ {formatBytes(model.sizeBytes, locale) ? (
571
+ <span className="text-xs tabular-nums text-muted-foreground">
572
+ {formatBytes(model.sizeBytes, locale)}
573
+ </span>
574
+ ) : null}
575
+ <ModelStatusBadge
576
+ status={model.status}
577
+ t={t}
578
+ />
579
+ </div>
580
+ </li>
581
+ ))}
582
+ </ul>
583
+ )
584
+ ) : null}
585
+ </section>
586
+
587
+ <section className="space-y-3 rounded-lg border border-border/60 p-3">
588
+ <div className="flex items-start justify-between gap-4">
589
+ <div className="space-y-1">
590
+ <label
591
+ htmlFor="ai-browser-enabled"
592
+ className="text-sm font-medium leading-none"
593
+ style={{ fontFamily: 'var(--heading-font-family, inherit)' }}
594
+ >
595
+ {t('ai.providers.browser')}
596
+ </label>
597
+ <p className="text-sm text-muted-foreground">{t('ai.providers.browserHint')}</p>
598
+ </div>
599
+ <Switch
600
+ id="ai-browser-enabled"
601
+ checked={ai.browserEnabled}
602
+ onCheckedChange={(checked) => updateSetting('ai', { browserEnabled: checked })}
603
+ />
604
+ </div>
605
+ {ai.browserEnabled && status && !status.webGpu.available ? (
606
+ <p className="text-xs text-muted-foreground">{t('ai.models.needsWebGpuAction')}</p>
607
+ ) : null}
608
+ {ai.browserEnabled && !probeWebLlmBrowserSupport().recommended ? (
609
+ <p className="rounded-md border border-amber-500/40 bg-amber-500/10 px-2.5 py-1.5 text-xs text-amber-900 dark:text-amber-100">
610
+ {t('ai.models.experimentalBrowser')}
611
+ </p>
612
+ ) : null}
613
+ {ai.browserEnabled ? (
614
+ browserModels.length === 0 ? (
615
+ <p className="text-sm text-muted-foreground">{t('ai.models.browserEmpty')}</p>
616
+ ) : (
617
+ <ul className="divide-y divide-border/60 overflow-hidden rounded-md border border-border/60">
618
+ {browserModels.map((model) => {
619
+ const size = formatBytes(model.sizeBytes, locale);
620
+ const isDownloading = download?.modelId === model.id;
621
+ const progress = isDownloading
622
+ ? download.progress
623
+ : (webllm.getDownloadProgress(model.id) ?? null);
624
+ const installed = isBrowserModelInstalled(model.id);
625
+ const canDownload =
626
+ !installed &&
627
+ model.status !== 'downloading' &&
628
+ model.status !== 'needs-webgpu';
629
+ return (
630
+ <li
631
+ key={model.id}
632
+ className="space-y-2 px-3 py-2.5"
633
+ >
634
+ <div className="flex flex-wrap items-center justify-between gap-3">
635
+ <div className="min-w-0">
636
+ <p className="truncate text-sm font-medium">{model.name}</p>
637
+ {size ? (
638
+ <p className="text-xs tabular-nums text-muted-foreground">{size}</p>
639
+ ) : null}
640
+ </div>
641
+ <ModelStatusBadge
642
+ status={isDownloading ? 'downloading' : model.status}
643
+ t={t}
644
+ />
645
+ </div>
646
+
647
+ {isDownloading || typeof progress === 'number' ? (
648
+ <div className="space-y-2">
649
+ <div
650
+ className="h-1.5 w-full overflow-hidden rounded-full bg-muted"
651
+ role="progressbar"
652
+ aria-valuemin={0}
653
+ aria-valuemax={100}
654
+ aria-valuenow={Math.round((progress ?? 0) * 100)}
655
+ aria-label={t('ai.models.downloadProgress', {
656
+ percent: Math.round((progress ?? 0) * 100),
657
+ })}
658
+ >
659
+ <div
660
+ className="h-full rounded-full bg-primary transition-[width]"
661
+ style={{ width: `${Math.round((progress ?? 0) * 100)}%` }}
662
+ />
663
+ </div>
664
+ <div className="flex items-center justify-between gap-2">
665
+ <p className="text-xs text-muted-foreground">
666
+ {t('ai.models.downloadProgress', {
667
+ percent: Math.round((progress ?? 0) * 100),
668
+ })}
669
+ </p>
670
+ <Button
671
+ variant="outline"
672
+ size="sm"
673
+ className="h-8"
674
+ onClick={() => cancelDownload(model.id)}
675
+ >
676
+ {t('ai.models.cancel')}
677
+ </Button>
678
+ </div>
679
+ </div>
680
+ ) : (
681
+ <div className="flex flex-wrap gap-2">
682
+ {canDownload ? (
683
+ <Button
684
+ variant="outline"
685
+ size="sm"
686
+ className="h-8"
687
+ disabled={!status?.webGpu.available}
688
+ onClick={() => void startDownload(model)}
689
+ >
690
+ {t('ai.models.download')}
691
+ </Button>
692
+ ) : null}
693
+ {installed ? (
694
+ <Button
695
+ variant="ghost"
696
+ size="sm"
697
+ className="h-8 text-destructive"
698
+ onClick={() => void deleteModel(model.id)}
699
+ >
700
+ {t('ai.models.delete')}
701
+ </Button>
702
+ ) : null}
703
+ </div>
704
+ )}
705
+ {download?.modelId === model.id && download.error ? (
706
+ <p className="text-xs text-destructive">{download.error}</p>
707
+ ) : null}
708
+ </li>
709
+ );
710
+ })}
711
+ </ul>
712
+ )
713
+ ) : null}
714
+ </section>
715
+
716
+ {status?.promptApiPresent ? (
717
+ <section className="space-y-3 rounded-lg border border-border/60 p-3">
718
+ <div className="flex items-start justify-between gap-4">
719
+ <div className="space-y-1">
720
+ <label
721
+ htmlFor="ai-prompt-api-enabled"
722
+ className="text-sm font-medium leading-none"
723
+ style={{ fontFamily: 'var(--heading-font-family, inherit)' }}
724
+ >
725
+ {t('ai.providers.promptApi')}
726
+ </label>
727
+ <p className="text-sm text-muted-foreground">
728
+ {t('ai.providers.promptApiHint')}
729
+ </p>
730
+ </div>
731
+ <Switch
732
+ id="ai-prompt-api-enabled"
733
+ checked={ai.promptApiEnabled !== false}
734
+ onCheckedChange={onPromptApiEnabledChange}
735
+ />
736
+ </div>
737
+ {ai.promptApiEnabled !== false ? (
738
+ promptApiModels.length === 0 ? (
739
+ <p className="text-sm text-muted-foreground">{t('ai.models.promptApiEmpty')}</p>
740
+ ) : (
741
+ <ul className="divide-y divide-border/60 overflow-hidden rounded-md border border-border/60">
742
+ {promptApiModels.map((model) => {
743
+ const isEnabling = promptApiSetup?.modelId === model.id;
744
+ const realProgress =
745
+ isEnabling &&
746
+ typeof promptApiSetup?.progress === 'number' &&
747
+ promptApiSetup.progress > 0
748
+ ? promptApiSetup.progress
749
+ : null;
750
+ // Enable only when the model still needs a one-shot create() warm —
751
+ // already-ready models rely on the provider switch alone.
752
+ const canEnable =
753
+ !isEnabling &&
754
+ (model.status === 'downloadable' || model.status === 'downloading');
755
+ return (
756
+ <li
757
+ key={model.id}
758
+ className="space-y-2 px-3 py-2.5"
759
+ >
760
+ <div className="flex flex-wrap items-center justify-between gap-3">
761
+ <p className="min-w-0 truncate text-sm font-medium">{model.name}</p>
762
+ {isEnabling ? (
763
+ <span className="inline-flex rounded-full bg-amber-500/15 px-2 py-0.5 text-[11px] font-medium text-amber-900 dark:text-amber-100">
764
+ {t('ai.models.enabling')}
765
+ </span>
766
+ ) : (
767
+ <ModelStatusBadge
768
+ status={model.status}
769
+ t={t}
770
+ />
771
+ )}
772
+ </div>
773
+ {isEnabling ? (
774
+ realProgress !== null ? (
775
+ <div className="space-y-2">
776
+ <div
777
+ className="h-1.5 w-full overflow-hidden rounded-full bg-muted"
778
+ role="progressbar"
779
+ aria-valuemin={0}
780
+ aria-valuemax={100}
781
+ aria-valuenow={Math.round(realProgress * 100)}
782
+ aria-label={t('ai.models.downloadProgress', {
783
+ percent: Math.round(realProgress * 100),
784
+ })}
785
+ >
786
+ <div
787
+ className="h-full rounded-full bg-primary transition-[width]"
788
+ style={{ width: `${Math.round(realProgress * 100)}%` }}
789
+ />
790
+ </div>
791
+ <p className="text-xs text-muted-foreground">
792
+ {t('ai.models.downloadProgress', {
793
+ percent: Math.round(realProgress * 100),
794
+ })}
795
+ </p>
796
+ </div>
797
+ ) : (
798
+ <p className="text-xs text-muted-foreground">
799
+ {t('ai.models.promptApiSettingUp')}
800
+ </p>
801
+ )
802
+ ) : canEnable ? (
803
+ <div className="flex flex-wrap gap-2">
804
+ <Button
805
+ variant="outline"
806
+ size="sm"
807
+ className="h-8"
808
+ onClick={() => void startPromptApiEnable(model)}
809
+ >
810
+ {t('ai.models.enable')}
811
+ </Button>
812
+ </div>
813
+ ) : null}
814
+ {promptApiSetup?.modelId === model.id && promptApiSetup.error ? (
815
+ <p className="text-xs text-destructive">{promptApiSetup.error}</p>
816
+ ) : null}
817
+ </li>
818
+ );
819
+ })}
820
+ </ul>
821
+ )
822
+ ) : null}
823
+ </section>
824
+ ) : null}
825
+ </div>
826
+ </div>
827
+ </div>
828
+ </div>
829
+ );
830
+ };