@shellui/core 0.5.4-alpha.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) 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 +26 -5
  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 +119 -134
  58. package/src/features/auth/components/OAuthCallbackView.tsx +12 -3
  59. package/src/features/auth/components/SessionLoadingView.tsx +21 -0
  60. package/src/features/auth/hooks/useAuth.tsx +12 -0
  61. package/src/features/auth/shellAccountRequests.ts +76 -0
  62. package/src/features/auth/utils/authRequestError.spec.ts +11 -0
  63. package/src/features/auth/utils/authRequestError.ts +10 -1
  64. package/src/features/auth/utils/authSessionPersistence.spec.ts +11 -0
  65. package/src/features/auth/utils/authSessionPersistence.ts +12 -0
  66. package/src/features/auth/utils/index.ts +5 -0
  67. package/src/features/auth/utils/resolveLoginSettings.spec.ts +33 -0
  68. package/src/features/auth/utils/resolveLoginSettings.ts +33 -0
  69. package/src/features/auth/utils/shareInFlight.spec.ts +41 -0
  70. package/src/features/auth/utils/shareInFlight.ts +14 -0
  71. package/src/features/config/ConfigProvider.ts +9 -1
  72. package/src/features/config/types.ts +43 -0
  73. package/src/features/layouts/appbar/AppBarLayout.tsx +8 -3
  74. package/src/features/layouts/filterNavigationForAuthState.spec.ts +41 -0
  75. package/src/features/layouts/floating/FloatingLayout.tsx +9 -4
  76. package/src/features/layouts/sidebar/SidebarLayout.tsx +9 -4
  77. package/src/features/layouts/utils.ts +6 -2
  78. package/src/features/layouts/windows/WindowsLayout.tsx +8 -3
  79. package/src/features/messaging/MessagingSecurityBootstrap.tsx +6 -6
  80. package/src/features/security/trustedFrames.spec.ts +65 -0
  81. package/src/features/security/trustedFrames.ts +52 -0
  82. package/src/features/settings/SettingsIcons.tsx +17 -0
  83. package/src/features/settings/SettingsProvider.tsx +28 -3
  84. package/src/features/settings/SettingsRoutes.tsx +8 -0
  85. package/src/features/settings/SettingsView.tsx +21 -4
  86. package/src/features/settings/components/Ai.tsx +830 -0
  87. package/src/features/settings/components/Develop.tsx +4 -0
  88. package/src/features/settings/components/Storage.tsx +197 -32
  89. package/src/features/settings/components/UserSettingsPanel.tsx +160 -12
  90. package/src/features/settings/components/createUserSettingsRoute.tsx +4 -0
  91. package/src/features/settings/components/develop/AiTestTools.tsx +231 -0
  92. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +54 -1
  93. package/src/features/settings/utils/buildSettingsForPropagation.ts +15 -1
  94. package/src/features/settings/utils/mergePreferencesIntoSettings.spec.ts +6 -0
  95. package/src/features/settings/utils/shouldShowStorageSettings.spec.ts +49 -0
  96. package/src/features/settings/utils/shouldShowStorageSettings.ts +19 -0
  97. package/src/features/storage/uploads/UploadToastCard.tsx +2 -442
  98. package/src/features/storage/uploads/UploadToaster.tsx +2 -44
  99. package/src/features/storage/uploads/uploadQueue.ts +128 -308
  100. package/src/features/storage/uploads/useUploadQueue.ts +7 -3
  101. package/src/features/transfers/TransferToastCard.tsx +467 -0
  102. package/src/features/transfers/TransferToaster.tsx +50 -0
  103. package/src/features/transfers/index.ts +33 -0
  104. package/src/features/transfers/transferQueue.spec.ts +97 -0
  105. package/src/features/transfers/transferQueue.ts +442 -0
  106. package/src/features/transfers/types.ts +38 -0
  107. package/src/features/transfers/useTransferQueue.ts +30 -0
  108. package/src/i18n/translations/en/common.json +49 -2
  109. package/src/i18n/translations/en/settings.json +152 -2
  110. package/src/i18n/translations/fr/common.json +49 -2
  111. package/src/i18n/translations/fr/settings.json +152 -2
  112. package/src/index.css +57 -4
  113. package/src/index.ts +1 -0
  114. package/src/routes/components/NavigationItemRoute.tsx +2 -1
