@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,222 @@
1
+ import type {
2
+ AiAdapter,
3
+ AiModel,
4
+ AiModelStatus,
5
+ AiPromptOptions,
6
+ AiStreamChunk,
7
+ } from '../types.js';
8
+ import {
9
+ getPromptApi,
10
+ type NormalizedPromptApi,
11
+ type PromptApiSession,
12
+ type PromptMessage,
13
+ } from '../promptApiSupport.js';
14
+
15
+ /** Single logical model exposed by the built-in Prompt API. */
16
+ export const PROMPT_API_MODEL_ID = 'prompt-api:default';
17
+
18
+ export type PromptApiAdapterOptions = {
19
+ /** Injectable resolver (tests). Defaults to the live Chrome global. */
20
+ getApi?: () => NormalizedPromptApi | null;
21
+ };
22
+
23
+ /**
24
+ * Chrome built-in **Prompt API** (`LanguageModel` / Gemini Nano) adapter.
25
+ *
26
+ * Shown only when the API is present *and* usable: `listModels` returns `[]` when
27
+ * the global is missing (Firefox/Safari/iPhone/older Chrome) or `availability()`
28
+ * is `unavailable`, so Settings omits the provider entirely — no warning, no stub.
29
+ *
30
+ * Settings UX is **Enable** (not Install/Download): Chrome often reports no
31
+ * transferable download progress, so a stuck 0% bar is wrong. The adapter's
32
+ * `download()` method is the warm/`create({ monitor })` path; callers must treat
33
+ * missing/zero progress as indeterminate setup.
34
+ *
35
+ * Conversations are **stateless** here: like Ollama, each prompt spins a fresh
36
+ * `LanguageModel` session seeded with the full history and is destroyed after the
37
+ * turn, so there is no per-session lock to get wedged (unlike WebLLM).
38
+ */
39
+ export class PromptApiAdapter implements AiAdapter {
40
+ readonly id = 'prompt-api' as const;
41
+ private readonly getApi: () => NormalizedPromptApi | null;
42
+ private downloadProgress: number | null = null;
43
+
44
+ constructor(options: PromptApiAdapterOptions = {}) {
45
+ this.getApi = options.getApi ?? (() => getPromptApi());
46
+ }
47
+
48
+ async isAvailable(): Promise<boolean> {
49
+ const api = this.getApi();
50
+ if (!api) return false;
51
+ const availability = await api.availability().catch(() => 'unavailable' as const);
52
+ return availability !== 'unavailable';
53
+ }
54
+
55
+ async listModels(): Promise<AiModel[]> {
56
+ const api = this.getApi();
57
+ if (!api) return [];
58
+ let availability: Awaited<ReturnType<NormalizedPromptApi['availability']>>;
59
+ try {
60
+ availability = await api.availability();
61
+ } catch {
62
+ return [];
63
+ }
64
+ if (availability === 'unavailable') return [];
65
+ const status: AiModelStatus =
66
+ availability === 'available'
67
+ ? 'ready'
68
+ : availability === 'downloading'
69
+ ? 'downloading'
70
+ : 'downloadable';
71
+ return [
72
+ {
73
+ id: PROMPT_API_MODEL_ID,
74
+ name: 'Chrome built-in (Gemini Nano)',
75
+ provider: 'prompt-api',
76
+ status,
77
+ description: 'Built-in browser model (Chrome Prompt API)',
78
+ },
79
+ ];
80
+ }
81
+
82
+ async load(_modelId: string, _signal?: AbortSignal): Promise<void> {
83
+ // Sessions are created per prompt; nothing to warm.
84
+ }
85
+
86
+ getDownloadProgress(_modelId: string): number | null {
87
+ return this.downloadProgress;
88
+ }
89
+
90
+ async download(
91
+ _modelId: string,
92
+ options?: { signal?: AbortSignal; onProgress?: (progress: number) => void },
93
+ ): Promise<void> {
94
+ const api = this.getApi();
95
+ if (!api) {
96
+ throw new Error('The Chrome built-in Prompt API is not available in this browser.');
97
+ }
98
+ const availability = await api.availability();
99
+ if (availability === 'available') {
100
+ options?.onProgress?.(1);
101
+ return;
102
+ }
103
+ // Creating a session with a monitor warms the built-in model. Chrome may or
104
+ // may not fire transferable downloadprogress events — callers should treat
105
+ // missing/zero progress as indeterminate setup, not a stuck 0% download.
106
+ this.downloadProgress = null;
107
+ try {
108
+ const session = await api.create({
109
+ signal: options?.signal,
110
+ monitor: (monitor) => {
111
+ monitor.addEventListener('downloadprogress', (event) => {
112
+ const ratio = typeof event.loaded === 'number' ? event.loaded : 0;
113
+ // Ignore 0 — that is what produced a stuck “0%” Install bar in Settings.
114
+ if (ratio > 0) {
115
+ this.downloadProgress = ratio;
116
+ options?.onProgress?.(ratio);
117
+ }
118
+ });
119
+ },
120
+ });
121
+ session.destroy?.();
122
+ options?.onProgress?.(1);
123
+ } finally {
124
+ this.downloadProgress = null;
125
+ }
126
+ }
127
+
128
+ async prompt(options: AiPromptOptions): Promise<string> {
129
+ const { session, latest } = await this.openSession(options);
130
+ try {
131
+ return await session.prompt(latest, { signal: options.signal });
132
+ } finally {
133
+ session.destroy?.();
134
+ }
135
+ }
136
+
137
+ async *promptStreaming(options: AiPromptOptions): AsyncIterable<AiStreamChunk> {
138
+ const { session, latest } = await this.openSession(options);
139
+ try {
140
+ const stream = session.promptStreaming(latest, { signal: options.signal });
141
+ let acc = '';
142
+ for await (const piece of toAsyncIterable(stream)) {
143
+ if (options.signal?.aborted) {
144
+ throw new DOMException('Prompt aborted', 'AbortError');
145
+ }
146
+ const text = typeof piece === 'string' ? piece : String(piece ?? '');
147
+ // Chrome has shipped both cumulative and delta chunk semantics; normalize
148
+ // to deltas so callers always receive incremental text.
149
+ let delta = text;
150
+ if (text.startsWith(acc)) {
151
+ delta = text.slice(acc.length);
152
+ acc = text;
153
+ } else {
154
+ acc += text;
155
+ }
156
+ if (delta) {
157
+ yield { text: delta, done: false };
158
+ }
159
+ }
160
+ yield { text: '', done: true };
161
+ } finally {
162
+ session.destroy?.();
163
+ }
164
+ }
165
+
166
+ async unload(_modelId?: string): Promise<void> {
167
+ // No persistent engine; sessions are per-prompt.
168
+ }
169
+
170
+ async resetConversation(_modelId?: string, _sessionId?: string): Promise<void> {
171
+ // Stateless: a fresh session is created for each prompt, so there is nothing
172
+ // to clear between LanguageModel conversations.
173
+ }
174
+
175
+ private async openSession(
176
+ options: AiPromptOptions,
177
+ ): Promise<{ session: PromptApiSession; latest: string }> {
178
+ const api = this.getApi();
179
+ if (!api) {
180
+ throw new Error('The Chrome built-in Prompt API is not available in this browser.');
181
+ }
182
+ const messages = buildPromptMessages(options);
183
+ const latest = messages[messages.length - 1]?.content ?? options.prompt;
184
+ const initialPrompts = messages.slice(0, -1);
185
+ const session = await api.create({
186
+ signal: options.signal,
187
+ initialPrompts: initialPrompts.length > 0 ? initialPrompts : undefined,
188
+ });
189
+ return { session, latest };
190
+ }
191
+ }
192
+
193
+ function buildPromptMessages(options: AiPromptOptions): PromptMessage[] {
194
+ if (options.messages && options.messages.length > 0) {
195
+ return options.messages;
196
+ }
197
+ const messages: PromptMessage[] = [];
198
+ if (options.systemPrompt) {
199
+ messages.push({ role: 'system', content: options.systemPrompt });
200
+ }
201
+ messages.push({ role: 'user', content: options.prompt });
202
+ return messages;
203
+ }
204
+
205
+ async function* toAsyncIterable(
206
+ stream: ReadableStream<string> | AsyncIterable<string>,
207
+ ): AsyncIterable<string> {
208
+ if (stream && typeof (stream as AsyncIterable<string>)[Symbol.asyncIterator] === 'function') {
209
+ yield* stream as AsyncIterable<string>;
210
+ return;
211
+ }
212
+ const reader = (stream as ReadableStream<string>).getReader();
213
+ try {
214
+ while (true) {
215
+ const { value, done } = await reader.read();
216
+ if (done) break;
217
+ if (value !== undefined) yield value as string;
218
+ }
219
+ } finally {
220
+ reader.releaseLock?.();
221
+ }
222
+ }
@@ -0,0 +1,69 @@
1
+ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
2
+ import { clearBrowserInstalledForTests } from '../browserInstallStore.js';
3
+ import { WebLLMEngineService, setSharedWebLLMEngineForTests } from '../engine/webllmEngine.js';
4
+ import * as browserSupport from '../webLlmBrowserSupport.js';
5
+ import { WebLLMAdapter } from './webllm.js';
6
+
7
+ vi.mock('../status.js', () => ({
8
+ probeWebGpu: vi.fn(async () => ({ available: true })),
9
+ }));
10
+
11
+ /**
12
+ * Firefox is experimental, NOT hard-blocked.
13
+ * Catalog models stay installable; failures surface via mapped errors instead.
14
+ */
15
+ describe('WebLLMAdapter on experimental browsers', () => {
16
+ const memory = new Map<string, string>();
17
+ let engine: WebLLMEngineService;
18
+
19
+ beforeEach(() => {
20
+ memory.clear();
21
+ vi.stubGlobal('localStorage', {
22
+ getItem: (key: string) => memory.get(key) ?? null,
23
+ setItem: (key: string, value: string) => {
24
+ memory.set(key, value);
25
+ },
26
+ removeItem: (key: string) => {
27
+ memory.delete(key);
28
+ },
29
+ });
30
+ clearBrowserInstalledForTests();
31
+ engine = new WebLLMEngineService({
32
+ useTransferToast: false,
33
+ loadModule: async () => {
34
+ throw new Error('WebGPUNotAvailableError: WebGPU is not supported');
35
+ },
36
+ createWorker: () => {
37
+ throw new Error('should not create worker');
38
+ },
39
+ });
40
+ setSharedWebLLMEngineForTests(engine);
41
+ vi.spyOn(browserSupport, 'probeWebLlmBrowserSupport').mockReturnValue({
42
+ recommended: false,
43
+ canInstall: true,
44
+ reason: 'firefox',
45
+ detail: browserSupport.WEBLLM_EXPERIMENTAL_BROWSER_MESSAGE,
46
+ });
47
+ });
48
+
49
+ afterEach(async () => {
50
+ vi.restoreAllMocks();
51
+ await engine.resetForTests();
52
+ setSharedWebLLMEngineForTests(null);
53
+ vi.unstubAllGlobals();
54
+ });
55
+
56
+ it('keeps catalog models installable (never "unsupported")', async () => {
57
+ const adapter = new WebLLMAdapter({ engine });
58
+ const models = await adapter.listModels();
59
+ expect(models.every((m) => m.status !== 'unsupported')).toBe(true);
60
+ expect(models.some((m) => m.status === 'downloadable')).toBe(true);
61
+ });
62
+
63
+ it('attempts Install and surfaces the mapped WebGPU error (no pre-block)', async () => {
64
+ const adapter = new WebLLMAdapter({ engine });
65
+ await expect(adapter.download('webllm:Llama-3.2-1B-Instruct-q4f16_1-MLC')).rejects.toThrow(
66
+ /experimental|Ollama|WebGPU/i,
67
+ );
68
+ });
69
+ });