@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,1011 @@
1
+ import type { ChatCompletionChunk, MLCEngineInterface } from '@mlc-ai/web-llm';
2
+ import { BROWSER_MODEL_CATALOG } from '../catalog.js';
3
+ import {
4
+ isBrowserModelInstalled,
5
+ markBrowserModelInstalled,
6
+ removeBrowserModelInstalled,
7
+ } from '../browserInstallStore.js';
8
+ import {
9
+ addTransfer,
10
+ completeTransfer,
11
+ failTransfer,
12
+ interruptTransfer,
13
+ isTransferSignalAborted,
14
+ markTransferCancelled,
15
+ setTransferProgress,
16
+ } from '../../transfers/transferQueue.js';
17
+ import { formatInstallFailureMessage, formatUnknownError, logAiError } from './formatAiError.js';
18
+ import { mapInitProgress } from './mapInitProgress.js';
19
+ import { mapWebLlmRuntimeError } from '../webLlmBrowserSupport.js';
20
+
21
+ export type WebLLMModule = typeof import('@mlc-ai/web-llm');
22
+
23
+ export type WebLLMEngineLike = Pick<
24
+ MLCEngineInterface,
25
+ 'chat' | 'unload' | 'reload' | 'setInitProgressCallback'
26
+ > & {
27
+ /** Clears an in-flight decode so the next chat.completions.create can start. */
28
+ interruptGenerate?: () => void;
29
+ /**
30
+ * Clears WebLLM chat / KV cache for a fresh conversation without unloading weights.
31
+ * WebWorkerMLCEngine returns a Promise; some doubles may be sync.
32
+ */
33
+ resetChat?: (keepStats?: boolean, modelId?: string) => void | Promise<void>;
34
+ /** Optional terminate for test doubles / worker clients. */
35
+ worker?: Worker;
36
+ };
37
+
38
+ export type LoadWebLLMModule = () => Promise<WebLLMModule>;
39
+
40
+ export type CreateWorkerFn = () => Worker | Promise<Worker>;
41
+
42
+ export type WebLLMEngineServiceOptions = {
43
+ loadModule?: LoadWebLLMModule;
44
+ createWorker?: CreateWorkerFn;
45
+ /** When false, skip transfer toaster (tests). Default true. */
46
+ useTransferToast?: boolean;
47
+ };
48
+
49
+ type ActiveInstall = {
50
+ localId: string;
51
+ transferId: string;
52
+ controller: AbortController;
53
+ progress: number;
54
+ progressText?: string;
55
+ };
56
+
57
+ function transferIdFor(localId: string): string {
58
+ return `ai-download:${localId}`;
59
+ }
60
+
61
+ function catalogEntry(localId: string) {
62
+ return BROWSER_MODEL_CATALOG.find((model) => model.id.replace(/^webllm:/, '') === localId);
63
+ }
64
+
65
+ function toLocalId(modelId: string): string {
66
+ return modelId.replace(/^webllm:/, '');
67
+ }
68
+
69
+ function isAbortError(error: unknown): boolean {
70
+ return (
71
+ (error instanceof DOMException && error.name === 'AbortError') ||
72
+ (error instanceof Error && error.name === 'AbortError')
73
+ );
74
+ }
75
+
76
+ const defaultLoadModule: LoadWebLLMModule = async () => {
77
+ const mod = await import('@mlc-ai/web-llm');
78
+ return normalizeWebLlmModule(mod);
79
+ };
80
+
81
+ /**
82
+ * Resolve `@mlc-ai/web-llm` after dynamic import.
83
+ * Vite optimizeDeps / interop can nest named exports under `.default` (or deeper)
84
+ * or drop them from a mangled prebundle — prefer excluding the package from optimizeDeps.
85
+ */
86
+ export function normalizeWebLlmModule(mod: unknown): WebLLMModule {
87
+ const candidates: unknown[] = [mod];
88
+ if (mod && typeof mod === 'object') {
89
+ const d1 = (mod as { default?: unknown }).default;
90
+ if (d1) candidates.push(d1);
91
+ if (d1 && typeof d1 === 'object') {
92
+ const d2 = (d1 as { default?: unknown }).default;
93
+ if (d2) candidates.push(d2);
94
+ }
95
+ }
96
+
97
+ for (const candidate of candidates) {
98
+ if (
99
+ candidate &&
100
+ typeof candidate === 'object' &&
101
+ typeof (candidate as { CreateWebWorkerMLCEngine?: unknown }).CreateWebWorkerMLCEngine ===
102
+ 'function'
103
+ ) {
104
+ return candidate as WebLLMModule;
105
+ }
106
+ }
107
+
108
+ // Last resort: find a function property that looks like the factory (mangled re-exports).
109
+ for (const candidate of candidates) {
110
+ if (!candidate || typeof candidate !== 'object') continue;
111
+ const record = candidate as Record<string, unknown>;
112
+ for (const [key, value] of Object.entries(record)) {
113
+ if (
114
+ typeof value === 'function' &&
115
+ /CreateWebWorkerMLCEngine/i.test(key) &&
116
+ key !== 'default'
117
+ ) {
118
+ return candidate as WebLLMModule;
119
+ }
120
+ }
121
+ }
122
+
123
+ // Optional v1 escape hatch: main-thread CreateMLCEngine if the worker factory is gone.
124
+ for (const candidate of candidates) {
125
+ if (
126
+ candidate &&
127
+ typeof candidate === 'object' &&
128
+ typeof (candidate as { CreateMLCEngine?: unknown }).CreateMLCEngine === 'function'
129
+ ) {
130
+ // eslint-disable-next-line no-console -- operator-facing fallback
131
+ console.warn(
132
+ '[shellui.ai]',
133
+ 'CreateWebWorkerMLCEngine missing after import; falling back to CreateMLCEngine (main thread). Prefer optimizeDeps.exclude for @mlc-ai/web-llm.',
134
+ );
135
+ const api = candidate as WebLLMModule & {
136
+ CreateMLCEngine: (
137
+ modelId: string | string[],
138
+ engineConfig?: unknown,
139
+ chatOpts?: unknown,
140
+ ) => Promise<unknown>;
141
+ };
142
+ return {
143
+ ...api,
144
+ CreateWebWorkerMLCEngine: async (
145
+ _worker: unknown,
146
+ modelId: string | string[],
147
+ engineConfig?: unknown,
148
+ chatOpts?: unknown,
149
+ ) => api.CreateMLCEngine(modelId, engineConfig, chatOpts),
150
+ } as WebLLMModule;
151
+ }
152
+ }
153
+
154
+ const keys = mod && typeof mod === 'object' ? Object.keys(mod as object) : [];
155
+ const defaultKeys =
156
+ mod &&
157
+ typeof mod === 'object' &&
158
+ (mod as { default?: unknown }).default &&
159
+ typeof (mod as { default: unknown }).default === 'object'
160
+ ? Object.keys((mod as { default: object }).default)
161
+ : [];
162
+ // eslint-disable-next-line no-console -- diagnose mangled Vite prebundles
163
+ console.error('[shellui.ai] web-llm import keys', keys, defaultKeys.length ? defaultKeys : null);
164
+
165
+ throw new Error(
166
+ 'Failed to load @mlc-ai/web-llm: CreateWebWorkerMLCEngine is missing. ' +
167
+ 'Exclude @mlc-ai/web-llm from Vite optimizeDeps and clear node_modules/.vite-shellui.',
168
+ );
169
+ }
170
+
171
+ /**
172
+ * Spawn the dedicated worker only at install/load time (never on module import).
173
+ * Prefer Vite's `?worker` constructor (shows a Network request for the worker chunk),
174
+ * then fall back to `new Worker(new URL(..., import.meta.url))`.
175
+ */
176
+ async function defaultCreateWorker(): Promise<Worker> {
177
+ let viteWorkerError: unknown;
178
+ try {
179
+ // Vite transforms this to a Worker constructor that fetches a bundled module worker.
180
+ const mod = await import('./webllm.worker.ts?worker&module');
181
+ const WorkerCtor = (mod as { default?: new () => Worker }).default;
182
+ if (typeof WorkerCtor === 'function') {
183
+ return new WorkerCtor();
184
+ }
185
+ viteWorkerError = new Error('Vite worker module did not export a Worker constructor');
186
+ } catch (error) {
187
+ viteWorkerError = error;
188
+ }
189
+
190
+ try {
191
+ return new Worker(new URL('./webllm.worker.ts', import.meta.url), {
192
+ type: 'module',
193
+ name: 'shellui-webllm',
194
+ });
195
+ } catch (error) {
196
+ throw new Error(
197
+ `Failed to start WebLLM worker: ${formatUnknownError(error)}. ` +
198
+ `Vite ?worker fallback: ${formatUnknownError(viteWorkerError)}. ` +
199
+ 'Check that shell Vite uses worker.format = "es" and can resolve webllm.worker.ts.',
200
+ { cause: error instanceof Error ? error : undefined },
201
+ );
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Shell-owned WebLLM runtime: one warm browser model + in-flight installs.
207
+ * Survives Settings unmount; progress is mirrored into the shared transfer toaster.
208
+ *
209
+ * v1 limit: only one browser model is warm at a time (WebLLM worker reload swaps it).
210
+ */
211
+ export class WebLLMEngineService {
212
+ private readonly loadModule: LoadWebLLMModule;
213
+ private readonly createWorker: CreateWorkerFn;
214
+ private readonly useTransferToast: boolean;
215
+
216
+ private worker: Worker | null = null;
217
+ private engine: WebLLMEngineLike | null = null;
218
+ private warmModelId: string | null = null;
219
+ private loadPromise: Promise<void> | null = null;
220
+ private loadingModelId: string | null = null;
221
+ private lastInstallError: string | null = null;
222
+ private readonly installs = new Map<string, ActiveInstall>();
223
+ private readonly progressListeners = new Set<(localId: string, progress: number) => void>();
224
+ /** Serializes prompt / promptStreaming on the shared worker (WebLLM holds a generation lock). */
225
+ private generationTail: Promise<void> = Promise.resolve();
226
+ /**
227
+ * LanguageModel session that last generated on the warm engine. When a prompt
228
+ * or reset arrives for a different session we **fully dispose the worker** and
229
+ * recreate a fresh engine (weights come from the WebLLM browser cache) so a new
230
+ * conversation never inherits the previous one's KV/chat state — or, worse, a
231
+ * stuck streaming/generation lock (upstream mlc-ai/web-llm#701, mlc-ai/mlc-llm#3113).
232
+ */
233
+ private servingSessionId: string | null = null;
234
+
235
+ constructor(options: WebLLMEngineServiceOptions = {}) {
236
+ this.loadModule = options.loadModule ?? defaultLoadModule;
237
+ this.createWorker = options.createWorker ?? defaultCreateWorker;
238
+ this.useTransferToast = options.useTransferToast !== false;
239
+ }
240
+
241
+ getLastInstallError(): string | null {
242
+ return this.lastInstallError;
243
+ }
244
+
245
+ subscribeProgress(listener: (localId: string, progress: number) => void): () => void {
246
+ this.progressListeners.add(listener);
247
+ return () => {
248
+ this.progressListeners.delete(listener);
249
+ };
250
+ }
251
+
252
+ getDownloadProgress(modelId: string): number | null {
253
+ const localId = toLocalId(modelId);
254
+ const active = this.installs.get(localId);
255
+ return active ? active.progress : null;
256
+ }
257
+
258
+ getDownloadProgressText(modelId: string): string | undefined {
259
+ return this.installs.get(toLocalId(modelId))?.progressText;
260
+ }
261
+
262
+ isDownloading(modelId: string): boolean {
263
+ return this.installs.has(toLocalId(modelId));
264
+ }
265
+
266
+ getWarmModelId(): string | null {
267
+ return this.warmModelId;
268
+ }
269
+
270
+ /**
271
+ * Fetch weights (via WebLLM / HF) + warm the worker engine.
272
+ * Marks the catalog model installed only after the engine can run.
273
+ */
274
+ async install(
275
+ modelId: string,
276
+ options?: { signal?: AbortSignal; onProgress?: (progress: number) => void },
277
+ ): Promise<void> {
278
+ const localId = toLocalId(modelId);
279
+ if (this.warmModelId === localId && this.engine) {
280
+ markBrowserModelInstalled(localId);
281
+ options?.onProgress?.(1);
282
+ return;
283
+ }
284
+ if (this.installs.has(localId)) {
285
+ throw new Error('A download is already in progress for this model.');
286
+ }
287
+
288
+ const entry = catalogEntry(localId);
289
+ const transferId = transferIdFor(localId);
290
+ const controller = new AbortController();
291
+ const onAbort = () => controller.abort();
292
+ options?.signal?.addEventListener('abort', onAbort, { once: true });
293
+
294
+ let toastSignal: AbortSignal | undefined;
295
+ if (this.useTransferToast) {
296
+ const added = addTransfer({
297
+ id: transferId,
298
+ kind: 'download',
299
+ name: entry?.name ?? localId,
300
+ detail: localId,
301
+ size: entry?.sizeBytes ?? 0,
302
+ });
303
+ toastSignal = added.signal;
304
+ toastSignal.addEventListener(
305
+ 'abort',
306
+ () => {
307
+ controller.abort();
308
+ },
309
+ { once: true },
310
+ );
311
+ }
312
+
313
+ const active: ActiveInstall = {
314
+ localId,
315
+ transferId,
316
+ controller,
317
+ progress: 0,
318
+ };
319
+ this.installs.set(localId, active);
320
+
321
+ const report = (ratio: number, text?: string) => {
322
+ active.progress = ratio;
323
+ active.progressText = text;
324
+ options?.onProgress?.(ratio);
325
+ this.progressListeners.forEach((listener) => listener(localId, ratio));
326
+ if (this.useTransferToast) {
327
+ setTransferProgress(transferId, {
328
+ ratio,
329
+ total: entry?.sizeBytes,
330
+ });
331
+ }
332
+ };
333
+
334
+ try {
335
+ if (controller.signal.aborted || options?.signal?.aborted) {
336
+ throw new DOMException('Download cancelled', 'AbortError');
337
+ }
338
+ this.lastInstallError = null;
339
+ await this.ensureEngine(localId, {
340
+ signal: controller.signal,
341
+ onProgress: report,
342
+ });
343
+ markBrowserModelInstalled(localId);
344
+ report(1, 'Ready');
345
+ if (this.useTransferToast && !isTransferSignalAborted(transferId, toastSignal)) {
346
+ completeTransfer(transferId);
347
+ }
348
+ } catch (error) {
349
+ const aborted = controller.signal.aborted || isAbortError(error);
350
+ if (aborted) {
351
+ if (this.useTransferToast) {
352
+ markTransferCancelled(transferId);
353
+ }
354
+ throw error instanceof DOMException
355
+ ? error
356
+ : new DOMException('Download cancelled', 'AbortError');
357
+ }
358
+ const mapped = mapWebLlmRuntimeError(error);
359
+ // Keep explicit worker-crash / engine messages; only remap raw WebGPU-ish throws.
360
+ const keepAsIs =
361
+ error instanceof Error &&
362
+ (/^WebLLM worker crashed/i.test(error.message) ||
363
+ /^CreateWebWorkerMLCEngine failed/i.test(error.message) ||
364
+ /^Failed to (load|start) WebLLM/i.test(error.message));
365
+ const beforeModelFetch = !active.progressText && active.progress <= 0;
366
+ const message =
367
+ (!keepAsIs ? mapped : null) ??
368
+ formatInstallFailureMessage(error, {
369
+ progressText: active.progressText,
370
+ beforeModelFetch,
371
+ fallback: 'Model download failed',
372
+ });
373
+ this.lastInstallError = message;
374
+ logAiError('install', error, {
375
+ modelId: localId,
376
+ stage: 'install',
377
+ progressText: active.progressText,
378
+ beforeModelFetch,
379
+ });
380
+ if (this.useTransferToast) {
381
+ failTransfer(transferId, message);
382
+ }
383
+ throw new Error(message, { cause: error instanceof Error ? error : undefined });
384
+ } finally {
385
+ options?.signal?.removeEventListener('abort', onAbort);
386
+ this.installs.delete(localId);
387
+ }
388
+ }
389
+
390
+ cancelDownload(modelId: string): void {
391
+ const localId = toLocalId(modelId);
392
+ const active = this.installs.get(localId);
393
+ if (!active) return;
394
+ active.controller.abort();
395
+ if (this.useTransferToast) {
396
+ interruptTransfer(active.transferId);
397
+ }
398
+ void this.disposeWorker();
399
+ }
400
+
401
+ async deleteInstalled(modelId: string): Promise<void> {
402
+ const localId = toLocalId(modelId);
403
+ this.cancelDownload(localId);
404
+ if (this.warmModelId === localId) {
405
+ await this.unload(localId);
406
+ }
407
+ removeBrowserModelInstalled(localId);
408
+ try {
409
+ const webllm = await this.loadModule();
410
+ await webllm.deleteModelAllInfoInCache(localId);
411
+ } catch {
412
+ // Best-effort cache wipe for v1.
413
+ }
414
+ }
415
+
416
+ /** Ensure the named model is loaded in the worker (uses WebLLM cache when present). */
417
+ async load(modelId: string, signal?: AbortSignal): Promise<void> {
418
+ const localId = toLocalId(modelId);
419
+ if (!isBrowserModelInstalled(localId) && this.warmModelId !== localId) {
420
+ throw new Error(
421
+ `Browser model "${modelId}" is not installed yet. Install it from Settings → AI.`,
422
+ );
423
+ }
424
+ if (this.warmModelId === localId && this.engine) return;
425
+ await this.ensureEngine(localId, {
426
+ signal,
427
+ onProgress: (ratio) => {
428
+ this.progressListeners.forEach((listener) => listener(localId, ratio));
429
+ },
430
+ });
431
+ }
432
+
433
+ async prompt(options: {
434
+ modelId: string;
435
+ prompt: string;
436
+ systemPrompt?: string;
437
+ signal?: AbortSignal;
438
+ messages?: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>;
439
+ sessionId?: string;
440
+ }): Promise<string> {
441
+ this.interruptForSessionSwitch(options.sessionId);
442
+ return this.withGenerationLock(async () => {
443
+ const engine = await this.ensureEngineForSession(
444
+ options.modelId,
445
+ options.sessionId,
446
+ options.signal,
447
+ );
448
+ const messages = resolveMessages(options);
449
+ try {
450
+ const response = await engine.chat.completions.create({
451
+ messages,
452
+ stream: false,
453
+ });
454
+ if (options.signal?.aborted) {
455
+ throw new DOMException('Prompt aborted', 'AbortError');
456
+ }
457
+ const choice = response.choices?.[0]?.message?.content;
458
+ return typeof choice === 'string' ? choice : '';
459
+ } finally {
460
+ if (options.signal?.aborted) {
461
+ // Dispose so the next prompt cannot inherit a stuck WebLLM lock.
462
+ await this.disposeEngineAndWorker();
463
+ } else {
464
+ this.clearGeneration(engine, 'prompt');
465
+ }
466
+ }
467
+ });
468
+ }
469
+
470
+ async *promptStreaming(options: {
471
+ modelId: string;
472
+ prompt: string;
473
+ systemPrompt?: string;
474
+ signal?: AbortSignal;
475
+ messages?: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>;
476
+ sessionId?: string;
477
+ }): AsyncIterable<{ text: string; done: boolean }> {
478
+ // Break any in-flight (or stuck) generation from a prior conversation BEFORE
479
+ // we queue behind the generation lock, so a switch cannot deadlock.
480
+ this.interruptForSessionSwitch(options.sessionId);
481
+ const release = await this.acquireGenerationLock();
482
+ let engine: WebLLMEngineLike | null = null;
483
+ try {
484
+ engine = await this.ensureEngineForSession(
485
+ options.modelId,
486
+ options.sessionId,
487
+ options.signal,
488
+ );
489
+ const messages = resolveMessages(options);
490
+ const stream = (await engine.chat.completions.create({
491
+ messages,
492
+ stream: true,
493
+ stream_options: { include_usage: false },
494
+ })) as AsyncIterable<ChatCompletionChunk>;
495
+
496
+ let finished = false;
497
+ for await (const chunk of stream) {
498
+ if (options.signal?.aborted) {
499
+ // eslint-disable-next-line no-console -- operator-facing interrupt signal
500
+ console.error('[shellui.ai]', 'promptStreaming aborted — interrupting WebLLM generation');
501
+ throw new DOMException('Prompt aborted', 'AbortError');
502
+ }
503
+ const delta = chunk.choices?.[0]?.delta?.content ?? '';
504
+ const finish = chunk.choices?.[0]?.finish_reason;
505
+ if (delta && !finished) {
506
+ yield { text: delta, done: false };
507
+ }
508
+ if (finish && !finished) {
509
+ finished = true;
510
+ yield { text: '', done: true };
511
+ // Keep draining the WebLLM async generator so its internal lock clears.
512
+ // Do not return early — abandoning the iterator leaves the next create() hanging.
513
+ }
514
+ }
515
+ if (!finished) {
516
+ yield { text: '', done: true };
517
+ }
518
+ } finally {
519
+ if (options.signal?.aborted) {
520
+ // Stop / abort: fully dispose the worker so the next prompt starts on a
521
+ // fresh engine instead of hitting a possibly-stuck WebLLM streaming lock
522
+ // (upstream mlc-ai/web-llm#701, mlc-ai/mlc-llm#3113). Weights stay cached.
523
+ await this.disposeEngineAndWorker();
524
+ } else if (engine) {
525
+ this.clearGeneration(engine, 'promptStreaming');
526
+ }
527
+ release();
528
+ }
529
+ }
530
+
531
+ async unload(modelId?: string): Promise<void> {
532
+ const localId = modelId ? toLocalId(modelId) : this.warmModelId;
533
+ if (localId && this.warmModelId && localId !== this.warmModelId) return;
534
+ try {
535
+ await this.engine?.unload();
536
+ } catch {
537
+ // ignore
538
+ }
539
+ await this.disposeWorker();
540
+ this.engine = null;
541
+ this.warmModelId = null;
542
+ this.servingSessionId = null;
543
+ }
544
+
545
+ /**
546
+ * Prepare for a new LanguageModel conversation (called on `create` / `destroy`).
547
+ *
548
+ * WebLLM's worker engine keeps chat + KV cache state between `chat.completions.create`
549
+ * calls and holds a per-model generation lock that only releases when the previous
550
+ * async stream fully drains. Ollama has none of this (each HTTP generate is
551
+ * independent), which is why only WebLLM hangs on conversation switch.
552
+ *
553
+ * Soft `resetChat` and even `reload` on the *living* worker proved unreliable in
554
+ * the field: an upstream streaming-lock bug (mlc-ai/web-llm#701 — the model lock
555
+ * is not always released after a streamed completion — and mlc-ai/mlc-llm#3113 —
556
+ * `interruptGenerate` can leave `interruptSignal`/the lock stuck) means the worker
557
+ * can stay wedged and the next `create()` hangs forever. `@mlc-ai/web-llm@0.2.85`
558
+ * (our pinned version) still ships this class of bug (#701 is not merged).
559
+ *
560
+ * The reliable v1 fix is **nuclear**: fully dispose the worker (terminate) so the
561
+ * stuck lock dies with it, then let the next prompt recreate a fresh engine —
562
+ * weights are served from the WebLLM browser cache (short warm, not a full HF
563
+ * re-download). We do NOT await `engine.unload()` because a wedged worker may
564
+ * never ack; `terminate()` forcibly kills it.
565
+ *
566
+ * `sessionId` (from `create`) becomes the engine's owning session so the first
567
+ * prompt of that session does not redundantly recreate again.
568
+ */
569
+ async resetConversation(_modelId?: string, sessionId?: string): Promise<void> {
570
+ // Eager interrupt BEFORE queuing behind the lock so a stuck stream unblocks.
571
+ this.safeInterrupt('resetConversation');
572
+ await this.withGenerationLock(async () => {
573
+ if (this.engine) {
574
+ await this.disposeEngineAndWorker();
575
+ }
576
+ this.servingSessionId = sessionId ?? null;
577
+ });
578
+ }
579
+
580
+ /** Fire interruptGenerate on the warm engine, swallowing errors. */
581
+ private safeInterrupt(context: string): void {
582
+ try {
583
+ this.engine?.interruptGenerate?.();
584
+ } catch (error) {
585
+ // eslint-disable-next-line no-console -- interrupt failures are easy to miss otherwise
586
+ console.error('[shellui.ai]', `interruptGenerate (${context}) failed`, error);
587
+ }
588
+ }
589
+
590
+ /** Eager (pre-lock) interrupt when a prompt targets a different session than the warm one. */
591
+ private interruptForSessionSwitch(sessionId?: string): void {
592
+ if (sessionId && this.servingSessionId !== null && sessionId !== this.servingSessionId) {
593
+ this.safeInterrupt('sessionSwitch');
594
+ }
595
+ }
596
+
597
+ /**
598
+ * Ensure a fresh-enough engine is warm and owned by `sessionId`, called under the
599
+ * generation lock. On a genuine conversation switch (same model, different session)
600
+ * we take the **nuclear** path: dispose the worker and recreate a fresh engine from
601
+ * the WebLLM browser cache. First-ever conversation and same-session multi-turn just
602
+ * load/reuse the warm engine (no recreate, no lost KV within the turn).
603
+ */
604
+ private async ensureEngineForSession(
605
+ modelId: string,
606
+ sessionId: string | undefined,
607
+ signal?: AbortSignal,
608
+ ): Promise<WebLLMEngineLike> {
609
+ const localId = toLocalId(modelId);
610
+ const switching =
611
+ sessionId !== undefined &&
612
+ this.servingSessionId !== null &&
613
+ this.servingSessionId !== sessionId;
614
+
615
+ if (switching && this.engine && this.warmModelId === localId) {
616
+ await this.recreateEngineForSwitch(localId, signal);
617
+ } else {
618
+ // First load, same-session multi-turn, or model switch (ensureEngine already
619
+ // spins a fresh worker when the model id changes).
620
+ await this.load(modelId, signal);
621
+ }
622
+
623
+ if (sessionId !== undefined) {
624
+ this.servingSessionId = sessionId;
625
+ }
626
+ return this.requireEngine();
627
+ }
628
+
629
+ /**
630
+ * Reliable "new chat" on a switch: break any in-flight generation, terminate the
631
+ * worker (killing any stuck streaming lock — mlc-ai/web-llm#701 / mlc-ai/mlc-llm#3113),
632
+ * then recreate a fresh engine for the same model. Weights come from the WebLLM
633
+ * browser cache, so this is a short warm rather than a full HF re-download.
634
+ */
635
+ private async recreateEngineForSwitch(localId: string, signal?: AbortSignal): Promise<void> {
636
+ this.safeInterrupt('recreateEngineForSwitch');
637
+ await this.disposeEngineAndWorker();
638
+ // eslint-disable-next-line no-console -- operator-facing breadcrumb for switch recreate
639
+ console.info(
640
+ '[shellui.ai]',
641
+ 'conversation switch — recreating WebLLM worker (weights from cache)',
642
+ { modelId: localId },
643
+ );
644
+ await this.ensureEngine(localId, {
645
+ signal,
646
+ onProgress: (ratio) => {
647
+ this.progressListeners.forEach((listener) => listener(localId, ratio));
648
+ },
649
+ });
650
+ }
651
+
652
+ /**
653
+ * Forcibly tear down the worker + engine. Deliberately does NOT await
654
+ * `engine.unload()`: a wedged worker (stuck streaming lock) may never ack, so we
655
+ * rely on `worker.terminate()`. Weights persist in the WebLLM browser cache.
656
+ */
657
+ private async disposeEngineAndWorker(): Promise<void> {
658
+ await this.disposeWorker();
659
+ this.engine = null;
660
+ this.warmModelId = null;
661
+ }
662
+
663
+ /** Test helper — reset singleton state. */
664
+ async resetForTests(): Promise<void> {
665
+ for (const active of this.installs.values()) {
666
+ active.controller.abort();
667
+ }
668
+ this.installs.clear();
669
+ await this.disposeWorker();
670
+ this.engine = null;
671
+ this.warmModelId = null;
672
+ this.loadPromise = null;
673
+ this.loadingModelId = null;
674
+ this.generationTail = Promise.resolve();
675
+ this.servingSessionId = null;
676
+ }
677
+
678
+ private async acquireGenerationLock(): Promise<() => void> {
679
+ const previous = this.generationTail;
680
+ let release!: () => void;
681
+ this.generationTail = new Promise<void>((resolve) => {
682
+ release = resolve;
683
+ });
684
+ await previous;
685
+ return release;
686
+ }
687
+
688
+ private async withGenerationLock<T>(fn: () => Promise<T>): Promise<T> {
689
+ const release = await this.acquireGenerationLock();
690
+ try {
691
+ return await fn();
692
+ } finally {
693
+ release();
694
+ }
695
+ }
696
+
697
+ /** Best-effort clear of WebLLM's in-flight decode lock between turns. */
698
+ private clearGeneration(engine: WebLLMEngineLike, context: string): void {
699
+ try {
700
+ engine.interruptGenerate?.();
701
+ } catch (error) {
702
+ // eslint-disable-next-line no-console -- interrupt failures are easy to miss otherwise
703
+ console.error('[shellui.ai]', `interruptGenerate after ${context} failed`, error);
704
+ }
705
+ }
706
+
707
+ private requireEngine(): WebLLMEngineLike {
708
+ if (!this.engine) {
709
+ throw new Error('WebLLM engine is not ready.');
710
+ }
711
+ return this.engine;
712
+ }
713
+
714
+ private async ensureEngine(
715
+ localId: string,
716
+ options: {
717
+ signal?: AbortSignal;
718
+ onProgress?: (progress: number, text?: string) => void;
719
+ },
720
+ ): Promise<void> {
721
+ if (this.warmModelId === localId && this.engine) {
722
+ options.onProgress?.(1, 'Ready');
723
+ return;
724
+ }
725
+
726
+ if (this.loadPromise && this.loadingModelId === localId) {
727
+ await this.loadPromise;
728
+ return;
729
+ }
730
+
731
+ this.loadingModelId = localId;
732
+ this.loadPromise = this.createAndLoad(localId, options);
733
+ try {
734
+ await this.loadPromise;
735
+ } finally {
736
+ this.loadPromise = null;
737
+ this.loadingModelId = null;
738
+ }
739
+ }
740
+
741
+ private async createAndLoad(
742
+ localId: string,
743
+ options: {
744
+ signal?: AbortSignal;
745
+ onProgress?: (progress: number, text?: string) => void;
746
+ },
747
+ ): Promise<void> {
748
+ if (options.signal?.aborted) {
749
+ throw new DOMException('Download cancelled', 'AbortError');
750
+ }
751
+
752
+ await this.disposeWorker();
753
+
754
+ let webllm: WebLLMModule;
755
+ try {
756
+ webllm = await this.loadModule();
757
+ } catch (error) {
758
+ logAiError('loadModule', error, { modelId: localId, stage: 'import(@mlc-ai/web-llm)' });
759
+ throw new Error(
760
+ `Failed to load @mlc-ai/web-llm: ${formatUnknownError(error)}. ` +
761
+ 'Is it installed and visible to the shell Vite app? ' +
762
+ '(shellui start should optimizeDeps.include @mlc-ai/web-llm and alias it from @shellui/core)',
763
+ { cause: error instanceof Error ? error : undefined },
764
+ );
765
+ }
766
+
767
+ let worker: Worker;
768
+ try {
769
+ worker = await this.createWorker();
770
+ } catch (error) {
771
+ logAiError('createWorker', error, { modelId: localId, stage: 'new Worker' });
772
+ throw new Error(
773
+ `Failed to start WebLLM worker: ${formatUnknownError(error)}. ` +
774
+ 'If Network shows no worker script, Vite module-worker bundling is broken.',
775
+ { cause: error instanceof Error ? error : undefined },
776
+ );
777
+ }
778
+ this.worker = worker;
779
+
780
+ let lastProgressText: string | undefined;
781
+ let sawProgress = false;
782
+ const reportProgress = (ratio: number, text?: string) => {
783
+ if (text) lastProgressText = text;
784
+ if (ratio > 0 || (text && text.length > 0)) sawProgress = true;
785
+ options.onProgress?.(ratio, text);
786
+ };
787
+
788
+ let settled = false;
789
+ const abortError = () => new DOMException('Download cancelled', 'AbortError');
790
+
791
+ // Worker script / uncaught failures never reach CreateWebWorkerMLCEngine's getPromise —
792
+ // surface them on the main thread so Install does not hang or collapse to a generic toast.
793
+ let detachWorkerGuards: () => void = () => undefined;
794
+ const workerCrashPromise = new Promise<never>((_, reject) => {
795
+ const onError = (event: Event) => {
796
+ const detail = formatUnknownError(event);
797
+ logAiError('worker.onerror', event, {
798
+ modelId: localId,
799
+ stage: 'worker.onerror',
800
+ progressText: lastProgressText,
801
+ beforeModelFetch: !sawProgress,
802
+ });
803
+ reject(
804
+ new Error(
805
+ `WebLLM worker crashed: ${detail || 'see DevTools → Worker console'}. ${
806
+ !sawProgress
807
+ ? 'No init progress yet — failure was before Hugging Face fetch (often GPU init).'
808
+ : `Last progress: ${lastProgressText ?? '(none)'}`
809
+ }`,
810
+ {
811
+ cause:
812
+ typeof ErrorEvent !== 'undefined' &&
813
+ event instanceof ErrorEvent &&
814
+ event.error instanceof Error
815
+ ? event.error
816
+ : undefined,
817
+ },
818
+ ),
819
+ );
820
+ };
821
+ const onMessageError = (event: MessageEvent) => {
822
+ logAiError('worker.onmessageerror', event, {
823
+ modelId: localId,
824
+ stage: 'worker.onmessageerror',
825
+ progressText: lastProgressText,
826
+ beforeModelFetch: !sawProgress,
827
+ });
828
+ reject(
829
+ new Error(
830
+ `WebLLM worker messageerror: ${formatUnknownError(event)}. ` +
831
+ 'A non-cloneable value may have been posted between worker and main thread.',
832
+ ),
833
+ );
834
+ };
835
+ worker.addEventListener('error', onError);
836
+ worker.addEventListener('messageerror', onMessageError);
837
+ detachWorkerGuards = () => {
838
+ worker.removeEventListener('error', onError);
839
+ worker.removeEventListener('messageerror', onMessageError);
840
+ };
841
+ });
842
+
843
+ // eslint-disable-next-line no-console -- stage breadcrumb for Install debugging
844
+ console.info('[shellui.ai]', 'CreateWebWorkerMLCEngine starting', {
845
+ modelId: localId,
846
+ hint: 'HF fetches (if any) appear under the Worker Network tab, not the main document',
847
+ });
848
+
849
+ let enginePromise: Promise<WebLLMEngineLike>;
850
+ try {
851
+ enginePromise = webllm.CreateWebWorkerMLCEngine(worker, localId, {
852
+ logLevel: 'INFO',
853
+ initProgressCallback: (report) => {
854
+ if (options.signal?.aborted) return;
855
+ const ratio = mapInitProgress(report);
856
+ reportProgress(ratio, report.text);
857
+ },
858
+ }) as Promise<WebLLMEngineLike>;
859
+ } catch (error) {
860
+ detachWorkerGuards();
861
+ await this.disposeWorker();
862
+ logAiError('CreateWebWorkerMLCEngine', error, {
863
+ modelId: localId,
864
+ stage: 'CreateWebWorkerMLCEngine.sync',
865
+ beforeModelFetch: true,
866
+ });
867
+ throw new Error(`CreateWebWorkerMLCEngine failed before load: ${formatUnknownError(error)}`, {
868
+ cause: error instanceof Error ? error : undefined,
869
+ });
870
+ }
871
+
872
+ // WebLLM rejects with a string (worker err.toString()) — always log the raw rejection.
873
+ enginePromise = enginePromise.catch((rejection) => {
874
+ logAiError('CreateWebWorkerMLCEngine.rejected', rejection, {
875
+ modelId: localId,
876
+ stage: 'CreateWebWorkerMLCEngine / reload',
877
+ progressText: lastProgressText,
878
+ beforeModelFetch: !sawProgress,
879
+ });
880
+ const mapped = mapWebLlmRuntimeError(rejection);
881
+ const detail = formatInstallFailureMessage(rejection, {
882
+ progressText: lastProgressText,
883
+ beforeModelFetch: !sawProgress,
884
+ fallback: 'WebLLM CreateWebWorkerMLCEngine rejected (see [shellui.ai] console)',
885
+ });
886
+ throw new Error(mapped ?? detail, {
887
+ cause: rejection instanceof Error ? rejection : undefined,
888
+ });
889
+ });
890
+
891
+ const abortPromise = new Promise<never>((_, reject) => {
892
+ if (options.signal?.aborted) {
893
+ reject(abortError());
894
+ return;
895
+ }
896
+ options.signal?.addEventListener(
897
+ 'abort',
898
+ () => {
899
+ void this.disposeWorker();
900
+ reject(abortError());
901
+ },
902
+ { once: true },
903
+ );
904
+ });
905
+
906
+ try {
907
+ const engine = await Promise.race([enginePromise, abortPromise, workerCrashPromise]);
908
+ settled = true;
909
+ detachWorkerGuards();
910
+
911
+ if (options.signal?.aborted) {
912
+ try {
913
+ await engine.unload();
914
+ } catch {
915
+ // ignore
916
+ }
917
+ await this.disposeWorker();
918
+ throw abortError();
919
+ }
920
+
921
+ this.engine = engine;
922
+ this.warmModelId = localId;
923
+ options.onProgress?.(1, 'Ready');
924
+ } catch (error) {
925
+ detachWorkerGuards();
926
+ await this.disposeWorker();
927
+ this.engine = null;
928
+ this.warmModelId = null;
929
+ if (options.signal?.aborted || isAbortError(error)) {
930
+ throw abortError();
931
+ }
932
+ logAiError('createAndLoad', error, {
933
+ modelId: localId,
934
+ stage: 'engine.reload',
935
+ progressText: lastProgressText,
936
+ beforeModelFetch: !sawProgress,
937
+ });
938
+ if (error instanceof Error) {
939
+ throw error;
940
+ }
941
+ throw new Error(
942
+ formatInstallFailureMessage(error, {
943
+ progressText: lastProgressText,
944
+ beforeModelFetch: !sawProgress,
945
+ fallback: 'Model download failed',
946
+ }),
947
+ );
948
+ } finally {
949
+ // If create eventually resolves after abort, drop the late engine.
950
+ if (!settled) {
951
+ void enginePromise
952
+ .then(async (engine) => {
953
+ try {
954
+ await engine.unload();
955
+ } catch {
956
+ // ignore
957
+ }
958
+ })
959
+ .catch(() => undefined);
960
+ }
961
+ }
962
+ }
963
+
964
+ private async disposeWorker(): Promise<void> {
965
+ const worker = this.worker;
966
+ this.worker = null;
967
+ if (!worker) return;
968
+ try {
969
+ worker.terminate();
970
+ } catch {
971
+ // ignore
972
+ }
973
+ }
974
+ }
975
+
976
+ function resolveMessages(options: {
977
+ systemPrompt?: string;
978
+ prompt: string;
979
+ messages?: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>;
980
+ }): Array<{ role: 'system' | 'user' | 'assistant'; content: string }> {
981
+ if (options.messages && options.messages.length > 0) {
982
+ return options.messages;
983
+ }
984
+ return buildMessages(options.systemPrompt, options.prompt);
985
+ }
986
+
987
+ function buildMessages(
988
+ systemPrompt: string | undefined,
989
+ prompt: string,
990
+ ): Array<{ role: 'system' | 'user' | 'assistant'; content: string }> {
991
+ const messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }> = [];
992
+ if (systemPrompt) {
993
+ messages.push({ role: 'system', content: systemPrompt });
994
+ }
995
+ messages.push({ role: 'user', content: prompt });
996
+ return messages;
997
+ }
998
+
999
+ let sharedEngine: WebLLMEngineService | null = null;
1000
+
1001
+ export function getSharedWebLLMEngine(): WebLLMEngineService {
1002
+ if (!sharedEngine) {
1003
+ sharedEngine = new WebLLMEngineService();
1004
+ }
1005
+ return sharedEngine;
1006
+ }
1007
+
1008
+ /** Replace the shared engine (tests). */
1009
+ export function setSharedWebLLMEngineForTests(engine: WebLLMEngineService | null): void {
1010
+ sharedEngine = engine;
1011
+ }