@shellui/core 0.5.4-alpha.1 → 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 (112) 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 +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/sidebar/SidebarLayout.tsx +9 -4
  75. package/src/features/layouts/utils.ts +6 -2
  76. package/src/features/layouts/windows/WindowsLayout.tsx +8 -3
  77. package/src/features/messaging/MessagingSecurityBootstrap.tsx +6 -6
  78. package/src/features/security/trustedFrames.spec.ts +65 -0
  79. package/src/features/security/trustedFrames.ts +52 -0
  80. package/src/features/settings/SettingsIcons.tsx +17 -0
  81. package/src/features/settings/SettingsProvider.tsx +28 -3
  82. package/src/features/settings/SettingsRoutes.tsx +8 -0
  83. package/src/features/settings/SettingsView.tsx +21 -4
  84. package/src/features/settings/components/Ai.tsx +830 -0
  85. package/src/features/settings/components/Develop.tsx +4 -0
  86. package/src/features/settings/components/Storage.tsx +197 -32
  87. package/src/features/settings/components/UserSettingsPanel.tsx +160 -12
  88. package/src/features/settings/components/createUserSettingsRoute.tsx +4 -0
  89. package/src/features/settings/components/develop/AiTestTools.tsx +231 -0
  90. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +54 -1
  91. package/src/features/settings/utils/buildSettingsForPropagation.ts +15 -1
  92. package/src/features/settings/utils/mergePreferencesIntoSettings.spec.ts +6 -0
  93. package/src/features/settings/utils/shouldShowStorageSettings.spec.ts +49 -0
  94. package/src/features/settings/utils/shouldShowStorageSettings.ts +19 -0
  95. package/src/features/storage/uploads/UploadToastCard.tsx +2 -442
  96. package/src/features/storage/uploads/UploadToaster.tsx +2 -44
  97. package/src/features/storage/uploads/uploadQueue.ts +128 -308
  98. package/src/features/storage/uploads/useUploadQueue.ts +7 -3
  99. package/src/features/transfers/TransferToastCard.tsx +467 -0
  100. package/src/features/transfers/TransferToaster.tsx +50 -0
  101. package/src/features/transfers/index.ts +33 -0
  102. package/src/features/transfers/transferQueue.spec.ts +97 -0
  103. package/src/features/transfers/transferQueue.ts +442 -0
  104. package/src/features/transfers/types.ts +38 -0
  105. package/src/features/transfers/useTransferQueue.ts +30 -0
  106. package/src/i18n/translations/en/common.json +46 -2
  107. package/src/i18n/translations/en/settings.json +151 -2
  108. package/src/i18n/translations/fr/common.json +46 -2
  109. package/src/i18n/translations/fr/settings.json +151 -2
  110. package/src/index.css +57 -4
  111. package/src/index.ts +1 -0
  112. package/src/routes/components/NavigationItemRoute.tsx +2 -1
