@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,288 @@
1
+ import { describe, expect, it } 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 { handleAiRequest, type AiHandlerContext, type AiSession } from './handleRequest.js';
6
+
7
+ class ReadyAdapter implements AiAdapter {
8
+ readonly id = 'ollama' as const;
9
+
10
+ async isAvailable(): Promise<boolean> {
11
+ return true;
12
+ }
13
+
14
+ async listModels(): Promise<AiModel[]> {
15
+ return [{ id: 'ollama:llama', name: 'llama', provider: 'ollama', status: 'ready' }];
16
+ }
17
+
18
+ async load(): Promise<void> {}
19
+
20
+ async prompt(options: AiPromptOptions): Promise<string> {
21
+ return `reply:${options.prompt}`;
22
+ }
23
+
24
+ async *promptStreaming(options: AiPromptOptions): AsyncIterable<AiStreamChunk> {
25
+ yield { text: `s:${options.prompt}`, done: true };
26
+ }
27
+
28
+ async unload(): Promise<void> {}
29
+ }
30
+
31
+ const baseSettings = {
32
+ developerFeatures: { enabled: false },
33
+ errorReporting: { enabled: false },
34
+ logging: { namespaces: { shellsdk: false, shellcore: false } },
35
+ appearance: {
36
+ name: 'default',
37
+ displayName: 'Default',
38
+ mode: 'light',
39
+ colorScheme: 'system',
40
+ colors: { light: {}, dark: {} },
41
+ },
42
+ language: { code: 'en' },
43
+ region: { timezone: 'UTC' },
44
+ ai: {
45
+ enabled: true,
46
+ defaultModelId: 'ollama:llama',
47
+ ollamaEnabled: true,
48
+ browserEnabled: true,
49
+ },
50
+ user: null,
51
+ accessToken: null,
52
+ } as Settings;
53
+
54
+ function makeCtx(
55
+ registry: AiRegistry,
56
+ sessions = new Map<string, AiSession>(),
57
+ settings: Settings = baseSettings,
58
+ ): AiHandlerContext {
59
+ return {
60
+ registry,
61
+ sessions,
62
+ activeSessionId: { current: null },
63
+ getSettings: () => settings,
64
+ };
65
+ }
66
+
67
+ describe('handleAiRequest', () => {
68
+ it('reports availability when a ready model exists', async () => {
69
+ const registry = new AiRegistry({ adapters: [new ReadyAdapter()] });
70
+ const result = await handleAiRequest(makeCtx(registry), { id: '1', op: 'availability' });
71
+ expect(result.response.data).toEqual({ availability: 'available' });
72
+ });
73
+
74
+ it('returns unavailable when AI is disabled', async () => {
75
+ const registry = new AiRegistry({ adapters: [new ReadyAdapter()] });
76
+ const result = await handleAiRequest(
77
+ makeCtx(registry, new Map(), {
78
+ ...baseSettings,
79
+ ai: { ...baseSettings.ai, enabled: false },
80
+ }),
81
+ { id: '2', op: 'availability' },
82
+ );
83
+ expect(result.response.data).toEqual({ availability: 'unavailable' });
84
+ });
85
+
86
+ it('creates a session and prompts', async () => {
87
+ const registry = new AiRegistry({ adapters: [new ReadyAdapter()] });
88
+ const sessions = new Map<string, AiSession>();
89
+ const ctx = makeCtx(registry, sessions);
90
+ const created = await handleAiRequest(ctx, { id: '3', op: 'create' });
91
+ const data = created.response.data as { sessionId: string; model: string };
92
+ expect(data.model).toBe('ollama:llama');
93
+ expect(sessions.has(data.sessionId)).toBe(true);
94
+ expect(ctx.activeSessionId.current).toBe(data.sessionId);
95
+
96
+ const prompted = await handleAiRequest(ctx, {
97
+ id: '4',
98
+ op: 'prompt',
99
+ sessionId: data.sessionId,
100
+ prompt: 'hi',
101
+ });
102
+ expect(prompted.response.data).toEqual({ text: 'reply:hi' });
103
+ });
104
+
105
+ it('streams chunks for promptStreaming', async () => {
106
+ const registry = new AiRegistry({ adapters: [new ReadyAdapter()] });
107
+ const ctx = makeCtx(registry);
108
+ const created = await handleAiRequest(ctx, { id: '5', op: 'create' });
109
+ const sessionId = (created.response.data as { sessionId: string }).sessionId;
110
+
111
+ const streamed = await handleAiRequest(ctx, {
112
+ id: '6',
113
+ op: 'promptStreaming',
114
+ sessionId,
115
+ prompt: 'x',
116
+ });
117
+ expect(streamed.stream).toBeDefined();
118
+ const stream = streamed.stream;
119
+ if (!stream) {
120
+ throw new Error('expected stream');
121
+ }
122
+ const chunks: string[] = [];
123
+ for await (const part of stream) {
124
+ if (part.chunk) chunks.push(part.chunk);
125
+ }
126
+ expect(chunks).toContain('s:x');
127
+ });
128
+
129
+ it('accumulates multi-turn history on a reused session', async () => {
130
+ const seen: AiPromptOptions[] = [];
131
+ class CaptureAdapter extends ReadyAdapter {
132
+ async prompt(options: AiPromptOptions): Promise<string> {
133
+ seen.push(options);
134
+ return `reply:${options.prompt}`;
135
+ }
136
+
137
+ async *promptStreaming(options: AiPromptOptions): AsyncIterable<AiStreamChunk> {
138
+ seen.push(options);
139
+ yield { text: `s:${options.prompt}`, done: true };
140
+ }
141
+ }
142
+
143
+ const registry = new AiRegistry({ adapters: [new CaptureAdapter()] });
144
+ const sessions = new Map<string, AiSession>();
145
+ const ctx = makeCtx(registry, sessions);
146
+ const created = await handleAiRequest(ctx, {
147
+ id: 'h1',
148
+ op: 'create',
149
+ initialPrompts: [{ role: 'system', content: 'sys' }],
150
+ });
151
+ const sessionId = (created.response.data as { sessionId: string }).sessionId;
152
+ const session = sessions.get(sessionId);
153
+ expect(session?.systemPrompt).toBe('sys');
154
+ expect(session?.messages).toEqual([]);
155
+
156
+ await handleAiRequest(ctx, { id: 'h2', op: 'prompt', sessionId, prompt: 'one' });
157
+ expect(session?.messages).toEqual([
158
+ { role: 'user', content: 'one' },
159
+ { role: 'assistant', content: 'reply:one' },
160
+ ]);
161
+ expect(seen[0]?.messages).toEqual([
162
+ { role: 'system', content: 'sys' },
163
+ { role: 'user', content: 'one' },
164
+ ]);
165
+
166
+ const streamed = await handleAiRequest(ctx, {
167
+ id: 'h3',
168
+ op: 'promptStreaming',
169
+ sessionId,
170
+ prompt: 'two',
171
+ });
172
+ for await (const _ of streamed.stream ?? []) {
173
+ // drain
174
+ }
175
+ expect(session?.messages).toEqual([
176
+ { role: 'user', content: 'one' },
177
+ { role: 'assistant', content: 'reply:one' },
178
+ { role: 'user', content: 'two' },
179
+ { role: 'assistant', content: 's:two' },
180
+ ]);
181
+ expect(seen[1]?.messages?.at(-1)).toEqual({ role: 'user', content: 'two' });
182
+ expect(
183
+ seen[1]?.messages?.some((m) => m.role === 'assistant' && m.content === 'reply:one'),
184
+ ).toBe(true);
185
+ });
186
+
187
+ it('destroy and create call resetConversation so a new session starts clean', async () => {
188
+ const resets: Array<string | undefined> = [];
189
+ class ResetTrackingAdapter extends ReadyAdapter {
190
+ async resetConversation(modelId?: string): Promise<void> {
191
+ resets.push(modelId);
192
+ }
193
+ }
194
+
195
+ const registry = new AiRegistry({ adapters: [new ResetTrackingAdapter()] });
196
+ const sessions = new Map<string, AiSession>();
197
+ const ctx = makeCtx(registry, sessions);
198
+
199
+ const createdA = await handleAiRequest(ctx, { id: 'd1', op: 'create' });
200
+ expect(resets).toEqual(['llama']);
201
+ const sessionA = (createdA.response.data as { sessionId: string }).sessionId;
202
+ expect(ctx.activeSessionId.current).toBe(sessionA);
203
+
204
+ await handleAiRequest(ctx, { id: 'd2', op: 'prompt', sessionId: sessionA, prompt: 'from A' });
205
+
206
+ await handleAiRequest(ctx, { id: 'd3', op: 'destroy', sessionId: sessionA });
207
+ expect(sessions.has(sessionA)).toBe(false);
208
+ expect(ctx.activeSessionId.current).toBeNull();
209
+ expect(resets).toEqual(['llama', 'llama']);
210
+
211
+ const createdB = await handleAiRequest(ctx, { id: 'd4', op: 'create' });
212
+ expect(resets).toEqual(['llama', 'llama', 'llama']);
213
+ const sessionB = (createdB.response.data as { sessionId: string }).sessionId;
214
+
215
+ const streamed = await handleAiRequest(ctx, {
216
+ id: 'd5',
217
+ op: 'promptStreaming',
218
+ sessionId: sessionB,
219
+ prompt: 'from B',
220
+ });
221
+ const chunks: string[] = [];
222
+ for await (const part of streamed.stream ?? []) {
223
+ if (part.chunk) chunks.push(part.chunk);
224
+ }
225
+ expect(chunks).toContain('s:from B');
226
+ });
227
+
228
+ it('late destroy of session A does not resetConversation after B is active', async () => {
229
+ const resets: string[] = [];
230
+ class ResetTrackingAdapter extends ReadyAdapter {
231
+ async resetConversation(modelId?: string): Promise<void> {
232
+ resets.push(modelId ?? '');
233
+ }
234
+
235
+ async *promptStreaming(): AsyncIterable<AiStreamChunk> {
236
+ yield { text: 'from-B', done: true };
237
+ }
238
+ }
239
+
240
+ const registry = new AiRegistry({ adapters: [new ResetTrackingAdapter()] });
241
+ const sessions = new Map<string, AiSession>();
242
+ const ctx = makeCtx(registry, sessions);
243
+
244
+ const createdA = await handleAiRequest(ctx, { id: 'r1', op: 'create' });
245
+ const sessionA = (createdA.response.data as { sessionId: string }).sessionId;
246
+ expect(resets).toEqual(['llama']);
247
+
248
+ // New chat B claims active before A's late destroy runs.
249
+ const createdB = await handleAiRequest(ctx, { id: 'r2', op: 'create' });
250
+ const sessionB = (createdB.response.data as { sessionId: string }).sessionId;
251
+ expect(ctx.activeSessionId.current).toBe(sessionB);
252
+ expect(resets).toEqual(['llama', 'llama']);
253
+
254
+ // Late destroy of A — map entry only; must not interrupt B.
255
+ await handleAiRequest(ctx, { id: 'r3', op: 'destroy', sessionId: sessionA });
256
+ expect(sessions.has(sessionA)).toBe(false);
257
+ expect(ctx.activeSessionId.current).toBe(sessionB);
258
+ expect(resets).toEqual(['llama', 'llama']);
259
+
260
+ const streamed = await handleAiRequest(ctx, {
261
+ id: 'r4',
262
+ op: 'promptStreaming',
263
+ sessionId: sessionB,
264
+ prompt: 'hello B',
265
+ });
266
+ const chunks: string[] = [];
267
+ for await (const part of streamed.stream ?? []) {
268
+ if (part.chunk) chunks.push(part.chunk);
269
+ }
270
+ expect(chunks).toContain('from-B');
271
+ });
272
+
273
+ it('destroy of the active session still resets conversation', async () => {
274
+ const resets: string[] = [];
275
+ class ResetTrackingAdapter extends ReadyAdapter {
276
+ async resetConversation(modelId?: string): Promise<void> {
277
+ resets.push(modelId ?? '');
278
+ }
279
+ }
280
+ const registry = new AiRegistry({ adapters: [new ResetTrackingAdapter()] });
281
+ const ctx = makeCtx(registry);
282
+ const created = await handleAiRequest(ctx, { id: 'a1', op: 'create' });
283
+ const sessionId = (created.response.data as { sessionId: string }).sessionId;
284
+ await handleAiRequest(ctx, { id: 'a2', op: 'destroy', sessionId });
285
+ expect(ctx.activeSessionId.current).toBeNull();
286
+ expect(resets).toEqual(['llama', 'llama']);
287
+ });
288
+ });
@@ -0,0 +1,325 @@
1
+ import type { AiRequestPayload, AiResponsePayload, AiStreamPayload, Settings } from '@shellui/sdk';
2
+ import { createDefaultAiRegistry } from './createRegistry.js';
3
+ import { DEFAULT_OLLAMA_BASE_URL, probeOllama, probeWebGpu } from './status.js';
4
+ import type { AiRegistry } from './registry.js';
5
+
6
+ function createSessionId(): string {
7
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
8
+ return crypto.randomUUID();
9
+ }
10
+ return `ai-${Date.now()}-${Math.random().toString(16).slice(2)}`;
11
+ }
12
+
13
+ export type AiSession = {
14
+ id: string;
15
+ modelId: string;
16
+ systemPrompt?: string;
17
+ /** Accumulated multi-turn history (user/assistant; system lives in systemPrompt). */
18
+ messages: Array<{ role: 'user' | 'assistant'; content: string }>;
19
+ abortController: AbortController;
20
+ };
21
+
22
+ export type AiHandlerContext = {
23
+ registry: AiRegistry;
24
+ sessions: Map<string, AiSession>;
25
+ getSettings: () => Settings;
26
+ /**
27
+ * Currently active LanguageModel session. Updated on create; cleared when that
28
+ * session is destroyed. Late destroy of a superseded session must not call
29
+ * resetConversation / interruptGenerate (would kill the new chat’s generation).
30
+ */
31
+ activeSessionId: { current: string | null };
32
+ };
33
+
34
+ function replyOk(id: string, data: unknown): AiResponsePayload {
35
+ return { id, data };
36
+ }
37
+
38
+ function replyErr(id: string, message: string, code?: string): AiResponsePayload {
39
+ return { id, error: { message, code } };
40
+ }
41
+
42
+ function isAiEnabled(settings: Settings): boolean {
43
+ return settings.ai?.enabled !== false;
44
+ }
45
+
46
+ function filterModelsBySettings<T extends { provider: string }>(
47
+ models: T[],
48
+ settings: Settings,
49
+ ): T[] {
50
+ const ollamaEnabled = settings.ai?.ollamaEnabled !== false;
51
+ const browserEnabled = settings.ai?.browserEnabled !== false;
52
+ const promptApiEnabled = settings.ai?.promptApiEnabled !== false;
53
+ return models.filter((model) => {
54
+ if (model.provider === 'ollama') return ollamaEnabled;
55
+ if (model.provider === 'webllm') return browserEnabled;
56
+ if (model.provider === 'prompt-api') return promptApiEnabled;
57
+ return true;
58
+ });
59
+ }
60
+
61
+ export function createShellAiRegistry(settings: Settings): AiRegistry {
62
+ return createDefaultAiRegistry({
63
+ ollama: {
64
+ baseUrl: settings.ai?.ollamaBaseUrl ?? DEFAULT_OLLAMA_BASE_URL,
65
+ },
66
+ includeWebLLM: settings.ai?.browserEnabled !== false,
67
+ defaultModelId: settings.ai?.defaultModelId ?? null,
68
+ });
69
+ }
70
+
71
+ export type AiHandleResult = {
72
+ response: AiResponsePayload;
73
+ /** Streaming chunks to emit before/after response (promptStreaming). */
74
+ stream?: AsyncIterable<AiStreamPayload>;
75
+ };
76
+
77
+ /**
78
+ * Pure request handler used by AiBridge (and unit tests).
79
+ */
80
+ export async function handleAiRequest(
81
+ ctx: AiHandlerContext,
82
+ payload: AiRequestPayload,
83
+ ): Promise<AiHandleResult> {
84
+ const settings = ctx.getSettings();
85
+ const { id, op } = payload;
86
+
87
+ if (!id || !op) {
88
+ return { response: replyErr(id || 'unknown', 'Invalid AI request', 'invalid_request') };
89
+ }
90
+
91
+ try {
92
+ switch (op) {
93
+ case 'status': {
94
+ const [webGpu, ollama, models] = await Promise.all([
95
+ probeWebGpu(),
96
+ probeOllama({
97
+ baseUrl: settings.ai?.ollamaBaseUrl ?? DEFAULT_OLLAMA_BASE_URL,
98
+ }),
99
+ ctx.registry.listModels(),
100
+ ]);
101
+ return {
102
+ response: replyOk(id, {
103
+ webGpu,
104
+ ollama,
105
+ models: filterModelsBySettings(models, settings),
106
+ defaultModelId: settings.ai?.defaultModelId ?? null,
107
+ enabled: isAiEnabled(settings),
108
+ }),
109
+ };
110
+ }
111
+
112
+ case 'listModels': {
113
+ const models = filterModelsBySettings(await ctx.registry.listModels(), settings);
114
+ return { response: replyOk(id, models) };
115
+ }
116
+
117
+ case 'availability': {
118
+ if (!isAiEnabled(settings)) {
119
+ return { response: replyOk(id, { availability: 'unavailable' }) };
120
+ }
121
+ const models = filterModelsBySettings(await ctx.registry.listModels(), settings);
122
+ const ready = models.some((m) => m.status === 'ready');
123
+ const downloadable = models.some(
124
+ (m) => m.status === 'downloadable' || m.status === 'needs-webgpu',
125
+ );
126
+ const availability = ready ? 'available' : downloadable ? 'downloadable' : 'unavailable';
127
+ return { response: replyOk(id, { availability }) };
128
+ }
129
+
130
+ case 'create': {
131
+ if (!isAiEnabled(settings)) {
132
+ return {
133
+ response: replyErr(id, 'AI is disabled in Settings → AI', 'ai_disabled'),
134
+ };
135
+ }
136
+ ctx.registry.setDefaultModelId(settings.ai?.defaultModelId ?? null);
137
+ const models = filterModelsBySettings(await ctx.registry.listModels(), settings).filter(
138
+ (m) => m.status === 'ready',
139
+ );
140
+ const preferred = payload.model ?? settings.ai?.defaultModelId ?? null;
141
+ const pick =
142
+ (preferred && models.find((m) => m.id === preferred)) ||
143
+ (settings.ai?.defaultModelId &&
144
+ models.find((m) => m.id === settings.ai?.defaultModelId)) ||
145
+ models[0];
146
+ if (!pick) {
147
+ return {
148
+ response: replyErr(
149
+ id,
150
+ 'No ready model. Install Ollama or download a browser model in Settings → AI.',
151
+ 'no_model',
152
+ ),
153
+ };
154
+ }
155
+ // Claim active before reset so a late destroy of the previous session
156
+ // cannot interrupt this conversation's upcoming generation.
157
+ const sessionId = createSessionId();
158
+ ctx.activeSessionId.current = sessionId;
159
+ try {
160
+ // Pass the new sessionId so the engine disposes the prior conversation's
161
+ // worker when switching away and claims this one (recreate on next prompt).
162
+ await ctx.registry.resetConversation(pick.id, sessionId);
163
+ } catch (error) {
164
+ // eslint-disable-next-line no-console -- create should still proceed; next prompt may hang otherwise
165
+ console.error('[shellui.ai]', 'resetConversation on create failed', error);
166
+ }
167
+ const systemPrompt = payload.initialPrompts
168
+ ?.filter((p) => p.role === 'system')
169
+ .map((p) => p.content)
170
+ .join('\n');
171
+ const seedMessages =
172
+ payload.initialPrompts
173
+ ?.filter((p) => p.role === 'user' || p.role === 'assistant')
174
+ .map((p) => ({
175
+ role: p.role as 'user' | 'assistant',
176
+ content: p.content,
177
+ })) ?? [];
178
+ const session: AiSession = {
179
+ id: sessionId,
180
+ modelId: pick.id,
181
+ systemPrompt: systemPrompt || undefined,
182
+ messages: seedMessages,
183
+ abortController: new AbortController(),
184
+ };
185
+ ctx.sessions.set(session.id, session);
186
+ return {
187
+ response: replyOk(id, { sessionId: session.id, model: session.modelId }),
188
+ };
189
+ }
190
+
191
+ case 'prompt': {
192
+ const session = payload.sessionId ? ctx.sessions.get(payload.sessionId) : undefined;
193
+ if (!session) {
194
+ return { response: replyErr(id, 'Unknown AI session', 'invalid_session') };
195
+ }
196
+ if (!payload.prompt) {
197
+ return { response: replyErr(id, 'Missing prompt', 'invalid_request') };
198
+ }
199
+ session.messages.push({ role: 'user', content: payload.prompt });
200
+ const messages = buildSessionMessages(session);
201
+ try {
202
+ const text = await ctx.registry.prompt({
203
+ modelId: session.modelId,
204
+ prompt: payload.prompt,
205
+ systemPrompt: session.systemPrompt,
206
+ messages,
207
+ sessionId: session.id,
208
+ signal: session.abortController.signal,
209
+ });
210
+ session.messages.push({ role: 'assistant', content: text });
211
+ return { response: replyOk(id, { text }) };
212
+ } catch (error) {
213
+ // Drop the user turn if generation failed so a retry can re-send cleanly.
214
+ session.messages.pop();
215
+ throw error;
216
+ }
217
+ }
218
+
219
+ case 'promptStreaming': {
220
+ const session = payload.sessionId ? ctx.sessions.get(payload.sessionId) : undefined;
221
+ if (!session) {
222
+ return { response: replyErr(id, 'Unknown AI session', 'invalid_session') };
223
+ }
224
+ if (!payload.prompt) {
225
+ return { response: replyErr(id, 'Missing prompt', 'invalid_request') };
226
+ }
227
+
228
+ session.messages.push({ role: 'user', content: payload.prompt });
229
+ const messages = buildSessionMessages(session);
230
+
231
+ const iterable = ctx.registry.promptStreaming({
232
+ modelId: session.modelId,
233
+ prompt: payload.prompt,
234
+ systemPrompt: session.systemPrompt,
235
+ messages,
236
+ sessionId: session.id,
237
+ signal: session.abortController.signal,
238
+ });
239
+
240
+ async function* mapStream(): AsyncIterable<AiStreamPayload> {
241
+ let assistant = '';
242
+ try {
243
+ for await (const chunk of iterable) {
244
+ if (chunk.text) assistant += chunk.text;
245
+ yield {
246
+ id,
247
+ chunk: chunk.text,
248
+ done: chunk.done,
249
+ };
250
+ }
251
+ yield { id, chunk: '', done: true };
252
+ session.messages.push({ role: 'assistant', content: assistant });
253
+ } catch (error) {
254
+ // Drop the pending user turn on failure.
255
+ if (session.messages.at(-1)?.role === 'user') {
256
+ session.messages.pop();
257
+ }
258
+ yield {
259
+ id,
260
+ done: true,
261
+ error: {
262
+ message: error instanceof Error ? error.message : 'Stream failed',
263
+ },
264
+ };
265
+ }
266
+ }
267
+
268
+ return {
269
+ response: replyOk(id, { started: true }),
270
+ stream: mapStream(),
271
+ };
272
+ }
273
+
274
+ case 'abort': {
275
+ const session = payload.sessionId ? ctx.sessions.get(payload.sessionId) : undefined;
276
+ session?.abortController.abort();
277
+ return { response: replyOk(id, { aborted: true }) };
278
+ }
279
+
280
+ case 'destroy': {
281
+ const session = payload.sessionId ? ctx.sessions.get(payload.sessionId) : undefined;
282
+ if (session) {
283
+ const wasActive = ctx.activeSessionId.current === session.id;
284
+ session.abortController.abort();
285
+ ctx.sessions.delete(session.id);
286
+ if (wasActive) {
287
+ ctx.activeSessionId.current = null;
288
+ // Only the active session may reset/interrupt — a late destroy of a
289
+ // superseded chat must not kill the new conversation's generation.
290
+ try {
291
+ await ctx.registry.resetConversation(session.modelId);
292
+ } catch (error) {
293
+ // eslint-disable-next-line no-console -- destroy still acks; log for operators
294
+ console.error('[shellui.ai]', 'resetConversation on destroy failed', error);
295
+ }
296
+ }
297
+ } else if (payload.sessionId && ctx.activeSessionId.current === payload.sessionId) {
298
+ // Session already gone from map but still marked active.
299
+ ctx.activeSessionId.current = null;
300
+ }
301
+ return { response: replyOk(id, { destroyed: true }) };
302
+ }
303
+
304
+ default:
305
+ return { response: replyErr(id, `Unknown AI op: ${op}`, 'unknown_op') };
306
+ }
307
+ } catch (error) {
308
+ return {
309
+ response: replyErr(id, error instanceof Error ? error.message : 'AI request failed'),
310
+ };
311
+ }
312
+ }
313
+
314
+ function buildSessionMessages(
315
+ session: AiSession,
316
+ ): Array<{ role: 'system' | 'user' | 'assistant'; content: string }> {
317
+ const messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }> = [];
318
+ if (session.systemPrompt) {
319
+ messages.push({ role: 'system', content: session.systemPrompt });
320
+ }
321
+ for (const turn of session.messages) {
322
+ messages.push(turn);
323
+ }
324
+ return messages;
325
+ }
@@ -0,0 +1,15 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { isAiFeatureEnabled } from './isAiFeatureEnabled.js';
3
+
4
+ describe('isAiFeatureEnabled', () => {
5
+ it('defaults to false when config.ai or ai.enabled is omitted', () => {
6
+ expect(isAiFeatureEnabled(undefined)).toBe(false);
7
+ expect(isAiFeatureEnabled({})).toBe(false);
8
+ expect(isAiFeatureEnabled({ ai: {} })).toBe(false);
9
+ });
10
+
11
+ it('is true only when config.ai.enabled is explicitly true', () => {
12
+ expect(isAiFeatureEnabled({ ai: { enabled: true } })).toBe(true);
13
+ expect(isAiFeatureEnabled({ ai: { enabled: false } })).toBe(false);
14
+ });
15
+ });
@@ -0,0 +1,9 @@
1
+ import type { ShellUIConfig } from '../config/types.js';
2
+
3
+ /**
4
+ * Deploy-time AI product gate from `shellui.config` (`ai.enabled`).
5
+ * Opt-in: only `true` enables AI; omitted means off. Distinct from Settings → AI `settings.ai.enabled`.
6
+ */
7
+ export function isAiFeatureEnabled(config: ShellUIConfig | undefined | null): boolean {
8
+ return config?.ai?.enabled === true;
9
+ }