@@ -0,0 +1,32 @@
1
+ import type { AiRequestPayload, AiResponsePayload } from '@shellui/sdk';
2
+
3
+ /** Pure responses when `config.ai.enabled` is not `true` (no adapters / WebLLM). */
4
+ export function buildAiDisabledResponse(payload: AiRequestPayload): AiResponsePayload {
5
+ const { id, op } = payload;
6
+
7
+ if (op === 'availability') {
8
+ return { id, data: { availability: 'unavailable' } };
9
+ }
10
+ if (op === 'listModels') {
11
+ return { id, data: { models: [] } };
12
+ }
13
+ if (op === 'status') {
14
+ return {
15
+ id,
16
+ data: {
17
+ webGpu: { available: false },
18
+ ollama: { reachable: false, baseUrl: '' },
19
+ models: [],
20
+ defaultModelId: null,
21
+ },
22
+ };
23
+ }
24
+
25
+ return {
26
+ id,
27
+ error: {
28
+ message: 'On-device AI is not enabled in shellui.config (set ai.enabled: true).',
29
+ code: 'ai_disabled',
30
+ },
31
+ };
32
+ }
@@ -0,0 +1,58 @@
1
+ import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
2
+ import {
3
+ BROWSER_INSTALL_STORAGE_KEY,
4
+ clearBrowserInstalledForTests,
5
+ estimateInstalledCatalogBytes,
6
+ isBrowserModelInstalled,
7
+ listBrowserInstalledIds,
8
+ markBrowserModelInstalled,
9
+ removeBrowserModelInstalled,
10
+ } from './browserInstallStore.js';
11
+
12
+ describe('browserInstallStore', () => {
13
+ const memory = new Map<string, string>();
14
+
15
+ beforeEach(() => {
16
+ memory.clear();
17
+ vi.stubGlobal('localStorage', {
18
+ getItem: (key: string) => memory.get(key) ?? null,
19
+ setItem: (key: string, value: string) => {
20
+ memory.set(key, value);
21
+ },
22
+ removeItem: (key: string) => {
23
+ memory.delete(key);
24
+ },
25
+ });
26
+ clearBrowserInstalledForTests();
27
+ });
28
+
29
+ afterEach(() => {
30
+ vi.unstubAllGlobals();
31
+ });
32
+
33
+ it('persists install records across mark/list/remove', () => {
34
+ expect(listBrowserInstalledIds()).toEqual([]);
35
+ markBrowserModelInstalled('webllm:Llama-3.2-1B-Instruct-q4f16_1-MLC');
36
+ expect(isBrowserModelInstalled('Llama-3.2-1B-Instruct-q4f16_1-MLC')).toBe(true);
37
+ expect(listBrowserInstalledIds()).toEqual(['Llama-3.2-1B-Instruct-q4f16_1-MLC']);
38
+ expect(memory.get(BROWSER_INSTALL_STORAGE_KEY)).toContain('Llama-3.2-1B-Instruct-q4f16_1-MLC');
39
+
40
+ removeBrowserModelInstalled('Llama-3.2-1B-Instruct-q4f16_1-MLC');
41
+ expect(listBrowserInstalledIds()).toEqual([]);
42
+ });
43
+
44
+ it('is shared for second-app reuse of the same origin catalog', () => {
45
+ markBrowserModelInstalled('Phi-3.5-mini-instruct-q4f16_1-MLC');
46
+ expect(isBrowserModelInstalled('webllm:Phi-3.5-mini-instruct-q4f16_1-MLC')).toBe(true);
47
+ });
48
+
49
+ it('estimates catalog bytes for installed records', () => {
50
+ markBrowserModelInstalled('webllm:a');
51
+ expect(
52
+ estimateInstalledCatalogBytes([
53
+ { id: 'webllm:a', sizeBytes: 100 },
54
+ { id: 'webllm:b', sizeBytes: 200 },
55
+ ]),
56
+ ).toBe(100);
57
+ });
58
+ });
@@ -0,0 +1,76 @@
1
+ /** Persist browser-catalog install records across reloads (shared by all apps in this origin). */
2
+
3
+ export const BROWSER_INSTALL_STORAGE_KEY = 'shellui:ai:browserInstalled';
4
+
5
+ export type BrowserInstallRecord = {
6
+ /** Local model id without `webllm:` prefix (WebLLM `model_id`). */
7
+ id: string;
8
+ installedAt: number;
9
+ /** Cache backend hint — WebLLM IndexedDB / Cache API for v1. */
10
+ cache?: 'webllm';
11
+ };
12
+
13
+ function readStore(): BrowserInstallRecord[] {
14
+ if (typeof localStorage === 'undefined') return [];
15
+ try {
16
+ const raw = localStorage.getItem(BROWSER_INSTALL_STORAGE_KEY);
17
+ if (!raw) return [];
18
+ const parsed = JSON.parse(raw) as unknown;
19
+ if (!Array.isArray(parsed)) return [];
20
+ return parsed.filter(
21
+ (item): item is BrowserInstallRecord =>
22
+ Boolean(item) &&
23
+ typeof item === 'object' &&
24
+ typeof (item as BrowserInstallRecord).id === 'string',
25
+ );
26
+ } catch {
27
+ return [];
28
+ }
29
+ }
30
+
31
+ function writeStore(records: BrowserInstallRecord[]): void {
32
+ if (typeof localStorage === 'undefined') return;
33
+ localStorage.setItem(BROWSER_INSTALL_STORAGE_KEY, JSON.stringify(records));
34
+ }
35
+
36
+ export function listBrowserInstalledIds(): string[] {
37
+ return readStore().map((record) => record.id);
38
+ }
39
+
40
+ export function isBrowserModelInstalled(modelId: string): boolean {
41
+ const localId = modelId.replace(/^webllm:/, '');
42
+ return listBrowserInstalledIds().includes(localId);
43
+ }
44
+
45
+ export function markBrowserModelInstalled(modelId: string): void {
46
+ const localId = modelId.replace(/^webllm:/, '');
47
+ const existing = readStore().filter((record) => record.id !== localId);
48
+ existing.push({ id: localId, installedAt: Date.now(), cache: 'webllm' });
49
+ writeStore(existing);
50
+ }
51
+
52
+ export function removeBrowserModelInstalled(modelId: string): void {
53
+ const localId = modelId.replace(/^webllm:/, '');
54
+ writeStore(readStore().filter((record) => record.id !== localId));
55
+ }
56
+
57
+ export function clearBrowserInstalledForTests(): void {
58
+ if (typeof localStorage === 'undefined') return;
59
+ localStorage.removeItem(BROWSER_INSTALL_STORAGE_KEY);
60
+ }
61
+
62
+ /** Sum of catalog `sizeBytes` for install records (estimate until real OPFS meters). */
63
+ export function estimateInstalledCatalogBytes(
64
+ catalog: ReadonlyArray<{ id: string; sizeBytes?: number }> = [],
65
+ ): number {
66
+ const installed = new Set(listBrowserInstalledIds());
67
+ let total = 0;
68
+ for (const model of catalog) {
69
+ const localId = model.id.replace(/^webllm:/, '');
70
+ if (!installed.has(localId)) continue;
71
+ if (typeof model.sizeBytes === 'number' && Number.isFinite(model.sizeBytes)) {
72
+ total += model.sizeBytes;
73
+ }
74
+ }
75
+ return total;
76
+ }
@@ -0,0 +1,31 @@
1
+ import type { AiModel } from './types.js';
2
+
3
+ /**
4
+ * Curated browser catalog for v1.
5
+ *
6
+ * Model ids (after the `webllm:` prefix) must match WebLLM `prebuiltAppConfig`
7
+ * `model_id` strings. WebLLM resolves Hugging Face weights from those entries —
8
+ * do not invent a separate HF downloader.
9
+ *
10
+ * Current ids (WebLLM 0.2.x):
11
+ * - `Llama-3.2-1B-Instruct-q4f16_1-MLC` → https://huggingface.co/mlc-ai/Llama-3.2-1B-Instruct-q4f16_1-MLC
12
+ * - `Phi-3.5-mini-instruct-q4f16_1-MLC` → https://huggingface.co/mlc-ai/Phi-3.5-mini-instruct-q4f16_1-MLC
13
+ */
14
+ export const BROWSER_MODEL_CATALOG: readonly AiModel[] = [
15
+ {
16
+ id: 'webllm:Llama-3.2-1B-Instruct-q4f16_1-MLC',
17
+ name: 'Llama 3.2 1B Instruct',
18
+ provider: 'webllm',
19
+ sizeBytes: 700_000_000,
20
+ status: 'downloadable',
21
+ description: 'Small instruct model (≈700 MB). Good mobile candidate.',
22
+ },
23
+ {
24
+ id: 'webllm:Phi-3.5-mini-instruct-q4f16_1-MLC',
25
+ name: 'Phi 3.5 Mini Instruct',
26
+ provider: 'webllm',
27
+ sizeBytes: 2_300_000_000,
28
+ status: 'downloadable',
29
+ description: 'Stronger small model (≈2.3 GB). Needs WebGPU + more disk.',
30
+ },
31
+ ] as const;
@@ -0,0 +1,83 @@
1
+ import { OllamaAdapter, type OllamaAdapterOptions } from './adapters/ollama.js';
2
+ import { WebLLMAdapter } from './adapters/webllm.js';
3
+ import { PromptApiAdapter } from './adapters/promptApi.js';
4
+ import { AiRegistry } from './registry.js';
5
+ import { DEFAULT_OLLAMA_BASE_URL } from './status.js';
6
+
7
+ export type CreateDefaultAiRegistryOptions = {
8
+ ollama?: OllamaAdapterOptions;
9
+ /** When false, skip registering the WebLLM adapter (tests). Default true. */
10
+ includeWebLLM?: boolean;
11
+ /** When false, skip registering the Chrome Prompt API adapter (tests). Default true. */
12
+ includePromptApi?: boolean;
13
+ defaultModelId?: string | null;
14
+ /** Inject a WebLLM adapter (Settings keeps one instance for download progress). */
15
+ webllmAdapter?: WebLLMAdapter;
16
+ /** Inject a Prompt API adapter (Settings keeps one instance for download progress). */
17
+ promptApiAdapter?: PromptApiAdapter;
18
+ };
19
+
20
+ let sharedWebLLMAdapter: WebLLMAdapter | null = null;
21
+ let sharedPromptApiAdapter: PromptApiAdapter | null = null;
22
+
23
+ /** Shared browser adapter so Settings download progress survives remounts. */
24
+ export function getSharedWebLLMAdapter(): WebLLMAdapter {
25
+ if (!sharedWebLLMAdapter) {
26
+ sharedWebLLMAdapter = new WebLLMAdapter();
27
+ }
28
+ return sharedWebLLMAdapter;
29
+ }
30
+
31
+ /** Shared Prompt API adapter so Settings built-in-model download progress persists. */
32
+ export function getSharedPromptApiAdapter(): PromptApiAdapter {
33
+ if (!sharedPromptApiAdapter) {
34
+ sharedPromptApiAdapter = new PromptApiAdapter();
35
+ }
36
+ return sharedPromptApiAdapter;
37
+ }
38
+
39
+ /**
40
+ * Shell entry: Ollama + WebLLM + Chrome Prompt API behind one registry.
41
+ *
42
+ * The Prompt API adapter is always registered but self-hides: its `listModels`
43
+ * returns `[]` unless the Chrome `LanguageModel` global is present and usable.
44
+ */
45
+ export function createDefaultAiRegistry(options: CreateDefaultAiRegistryOptions = {}): AiRegistry {
46
+ const adapters = [
47
+ new OllamaAdapter(options.ollama ?? { baseUrl: DEFAULT_OLLAMA_BASE_URL }),
48
+ ...(options.includeWebLLM === false ? [] : [options.webllmAdapter ?? getSharedWebLLMAdapter()]),
49
+ ...(options.includePromptApi === false
50
+ ? []
51
+ : [options.promptApiAdapter ?? getSharedPromptApiAdapter()]),
52
+ ];
53
+ return new AiRegistry({
54
+ adapters,
55
+ defaultModelId: options.defaultModelId ?? null,
56
+ });
57
+ }
58
+
59
+ export type {
60
+ AiAdapter,
61
+ AiAvailability,
62
+ AiModel,
63
+ AiModelStatus,
64
+ AiPromptOptions,
65
+ AiProviderId,
66
+ AiRegistryOptions,
67
+ AiRuntimeStatus,
68
+ AiStreamChunk,
69
+ } from './types.js';
70
+
71
+ export { AiRegistry } from './registry.js';
72
+ export { OllamaAdapter } from './adapters/ollama.js';
73
+ export type { OllamaAdapterOptions } from './adapters/ollama.js';
74
+ export { WebLLMAdapter } from './adapters/webllm.js';
75
+ export { PromptApiAdapter, PROMPT_API_MODEL_ID } from './adapters/promptApi.js';
76
+ export { getPromptApi, isPromptApiPresent } from './promptApiSupport.js';
77
+ export { BROWSER_MODEL_CATALOG } from './catalog.js';
78
+ export {
79
+ DEFAULT_OLLAMA_BASE_URL,
80
+ probeOllama,
81
+ probeWebGpu,
82
+ type ProbeOllamaOptions,
83
+ } from './status.js';
@@ -0,0 +1,108 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import type { Settings } from '@shellui/sdk';
3
+ import { AiRegistry } from './registry.js';
4
+ import type { AiAdapter, AiModel, AiPromptOptions, AiStreamChunk } from './types.js';
5
+ import {
6
+ collectDevelopAiDiagnostics,
7
+ DEVELOP_AI_TEST_PROMPT,
8
+ runDevelopAiPrompt,
9
+ runDevelopAiStream,
10
+ } from './developHarness.js';
11
+
12
+ const tinyModel: AiModel = {
13
+ id: 'ollama:tiny',
14
+ name: 'tiny',
15
+ provider: 'ollama',
16
+ status: 'ready',
17
+ };
18
+
19
+ const fakeAdapter: AiAdapter = {
20
+ id: 'ollama',
21
+ isAvailable: async () => true,
22
+ listModels: async () => [tinyModel],
23
+ load: async () => undefined,
24
+ prompt: async (options: AiPromptOptions) =>
25
+ options.prompt === DEVELOP_AI_TEST_PROMPT ? 'pong' : `echo:${options.prompt}`,
26
+ promptStreaming: async function* (): AsyncIterable<AiStreamChunk> {
27
+ yield { text: 'po', done: false };
28
+ yield { text: 'ng', done: true };
29
+ },
30
+ unload: async () => undefined,
31
+ };
32
+
33
+ vi.mock('./status.js', async (importOriginal) => {
34
+ const actual = await importOriginal<typeof import('./status.js')>();
35
+ return {
36
+ ...actual,
37
+ probeWebGpu: vi.fn(async () => ({ available: true })),
38
+ probeOllama: vi.fn(async () => ({
39
+ reachable: true,
40
+ baseUrl: 'http://127.0.0.1:11434',
41
+ latencyMs: 12,
42
+ })),
43
+ };
44
+ });
45
+
46
+ vi.mock('./handleRequest.js', async (importOriginal) => {
47
+ const actual = await importOriginal<typeof import('./handleRequest.js')>();
48
+ return {
49
+ ...actual,
50
+ createShellAiRegistry: vi.fn(
51
+ (settings: Settings) =>
52
+ new AiRegistry({
53
+ adapters: [fakeAdapter],
54
+ defaultModelId: settings.ai?.defaultModelId ?? 'ollama:tiny',
55
+ }),
56
+ ),
57
+ };
58
+ });
59
+
60
+ const baseSettings = {
61
+ developerFeatures: { enabled: true },
62
+ errorReporting: { enabled: false },
63
+ logging: { namespaces: { shellsdk: false, shellcore: false } },
64
+ appearance: {
65
+ name: 'default',
66
+ displayName: 'Default',
67
+ mode: 'light',
68
+ colorScheme: 'system',
69
+ colors: { light: {}, dark: {} },
70
+ },
71
+ language: { code: 'en' },
72
+ region: { timezone: 'UTC' },
73
+ ai: {
74
+ enabled: true,
75
+ defaultModelId: 'ollama:tiny',
76
+ ollamaEnabled: true,
77
+ browserEnabled: true,
78
+ },
79
+ user: null,
80
+ accessToken: null,
81
+ } as Settings;
82
+
83
+ describe('developHarness', () => {
84
+ it('collects diagnostics from probes + registry', async () => {
85
+ const diagnostics = await collectDevelopAiDiagnostics(baseSettings);
86
+ expect(diagnostics.webGpuAvailable).toBe(true);
87
+ expect(diagnostics.ollamaReachable).toBe(true);
88
+ expect(diagnostics.ollamaLatencyMs).toBe(12);
89
+ expect(diagnostics.adapters).toEqual(['ollama']);
90
+ expect(diagnostics.defaultModelId).toBe('ollama:tiny');
91
+ expect(diagnostics.models.map((m) => m.id)).toContain('ollama:tiny');
92
+ });
93
+
94
+ it('runs a one-shot prompt through handleAiRequest', async () => {
95
+ const result = await runDevelopAiPrompt(baseSettings);
96
+ expect(result.modelId).toBe('ollama:tiny');
97
+ expect(result.text).toBe('pong');
98
+ });
99
+
100
+ it('streams chunks through handleAiRequest', async () => {
101
+ const chunks: string[] = [];
102
+ const result = await runDevelopAiStream(baseSettings, DEVELOP_AI_TEST_PROMPT, (chunk) => {
103
+ chunks.push(chunk);
104
+ });
105
+ expect(chunks.join('')).toBe('pong');
106
+ expect(result.text).toBe('pong');
107
+ });
108
+ });
@@ -0,0 +1,161 @@
1
+ import type { Settings } from '@shellui/sdk';
2
+ import { createShellAiRegistry, handleAiRequest } from './handleRequest.js';
3
+ import type { AiModel } from './types.js';
4
+ import { DEFAULT_OLLAMA_BASE_URL, probeOllama, probeWebGpu } from './status.js';
5
+
6
+ /** Tiny prompt used by Settings → Develop AI buttons. */
7
+ export const DEVELOP_AI_TEST_PROMPT = 'Reply with exactly: pong';
8
+
9
+ export type DevelopAiDiagnostics = {
10
+ webGpuAvailable: boolean;
11
+ webGpuDetail?: string;
12
+ ollamaReachable: boolean;
13
+ ollamaBaseUrl: string;
14
+ ollamaDetail?: string;
15
+ ollamaLatencyMs?: number;
16
+ defaultModelId: string | null;
17
+ adapters: string[];
18
+ models: AiModel[];
19
+ aiEnabled: boolean;
20
+ };
21
+
22
+ export type DevelopAiPromptResult = {
23
+ modelId: string;
24
+ text: string;
25
+ };
26
+
27
+ function nextRequestId(prefix: string): string {
28
+ return `${prefix}-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
29
+ }
30
+
31
+ function assertOk<T>(response: { data?: unknown; error?: { message: string } }): T {
32
+ if (response.error) {
33
+ throw new Error(response.error.message);
34
+ }
35
+ return response.data as T;
36
+ }
37
+
38
+ /** Diagnostics via the same registry factory and probes the shell uses. */
39
+ export async function collectDevelopAiDiagnostics(
40
+ settings: Settings,
41
+ ): Promise<DevelopAiDiagnostics> {
42
+ const registry = createShellAiRegistry(settings);
43
+ const [webGpu, ollama, models] = await Promise.all([
44
+ probeWebGpu(),
45
+ probeOllama({
46
+ baseUrl: settings.ai?.ollamaBaseUrl ?? DEFAULT_OLLAMA_BASE_URL,
47
+ }),
48
+ registry.listModels(),
49
+ ]);
50
+
51
+ const ollamaEnabled = settings.ai?.ollamaEnabled !== false;
52
+ const browserEnabled = settings.ai?.browserEnabled !== false;
53
+ const filtered = models.filter((model) => {
54
+ if (model.provider === 'ollama') return ollamaEnabled;
55
+ if (model.provider === 'webllm') return browserEnabled;
56
+ return true;
57
+ });
58
+
59
+ return {
60
+ webGpuAvailable: webGpu.available,
61
+ webGpuDetail: webGpu.detail,
62
+ ollamaReachable: ollama.reachable,
63
+ ollamaBaseUrl: ollama.baseUrl,
64
+ ollamaDetail: ollama.detail,
65
+ ollamaLatencyMs: ollama.latencyMs,
66
+ defaultModelId: settings.ai?.defaultModelId ?? registry.getDefaultModelId(),
67
+ adapters: registry.listAdapters().map((adapter) => adapter.id),
68
+ models: filtered,
69
+ aiEnabled: settings.ai?.enabled !== false,
70
+ };
71
+ }
72
+
73
+ /** One-shot prompt through `handleAiRequest` (same path as iframe apps). */
74
+ export async function runDevelopAiPrompt(
75
+ settings: Settings,
76
+ prompt: string = DEVELOP_AI_TEST_PROMPT,
77
+ ): Promise<DevelopAiPromptResult> {
78
+ const registry = createShellAiRegistry(settings);
79
+ const sessions = new Map();
80
+ const ctx = {
81
+ registry,
82
+ sessions,
83
+ activeSessionId: { current: null as string | null },
84
+ getSettings: () => settings,
85
+ };
86
+
87
+ const created = await handleAiRequest(ctx, {
88
+ id: nextRequestId('develop-create'),
89
+ op: 'create',
90
+ });
91
+ const session = assertOk<{ sessionId: string; model: string }>(created.response);
92
+
93
+ try {
94
+ const prompted = await handleAiRequest(ctx, {
95
+ id: nextRequestId('develop-prompt'),
96
+ op: 'prompt',
97
+ sessionId: session.sessionId,
98
+ prompt,
99
+ });
100
+ const data = assertOk<{ text: string }>(prompted.response);
101
+ return { modelId: session.model, text: data.text };
102
+ } finally {
103
+ await handleAiRequest(ctx, {
104
+ id: nextRequestId('develop-destroy'),
105
+ op: 'destroy',
106
+ sessionId: session.sessionId,
107
+ });
108
+ }
109
+ }
110
+
111
+ /** Streaming prompt through `handleAiRequest`, appending chunks via callback. */
112
+ export async function runDevelopAiStream(
113
+ settings: Settings,
114
+ prompt: string,
115
+ onChunk: (chunk: string) => void,
116
+ ): Promise<DevelopAiPromptResult> {
117
+ const registry = createShellAiRegistry(settings);
118
+ const sessions = new Map();
119
+ const ctx = {
120
+ registry,
121
+ sessions,
122
+ activeSessionId: { current: null as string | null },
123
+ getSettings: () => settings,
124
+ };
125
+
126
+ const created = await handleAiRequest(ctx, {
127
+ id: nextRequestId('develop-create'),
128
+ op: 'create',
129
+ });
130
+ const session = assertOk<{ sessionId: string; model: string }>(created.response);
131
+
132
+ try {
133
+ const streamed = await handleAiRequest(ctx, {
134
+ id: nextRequestId('develop-stream'),
135
+ op: 'promptStreaming',
136
+ sessionId: session.sessionId,
137
+ prompt,
138
+ });
139
+ assertOk<{ started: boolean }>(streamed.response);
140
+
141
+ let text = '';
142
+ if (streamed.stream) {
143
+ for await (const part of streamed.stream) {
144
+ if (part.error) {
145
+ throw new Error(part.error.message);
146
+ }
147
+ if (part.chunk) {
148
+ text += part.chunk;
149
+ onChunk(part.chunk);
150
+ }
151
+ }
152
+ }
153
+ return { modelId: session.model, text };
154
+ } finally {
155
+ await handleAiRequest(ctx, {
156
+ id: nextRequestId('develop-destroy'),
157
+ op: 'destroy',
158
+ sessionId: session.sessionId,
159
+ });
160
+ }
161
+ }
@@ -0,0 +1,85 @@
1
+ import { describe, expect, it, vi, afterEach } from 'vitest';
2
+ import { formatInstallFailureMessage, formatUnknownError, logAiError } from './formatAiError.js';
3
+
4
+ describe('formatUnknownError', () => {
5
+ it('prefers Error.message', () => {
6
+ expect(formatUnknownError(new Error('WebGPU device lost'))).toBe('WebGPU device lost');
7
+ expect(formatUnknownError(new TypeError('Failed to fetch'))).toBe('TypeError: Failed to fetch');
8
+ });
9
+
10
+ it('stringifies non-Error throws (WebLLM worker rejects with strings)', () => {
11
+ expect(formatUnknownError('boom')).toBe('boom');
12
+ expect(
13
+ formatUnknownError(
14
+ 'WebGPUNotAvailableError: WebGPU is not supported in your current environment',
15
+ ),
16
+ ).toContain('WebGPU is not supported');
17
+ expect(formatUnknownError({ message: 'from object' })).toBe('from object');
18
+ expect(formatUnknownError({ code: 42 })).toBe('{"code":42}');
19
+ expect(formatUnknownError(null)).toBe('null');
20
+ });
21
+
22
+ it('unwraps Error.cause when message is empty', () => {
23
+ const err = new Error('');
24
+ Object.defineProperty(err, 'cause', { value: new Error('root cause') });
25
+ expect(formatUnknownError(err)).toContain('root cause');
26
+ });
27
+ });
28
+
29
+ describe('formatInstallFailureMessage', () => {
30
+ it('appends last progress text', () => {
31
+ expect(
32
+ formatInstallFailureMessage(new Error('Device lost'), {
33
+ progressText: 'Loading model from cache…',
34
+ }),
35
+ ).toBe('Device lost (Failed during: Loading model from cache…)');
36
+ });
37
+
38
+ it('uses fallback when the throw has no useful message', () => {
39
+ expect(formatInstallFailureMessage({}, { fallback: 'Model download failed' })).toContain(
40
+ 'Model download failed',
41
+ );
42
+ });
43
+
44
+ it('explains pre-HF failure when no progress was seen', () => {
45
+ const msg = formatInstallFailureMessage(
46
+ {},
47
+ { beforeModelFetch: true, fallback: 'Model download failed' },
48
+ );
49
+ expect(msg).toMatch(/before model download|Hugging Face/i);
50
+ expect(msg).toMatch(/Worker/i);
51
+ });
52
+
53
+ it('annotates real errors that failed before HF fetch', () => {
54
+ expect(
55
+ formatInstallFailureMessage(new Error('Unable to find a compatible GPU'), {
56
+ beforeModelFetch: true,
57
+ }),
58
+ ).toMatch(/before Hugging Face fetch/i);
59
+ });
60
+ });
61
+
62
+ describe('logAiError', () => {
63
+ afterEach(() => {
64
+ vi.restoreAllMocks();
65
+ });
66
+
67
+ it('logs under [shellui.ai] with stack when available', () => {
68
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
69
+ const err = new Error('nope');
70
+ logAiError('install', err, { modelId: 'Llama', progressText: 'Downloading' });
71
+ expect(spy).toHaveBeenCalled();
72
+ expect(spy.mock.calls[0]?.[0]).toBe('[shellui.ai]');
73
+ expect(spy.mock.calls[0]?.[1]).toBe('install');
74
+ });
75
+
76
+ it('logs string rejections with rawType', () => {
77
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
78
+ logAiError('CreateWebWorkerMLCEngine.rejected', 'Error: boom', {
79
+ beforeModelFetch: true,
80
+ });
81
+ const payload = spy.mock.calls[0]?.[2] as { rawType?: string; beforeModelFetch?: boolean };
82
+ expect(payload.rawType).toBe('string');
83
+ expect(payload.beforeModelFetch).toBe(true);
84
+ });
85
+ });