dsh-open-model 1.0.0 → 1.1.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/client.js DELETED
@@ -1,709 +0,0 @@
1
- window.__ModuleLoader__.load({
2
- id: 'dsh-open-model',
3
- factory(require) {
4
- const { createElement: h, useEffect, useId, useRef, useState, useSyncExternalStore } = require('react');
5
- const { Button, Switch, IconSparkleRegular, IconSparkle16 } = require('@deepseek-ai/dsh-client-ui-primitives');
6
- const panelId = 'dsh-free-model';
7
- const apiPath = '/api/dsh-free-model/models';
8
- const availabilityPath = `${apiPath}/availability`;
9
- const updatePath = '/api/dsh-free-model/update';
10
- const updateCheckInterval = 5 * 60 * 1000;
11
- const packageName = 'dsh-open-model';
12
- const repositoryUrl = 'https://github.com/houyanchao/dsh-open-model';
13
- const npmRegistry = 'https://registry.npmjs.org/';
14
- const publishedVersion = /^\d+\.\d+\.\d+(?:-[\da-z-]+(?:\.[\da-z-]+)*)?(?:\+[\da-z-]+(?:\.[\da-z-]+)*)?$/i;
15
- const recommendedPlugins = [
16
- { name: 'dsh-timeline', description: 'timelineDescription' },
17
- { name: 'dsh-use-chatgpt', description: 'chatgptDescription' },
18
- { name: 'timeline', description: 'browserDescription', stores: [
19
- { label: 'chrome', href: 'https://chromewebstore.google.com/detail/fgebdnlceacaiaeikopldglhffljjlhh' },
20
- { label: 'edge', href: 'https://microsoftedge.microsoft.com/addons/detail/ekednjjojnhlajfobalaaihkibbdcbab' },
21
- ] },
22
- ];
23
- const resultStatuses = new Set(['checking', 'available', 'unavailable']);
24
- const emptyAvailability = { checking: false, models: [] };
25
- const reasonKeys = new Map(Object.entries({
26
- AUTH: 'reasonAuth', QUOTA: 'reasonQuota', RATE_LIMIT: 'reasonRateLimit', TIMEOUT: 'reasonTimeout',
27
- MODEL_UNAVAILABLE: 'reasonRoute', TRANSPORT: 'reasonNetwork', INVALID_REQUEST: 'reasonRequest',
28
- MALFORMED_RESPONSE: 'reasonFormat', EMPTY_RESPONSE: 'reasonEmpty', SERVER: 'reasonServer',
29
- }));
30
-
31
- const messages = {
32
- zh: {
33
- title: '免费模型',
34
- hint: '开启的模型会显示在对话的「免费模型」分组中。',
35
- refresh: '刷新列表',
36
- loading: '正在读取 Kilo 模型列表…',
37
- empty: 'Kilo 当前没有可用的免费文本模型。',
38
- loadError: '无法读取模型列表,请重试。',
39
- saveError: '无法保存此模型的显示设置,请重试。',
40
- toggle: '在模型选择器中显示 {name}',
41
- checkAvailability: '检测可用性',
42
- checkingAvailability: '正在检测可用性…',
43
- checkCooldown: '请稍后再测',
44
- checkError: '无法检测模型可用性,请重试。',
45
- checkProgressError: '无法更新检测进度,请刷新列表。',
46
- unchecked: '未检测',
47
- checking: '检测中',
48
- available: '可用',
49
- unavailable: '不可用',
50
- checkedAt: '检测时间 {time}',
51
- reasonAuth: '匿名访问被拒绝',
52
- reasonQuota: '免费额度不足',
53
- reasonRateLimit: '暂时限流',
54
- reasonTimeout: '超时',
55
- reasonRoute: '上游暂未提供模型',
56
- reasonNetwork: '无法连接 Kilo',
57
- reasonRequest: '请求被拒绝',
58
- reasonFormat: '响应格式异常',
59
- reasonEmpty: '未收到文本回复',
60
- reasonServer: '上游服务异常',
61
- reasonUnknown: '本次检测失败',
62
- updateBadge: '更新',
63
- updateTitle: '有新版本',
64
- updateDetails: '查看更新',
65
- viewProject: '查看 GitHub 仓库',
66
- otherPlugins: '作者的其他插件',
67
- timelineDescription: '为 DSH 对话添加提问时间轴、收藏夹、提示词库和多格式导出。',
68
- chatgptDescription: '关联 ChatGPT 账号,在 DSH 中使用套餐额度,并切换账号和模型。',
69
- browserDescription: '为 ChatGPT、Gemini、DeepSeek 等网页添加对话时间轴、收藏夹和提示词库。',
70
- install: '安装',
71
- installed: '已安装',
72
- installing: '安装中…',
73
- checkInstall: '检测中…',
74
- retryInventory: '重新检测',
75
- installUnavailable: '安装不可用',
76
- installAction: '{name} · {action}',
77
- inventoryError: '无法读取已安装插件,请重新检测。',
78
- installError: '安装失败,请重试。',
79
- chrome: 'Chrome 版',
80
- edge: 'Edge 版',
81
- storeLabel: '{name} · {store}',
82
- },
83
- en: {
84
- title: 'Free Models',
85
- hint: 'Enabled models appear in the model picker.',
86
- refresh: 'Refresh list',
87
- loading: 'Loading the Kilo model list…',
88
- empty: 'Kilo currently lists no free text models.',
89
- loadError: 'Could not load the model list. Try again.',
90
- saveError: 'Could not save visibility for this model. Try again.',
91
- toggle: 'Show {name} in the model picker',
92
- checkAvailability: 'Check availability',
93
- checkingAvailability: 'Checking availability…',
94
- checkCooldown: 'Check again shortly',
95
- checkError: 'Could not start the model availability check. Try again.',
96
- checkProgressError: 'Could not update check progress. Refresh the list.',
97
- unchecked: 'Not checked',
98
- checking: 'Checking',
99
- available: 'Available',
100
- unavailable: 'Unavailable',
101
- checkedAt: 'Checked at {time}',
102
- reasonAuth: 'Anonymous access denied',
103
- reasonQuota: 'Free quota exhausted',
104
- reasonRateLimit: 'Temporarily rate limited',
105
- reasonTimeout: 'Request timed out',
106
- reasonRoute: 'Model unavailable upstream',
107
- reasonNetwork: 'Could not connect to Kilo',
108
- reasonRequest: 'Request rejected',
109
- reasonFormat: 'Unexpected response format',
110
- reasonEmpty: 'No text reply received',
111
- reasonServer: 'Upstream service error',
112
- reasonUnknown: 'Check failed',
113
- updateBadge: 'Update',
114
- updateTitle: 'Update available',
115
- updateDetails: 'View update',
116
- viewProject: 'View GitHub repository',
117
- otherPlugins: 'More plugins by this author',
118
- timelineDescription: 'Add a question timeline, bookmark folders, a prompt library, and chat exports to DSH.',
119
- chatgptDescription: 'Connect your ChatGPT account to use your plan in DSH and switch between accounts and models.',
120
- browserDescription: 'Add a chat timeline, bookmarks, and a prompt library to ChatGPT, Gemini, DeepSeek, and other AI chat sites.',
121
- install: 'Install',
122
- installed: 'Installed',
123
- installing: 'Installing…',
124
- checkInstall: 'Checking…',
125
- retryInventory: 'Check again',
126
- installUnavailable: 'Install unavailable',
127
- installAction: '{name} · {action}',
128
- inventoryError: 'Could not load installed plugins. Check again.',
129
- installError: 'Installation failed. Try again.',
130
- chrome: 'Chrome',
131
- edge: 'Edge',
132
- storeLabel: '{name} · {store}',
133
- },
134
- };
135
-
136
- const styles = `
137
- .dsh-free-model-page {
138
- width: 100%; height: 100%; min-width: 0; overflow: auto;
139
- background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-primary);
140
- font-size: 14px; line-height: 1.5;
141
- }
142
- .dsh-free-model-content { width: min(calc(100% - 36px), 760px); margin-inline: auto; padding-block: 28px 48px; }
143
- .dsh-free-model-update-banner {
144
- display: flex; align-items: center; flex-wrap: wrap; gap: 8px 16px;
145
- margin-block-end: 24px; padding: 8px 12px 8px 14px; border-radius: 12px;
146
- border: 1px solid var(--dsw-alias-border-l3, color-mix(in srgb, currentColor 12%, transparent));
147
- background: color-mix(in srgb, currentColor 3%, var(--dsw-alias-bg-layer-1));
148
- }
149
- .dsh-free-model-update-banner-content {
150
- display: flex; align-items: baseline; flex-wrap: wrap; gap: 2px 8px;
151
- flex: 1 1 180px; min-width: 0; margin: 0; overflow-wrap: anywhere;
152
- }
153
- .dsh-free-model-update-title { font-weight: 600; }
154
- .dsh-free-model-update-version { color: var(--dsw-alias-label-secondary); font-size: 13px; }
155
- .dsh-free-model-update-action, .dsh-free-model-plugin-action {
156
- display: inline-flex; align-items: center; min-height: 32px; padding-inline: 12px;
157
- border-radius: 999px; white-space: nowrap;
158
- border: 1px solid var(--dsw-alias-border-l3, color-mix(in srgb, currentColor 16%, transparent));
159
- background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-primary);
160
- font-size: 13px; font-weight: 550; text-decoration: none;
161
- }
162
- .dsh-free-model-update-action { margin-inline-start: auto; }
163
- .dsh-free-model-plugin-action { justify-content: center; box-sizing: border-box; font-family: inherit; cursor: pointer; }
164
- :is(.dsh-free-model-update-action, .dsh-free-model-plugin-action):hover { background: var(--dsw-alias-interactive-bg-hover); }
165
- :is(.dsh-free-model-update-action, .dsh-free-model-plugin-action):focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
166
- .dsh-free-model-header { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 6px 12px; }
167
- .dsh-free-model-header h1 { margin: 0; font-size: 24px; line-height: 1.3; font-weight: 600; }
168
- .dsh-free-model-hint { grid-column: 1 / -1; margin: 0; color: var(--dsw-alias-label-secondary); }
169
- .dsh-free-model-header-links { display: flex; align-items: center; justify-content: flex-end; gap: 6px; }
170
- .dsh-free-model-version { color: var(--dsw-alias-label-secondary); font-size: 13px; white-space: nowrap; }
171
- .dsh-free-model-project-link {
172
- display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px;
173
- border-radius: 50%; color: var(--dsw-alias-label-secondary); text-decoration: none;
174
- }
175
- .dsh-free-model-project-link:is(:hover, :focus-visible) {
176
- color: var(--dsw-alias-label-primary); background: color-mix(in srgb, currentColor 8%, transparent);
177
- }
178
- .dsh-free-model-actions { display: flex; justify-content: flex-end; flex-wrap: wrap; gap: 8px; margin-block-start: 16px; }
179
- .dsh-free-model-status { margin-block: 20px 0; }
180
- .dsh-free-model-list { padding: 0; margin: 20px 0 0; list-style: none; }
181
- .dsh-free-model-row {
182
- display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center;
183
- gap: 4px 16px; padding-block: 12px; border-block-end: 1px solid var(--dsw-alias-line-secondary, color-mix(in srgb, currentColor 12%, transparent));
184
- }
185
- .dsh-free-model-row:first-child { border-block-start: 1px solid var(--dsw-alias-line-secondary, color-mix(in srgb, currentColor 12%, transparent)); }
186
- .dsh-free-model-row-heading { display: flex; align-items: baseline; flex-wrap: wrap; gap: 3px 8px; }
187
- .dsh-free-model-name { display: block; font-weight: 550; overflow-wrap: anywhere; }
188
- .dsh-free-model-badge {
189
- padding: 1px 7px; border-radius: 4px; font-size: 12px; font-weight: 550;
190
- color: var(--dsw-alias-label-secondary); background: color-mix(in srgb, currentColor 11%, transparent);
191
- }
192
- .dsh-free-model-badge[data-status='available'] { color: var(--dsw-alias-state-success-primary, #238454); }
193
- .dsh-free-model-badge[data-status='unavailable'] { color: var(--dsw-alias-state-error-primary, #b63f39); }
194
- .dsh-free-model-reason, .dsh-free-model-duration { font-size: 12px; color: var(--dsw-alias-label-secondary); }
195
- .dsh-free-model-duration { font-variant-numeric: tabular-nums; white-space: nowrap; }
196
- .dsh-free-model-id { display: block; margin-block-start: 3px; font-size: 12px; color: var(--dsw-alias-label-secondary); overflow-wrap: anywhere; }
197
- .dsh-free-model-error { color: var(--dsw-alias-state-warn-label, #a1421c); overflow-wrap: anywhere; }
198
- .dsh-free-model-row .dsh-free-model-error { grid-column: 1 / -1; margin: 0; }
199
- .dsh-free-model-update-badge {
200
- display: inline-flex; align-items: center; padding: 1px 6px; border-radius: 999px;
201
- background: var(--dsw-alias-label-primary); color: var(--dsw-alias-bg-layer-1);
202
- font-size: 11px; font-weight: 550; line-height: 16px; white-space: nowrap;
203
- }
204
- .dsh-free-model-update-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--dsw-alias-label-primary); }
205
- .dsh-free-model-update-sr {
206
- position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap;
207
- }
208
- .dsh-free-model-recommendations {
209
- margin-block-start: 36px; container-type: inline-size;
210
- --plugin-divider: var(--dsw-alias-line-secondary, color-mix(in srgb, currentColor 12%, transparent));
211
- }
212
- .dsh-free-model-recommendations h2 { margin: 0 0 12px; font-size: 16px; font-weight: 600; line-height: 1.4; }
213
- .dsh-free-model-plugins { margin: 0; padding: 0 16px; list-style: none; border: 1px solid var(--plugin-divider); border-radius: 14px; }
214
- .dsh-free-model-plugin { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 8px 16px; padding-block: 13px; }
215
- .dsh-free-model-plugin + .dsh-free-model-plugin { border-block-start: 1px solid var(--plugin-divider); }
216
- .dsh-free-model-plugin-name { font-weight: 550; }
217
- .dsh-free-model-plugin p { margin: 2px 0 0; font-size: 13px; color: var(--dsw-alias-label-secondary); overflow-wrap: anywhere; }
218
- .dsh-free-model-plugin-actions { display: flex; flex-wrap: wrap; gap: 6px; }
219
- a.dsh-free-model-plugin-action {
220
- background: var(--dsw-static-neutral-bluish-1000, #0f1115); color: #fff; border-color: rgb(255 255 255 / 18%);
221
- }
222
- a.dsh-free-model-plugin-action:hover { background: var(--dsw-static-neutral-bluish-850, #2c2c2e); }
223
- a.dsh-free-model-plugin-action:focus-visible { outline-color: var(--dsw-alias-label-primary, #0f1115); }
224
- .dsh-free-model-plugin-action:disabled { cursor: default; background: transparent; color: var(--dsw-alias-label-secondary); }
225
- .dsh-free-model-plugin-action[data-state='installed'] { border-color: transparent; background: color-mix(in srgb, currentColor 6%, transparent); }
226
- .dsh-free-model-plugin .dsh-free-model-error { grid-column: 1 / -1; color: var(--dsw-alias-state-warn-label, #a1421c); }
227
- @container (max-width: 370px) {
228
- .dsh-free-model-plugin { grid-template-columns: minmax(0, 1fr); }
229
- .dsh-free-model-plugins { padding-inline: 12px; }
230
- }
231
- `;
232
-
233
- async function request(path, signal, body) {
234
- const headers = { accept: 'application/json' };
235
- if (body !== undefined) headers['content-type'] = 'application/json';
236
- const response = await fetch(path, {
237
- method: body === undefined ? 'GET' : 'POST', headers, cache: 'no-store', signal,
238
- ...(body === undefined ? {} : { body: JSON.stringify(body) }),
239
- });
240
- const data = await response.json().catch(() => undefined);
241
- if (!response.ok) throw new Error(typeof data?.error === 'string' ? data.error : '');
242
- return data;
243
- }
244
-
245
- function monitorUpdates(ctx) {
246
- let update = null;
247
- const listeners = new Set();
248
- ctx.effect(() => {
249
- const controller = new AbortController();
250
- const { signal } = controller;
251
- let checking = false;
252
- async function refresh() {
253
- if (checking || signal.aborted) return;
254
- checking = true;
255
- let next = update && { currentVersion: update.currentVersion };
256
- try {
257
- const data = await request(updatePath, signal);
258
- if (typeof data?.currentVersion === 'string') {
259
- next = { currentVersion: data.currentVersion };
260
- if (data.status === 'update_available' && typeof data.latestVersion === 'string') {
261
- next.latestVersion = data.latestVersion;
262
- }
263
- }
264
- } catch {
265
- // The update request is independent of the model list.
266
- } finally {
267
- checking = false;
268
- }
269
- if (signal.aborted || (update?.currentVersion === next?.currentVersion
270
- && update?.latestVersion === next?.latestVersion)) return;
271
- update = next;
272
- for (const listener of listeners) listener();
273
- }
274
- const recheck = () => { void refresh(); };
275
- const timer = window.setInterval(recheck, updateCheckInterval);
276
- window.addEventListener('focus', recheck);
277
- recheck();
278
- return () => {
279
- controller.abort();
280
- window.clearInterval(timer);
281
- window.removeEventListener('focus', recheck);
282
- };
283
- }, 'free-model: update checks');
284
- return {
285
- getSnapshot: () => update,
286
- subscribe(listener) {
287
- listeners.add(listener);
288
- return () => listeners.delete(listener);
289
- },
290
- };
291
- }
292
-
293
- function UpdateBanner({ ctx, t, update }) {
294
- if (!update?.latestVersion) return null;
295
-
296
- function openDetails(event) {
297
- if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
298
- try {
299
- const navigation = ctx.get('pluginNavigation');
300
- if (typeof navigation?.openBundle !== 'function') return;
301
- navigation.openBundle(packageName);
302
- event.preventDefault();
303
- } catch {
304
- // The link leads to npm if plugin management is unavailable.
305
- }
306
- }
307
- return h('div', { className: 'dsh-free-model-update-banner' },
308
- h('p', { className: 'dsh-free-model-update-banner-content' },
309
- h('strong', { className: 'dsh-free-model-update-title' }, t('updateTitle')),
310
- h('span', { className: 'dsh-free-model-update-version' }, `v${update.latestVersion}`),
311
- ),
312
- h('a', { className: 'dsh-free-model-update-action', href: `https://www.npmjs.com/package/${packageName}`,
313
- target: '_blank', rel: 'noopener noreferrer', onClick: openDetails }, t('updateDetails')),
314
- );
315
- }
316
-
317
- function HeaderLinks({ t, currentVersion }) {
318
- const label = t('viewProject');
319
- return h('div', { className: 'dsh-free-model-header-links' },
320
- currentVersion && h('span', { className: 'dsh-free-model-version' }, `v${currentVersion}`),
321
- h('a', { className: 'dsh-free-model-project-link', href: repositoryUrl, target: '_blank',
322
- rel: 'noopener noreferrer', title: label, 'aria-label': label },
323
- h('svg', { width: 18, height: 18, viewBox: '0 0 16 16', fill: 'currentColor', 'aria-hidden': true, focusable: 'false' },
324
- h('path', { d: 'M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8z' }),
325
- ),
326
- ),
327
- );
328
- }
329
-
330
- function rpcValue(reply) {
331
- if (!reply?.ok) throw new Error(reply?.error?.message);
332
- return reply.value;
333
- }
334
-
335
- function createPluginInstaller(ctx) {
336
- const listeners = new Set();
337
- const initial = { inventory: 'unavailable', installed: new Set(), pending: null, error: null };
338
- let state = initial;
339
- let manager;
340
- let revision = 0;
341
-
342
- function update(changes) {
343
- state = { ...state, ...changes };
344
- for (const listener of listeners) listener();
345
- }
346
-
347
- async function refresh() {
348
- if (!manager) return;
349
- const current = ++revision;
350
- try {
351
- const bundles = rpcValue(await manager.listBundles());
352
- const installed = new Set(bundles.filter(bundle =>
353
- bundle.installed || bundle.availability === 'profile' || bundle.availability === 'installation')
354
- .map(bundle => bundle.name));
355
- if (current === revision) update({ inventory: 'ready', installed, error: installed.has(state.error?.name) ? null : state.error });
356
- } catch {
357
- if (current === revision) update({ inventory: 'failed' });
358
- }
359
- }
360
-
361
- ctx.inject(['remote', 'remote.pluginManager'], scope => {
362
- scope.effect(() => {
363
- manager = scope.remote.pluginManager;
364
- const recheck = () => { if (listeners.size) void refresh(); };
365
- const unsubscribe = scope.remote.$on('plugin-manager/changed', recheck);
366
- const reset = scope.on('connection/reset', recheck);
367
- window.addEventListener('focus', recheck);
368
- update({ ...initial, inventory: 'loading' });
369
- recheck();
370
- return () => {
371
- manager = undefined;
372
- revision++;
373
- update(initial);
374
- unsubscribe();
375
- reset();
376
- window.removeEventListener('focus', recheck);
377
- };
378
- }, 'free-model: plugin inventory');
379
- });
380
-
381
- async function install(name) {
382
- if (!manager || state.inventory !== 'ready' || state.pending || state.installed.has(name)) return;
383
- const host = manager;
384
- update({ pending: name, error: null });
385
- try {
386
- const info = rpcValue(await host.inspect(name, { registry: npmRegistry }));
387
- if (host !== manager) return;
388
- if (info.status !== 'accepted') throw new Error(info.reason);
389
- if (info.registry !== npmRegistry || info.name !== name || info.bundle !== true
390
- || typeof info.version !== 'string' || !publishedVersion.test(info.version)) throw new Error();
391
-
392
- const requestId = globalThis.crypto?.randomUUID?.();
393
- const options = {
394
- enabled: true, registry: npmRegistry, expected: { name, version: info.version },
395
- ...(requestId && { requestId }),
396
- };
397
- let result;
398
- try {
399
- result = rpcValue(await host.installBundle(`${name}@${info.version}`, options));
400
- } catch (error) {
401
- // A lost reply can leave pnpm running. Join that request before allowing a retry.
402
- if (!requestId || host !== manager) throw error;
403
- result = rpcValue(await host.waitForInstall(requestId));
404
- if (!result) throw error;
405
- }
406
- if (!['applied', 'restart-required', 'overridden'].includes(result.application)) {
407
- throw new Error(result.error?.diagnostic || result.error?.code);
408
- }
409
- } catch (error) {
410
- if (host === manager) update({ error: { name, message: error.message } });
411
- } finally {
412
- if (host === manager) {
413
- await refresh();
414
- if (host === manager) update({ pending: null });
415
- }
416
- }
417
- }
418
-
419
- return {
420
- getSnapshot: () => state,
421
- subscribe(listener) {
422
- listeners.add(listener);
423
- if (listeners.size === 1) void refresh();
424
- return () => listeners.delete(listener);
425
- },
426
- install, refresh,
427
- };
428
- }
429
-
430
- function PluginInstallButton({ name, installer, state, t }) {
431
- let label = 'install';
432
- if (state.pending === name) label = 'installing';
433
- else if (state.inventory === 'unavailable') label = 'installUnavailable';
434
- else if (state.inventory === 'failed') label = 'retryInventory';
435
- else if (state.inventory === 'loading') label = 'checkInstall';
436
- else if (state.installed.has(name)) label = 'installed';
437
- return h('button', { type: 'button', className: 'dsh-free-model-plugin-action',
438
- 'data-state': label, 'aria-label': t('installAction', { name, action: t(label) }),
439
- disabled: !!state.pending || (label !== 'install' && label !== 'retryInventory'),
440
- onClick: () => { void (label === 'retryInventory' ? installer.refresh() : installer.install(name)); },
441
- }, t(label));
442
- }
443
-
444
- function PluginRecommendations({ installer, t }) {
445
- const headingId = useId();
446
- const state = useSyncExternalStore(installer.subscribe, installer.getSnapshot);
447
- return h('section', { className: 'dsh-free-model-recommendations', 'aria-labelledby': headingId },
448
- h('h2', { id: headingId }, t('otherPlugins')),
449
- h('ul', { className: 'dsh-free-model-plugins' }, recommendedPlugins.map(({ name, description, stores }) =>
450
- h('li', { key: name, className: 'dsh-free-model-plugin' },
451
- h('div', null,
452
- h('span', { className: 'dsh-free-model-plugin-name' }, name),
453
- h('p', null, t(description)),
454
- ),
455
- h('div', { className: 'dsh-free-model-plugin-actions', 'aria-live': 'polite' },
456
- stores ? stores.map(store =>
457
- h('a', { key: store.label, className: 'dsh-free-model-plugin-action', href: store.href,
458
- target: '_blank', rel: 'noopener noreferrer', 'aria-label': t('storeLabel', { name, store: t(store.label) }) }, t(store.label)),
459
- ) : h(PluginInstallButton, { name, installer, state, t }),
460
- ),
461
- state.error?.name === name && !state.installed.has(name) && h('p', { className: 'dsh-free-model-error', role: 'alert' },
462
- t('installError'), state.error.message && ` ${state.error.message}`),
463
- ),
464
- )),
465
- state.inventory === 'failed' && h('p', { className: 'dsh-free-model-error', role: 'alert' }, t('inventoryError')),
466
- );
467
- }
468
-
469
- function parseAvailability(data) {
470
- if (typeof data?.checking !== 'boolean' || !Array.isArray(data.models)
471
- || (data.retryAt !== undefined && !Number.isFinite(data.retryAt))
472
- || !data.models.every(result => typeof result?.id === 'string' && resultStatuses.has(result.status))) {
473
- throw new Error();
474
- }
475
- return data;
476
- }
477
-
478
- function ModelPage({ ctx, t, updates, installer }) {
479
- const headingId = useId();
480
- const update = useSyncExternalStore(updates.subscribe, updates.getSnapshot);
481
- const writes = useRef(new Map());
482
- const checkRequest = useRef(null);
483
- const [models, setModels] = useState(null);
484
- const [loadError, setLoadError] = useState(null);
485
- const [loading, setLoading] = useState(true);
486
- const [revision, setRevision] = useState(0);
487
- const [rows, setRows] = useState(new Map());
488
- const [availability, setAvailability] = useState(emptyAvailability);
489
- const [availabilityError, setAvailabilityError] = useState(null);
490
- const [starting, setStarting] = useState(false);
491
- const [cooldown, setCooldown] = useState(false);
492
-
493
- useEffect(() => {
494
- const controller = new AbortController();
495
- const { signal } = controller;
496
- // An active check is kept current by its dedicated polling request.
497
- const polling = availability.checking;
498
- const path = revision > 0 ? `${apiPath}?refresh=1` : apiPath;
499
- request(path, signal).then(data => {
500
- if (!Array.isArray(data?.models) || !data.models.every(model => (
501
- typeof model?.id === 'string' && typeof model?.name === 'string' && typeof model?.enabled === 'boolean'
502
- ))) throw new Error();
503
- if (signal.aborted) return;
504
- setModels(data.models);
505
- if (!polling && data.availability !== undefined) setAvailability(parseAvailability(data.availability));
506
- }).catch(error => {
507
- if (!signal.aborted) setLoadError(error.message);
508
- }).finally(() => {
509
- if (!signal.aborted) setLoading(false);
510
- });
511
- return () => controller.abort();
512
- }, [revision]);
513
-
514
- useEffect(() => {
515
- const active = writes.current;
516
- return () => {
517
- for (const controller of active.values()) controller.abort();
518
- active.clear();
519
- checkRequest.current?.abort();
520
- };
521
- }, []);
522
-
523
- useEffect(() => {
524
- if (!availability.checking) return;
525
- const controller = new AbortController();
526
- const { signal } = controller;
527
- let timer = setTimeout(poll, 1000);
528
- async function poll() {
529
- try {
530
- const snapshot = parseAvailability(await request(availabilityPath, signal));
531
- if (signal.aborted) return;
532
- setAvailability(snapshot);
533
- if (snapshot.checking) timer = setTimeout(poll, 1000);
534
- } catch (error) {
535
- if (signal.aborted) return;
536
- setAvailability(current => ({ ...current, checking: false, retryAt: undefined }));
537
- setAvailabilityError(error.message || t('checkProgressError'));
538
- }
539
- }
540
- return () => {
541
- clearTimeout(timer);
542
- controller.abort();
543
- };
544
- }, [availability.checking]);
545
-
546
- useEffect(() => {
547
- let timer;
548
- function updateCooldown() {
549
- const delay = (availability.retryAt ?? 0) - Date.now();
550
- setCooldown(delay > 0);
551
- if (delay > 0) timer = setTimeout(updateCooldown, Math.min(delay, 2_147_483_647));
552
- }
553
- updateCooldown();
554
- return () => clearTimeout(timer);
555
- }, [availability.retryAt]);
556
-
557
- function refresh() {
558
- if (loading || writes.current.size || checkRequest.current) return;
559
- setLoading(true);
560
- setLoadError(null);
561
- setAvailabilityError(null);
562
- setRows(new Map());
563
- setRevision(value => value + 1);
564
- }
565
-
566
- async function checkAvailability() {
567
- if (loading || checkRequest.current || availability.checking || availability.retryAt > Date.now()) return;
568
- const controller = new AbortController();
569
- const { signal } = controller;
570
- checkRequest.current = controller;
571
- setStarting(true);
572
- setAvailabilityError(null);
573
- try {
574
- const snapshot = parseAvailability(await request(availabilityPath, signal, {}));
575
- if (!signal.aborted) setAvailability(snapshot);
576
- } catch (error) {
577
- if (!signal.aborted) setAvailabilityError(error.message || t('checkError'));
578
- } finally {
579
- checkRequest.current = null;
580
- if (!signal.aborted) setStarting(false);
581
- }
582
- }
583
-
584
- function setRow(id, state) {
585
- setRows(previous => {
586
- const next = new Map(previous);
587
- if (state === undefined) next.delete(id);
588
- else next.set(id, state);
589
- return next;
590
- });
591
- }
592
-
593
- async function changeVisibility(id, enabled) {
594
- if (loading || writes.current.has(id)) return;
595
- const controller = new AbortController();
596
- const { signal } = controller;
597
- writes.current.set(id, controller);
598
- setRow(id, { saving: true });
599
- try {
600
- const saved = await request(apiPath, signal, { id, enabled });
601
- if (saved?.id !== id || saved.enabled !== enabled) throw new Error();
602
- if (signal.aborted) return;
603
- setModels(current => current.map(model => model.id === id ? { ...model, enabled } : model));
604
- setRow(id, undefined);
605
- } catch (error) {
606
- if (!signal.aborted) setRow(id, { error: error.message });
607
- } finally {
608
- if (writes.current.get(id) === controller) writes.current.delete(id);
609
- }
610
- }
611
-
612
- const checking = starting || availability.checking;
613
- const results = new Map(availability.models.map(result => [result.id, result]));
614
- return h('section', { className: 'dsh-free-model-page', 'aria-labelledby': headingId },
615
- h('div', { className: 'dsh-free-model-content' },
616
- h(UpdateBanner, { ctx, t, update }),
617
- h('header', { className: 'dsh-free-model-header' },
618
- h('h1', { id: headingId }, t('title')),
619
- h(HeaderLinks, { t, currentVersion: update?.currentVersion }),
620
- h('p', { className: 'dsh-free-model-hint' }, t('hint')),
621
- ),
622
- h('div', { className: 'dsh-free-model-actions' },
623
- h(Button, {
624
- variant: 'outline', size: 'sm', onClick: checkAvailability,
625
- disabled: loading || checking || cooldown || !models?.length,
626
- }, t(checking ? 'checkingAvailability' : cooldown ? 'checkCooldown' : 'checkAvailability')),
627
- h(Button, { variant: 'outline', size: 'sm', onClick: refresh, disabled: loading || starting || writes.current.size > 0 }, t('refresh')),
628
- ),
629
- loading && h('p', { className: 'dsh-free-model-status', role: 'status' }, t('loading')),
630
- loadError !== null && h('p', { className: 'dsh-free-model-status dsh-free-model-error', role: 'alert' }, loadError || t('loadError')),
631
- availabilityError !== null && h('p', { className: 'dsh-free-model-status dsh-free-model-error', role: 'alert' }, availabilityError),
632
- !loading && loadError === null && models?.length === 0
633
- && h('p', { className: 'dsh-free-model-status', role: 'status' }, t('empty')),
634
- models?.length > 0 && h('ul', { className: 'dsh-free-model-list', 'aria-labelledby': headingId },
635
- models.map(model => {
636
- const state = rows.get(model.id);
637
- const result = results.get(model.id);
638
- const status = result && (result.status !== 'checking' || availability.checking) ? result.status : 'unchecked';
639
- const checkedAt = Number.isFinite(result?.checkedAt)
640
- ? t('checkedAt', { time: new Date(result.checkedAt).toLocaleString() })
641
- : undefined;
642
- const elapsedMs = result?.elapsedMs;
643
- const showDuration = (status === 'available' || status === 'unavailable')
644
- && result.reason !== 'TIMEOUT' && Number.isSafeInteger(elapsedMs) && elapsedMs >= 0;
645
- return h('li', { className: 'dsh-free-model-row', key: model.id, 'aria-busy': state?.saving === true },
646
- h('div', null,
647
- h('div', { className: 'dsh-free-model-row-heading' },
648
- h('span', { className: 'dsh-free-model-name' }, model.name),
649
- h('span', { className: 'dsh-free-model-badge', 'data-status': status, title: checkedAt }, t(status)),
650
- status === 'unavailable' && h('span', { className: 'dsh-free-model-reason' }, t(reasonKeys.get(result.reason) ?? 'reasonUnknown')),
651
- showDuration && h('span', { className: 'dsh-free-model-duration' }, `${elapsedMs} ms`),
652
- ),
653
- h('code', { className: 'dsh-free-model-id' }, model.id),
654
- ),
655
- h(Switch, {
656
- checked: model.enabled,
657
- disabled: loading || state?.saving === true,
658
- label: t('toggle', { name: model.name }),
659
- onChange: enabled => { void changeVisibility(model.id, enabled); },
660
- }),
661
- state?.error !== undefined
662
- && h('p', { className: 'dsh-free-model-error', role: 'alert' }, state.error || t('saveError')),
663
- );
664
- }),
665
- ),
666
- h(PluginRecommendations, { installer, t }),
667
- ),
668
- );
669
- }
670
-
671
- function SidebarIcon({ size }) {
672
- const Icon = IconSparkleRegular ?? IconSparkle16;
673
- return Icon ? h(Icon, { size }) : null;
674
- }
675
-
676
- function SidebarUpdateBadge({ t, updates, wide }) {
677
- const update = useSyncExternalStore(updates.subscribe, updates.getSnapshot);
678
- if (!update?.latestVersion) return null;
679
- if (wide) return h('span', { className: 'dsh-free-model-update-badge' }, t('updateBadge'));
680
- return h('span', { className: 'dsh-free-model-update-dot' },
681
- h('span', { className: 'dsh-free-model-update-sr' }, t('updateBadge')),
682
- );
683
- }
684
-
685
- function apply(ctx) {
686
- ctx.effect(() => ctx.locale.register(panelId, messages), 'free-model: translations');
687
- const t = ctx.locale.bind(panelId);
688
- const updates = monitorUpdates(ctx);
689
- const installer = createPluginInstaller(ctx);
690
- ctx.effect(() => {
691
- const style = document.createElement('style');
692
- style.textContent = styles;
693
- document.head.append(style);
694
- return () => style.remove();
695
- }, 'free-model: styles');
696
- ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
697
- name: 'sidebar.panellist', id: panelId, order: 30, label: () => t('title'),
698
- }, SidebarIcon));
699
- ctx.slots.inject('sidebar.panellist.trailing', () => ctx.slots.register({
700
- name: 'sidebar.panellist.trailing', id: panelId, locale: panelId,
701
- }, function Trailing(props) { return h(SidebarUpdateBadge, { ...props, updates }); }));
702
- ctx.slots.inject('main', () => ctx.slots.register({
703
- name: 'main', key: panelId, locale: panelId,
704
- }, function Panel(props) { return h(ModelPage, { ...props, ctx, updates, installer }); }));
705
- }
706
-
707
- return { inject: ['locale', 'slots'], apply };
708
- },
709
- });