@@ -0,0 +1,106 @@
1
+ import { useEffect, useMemo, useRef } from 'react';
2
+ import {
3
+ postShellMessage,
4
+ shellui,
5
+ type AiRequestPayload,
6
+ type AiResponsePayload,
7
+ type AiStreamPayload,
8
+ type ShellUIMessage,
9
+ } from '@shellui/sdk';
10
+ import { useConfig } from '../config/useConfig';
11
+ import { getAiRequestTrustDenial } from '../security/trustedFrames';
12
+ import { useSettings } from '../settings/hooks/useSettings';
13
+ import { createShellAiRegistry, handleAiRequest, type AiSession } from './handleRequest';
14
+
15
+ function replyToSender(
16
+ message: ShellUIMessage,
17
+ payload: AiResponsePayload | AiStreamPayload,
18
+ type: 'SHELLUI_AI_RESPONSE' | 'SHELLUI_AI_STREAM',
19
+ ): void {
20
+ const reply = { type, payload };
21
+ const from = message.from?.filter(Boolean) as string[] | undefined;
22
+ if (from?.length) {
23
+ shellui.sendMessage({ ...reply, to: from });
24
+ return;
25
+ }
26
+ postShellMessage(reply);
27
+ }
28
+
29
+ /**
30
+ * Root-window bridge: iframe `SHELLUI_AI_*` messages are handled here.
31
+ * Adapters/registry live in this core feature module; the SDK only postMessages.
32
+ * Requests use the same privileged + trusted-frame policy as storage.
33
+ */
34
+ export const AiBridge = () => {
35
+ const { config } = useConfig();
36
+ const { settings } = useSettings();
37
+ const sessionsRef = useRef(new Map<string, AiSession>());
38
+ const activeSessionIdRef = useRef<string | null>(null);
39
+ const settingsRef = useRef(settings);
40
+ settingsRef.current = settings;
41
+
42
+ const registry = useMemo(
43
+ () => createShellAiRegistry(settings),
44
+ // Rebuild when provider toggles / base URL / default change.
45
+ // Listing models / opening Settings must not import @mlc-ai/web-llm —
46
+ // that happens only inside WebLLMEngineService install/load/delete.
47
+ [
48
+ settings.ai?.ollamaBaseUrl,
49
+ settings.ai?.ollamaEnabled,
50
+ settings.ai?.browserEnabled,
51
+ settings.ai?.defaultModelId,
52
+ ],
53
+ );
54
+
55
+ useEffect(() => {
56
+ registry.setDefaultModelId(settings.ai?.defaultModelId ?? null);
57
+ }, [registry, settings.ai?.defaultModelId]);
58
+
59
+ useEffect(() => {
60
+ if (typeof window === 'undefined' || window.parent !== window) {
61
+ return;
62
+ }
63
+
64
+ const listener = (message: ShellUIMessage) => {
65
+ const payload = message.payload as AiRequestPayload | undefined;
66
+ if (!payload?.id || !payload.op) return;
67
+
68
+ const trustDenial = getAiRequestTrustDenial(message.from, shellui.frameRegistry, config);
69
+ if (trustDenial) {
70
+ replyToSender(
71
+ message,
72
+ {
73
+ id: payload.id,
74
+ error: { message: trustDenial.message, code: trustDenial.code },
75
+ },
76
+ 'SHELLUI_AI_RESPONSE',
77
+ );
78
+ return;
79
+ }
80
+
81
+ void handleAiRequest(
82
+ {
83
+ registry,
84
+ sessions: sessionsRef.current,
85
+ activeSessionId: activeSessionIdRef,
86
+ getSettings: () => settingsRef.current,
87
+ },
88
+ payload,
89
+ ).then(async (result) => {
90
+ if (result.stream) {
91
+ // Ack start, then stream chunks to the requesting iframe only.
92
+ replyToSender(message, result.response, 'SHELLUI_AI_RESPONSE');
93
+ for await (const chunk of result.stream) {
94
+ replyToSender(message, chunk, 'SHELLUI_AI_STREAM');
95
+ }
96
+ return;
97
+ }
98
+ replyToSender(message, result.response, 'SHELLUI_AI_RESPONSE');
99
+ });
100
+ };
101
+
102
+ return shellui.addMessageListener('SHELLUI_AI_REQUEST', listener);
103
+ }, [registry, config]);
104
+
105
+ return null;
106
+ };
@@ -0,0 +1,39 @@
1
+ import { useEffect } from 'react';
2
+ import {
3
+ postShellMessage,
4
+ shellui,
5
+ type AiRequestPayload,
6
+ type ShellUIMessage,
7
+ } from '@shellui/sdk';
8
+ import { buildAiDisabledResponse } from './aiDisabledResponses';
9
+
10
+ function reply(message: ShellUIMessage, payload: ReturnType<typeof buildAiDisabledResponse>): void {
11
+ const replyMessage = { type: 'SHELLUI_AI_RESPONSE' as const, payload };
12
+ const from = message.from?.filter(Boolean) as string[] | undefined;
13
+ if (from?.length) {
14
+ shellui.sendMessage({ ...replyMessage, to: from });
15
+ return;
16
+ }
17
+ postShellMessage(replyMessage);
18
+ }
19
+
20
+ /**
21
+ * Lightweight stand-in when `config.ai.enabled` is not `true`.
22
+ * Answers SDK AI requests immediately so apps do not hang waiting for AiBridge,
23
+ * without importing adapters, registry, or `@mlc-ai/web-llm`.
24
+ */
25
+ export function AiUnavailableResponder() {
26
+ useEffect(() => {
27
+ if (typeof window === 'undefined' || window.parent !== window) {
28
+ return;
29
+ }
30
+
31
+ return shellui.addMessageListener('SHELLUI_AI_REQUEST', (message: ShellUIMessage) => {
32
+ const payload = message.payload as AiRequestPayload | undefined;
33
+ if (!payload?.id || !payload.op) return;
34
+ reply(message, buildAiDisabledResponse(payload));
35
+ });
36
+ }, []);
37
+
38
+ return null;
39
+ }
@@ -0,0 +1,52 @@
1
+ # On-device AI (core module)
2
+
3
+ Local AI is an **opt-in `@shellui/core` preview**. Embedded apps call `@shellui/sdk` (`shellui.ai`); this module owns adapters, registry, and the shell bridge. Requests use the same privileged companion + trusted-frame policy as storage.
4
+
5
+ ## Config opt-in
6
+
7
+ `shellui.config.json`:
8
+
9
+ ```json
10
+ { "ai": { "enabled": true } }
11
+ ```
12
+
13
+ Default is **disabled** (`ai` or `enabled` omitted, or `false`). Unless `enabled` is `true`, `ShellAiHost` mounts `AiUnavailableResponder` instead of lazily loading `AiBridge`, Settings → AI is hidden, and WebLLM is never imported.
14
+
15
+ ## Layout
16
+
17
+ ```
18
+ features/ai/
19
+ ShellAiHost.tsx Config gate + lazy AiBridge
20
+ AiUnavailableResponder Tiny SDK replies when config AI is off
21
+ adapters/ OllamaAdapter, WebLLMAdapter
22
+ engine/ WebLLMEngineService + webllm.worker.ts (CreateWebWorkerMLCEngine)
23
+ browserInstallStore.ts Persist browser catalog installs (reload / same-origin reuse)
24
+ catalog.ts Curated browser model list (WebLLM model_id strings)
25
+ createRegistry.ts Default registry factory (Ollama + shared WebLLM)
26
+ registry.ts Adapter multiplex
27
+ status.ts WebGPU + Ollama soft probes
28
+ types.ts Adapter / model types
29
+ handleRequest.ts SHELLUI_AI_* request handler
30
+ developHarness.ts Settings → Develop diagnostics / prompt harness
31
+ AiBridge.tsx Root-window message bridge (lazy from ShellAiHost)
32
+ *.spec.ts Unit tests (mocked engine; no live HF / WebGPU in CI)
33
+ ```
34
+
35
+ Shared progress UI: `features/transfers/` (`TransferToaster` / `transferQueue`) — used by storage uploads and AI model downloads. Transfer toaster stays mounted regardless of `ai.enabled`.
36
+
37
+ Settings UI: `features/settings/components/Ai.tsx` (Preferences → AI).
38
+ Developer harness: `features/settings/components/develop/AiTestTools.tsx` (Develop → Testing).
39
+
40
+ ## Browser runtime notes
41
+
42
+ - Dependency: `@mlc-ai/web-llm` (dynamically imported when browser AI is used).
43
+ - Worker: `engine/webllm.worker.ts` + `CreateWebWorkerMLCEngine` so the UI thread stays responsive.
44
+ - Progress: WebLLM `initProgressCallback` → transfer toaster + Settings panel (no fake timers).
45
+ - Warm model: Install leaves the engine ready for `prompt` / `promptStreaming`. v1 keeps **one** browser model warm at a time.
46
+
47
+ ## Disable (not uninstall)
48
+
49
+ - **Config:** omit `ai` or set `"ai": { "enabled": false }` — removes AI product surface and never loads WebLLM.
50
+ - **Settings → AI:** turn off "Allow apps to use AI" or toggle Ollama / browser providers (config AI must still be on).
51
+
52
+ There is no separate `@shellui/ai` package to remove.
@@ -0,0 +1,24 @@
1
+ import { lazy, Suspense } from 'react';
2
+ import { useConfig } from '../config/useConfig';
3
+ import { AiUnavailableResponder } from './AiUnavailableResponder';
4
+ import { isAiFeatureEnabled } from './isAiFeatureEnabled';
5
+
6
+ /**
7
+ * Lazy-load the full AiBridge (adapters / WebLLM engine graph) only when
8
+ * `config.ai.enabled` is true. Other shells get a tiny unavailable responder.
9
+ */
10
+ const AiBridgeLazy = lazy(() => import('./AiBridge').then((mod) => ({ default: mod.AiBridge })));
11
+
12
+ export function ShellAiHost() {
13
+ const { config } = useConfig();
14
+
15
+ if (!isAiFeatureEnabled(config)) {
16
+ return <AiUnavailableResponder />;
17
+ }
18
+
19
+ return (
20
+ <Suspense fallback={null}>
21
+ <AiBridgeLazy />
22
+ </Suspense>
23
+ );
24
+ }
@@ -0,0 +1,170 @@
1
+ import { DEFAULT_OLLAMA_BASE_URL, probeOllama } from '../status.js';
2
+ import type { AiAdapter, AiModel, AiPromptOptions, AiStreamChunk } from '../types.js';
3
+
4
+ export type OllamaAdapterOptions = {
5
+ baseUrl?: string;
6
+ fetchImpl?: typeof fetch;
7
+ timeoutMs?: number;
8
+ };
9
+
10
+ type OllamaTag = {
11
+ name: string;
12
+ size?: number;
13
+ };
14
+
15
+ type OllamaTagsResponse = {
16
+ models?: OllamaTag[];
17
+ };
18
+
19
+ type OllamaGenerateResponse = {
20
+ response?: string;
21
+ done?: boolean;
22
+ };
23
+
24
+ /**
25
+ * Local Ollama HTTP adapter. Soft-fails when the daemon is down or CORS blocks us.
26
+ */
27
+ export class OllamaAdapter implements AiAdapter {
28
+ readonly id = 'ollama' as const;
29
+ private readonly baseUrl: string;
30
+ private readonly fetchImpl: typeof fetch;
31
+ private readonly timeoutMs: number;
32
+
33
+ constructor(options: OllamaAdapterOptions = {}) {
34
+ this.baseUrl = (options.baseUrl ?? DEFAULT_OLLAMA_BASE_URL).replace(/\/+$/, '');
35
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
36
+ this.timeoutMs = options.timeoutMs ?? 2_000;
37
+ }
38
+
39
+ getBaseUrl(): string {
40
+ return this.baseUrl;
41
+ }
42
+
43
+ async isAvailable(): Promise<boolean> {
44
+ const status = await probeOllama({
45
+ baseUrl: this.baseUrl,
46
+ fetchImpl: this.fetchImpl,
47
+ timeoutMs: this.timeoutMs,
48
+ });
49
+ return status.reachable;
50
+ }
51
+
52
+ async listModels(): Promise<AiModel[]> {
53
+ if (!(await this.isAvailable())) {
54
+ return [];
55
+ }
56
+
57
+ try {
58
+ const response = await this.fetchImpl(`${this.baseUrl}/api/tags`, { method: 'GET' });
59
+ if (!response.ok) return [];
60
+ const body = (await response.json()) as OllamaTagsResponse;
61
+ return (body.models ?? []).map((tag) => ({
62
+ id: `ollama:${tag.name}`,
63
+ name: tag.name,
64
+ provider: 'ollama' as const,
65
+ sizeBytes: tag.size,
66
+ status: 'ready' as const,
67
+ description: 'Local Ollama model',
68
+ }));
69
+ } catch {
70
+ return [];
71
+ }
72
+ }
73
+
74
+ async load(_modelId: string, _signal?: AbortSignal): Promise<void> {
75
+ // Ollama loads on first generate; nothing to warm here in v1.
76
+ }
77
+
78
+ async prompt(options: AiPromptOptions): Promise<string> {
79
+ const body = {
80
+ model: options.modelId,
81
+ prompt: options.prompt,
82
+ system: options.systemPrompt,
83
+ stream: false,
84
+ };
85
+
86
+ const response = await this.fetchImpl(`${this.baseUrl}/api/generate`, {
87
+ method: 'POST',
88
+ headers: { 'Content-Type': 'application/json' },
89
+ body: JSON.stringify(body),
90
+ signal: options.signal,
91
+ });
92
+
93
+ if (!response.ok) {
94
+ throw new Error(`Ollama generate failed with HTTP ${response.status}`);
95
+ }
96
+
97
+ const json = (await response.json()) as OllamaGenerateResponse;
98
+ return json.response ?? '';
99
+ }
100
+
101
+ async *promptStreaming(options: AiPromptOptions): AsyncIterable<AiStreamChunk> {
102
+ const body = {
103
+ model: options.modelId,
104
+ prompt: options.prompt,
105
+ system: options.systemPrompt,
106
+ stream: true,
107
+ };
108
+
109
+ const response = await this.fetchImpl(`${this.baseUrl}/api/generate`, {
110
+ method: 'POST',
111
+ headers: { 'Content-Type': 'application/json' },
112
+ body: JSON.stringify(body),
113
+ signal: options.signal,
114
+ });
115
+
116
+ if (!response.ok) {
117
+ throw new Error(`Ollama stream failed with HTTP ${response.status}`);
118
+ }
119
+
120
+ if (!response.body) {
121
+ const text = await this.prompt(options);
122
+ yield { text, done: true };
123
+ return;
124
+ }
125
+
126
+ const reader = response.body.getReader();
127
+ const decoder = new TextDecoder();
128
+ let buffer = '';
129
+
130
+ while (true) {
131
+ const { value, done } = await reader.read();
132
+ if (done) break;
133
+ buffer += decoder.decode(value, { stream: true });
134
+ const lines = buffer.split('\n');
135
+ buffer = lines.pop() ?? '';
136
+
137
+ for (const line of lines) {
138
+ const trimmed = line.trim();
139
+ if (!trimmed) continue;
140
+ let parsed: OllamaGenerateResponse;
141
+ try {
142
+ parsed = JSON.parse(trimmed) as OllamaGenerateResponse;
143
+ } catch {
144
+ continue;
145
+ }
146
+ const text = parsed.response ?? '';
147
+ if (text || parsed.done) {
148
+ yield { text, done: Boolean(parsed.done) };
149
+ }
150
+ }
151
+ }
152
+
153
+ if (buffer.trim()) {
154
+ try {
155
+ const parsed = JSON.parse(buffer.trim()) as OllamaGenerateResponse;
156
+ yield { text: parsed.response ?? '', done: Boolean(parsed.done ?? true) };
157
+ } catch {
158
+ // ignore trailing junk
159
+ }
160
+ }
161
+ }
162
+
163
+ async unload(_modelId?: string): Promise<void> {
164
+ // No persistent engine process in the browser adapter.
165
+ }
166
+
167
+ async resetConversation(_modelId?: string, _sessionId?: string): Promise<void> {
168
+ // Stateless HTTP — nothing to clear between LanguageModel sessions.
169
+ }
170
+ }
@@ -0,0 +1,135 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { PromptApiAdapter, PROMPT_API_MODEL_ID } from './promptApi.js';
3
+ import type { NormalizedPromptApi, PromptApiSession } from '../promptApiSupport.js';
4
+
5
+ function fakeApi(options: {
6
+ availability?: string;
7
+ streamChunks?: string[];
8
+ onCreate?: (opts: unknown) => void;
9
+ }): NormalizedPromptApi {
10
+ const availability = options.availability ?? 'available';
11
+ return {
12
+ availability: async () => availability as never,
13
+ create: async (opts) => {
14
+ options.onCreate?.(opts);
15
+ const session: PromptApiSession = {
16
+ prompt: async (input: string) => `echo:${input}`,
17
+ promptStreaming: (_input: string) =>
18
+ (async function* () {
19
+ for (const chunk of options.streamChunks ?? ['Hello', ' world']) {
20
+ yield chunk;
21
+ }
22
+ })(),
23
+ destroy: vi.fn(),
24
+ };
25
+ return session;
26
+ },
27
+ };
28
+ }
29
+
30
+ describe('PromptApiAdapter', () => {
31
+ it('lists nothing when the Prompt API is absent (provider hidden entirely)', async () => {
32
+ const adapter = new PromptApiAdapter({ getApi: () => null });
33
+ expect(await adapter.listModels()).toEqual([]);
34
+ expect(await adapter.isAvailable()).toBe(false);
35
+ });
36
+
37
+ it('lists nothing when availability is unavailable', async () => {
38
+ const adapter = new PromptApiAdapter({
39
+ getApi: () => fakeApi({ availability: 'unavailable' }),
40
+ });
41
+ expect(await adapter.listModels()).toEqual([]);
42
+ expect(await adapter.isAvailable()).toBe(false);
43
+ });
44
+
45
+ it('exposes one ready model when available', async () => {
46
+ const adapter = new PromptApiAdapter({ getApi: () => fakeApi({ availability: 'available' }) });
47
+ const models = await adapter.listModels();
48
+ expect(models).toHaveLength(1);
49
+ expect(models[0]).toMatchObject({
50
+ id: PROMPT_API_MODEL_ID,
51
+ provider: 'prompt-api',
52
+ status: 'ready',
53
+ });
54
+ expect(await adapter.isAvailable()).toBe(true);
55
+ });
56
+
57
+ it('marks the model downloadable / downloading per availability', async () => {
58
+ const downloadable = new PromptApiAdapter({
59
+ getApi: () => fakeApi({ availability: 'downloadable' }),
60
+ });
61
+ expect((await downloadable.listModels())[0]?.status).toBe('downloadable');
62
+ const downloading = new PromptApiAdapter({
63
+ getApi: () => fakeApi({ availability: 'downloading' }),
64
+ });
65
+ expect((await downloading.listModels())[0]?.status).toBe('downloading');
66
+ });
67
+
68
+ it('warm/enable ignores zero downloadprogress and only reports real loaded > 0', async () => {
69
+ const progressEvents: number[] = [];
70
+ const adapter = new PromptApiAdapter({
71
+ getApi: () => ({
72
+ availability: async () => 'downloadable' as const,
73
+ create: async (opts) => {
74
+ opts?.monitor?.({
75
+ addEventListener: (_type, listener) => {
76
+ listener({ loaded: 0 });
77
+ listener({ loaded: 0.4 });
78
+ },
79
+ });
80
+ return {
81
+ prompt: async () => '',
82
+ promptStreaming: () => (async function* () {})(),
83
+ destroy: vi.fn(),
84
+ };
85
+ },
86
+ }),
87
+ });
88
+ await adapter.download('default', {
89
+ onProgress: (p) => progressEvents.push(p),
90
+ });
91
+ // 0 must not surface (would render a stuck “0%” Install bar); 0.4 and final 1 do.
92
+ expect(progressEvents).toEqual([0.4, 1]);
93
+ });
94
+
95
+ it('prompts via a fresh session and seeds history as initialPrompts', async () => {
96
+ const created: unknown[] = [];
97
+ const adapter = new PromptApiAdapter({
98
+ getApi: () => fakeApi({ onCreate: (opts) => created.push(opts) }),
99
+ });
100
+ const answer = await adapter.prompt({
101
+ modelId: 'default',
102
+ prompt: 'ignored',
103
+ messages: [
104
+ { role: 'system', content: 'be brief' },
105
+ { role: 'user', content: 'hello' },
106
+ ],
107
+ });
108
+ expect(answer).toBe('echo:hello');
109
+ expect(created[0]).toMatchObject({
110
+ initialPrompts: [{ role: 'system', content: 'be brief' }],
111
+ });
112
+ });
113
+
114
+ it('streams deltas (normalizing cumulative chunks)', async () => {
115
+ const adapter = new PromptApiAdapter({
116
+ getApi: () => fakeApi({ streamChunks: ['Hello', 'Hello world'] }),
117
+ });
118
+ const parts: string[] = [];
119
+ for await (const chunk of adapter.promptStreaming({ modelId: 'default', prompt: 'hi' })) {
120
+ if (chunk.text) parts.push(chunk.text);
121
+ }
122
+ expect(parts.join('')).toBe('Hello world');
123
+ });
124
+
125
+ it('streams deltas (already-incremental chunks)', async () => {
126
+ const adapter = new PromptApiAdapter({
127
+ getApi: () => fakeApi({ streamChunks: ['Hel', 'lo', ' world'] }),
128
+ });
129
+ const parts: string[] = [];
130
+ for await (const chunk of adapter.promptStreaming({ modelId: 'default', prompt: 'hi' })) {
131
+ if (chunk.text) parts.push(chunk.text);
132
+ }
133
+ expect(parts.join('')).toBe('Hello world');
134
+ });
135
+ });