@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.
- package/README.md +2 -0
- package/package.json +6 -4
- package/schemas/shellui.config.schema.json +104 -64
- package/src/app.tsx +5 -3
- package/src/components/ContentView.tsx +26 -5
- package/src/components/LoadingOverlay.tsx +1 -1
- package/src/components/ui/sonner.spec.tsx +138 -0
- package/src/components/ui/sonner.tsx +5 -5
- package/src/components/ui/switch.tsx +1 -1
- package/src/features/admin/AdminView.tsx +14 -3
- package/src/features/ai/AiBridge.tsx +106 -0
- package/src/features/ai/AiUnavailableResponder.tsx +39 -0
- package/src/features/ai/README.md +52 -0
- package/src/features/ai/ShellAiHost.tsx +24 -0
- package/src/features/ai/adapters/ollama.ts +170 -0
- package/src/features/ai/adapters/promptApi.spec.ts +135 -0
- package/src/features/ai/adapters/promptApi.ts +222 -0
- package/src/features/ai/adapters/webllm.experimental.spec.ts +69 -0
- package/src/features/ai/adapters/webllm.spec.ts +527 -0
- package/src/features/ai/adapters/webllm.ts +142 -0
- package/src/features/ai/aiDisabledResponses.spec.ts +29 -0
- package/src/features/ai/aiDisabledResponses.ts +32 -0
- package/src/features/ai/browserInstallStore.spec.ts +58 -0
- package/src/features/ai/browserInstallStore.ts +76 -0
- package/src/features/ai/catalog.ts +31 -0
- package/src/features/ai/createRegistry.ts +83 -0
- package/src/features/ai/developHarness.spec.ts +108 -0
- package/src/features/ai/developHarness.ts +161 -0
- package/src/features/ai/engine/formatAiError.spec.ts +85 -0
- package/src/features/ai/engine/formatAiError.ts +132 -0
- package/src/features/ai/engine/mapInitProgress.ts +9 -0
- package/src/features/ai/engine/normalizeWebLlmModule.spec.ts +47 -0
- package/src/features/ai/engine/vite-worker.d.ts +6 -0
- package/src/features/ai/engine/webllm.worker.ts +51 -0
- package/src/features/ai/engine/webllmEngine.ts +1011 -0
- package/src/features/ai/handleRequest.spec.ts +288 -0
- package/src/features/ai/handleRequest.ts +325 -0
- package/src/features/ai/isAiFeatureEnabled.spec.ts +15 -0
- package/src/features/ai/isAiFeatureEnabled.ts +9 -0
- package/src/features/ai/promptApiSupport.spec.ts +64 -0
- package/src/features/ai/promptApiSupport.ts +117 -0
- package/src/features/ai/registry.spec.ts +100 -0
- package/src/features/ai/registry.ts +131 -0
- package/src/features/ai/status.spec.ts +92 -0
- package/src/features/ai/status.ts +85 -0
- package/src/features/ai/types.ts +100 -0
- package/src/features/ai/webLlmBrowserSupport.spec.ts +86 -0
- package/src/features/ai/webLlmBrowserSupport.ts +92 -0
- package/src/features/alertDialog/DialogContext.tsx +3 -1
- package/src/features/auth/AuthProvider.tsx +254 -39
- package/src/features/auth/backends/index.ts +8 -0
- package/src/features/auth/backends/shellui.spec.ts +201 -0
- package/src/features/auth/backends/shellui.ts +93 -16
- package/src/features/auth/backends/supabase.ts +8 -0
- package/src/features/auth/backends/types.ts +16 -1
- package/src/features/auth/components/LoginButton.tsx +26 -2
- package/src/features/auth/components/LoginView.tsx +119 -134
- package/src/features/auth/components/OAuthCallbackView.tsx +12 -3
- package/src/features/auth/components/SessionLoadingView.tsx +21 -0
- package/src/features/auth/hooks/useAuth.tsx +12 -0
- package/src/features/auth/shellAccountRequests.ts +76 -0
- package/src/features/auth/utils/authRequestError.spec.ts +11 -0
- package/src/features/auth/utils/authRequestError.ts +10 -1
- package/src/features/auth/utils/authSessionPersistence.spec.ts +11 -0
- package/src/features/auth/utils/authSessionPersistence.ts +12 -0
- package/src/features/auth/utils/index.ts +5 -0
- package/src/features/auth/utils/resolveLoginSettings.spec.ts +33 -0
- package/src/features/auth/utils/resolveLoginSettings.ts +33 -0
- package/src/features/auth/utils/shareInFlight.spec.ts +41 -0
- package/src/features/auth/utils/shareInFlight.ts +14 -0
- package/src/features/config/ConfigProvider.ts +9 -1
- package/src/features/config/types.ts +43 -0
- package/src/features/layouts/appbar/AppBarLayout.tsx +8 -3
- package/src/features/layouts/filterNavigationForAuthState.spec.ts +41 -0
- package/src/features/layouts/floating/FloatingLayout.tsx +9 -4
- package/src/features/layouts/sidebar/SidebarLayout.tsx +9 -4
- package/src/features/layouts/utils.ts +6 -2
- package/src/features/layouts/windows/WindowsLayout.tsx +8 -3
- package/src/features/messaging/MessagingSecurityBootstrap.tsx +6 -6
- package/src/features/security/trustedFrames.spec.ts +65 -0
- package/src/features/security/trustedFrames.ts +52 -0
- package/src/features/settings/SettingsIcons.tsx +17 -0
- package/src/features/settings/SettingsProvider.tsx +28 -3
- package/src/features/settings/SettingsRoutes.tsx +8 -0
- package/src/features/settings/SettingsView.tsx +21 -4
- package/src/features/settings/components/Ai.tsx +830 -0
- package/src/features/settings/components/Develop.tsx +4 -0
- package/src/features/settings/components/Storage.tsx +197 -32
- package/src/features/settings/components/UserSettingsPanel.tsx +160 -12
- package/src/features/settings/components/createUserSettingsRoute.tsx +4 -0
- package/src/features/settings/components/develop/AiTestTools.tsx +231 -0
- package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +54 -1
- package/src/features/settings/utils/buildSettingsForPropagation.ts +15 -1
- package/src/features/settings/utils/mergePreferencesIntoSettings.spec.ts +6 -0
- package/src/features/settings/utils/shouldShowStorageSettings.spec.ts +49 -0
- package/src/features/settings/utils/shouldShowStorageSettings.ts +19 -0
- package/src/features/storage/uploads/UploadToastCard.tsx +2 -442
- package/src/features/storage/uploads/UploadToaster.tsx +2 -44
- package/src/features/storage/uploads/uploadQueue.ts +128 -308
- package/src/features/storage/uploads/useUploadQueue.ts +7 -3
- package/src/features/transfers/TransferToastCard.tsx +467 -0
- package/src/features/transfers/TransferToaster.tsx +50 -0
- package/src/features/transfers/index.ts +33 -0
- package/src/features/transfers/transferQueue.spec.ts +97 -0
- package/src/features/transfers/transferQueue.ts +442 -0
- package/src/features/transfers/types.ts +38 -0
- package/src/features/transfers/useTransferQueue.ts +30 -0
- package/src/i18n/translations/en/common.json +49 -2
- package/src/i18n/translations/en/settings.json +152 -2
- package/src/i18n/translations/fr/common.json +49 -2
- package/src/i18n/translations/fr/settings.json +152 -2
- package/src/index.css +57 -4
- package/src/index.ts +1 -0
- package/src/routes/components/NavigationItemRoute.tsx +2 -1
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { getPromptApi, isPromptApiPresent } from './promptApiSupport.js';
|
|
3
|
+
|
|
4
|
+
/** Resolve or fail the test — keeps assertions free of non-null (`!`) operators. */
|
|
5
|
+
function resolve(scope: typeof globalThis) {
|
|
6
|
+
const api = getPromptApi(scope);
|
|
7
|
+
if (!api) throw new Error('expected Prompt API to be detected');
|
|
8
|
+
return api;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function modernScope(availability: string) {
|
|
12
|
+
return {
|
|
13
|
+
LanguageModel: {
|
|
14
|
+
availability: async () => availability,
|
|
15
|
+
create: async () => ({
|
|
16
|
+
prompt: async () => 'ok',
|
|
17
|
+
promptStreaming: () => (async function* () {})(),
|
|
18
|
+
destroy: () => undefined,
|
|
19
|
+
}),
|
|
20
|
+
},
|
|
21
|
+
} as unknown as typeof globalThis;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function legacyScope(available: string) {
|
|
25
|
+
return {
|
|
26
|
+
ai: {
|
|
27
|
+
languageModel: {
|
|
28
|
+
capabilities: async () => ({ available }),
|
|
29
|
+
create: async () => ({
|
|
30
|
+
prompt: async () => 'ok',
|
|
31
|
+
promptStreaming: () => (async function* () {})(),
|
|
32
|
+
destroy: () => undefined,
|
|
33
|
+
}),
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
} as unknown as typeof globalThis;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
describe('getPromptApi', () => {
|
|
40
|
+
it('returns null when no Prompt API global is present (Firefox / Safari / iPhone)', () => {
|
|
41
|
+
const scope = {} as unknown as typeof globalThis;
|
|
42
|
+
expect(getPromptApi(scope)).toBeNull();
|
|
43
|
+
expect(isPromptApiPresent(scope)).toBe(false);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('detects the modern LanguageModel global and normalizes availability', async () => {
|
|
47
|
+
expect(await resolve(modernScope('available')).availability()).toBe('available');
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('maps downloadable / downloading availability', async () => {
|
|
51
|
+
expect(await resolve(modernScope('downloadable')).availability()).toBe('downloadable');
|
|
52
|
+
expect(await resolve(modernScope('downloading')).availability()).toBe('downloading');
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('normalizes unknown / no availability to unavailable', async () => {
|
|
56
|
+
expect(await resolve(modernScope('no')).availability()).toBe('unavailable');
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it('supports the legacy ai.languageModel capabilities() shape', async () => {
|
|
60
|
+
expect(await resolve(legacyScope('readily')).availability()).toBe('available');
|
|
61
|
+
expect(await resolve(legacyScope('after-download')).availability()).toBe('downloadable');
|
|
62
|
+
expect(await resolve(legacyScope('no')).availability()).toBe('unavailable');
|
|
63
|
+
});
|
|
64
|
+
});
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Feature-detection + normalization for the **Chrome built-in Prompt API**
|
|
3
|
+
* (`LanguageModel` / Gemini Nano). This is Chromium-only — Firefox, Safari, and
|
|
4
|
+
* iPhone do not expose it, so callers must treat a `null` result as "hide the
|
|
5
|
+
* provider entirely" (no warning, no disabled stub).
|
|
6
|
+
*
|
|
7
|
+
* Chrome has shipped a few shapes over time; we normalize the two we support:
|
|
8
|
+
* - **Modern global** `LanguageModel` with `availability()` + `create()`.
|
|
9
|
+
* - **Legacy namespace** `ai.languageModel` with `capabilities()`/`availability()` + `create()`.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** Normalized availability, following the current Prompt API spec vocabulary. */
|
|
13
|
+
export type PromptApiAvailability = 'available' | 'downloadable' | 'downloading' | 'unavailable';
|
|
14
|
+
|
|
15
|
+
export type PromptRole = 'system' | 'user' | 'assistant';
|
|
16
|
+
export type PromptMessage = { role: PromptRole; content: string };
|
|
17
|
+
|
|
18
|
+
export type PromptApiMonitor = {
|
|
19
|
+
addEventListener(type: 'downloadprogress', listener: (event: { loaded: number }) => void): void;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export type PromptApiCreateOptions = {
|
|
23
|
+
initialPrompts?: PromptMessage[];
|
|
24
|
+
signal?: AbortSignal;
|
|
25
|
+
monitor?: (monitor: PromptApiMonitor) => void;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export type PromptApiSession = {
|
|
29
|
+
prompt(input: string, options?: { signal?: AbortSignal }): Promise<string>;
|
|
30
|
+
promptStreaming(
|
|
31
|
+
input: string,
|
|
32
|
+
options?: { signal?: AbortSignal },
|
|
33
|
+
): ReadableStream<string> | AsyncIterable<string>;
|
|
34
|
+
destroy?(): void;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/** Small normalized surface the adapter talks to, regardless of the Chrome shape. */
|
|
38
|
+
export type NormalizedPromptApi = {
|
|
39
|
+
availability(): Promise<PromptApiAvailability>;
|
|
40
|
+
create(options?: PromptApiCreateOptions): Promise<PromptApiSession>;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
function normalizeAvailability(value: unknown): PromptApiAvailability {
|
|
44
|
+
switch (value) {
|
|
45
|
+
case 'available':
|
|
46
|
+
case 'readily':
|
|
47
|
+
return 'available';
|
|
48
|
+
case 'downloadable':
|
|
49
|
+
case 'after-download':
|
|
50
|
+
return 'downloadable';
|
|
51
|
+
case 'downloading':
|
|
52
|
+
return 'downloading';
|
|
53
|
+
default:
|
|
54
|
+
return 'unavailable';
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
type ModernPromptApiGlobal = {
|
|
59
|
+
availability?: (options?: unknown) => Promise<string>;
|
|
60
|
+
create?: (options?: unknown) => Promise<PromptApiSession>;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
type LegacyPromptApiNamespace = {
|
|
64
|
+
languageModel?: {
|
|
65
|
+
availability?: (options?: unknown) => Promise<string>;
|
|
66
|
+
capabilities?: () => Promise<{ available?: string }>;
|
|
67
|
+
create?: (options?: unknown) => Promise<PromptApiSession>;
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Resolve the Chrome Prompt API from a global scope, or `null` when absent.
|
|
73
|
+
* `scope` is injectable so tests can pass a fake `globalThis`.
|
|
74
|
+
*/
|
|
75
|
+
export function getPromptApi(
|
|
76
|
+
scope: typeof globalThis = typeof globalThis !== 'undefined' ? globalThis : ({} as never),
|
|
77
|
+
): NormalizedPromptApi | null {
|
|
78
|
+
const global = scope as unknown as {
|
|
79
|
+
LanguageModel?: ModernPromptApiGlobal;
|
|
80
|
+
ai?: LegacyPromptApiNamespace;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const modern = global.LanguageModel;
|
|
84
|
+
if (modern && typeof modern.create === 'function' && typeof modern.availability === 'function') {
|
|
85
|
+
const create = modern.create.bind(modern);
|
|
86
|
+
const availability = modern.availability.bind(modern);
|
|
87
|
+
return {
|
|
88
|
+
availability: async () => normalizeAvailability(await availability()),
|
|
89
|
+
create: (options) => create(options) as Promise<PromptApiSession>,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const legacy = global.ai?.languageModel;
|
|
94
|
+
if (legacy && typeof legacy.create === 'function') {
|
|
95
|
+
const create = legacy.create.bind(legacy);
|
|
96
|
+
return {
|
|
97
|
+
availability: async () => {
|
|
98
|
+
if (typeof legacy.availability === 'function') {
|
|
99
|
+
return normalizeAvailability(await legacy.availability());
|
|
100
|
+
}
|
|
101
|
+
if (typeof legacy.capabilities === 'function') {
|
|
102
|
+
const caps = await legacy.capabilities();
|
|
103
|
+
return normalizeAvailability(caps?.available);
|
|
104
|
+
}
|
|
105
|
+
return 'unavailable';
|
|
106
|
+
},
|
|
107
|
+
create: (options) => create(options) as Promise<PromptApiSession>,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Cheap presence check (does not call `availability()`). */
|
|
115
|
+
export function isPromptApiPresent(scope?: typeof globalThis): boolean {
|
|
116
|
+
return getPromptApi(scope) !== null;
|
|
117
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { AiRegistry } from './registry.js';
|
|
3
|
+
import type { AiAdapter, AiModel, AiPromptOptions, AiStreamChunk } from './types.js';
|
|
4
|
+
|
|
5
|
+
class FakeAdapter implements AiAdapter {
|
|
6
|
+
readonly id: 'ollama' | 'webllm';
|
|
7
|
+
private readonly models: AiModel[];
|
|
8
|
+
|
|
9
|
+
constructor(id: 'ollama' | 'webllm', models: AiModel[]) {
|
|
10
|
+
this.id = id;
|
|
11
|
+
this.models = models;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
async isAvailable(): Promise<boolean> {
|
|
15
|
+
return true;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async listModels(): Promise<AiModel[]> {
|
|
19
|
+
return this.models;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async load(): Promise<void> {}
|
|
23
|
+
|
|
24
|
+
async prompt(options: AiPromptOptions): Promise<string> {
|
|
25
|
+
return `echo:${options.modelId}:${options.prompt}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async *promptStreaming(options: AiPromptOptions): AsyncIterable<AiStreamChunk> {
|
|
29
|
+
yield { text: `chunk:${options.prompt}`, done: true };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async unload(): Promise<void> {}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
describe('AiRegistry', () => {
|
|
36
|
+
it('lists models from every adapter', async () => {
|
|
37
|
+
const registry = new AiRegistry({
|
|
38
|
+
adapters: [
|
|
39
|
+
new FakeAdapter('ollama', [
|
|
40
|
+
{
|
|
41
|
+
id: 'ollama:llama',
|
|
42
|
+
name: 'llama',
|
|
43
|
+
provider: 'ollama',
|
|
44
|
+
status: 'ready',
|
|
45
|
+
},
|
|
46
|
+
]),
|
|
47
|
+
new FakeAdapter('webllm', [
|
|
48
|
+
{
|
|
49
|
+
id: 'webllm:tiny',
|
|
50
|
+
name: 'tiny',
|
|
51
|
+
provider: 'webllm',
|
|
52
|
+
status: 'downloadable',
|
|
53
|
+
},
|
|
54
|
+
]),
|
|
55
|
+
],
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
const models = await registry.listModels();
|
|
59
|
+
expect(models.map((m) => m.id)).toEqual(['ollama:llama', 'webllm:tiny']);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('resolves provider-qualified model ids', async () => {
|
|
63
|
+
const ollama = new FakeAdapter('ollama', [
|
|
64
|
+
{ id: 'ollama:llama', name: 'llama', provider: 'ollama', status: 'ready' },
|
|
65
|
+
]);
|
|
66
|
+
const registry = new AiRegistry({ adapters: [ollama] });
|
|
67
|
+
const resolved = registry.resolveModel('ollama:llama');
|
|
68
|
+
expect(resolved?.adapter).toBe(ollama);
|
|
69
|
+
expect(resolved?.modelId).toBe('llama');
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it('picks a ready default model for availability', async () => {
|
|
73
|
+
const registry = new AiRegistry({
|
|
74
|
+
adapters: [
|
|
75
|
+
new FakeAdapter('ollama', [
|
|
76
|
+
{ id: 'ollama:a', name: 'a', provider: 'ollama', status: 'ready' },
|
|
77
|
+
{ id: 'ollama:b', name: 'b', provider: 'ollama', status: 'ready' },
|
|
78
|
+
]),
|
|
79
|
+
],
|
|
80
|
+
defaultModelId: 'ollama:b',
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
const ready = await registry.resolveReadyModel();
|
|
84
|
+
expect(ready?.qualifiedId).toBe('ollama:b');
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it('routes prompt to the owning adapter', async () => {
|
|
88
|
+
const registry = new AiRegistry({
|
|
89
|
+
adapters: [
|
|
90
|
+
new FakeAdapter('ollama', [
|
|
91
|
+
{ id: 'ollama:llama', name: 'llama', provider: 'ollama', status: 'ready' },
|
|
92
|
+
]),
|
|
93
|
+
],
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
await expect(registry.prompt({ modelId: 'ollama:llama', prompt: 'hi' })).resolves.toBe(
|
|
97
|
+
'echo:llama:hi',
|
|
98
|
+
);
|
|
99
|
+
});
|
|
100
|
+
});
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AiAdapter,
|
|
3
|
+
AiModel,
|
|
4
|
+
AiPromptOptions,
|
|
5
|
+
AiRegistryOptions,
|
|
6
|
+
AiStreamChunk,
|
|
7
|
+
} from './types.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Multiplexes registered adapters. Apps never see this — only the shell bridge.
|
|
11
|
+
*/
|
|
12
|
+
export class AiRegistry {
|
|
13
|
+
private readonly adapters: Map<string, AiAdapter>;
|
|
14
|
+
private defaultModelId: string | null;
|
|
15
|
+
|
|
16
|
+
constructor(options: AiRegistryOptions) {
|
|
17
|
+
this.adapters = new Map(options.adapters.map((adapter) => [adapter.id, adapter]));
|
|
18
|
+
this.defaultModelId = options.defaultModelId ?? null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
getAdapter(providerId: string): AiAdapter | undefined {
|
|
22
|
+
return this.adapters.get(providerId);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
listAdapters(): AiAdapter[] {
|
|
26
|
+
return [...this.adapters.values()];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
setDefaultModelId(modelId: string | null): void {
|
|
30
|
+
this.defaultModelId = modelId;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
getDefaultModelId(): string | null {
|
|
34
|
+
return this.defaultModelId;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async listModels(): Promise<AiModel[]> {
|
|
38
|
+
const lists = await Promise.all(this.listAdapters().map((adapter) => adapter.listModels()));
|
|
39
|
+
return lists.flat();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Resolve `provider:name` ids (e.g. `ollama:llama3.2`) or bare ids unique across adapters.
|
|
44
|
+
*/
|
|
45
|
+
resolveModel(modelId: string): { adapter: AiAdapter; modelId: string } | null {
|
|
46
|
+
const colon = modelId.indexOf(':');
|
|
47
|
+
if (colon > 0) {
|
|
48
|
+
const provider = modelId.slice(0, colon);
|
|
49
|
+
const localId = modelId.slice(colon + 1);
|
|
50
|
+
const adapter = this.adapters.get(provider);
|
|
51
|
+
if (!adapter || !localId) return null;
|
|
52
|
+
return { adapter, modelId: localId };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Bare id: prefer default adapter order — first match wins when listing later.
|
|
56
|
+
for (const adapter of this.listAdapters()) {
|
|
57
|
+
// Caller may pass a fully-qualified id already; bare ids are rare.
|
|
58
|
+
if (modelId.startsWith(`${adapter.id}:`)) {
|
|
59
|
+
return { adapter, modelId: modelId.slice(adapter.id.length + 1) };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async resolveReadyModel(preferredId?: string | null): Promise<{
|
|
66
|
+
adapter: AiAdapter;
|
|
67
|
+
modelId: string;
|
|
68
|
+
qualifiedId: string;
|
|
69
|
+
} | null> {
|
|
70
|
+
const models = await this.listModels();
|
|
71
|
+
const ready = models.filter((model) => model.status === 'ready');
|
|
72
|
+
if (ready.length === 0) return null;
|
|
73
|
+
|
|
74
|
+
const pick =
|
|
75
|
+
(preferredId && ready.find((model) => model.id === preferredId)) ||
|
|
76
|
+
(this.defaultModelId && ready.find((model) => model.id === this.defaultModelId)) ||
|
|
77
|
+
ready[0];
|
|
78
|
+
|
|
79
|
+
if (!pick) return null;
|
|
80
|
+
|
|
81
|
+
const resolved = this.resolveModel(pick.id);
|
|
82
|
+
if (!resolved) return null;
|
|
83
|
+
return {
|
|
84
|
+
adapter: resolved.adapter,
|
|
85
|
+
modelId: resolved.modelId,
|
|
86
|
+
qualifiedId: pick.id,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async prompt(options: AiPromptOptions): Promise<string> {
|
|
91
|
+
const resolved = this.resolveModel(options.modelId);
|
|
92
|
+
if (!resolved) {
|
|
93
|
+
throw new Error(`Unknown model: ${options.modelId}`);
|
|
94
|
+
}
|
|
95
|
+
await resolved.adapter.load(resolved.modelId, options.signal);
|
|
96
|
+
return resolved.adapter.prompt({ ...options, modelId: resolved.modelId });
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
promptStreaming(options: AiPromptOptions): AsyncIterable<AiStreamChunk> {
|
|
100
|
+
const resolved = this.resolveModel(options.modelId);
|
|
101
|
+
if (!resolved) {
|
|
102
|
+
throw new Error(`Unknown model: ${options.modelId}`);
|
|
103
|
+
}
|
|
104
|
+
const adapter = resolved.adapter;
|
|
105
|
+
const modelId = resolved.modelId;
|
|
106
|
+
return (async function* () {
|
|
107
|
+
await adapter.load(modelId, options.signal);
|
|
108
|
+
yield* adapter.promptStreaming({ ...options, modelId });
|
|
109
|
+
})();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Clear conversation state on the adapter that owns `modelId` (WebLLM hard reset).
|
|
114
|
+
* `sessionId` (from `create`) becomes the adapter's new owning session.
|
|
115
|
+
* No-op when the adapter does not implement resetConversation.
|
|
116
|
+
*/
|
|
117
|
+
async resetConversation(modelId?: string | null, sessionId?: string): Promise<void> {
|
|
118
|
+
if (!modelId) {
|
|
119
|
+
// Reset every adapter that supports it (destroy without a clear model).
|
|
120
|
+
await Promise.all(
|
|
121
|
+
this.listAdapters().map(
|
|
122
|
+
(adapter) => adapter.resetConversation?.(undefined, sessionId) ?? Promise.resolve(),
|
|
123
|
+
),
|
|
124
|
+
);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const resolved = this.resolveModel(modelId);
|
|
128
|
+
if (!resolved) return;
|
|
129
|
+
await resolved.adapter.resetConversation?.(resolved.modelId, sessionId);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { OllamaAdapter } from './adapters/ollama.js';
|
|
3
|
+
import { probeOllama, probeWebGpu } from './status.js';
|
|
4
|
+
|
|
5
|
+
describe('probeOllama', () => {
|
|
6
|
+
it('reports reachable when /api/tags succeeds', async () => {
|
|
7
|
+
const fetchImpl = vi.fn(
|
|
8
|
+
async () => new Response(JSON.stringify({ models: [] }), { status: 200 }),
|
|
9
|
+
);
|
|
10
|
+
const status = await probeOllama({ fetchImpl: fetchImpl as unknown as typeof fetch });
|
|
11
|
+
expect(status.reachable).toBe(true);
|
|
12
|
+
expect(status.baseUrl).toContain('11434');
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it('soft-fails when fetch throws', async () => {
|
|
16
|
+
const fetchImpl = vi.fn(async () => {
|
|
17
|
+
throw new Error('Failed to fetch');
|
|
18
|
+
});
|
|
19
|
+
const status = await probeOllama({ fetchImpl: fetchImpl as unknown as typeof fetch });
|
|
20
|
+
expect(status.reachable).toBe(false);
|
|
21
|
+
expect(status.detail).toMatch(/Failed to fetch/);
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
describe('probeWebGpu', () => {
|
|
26
|
+
it('reports unavailable when navigator.gpu is missing', async () => {
|
|
27
|
+
const status = await probeWebGpu(undefined);
|
|
28
|
+
expect(status.available).toBe(false);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('reports available when requestAdapter returns an adapter', async () => {
|
|
32
|
+
const status = await probeWebGpu({
|
|
33
|
+
requestAdapter: async () => ({}),
|
|
34
|
+
});
|
|
35
|
+
expect(status.available).toBe(true);
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
describe('OllamaAdapter', () => {
|
|
40
|
+
it('lists tagged models when Ollama is up', async () => {
|
|
41
|
+
const fetchImpl = vi.fn(async (input: RequestInfo | URL) => {
|
|
42
|
+
const url = String(input);
|
|
43
|
+
if (url.endsWith('/api/tags')) {
|
|
44
|
+
return new Response(
|
|
45
|
+
JSON.stringify({
|
|
46
|
+
models: [{ name: 'llama3.2:latest', size: 2_000_000_000 }],
|
|
47
|
+
}),
|
|
48
|
+
{ status: 200 },
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
return new Response('not found', { status: 404 });
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const adapter = new OllamaAdapter({ fetchImpl: fetchImpl as unknown as typeof fetch });
|
|
55
|
+
const models = await adapter.listModels();
|
|
56
|
+
expect(models).toEqual([
|
|
57
|
+
expect.objectContaining({
|
|
58
|
+
id: 'ollama:llama3.2:latest',
|
|
59
|
+
status: 'ready',
|
|
60
|
+
provider: 'ollama',
|
|
61
|
+
}),
|
|
62
|
+
]);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('returns empty list when Ollama is down', async () => {
|
|
66
|
+
const fetchImpl = vi.fn(async () => {
|
|
67
|
+
throw new TypeError('Network error');
|
|
68
|
+
});
|
|
69
|
+
const adapter = new OllamaAdapter({ fetchImpl: fetchImpl as unknown as typeof fetch });
|
|
70
|
+
await expect(adapter.listModels()).resolves.toEqual([]);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('prompts via /api/generate', async () => {
|
|
74
|
+
const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
75
|
+
const url = String(input);
|
|
76
|
+
if (url.endsWith('/api/tags')) {
|
|
77
|
+
return new Response(JSON.stringify({ models: [] }), { status: 200 });
|
|
78
|
+
}
|
|
79
|
+
if (url.endsWith('/api/generate') && init?.method === 'POST') {
|
|
80
|
+
return new Response(JSON.stringify({ response: 'hello world', done: true }), {
|
|
81
|
+
status: 200,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
return new Response('no', { status: 404 });
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const adapter = new OllamaAdapter({ fetchImpl: fetchImpl as unknown as typeof fetch });
|
|
88
|
+
await expect(adapter.prompt({ modelId: 'llama3.2', prompt: 'hi' })).resolves.toBe(
|
|
89
|
+
'hello world',
|
|
90
|
+
);
|
|
91
|
+
});
|
|
92
|
+
});
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { AiRuntimeStatus } from './types.js';
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_OLLAMA_BASE_URL = 'http://127.0.0.1:11434';
|
|
4
|
+
|
|
5
|
+
/** Soft WebGPU probe for Settings → AI. Never throws. */
|
|
6
|
+
export async function probeWebGpu(
|
|
7
|
+
gpu: { requestAdapter?: () => Promise<unknown> } | undefined = (
|
|
8
|
+
globalThis as { navigator?: { gpu?: { requestAdapter?: () => Promise<unknown> } } }
|
|
9
|
+
).navigator?.gpu,
|
|
10
|
+
): Promise<AiRuntimeStatus['webGpu']> {
|
|
11
|
+
if (!gpu || typeof gpu.requestAdapter !== 'function') {
|
|
12
|
+
return { available: false, detail: 'WebGPU is not exposed in this browser.' };
|
|
13
|
+
}
|
|
14
|
+
try {
|
|
15
|
+
const adapter = await gpu.requestAdapter();
|
|
16
|
+
if (!adapter) {
|
|
17
|
+
return { available: false, detail: 'No WebGPU adapter (GPU blocked or unsupported).' };
|
|
18
|
+
}
|
|
19
|
+
return { available: true };
|
|
20
|
+
} catch (error) {
|
|
21
|
+
return {
|
|
22
|
+
available: false,
|
|
23
|
+
detail: error instanceof Error ? error.message : 'WebGPU probe failed.',
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export type ProbeOllamaOptions = {
|
|
29
|
+
baseUrl?: string;
|
|
30
|
+
fetchImpl?: typeof fetch;
|
|
31
|
+
timeoutMs?: number;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** Soft Ollama probe. Soft-fails when offline, CORS-blocked, or timed out. */
|
|
35
|
+
export async function probeOllama(
|
|
36
|
+
options: ProbeOllamaOptions = {},
|
|
37
|
+
): Promise<AiRuntimeStatus['ollama']> {
|
|
38
|
+
const baseUrl = (options.baseUrl ?? DEFAULT_OLLAMA_BASE_URL).replace(/\/+$/, '');
|
|
39
|
+
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
40
|
+
const timeoutMs = options.timeoutMs ?? 2_000;
|
|
41
|
+
|
|
42
|
+
if (typeof fetchImpl !== 'function') {
|
|
43
|
+
return { reachable: false, baseUrl, detail: 'fetch is unavailable.' };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const controller = new AbortController();
|
|
47
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
48
|
+
const startedAt = Date.now();
|
|
49
|
+
|
|
50
|
+
try {
|
|
51
|
+
const response = await fetchImpl(`${baseUrl}/api/tags`, {
|
|
52
|
+
method: 'GET',
|
|
53
|
+
signal: controller.signal,
|
|
54
|
+
});
|
|
55
|
+
const latencyMs = Date.now() - startedAt;
|
|
56
|
+
if (!response.ok) {
|
|
57
|
+
return {
|
|
58
|
+
reachable: false,
|
|
59
|
+
baseUrl,
|
|
60
|
+
detail: `Ollama responded with HTTP ${response.status}.`,
|
|
61
|
+
latencyMs,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
return { reachable: true, baseUrl, latencyMs };
|
|
65
|
+
} catch (error) {
|
|
66
|
+
const latencyMs = Date.now() - startedAt;
|
|
67
|
+
const aborted =
|
|
68
|
+
(error instanceof Error && error.name === 'AbortError') ||
|
|
69
|
+
(typeof DOMException !== 'undefined' &&
|
|
70
|
+
error instanceof DOMException &&
|
|
71
|
+
error.name === 'AbortError');
|
|
72
|
+
return {
|
|
73
|
+
reachable: false,
|
|
74
|
+
baseUrl,
|
|
75
|
+
latencyMs,
|
|
76
|
+
detail: aborted
|
|
77
|
+
? 'Ollama did not respond in time (is it running?).'
|
|
78
|
+
: error instanceof Error
|
|
79
|
+
? error.message
|
|
80
|
+
: 'Ollama probe failed.',
|
|
81
|
+
};
|
|
82
|
+
} finally {
|
|
83
|
+
clearTimeout(timer);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared AI types for shell-side adapters and registry (core feature module).
|
|
3
|
+
* SDK protocol payloads live in `@shellui/sdk` so iframes never import these types.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export type AiProviderId = 'ollama' | 'webllm' | 'prompt-api';
|
|
7
|
+
|
|
8
|
+
export type AiModelStatus =
|
|
9
|
+
| 'ready'
|
|
10
|
+
| 'downloadable'
|
|
11
|
+
| 'downloading'
|
|
12
|
+
| 'unavailable'
|
|
13
|
+
| 'needs-webgpu'
|
|
14
|
+
/** Browser present but WebLLM runtime unsupported (e.g. Firefox). */
|
|
15
|
+
| 'unsupported';
|
|
16
|
+
|
|
17
|
+
export type AiModel = {
|
|
18
|
+
id: string;
|
|
19
|
+
name: string;
|
|
20
|
+
provider: AiProviderId;
|
|
21
|
+
/** Approximate size in bytes when known (catalog / Ollama). */
|
|
22
|
+
sizeBytes?: number;
|
|
23
|
+
status: AiModelStatus;
|
|
24
|
+
/** Short human label (e.g. quant, parameter count). */
|
|
25
|
+
description?: string;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export type AiPromptOptions = {
|
|
29
|
+
modelId: string;
|
|
30
|
+
prompt: string;
|
|
31
|
+
signal?: AbortSignal;
|
|
32
|
+
systemPrompt?: string;
|
|
33
|
+
/**
|
|
34
|
+
* Full chat history for this turn (including the latest user message).
|
|
35
|
+
* When set, adapters that support multi-turn (WebLLM) should prefer this
|
|
36
|
+
* over building `[system?, user: prompt]` alone.
|
|
37
|
+
*/
|
|
38
|
+
messages?: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>;
|
|
39
|
+
/**
|
|
40
|
+
* Owning LanguageModel session id. Stateful adapters (WebLLM) fully dispose and
|
|
41
|
+
* recreate the worker engine when this changes so a new conversation never
|
|
42
|
+
* inherits the previous conversation's KV/chat state (or a stuck generation lock).
|
|
43
|
+
*/
|
|
44
|
+
sessionId?: string;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export type AiStreamChunk = {
|
|
48
|
+
text: string;
|
|
49
|
+
done: boolean;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
export type AiAvailability = 'available' | 'downloadable' | 'downloading' | 'unavailable';
|
|
53
|
+
|
|
54
|
+
export type AiRuntimeStatus = {
|
|
55
|
+
webGpu: {
|
|
56
|
+
available: boolean;
|
|
57
|
+
detail?: string;
|
|
58
|
+
};
|
|
59
|
+
ollama: {
|
|
60
|
+
reachable: boolean;
|
|
61
|
+
baseUrl: string;
|
|
62
|
+
detail?: string;
|
|
63
|
+
/** Round-trip time for the soft probe when reachable (or until failure). */
|
|
64
|
+
latencyMs?: number;
|
|
65
|
+
};
|
|
66
|
+
models: AiModel[];
|
|
67
|
+
defaultModelId: string | null;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
export type AiAdapter = {
|
|
71
|
+
readonly id: AiProviderId;
|
|
72
|
+
/** Soft probe — never throws. */
|
|
73
|
+
isAvailable(): Promise<boolean>;
|
|
74
|
+
listModels(): Promise<AiModel[]>;
|
|
75
|
+
/** Prepare weights / connection for a model id. Idempotent. */
|
|
76
|
+
load(modelId: string, signal?: AbortSignal): Promise<void>;
|
|
77
|
+
prompt(options: AiPromptOptions): Promise<string>;
|
|
78
|
+
promptStreaming(options: AiPromptOptions): AsyncIterable<AiStreamChunk>;
|
|
79
|
+
unload(modelId?: string): Promise<void>;
|
|
80
|
+
/**
|
|
81
|
+
* Clear adapter-owned conversation state (e.g. WebLLM chat/KV). WebLLM disposes the
|
|
82
|
+
* whole worker (weights persist in the browser cache and reload fast). Optional —
|
|
83
|
+
* Ollama is a no-op. Called on LanguageModel session destroy/create. `sessionId`
|
|
84
|
+
* (when provided, from `create`) becomes the new owning session.
|
|
85
|
+
*/
|
|
86
|
+
resetConversation?(modelId?: string, sessionId?: string): Promise<void>;
|
|
87
|
+
/** Optional browser/catalog download with 0–1 progress. */
|
|
88
|
+
download?(
|
|
89
|
+
modelId: string,
|
|
90
|
+
options?: { signal?: AbortSignal; onProgress?: (progress: number) => void },
|
|
91
|
+
): Promise<void>;
|
|
92
|
+
cancelDownload?(modelId: string): void;
|
|
93
|
+
deleteInstalled?(modelId: string): Promise<void>;
|
|
94
|
+
getDownloadProgress?(modelId: string): number | null;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
export type AiRegistryOptions = {
|
|
98
|
+
adapters: AiAdapter[];
|
|
99
|
+
defaultModelId?: string | null;
|
|
100
|
+
};
|