odant-work 1.0.20 → 1.0.22

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 (36) hide show
  1. package/#system/package-manifest.json +37 -24
  2. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +21 -2
  3. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/file.js +58 -0
  4. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/readme.md +2 -2
  5. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/feed.js +2 -11
  6. package/$server/$folder/lib/chat-item/chat-item.js +17 -1
  7. package/$server/$folder/lib/local-models-transfer/local-models-transfer.js +972 -0
  8. package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +408 -111
  9. package/MODELS/Local/$provider/handlers/methods/transfer/$handler/class.js +41 -0
  10. package/logo.png +0 -0
  11. package/package.json +1 -1
  12. package/rules/threats.md +117 -116
  13. package/sources/client.js +1 -0
  14. package/sources/data/progress.md +15 -0
  15. package/sources/host/auto-updater.js +6 -2
  16. package/sources/host/http-server.js +23 -0
  17. package/sources/host/websocket.js +127 -120
  18. package/sources/modules/agent/index.js +6 -1
  19. package/sources/modules/agent/readme.md +217 -216
  20. package/sources/modules/agent/session.js +43 -8
  21. package/sources/modules/agent/tools/chrome.js +263 -0
  22. package/sources/modules/bridge/chrome.js +673 -0
  23. package/sources/modules/bridge/hub.js +395 -361
  24. package/sources/modules/chrome-extension/background.js +299 -0
  25. package/sources/modules/chrome-extension/manifest.json +25 -0
  26. package/sources/modules/chrome-extension/options.html +48 -0
  27. package/sources/modules/chrome-extension/options.js +104 -0
  28. package/sources/modules/chrome-extension/popup.html +25 -0
  29. package/sources/modules/chrome-extension/popup.js +32 -0
  30. package/sources/modules/trainer/huggingface.js +412 -65
  31. package/sources/modules/trainer/index.js +288 -1
  32. package/sources/modules/trainer/tar-stream.js +458 -0
  33. package/sources/modules/trainer/transfer.js +1570 -0
  34. package/sources/modules/user-profile/user-profile.js +34 -10
  35. package/sources/modules/user-profile/user-token.js +168 -0
  36. package/sw.js +85 -9
@@ -0,0 +1,972 @@
1
+ /**
2
+ * Единый системный диалог выгрузки и загрузки локальных моделей (/MODELS/Local):
3
+ * - прямой перенос на диск / USB-флешку (с обзорщиком дисков, проверкой места и SHA-256 манифестом);
4
+ * - дополнительный потоковый перенос файлом .tar через браузер (для удалённого доступа).
5
+ */
6
+ const TRANSFER_STYLE = /*css*/`
7
+ :host {
8
+ @apply --vertical;
9
+ gap: 12px;
10
+ padding: 14px 18px;
11
+ width: min(820px, 92vw);
12
+ max-height: 78vh;
13
+ overflow-y: auto;
14
+ box-sizing: border-box;
15
+ background: var(--content-background, #ffffff);
16
+ color: var(--content-color, #1e293b);
17
+ font-size: 13px;
18
+ }
19
+ .row {
20
+ display: flex;
21
+ align-items: center;
22
+ gap: 8px;
23
+ flex-wrap: wrap;
24
+ }
25
+ .between {
26
+ justify-content: space-between;
27
+ }
28
+ .tabs {
29
+ display: flex;
30
+ gap: 4px;
31
+ border-bottom: 1px solid var(--border-color, #cbd5e1);
32
+ }
33
+ .tab-btn {
34
+ appearance: none;
35
+ border: none;
36
+ border-bottom: 2px solid transparent;
37
+ background: transparent;
38
+ color: inherit;
39
+ opacity: 0.72;
40
+ padding: 7px 14px;
41
+ font-size: 13px;
42
+ font-weight: 600;
43
+ cursor: pointer;
44
+ display: inline-flex;
45
+ align-items: center;
46
+ gap: 6px;
47
+ }
48
+ .tab-btn:hover { opacity: 1; }
49
+ .tab-btn.active {
50
+ opacity: 1;
51
+ color: var(--accent-color, #2563eb);
52
+ border-bottom-color: var(--accent-color, #2563eb);
53
+ }
54
+ .pill {
55
+ appearance: none;
56
+ display: inline-flex;
57
+ align-items: center;
58
+ gap: 6px;
59
+ padding: 5px 11px;
60
+ border-radius: 6px;
61
+ border: 1px solid var(--border-color, #cbd5e1);
62
+ background: var(--subtle-background, #f8fafc);
63
+ color: inherit;
64
+ font-size: 12px;
65
+ font-weight: 600;
66
+ cursor: pointer;
67
+ }
68
+ .pill.active {
69
+ background: var(--accent-color, #2563eb);
70
+ border-color: var(--accent-color, #2563eb);
71
+ color: #ffffff;
72
+ }
73
+ .card {
74
+ display: flex;
75
+ flex-direction: column;
76
+ gap: 8px;
77
+ padding: 11px 13px;
78
+ border-radius: 8px;
79
+ border: 1px solid var(--border-color, #cbd5e1);
80
+ background: var(--subtle-background, #f8fafc);
81
+ }
82
+ .sec-title {
83
+ font-size: 11.5px;
84
+ font-weight: 700;
85
+ text-transform: uppercase;
86
+ letter-spacing: 0.04em;
87
+ opacity: 0.75;
88
+ }
89
+ .roots-bar {
90
+ display: flex;
91
+ flex-wrap: wrap;
92
+ gap: 6px;
93
+ }
94
+ .root-chip {
95
+ display: inline-flex;
96
+ align-items: center;
97
+ gap: 6px;
98
+ padding: 5px 10px;
99
+ border-radius: 6px;
100
+ border: 1px solid var(--border-color, #cbd5e1);
101
+ background: var(--content-background, #ffffff);
102
+ color: inherit;
103
+ font-size: 12px;
104
+ cursor: pointer;
105
+ }
106
+ .root-chip:hover {
107
+ border-color: var(--accent-color, #2563eb);
108
+ background: var(--accent-soft, rgba(37, 99, 235, 0.08));
109
+ }
110
+ .root-chip.selected {
111
+ border-color: var(--accent-color, #2563eb);
112
+ background: var(--accent-soft, rgba(37, 99, 235, 0.12));
113
+ font-weight: 600;
114
+ }
115
+ .dirs-list {
116
+ max-height: 155px;
117
+ overflow-y: auto;
118
+ border: 1px solid var(--border-color, #cbd5e1);
119
+ border-radius: 6px;
120
+ background: var(--content-background, #ffffff);
121
+ }
122
+ .dir-item {
123
+ display: flex;
124
+ align-items: center;
125
+ justify-content: space-between;
126
+ gap: 8px;
127
+ padding: 5px 10px;
128
+ cursor: pointer;
129
+ border-bottom: 1px solid var(--border-color, #e2e8f0);
130
+ font-size: 12.5px;
131
+ }
132
+ .dir-item:last-child { border-bottom: none; }
133
+ .dir-item:hover { background: var(--accent-soft, rgba(37, 99, 235, 0.08)); }
134
+ .items-list {
135
+ max-height: 210px;
136
+ overflow-y: auto;
137
+ display: flex;
138
+ flex-direction: column;
139
+ gap: 5px;
140
+ }
141
+ .item-row {
142
+ display: flex;
143
+ align-items: center;
144
+ justify-content: space-between;
145
+ gap: 10px;
146
+ padding: 6px 10px;
147
+ border-radius: 6px;
148
+ border: 1px solid var(--border-color, #cbd5e1);
149
+ background: var(--content-background, #ffffff);
150
+ font-size: 12.5px;
151
+ }
152
+ .badge {
153
+ display: inline-flex;
154
+ align-items: center;
155
+ padding: 2px 7px;
156
+ border-radius: 999px;
157
+ font-size: 11px;
158
+ font-weight: 600;
159
+ white-space: nowrap;
160
+ }
161
+ .badge.ok {
162
+ background: light-dark(#dcfce7, #14532d);
163
+ color: light-dark(#166534, #bbf7d0);
164
+ }
165
+ .badge.warn {
166
+ background: light-dark(#fef3c7, #451a03);
167
+ color: light-dark(#92400e, #fde68a);
168
+ }
169
+ .badge.info {
170
+ background: var(--accent-soft, rgba(37, 99, 235, 0.12));
171
+ color: var(--accent-color, #2563eb);
172
+ }
173
+ input[type="text"], input:not([type]) {
174
+ padding: 6px 10px;
175
+ font-size: 12.5px;
176
+ border: 1px solid var(--border-color, #cbd5e1);
177
+ border-radius: 6px;
178
+ background: var(--content-background, #ffffff);
179
+ color: inherit;
180
+ min-width: 0;
181
+ }
182
+ .btn {
183
+ display: inline-flex;
184
+ align-items: center;
185
+ gap: 6px;
186
+ padding: 6px 12px;
187
+ font-size: 12.5px;
188
+ font-weight: 600;
189
+ border-radius: 6px;
190
+ border: 1px solid var(--border-color, #cbd5e1);
191
+ background: var(--content-background, #ffffff);
192
+ color: inherit;
193
+ cursor: pointer;
194
+ white-space: nowrap;
195
+ }
196
+ .btn:disabled {
197
+ opacity: 0.48;
198
+ cursor: not-allowed;
199
+ }
200
+ .btn.primary {
201
+ background: var(--accent-color, #2563eb);
202
+ border-color: var(--accent-color, #2563eb);
203
+ color: #ffffff;
204
+ }
205
+ .btn.danger {
206
+ color: light-dark(#b91c1c, #fca5a5);
207
+ border-color: light-dark(#fecaca, #7f1d1d);
208
+ }
209
+ .msg {
210
+ padding: 8px 11px;
211
+ border-radius: 6px;
212
+ font-size: 12.5px;
213
+ }
214
+ .msg.ok {
215
+ background: light-dark(#dcfce7, #14532d);
216
+ color: light-dark(#166534, #bbf7d0);
217
+ }
218
+ .msg.err {
219
+ background: light-dark(#fee2e2, #450a0a);
220
+ color: light-dark(#991b1b, #fecaca);
221
+ }
222
+ .progress-track {
223
+ width: 100%;
224
+ height: 7px;
225
+ background: var(--border-color, #e2e8f0);
226
+ border-radius: 4px;
227
+ overflow: hidden;
228
+ }
229
+ .progress-fill {
230
+ height: 100%;
231
+ background: var(--accent-color, #2563eb);
232
+ transition: width 0.2s ease;
233
+ }
234
+ `;
235
+
236
+ function fmtGb(bytes) {
237
+ const n = Number(bytes) || 0;
238
+ if (n > 0 && n < 10 * 1024 * 1024)
239
+ return `${Math.max(0.1, +(n / (1024 * 1024)).toFixed(1))} МБ`;
240
+ return `${(n / (1024 ** 3)).toFixed(2)} ГБ`;
241
+ }
242
+
243
+ function fmtEta(sec) {
244
+ const s = Number(sec);
245
+ if (!Number.isFinite(s) || s <= 0)
246
+ return '';
247
+ if (s < 60)
248
+ return `~${s} с`;
249
+ const m = Math.floor(s / 60);
250
+ const rem = s % 60;
251
+ return `~${m} мин ${rem} с`;
252
+ }
253
+
254
+ ODA({
255
+ is: 'item-local-models-transfer',
256
+ imports: 'oda//icon',
257
+ template: /*html*/`
258
+ <style>${TRANSFER_STYLE}</style>
259
+
260
+ <div class="msg ok" ~if="notice">{{notice}}</div>
261
+ <div class="msg err" ~if="error">{{error}}</div>
262
+
263
+ <!-- Активные или недавно завершённые задачи переноса -->
264
+ <div class="card" ~if="activeJobs.length">
265
+ <div class="sec-title">Выполняется перенос</div>
266
+ <div ~for="activeJobs" style="display:flex;flex-direction:column;gap:5px;">
267
+ <div class="row between">
268
+ <div>
269
+ <strong>{{$for.item.label}}</strong>
270
+ <span style="opacity:0.78;font-size:12px;">
271
+ <span ~if="$for.item.currentItem"> · {{$for.item.currentItem}}</span>
272
+ <span ~if="$for.item.currentFile"> ({{$for.item.currentFile}})</span>
273
+ </span>
274
+ </div>
275
+ <div class="row">
276
+ <span style="font-size:12px;font-weight:600;">
277
+ {{$for.item.progress || 0}}% · {{fmtSize($for.item.copiedBytes)}} / {{fmtSize($for.item.totalBytes)}} · {{$for.item.speedMBs || 0}} МБ/с {{fmtTime($for.item.etaSeconds)}}
278
+ </span>
279
+ <button type="button" class="btn danger" @tap="cancelJob($for.item.id)">Отменить</button>
280
+ </div>
281
+ </div>
282
+ <div class="progress-track">
283
+ <div class="progress-fill" ~style="{width: ($for.item.progress || 0) + '%'}"></div>
284
+ </div>
285
+ </div>
286
+ </div>
287
+
288
+ <!-- Прогресс загрузки .tar через браузер (XHR) -->
289
+ <div class="card" ~if="tarUploading">
290
+ <div class="row between">
291
+ <strong>Отправка и установка архива .tar…</strong>
292
+ <span style="font-size:12px;font-weight:600;">{{tarUploadProgress}}%</span>
293
+ </div>
294
+ <div class="progress-track">
295
+ <div class="progress-fill" ~style="{width: tarUploadProgress + '%'}"></div>
296
+ </div>
297
+ </div>
298
+
299
+ <!-- Вкладки Выгрузка / Загрузка -->
300
+ <div class="row between">
301
+ <div class="tabs">
302
+ <button type="button" class="tab-btn" ~class="{'active': mode === 'export'}" @tap="switchMode('export')">
303
+ <oda-icon icon="carbon:upload" icon-size="16"></oda-icon>
304
+ <span>Выгрузить (Бэкап)</span>
305
+ </button>
306
+ <button type="button" class="tab-btn" ~class="{'active': mode === 'import'}" @tap="switchMode('import')">
307
+ <oda-icon icon="carbon:download" icon-size="16"></oda-icon>
308
+ <span>Загрузить (Восстановить)</span>
309
+ </button>
310
+ </div>
311
+ <div class="row">
312
+ <button type="button" class="pill" ~class="{'active': transport === 'disk'}" @tap="transport = 'disk'">
313
+ <oda-icon icon="carbon:usb" icon-size="14"></oda-icon>
314
+ <span>Диск / Флешка</span>
315
+ </button>
316
+ <button type="button" class="pill" ~class="{'active': transport === 'tar'}" @tap="transport = 'tar'">
317
+ <oda-icon icon="icons:archive" icon-size="14"></oda-icon>
318
+ <span>Файл .tar (браузер)</span>
319
+ </button>
320
+ </div>
321
+ </div>
322
+
323
+ <!-- ОБЗОРЩИК ДИСКОВ И ПАПОК СЕРВЕРА (для обоих режимов на диске/флешке) -->
324
+ <div class="card" ~if="transport === 'disk'">
325
+ <div class="row between">
326
+ <span class="sec-title">{{mode === 'export' ? 'Куда выгрузить (диск или флешка)' : 'Откуда загрузить (папка с бэкапом)'}}</span>
327
+ <span style="font-size:12px;opacity:0.8;" ~if="dirInfo">
328
+ Свободно на диске: <strong>{{dirInfo.freeGb}} ГБ</strong> из {{dirInfo.totalGb}} ГБ
329
+ </span>
330
+ </div>
331
+
332
+ <div class="roots-bar" ~if="roots.length">
333
+ <button type="button" class="root-chip" ~for="roots"
334
+ ~class="{'selected': isRootSelected($for.item.path)}"
335
+ @tap="openDir($for.item.path)">
336
+ <oda-icon :icon="$for.item.kind === 'removable' ? 'carbon:usb' : 'carbon:folder'" icon-size="15"></oda-icon>
337
+ <span>{{$for.item.label}} ({{$for.item.freeGb}} ГБ своб.)</span>
338
+ </button>
339
+ </div>
340
+
341
+ <div class="row">
342
+ <button type="button" class="btn" :disabled="!dirInfo?.parentPath" @tap="openDir(dirInfo.parentPath)">Вверх</button>
343
+ <input type="text" style="flex:1;" :value="currentPath" placeholder="Путь на диске или флешке, например E:\\ModelsBackup"
344
+ @input="currentPath = $this.value" @keydown.enter="openDir(currentPath)">
345
+ <button type="button" class="btn" @tap="openDir(currentPath)">Открыть</button>
346
+ <button type="button" class="btn" ~if="mode === 'export'" @tap="promptNewFolder()">+ Папка</button>
347
+ </div>
348
+
349
+ <div class="dirs-list" ~if="dirInfo">
350
+ <div ~if="!dirInfo.dirs?.length" style="padding:8px 10px;opacity:0.65;font-size:12px;">
351
+ Вложенных папок нет
352
+ </div>
353
+ <div class="dir-item" ~for="dirInfo.dirs" @tap="openDir($for.item.path)">
354
+ <div class="row" style="gap:6px;">
355
+ <oda-icon icon="icons:folder" icon-size="16"></oda-icon>
356
+ <span>{{$for.item.name}}</span>
357
+ </div>
358
+ <span class="badge info" ~if="$for.item.hasBackup">Пакет моделей</span>
359
+ </div>
360
+ </div>
361
+ </div>
362
+
363
+ <!-- РЕЖИМ 1: ВЫГРУЗКА -->
364
+ <div ~if="mode === 'export'" style="display:flex;flex-direction:column;gap:10px;">
365
+ <div class="card">
366
+ <div class="row between">
367
+ <span class="sec-title">Что выгрузить из /MODELS/Local</span>
368
+ <div class="row">
369
+ <button type="button" class="btn" @tap="selectAllExport(true)">Выбрать всё</button>
370
+ <button type="button" class="btn" @tap="selectAllExport(false)">Снять всё</button>
371
+ </div>
372
+ </div>
373
+
374
+ <div ~if="!hasAnyExportItem" style="opacity:0.75;padding:6px 0;">
375
+ В /MODELS/Local пока нет установленных моделей, адаптеров или датасетов.
376
+ </div>
377
+
378
+ <div class="items-list" ~if="hasAnyExportItem">
379
+ <label class="item-row" ~for="inventory.models" style="cursor:pointer;">
380
+ <div class="row">
381
+ <input type="checkbox" :checked="selectedExportModels.includes($for.item.id)"
382
+ @change="toggleId('selectedExportModels', $for.item.id, $event.target.checked)">
383
+ <oda-icon :icon="$for.item.icon || 'ai:ollama'" icon-size="18"></oda-icon>
384
+ <div>
385
+ <strong>{{$for.item.label || $for.item.id}}</strong>
386
+ <span style="opacity:0.72;font-size:11.5px;"> ({{$for.item.filesCount}} файлов)</span>
387
+ </div>
388
+ </div>
389
+ <span style="font-weight:600;white-space:nowrap;">{{fmtSize($for.item.sizeBytes)}}</span>
390
+ </label>
391
+
392
+ <label class="item-row" ~for="inventory.adapters" style="cursor:pointer;">
393
+ <div class="row">
394
+ <input type="checkbox" :checked="selectedExportAdapters.includes($for.item.id)"
395
+ @change="toggleId('selectedExportAdapters', $for.item.id, $event.target.checked)">
396
+ <oda-icon icon="carbon:chip" icon-size="18"></oda-icon>
397
+ <div><strong>LoRA-адаптер: {{$for.item.label || $for.item.id}}</strong></div>
398
+ </div>
399
+ <span style="font-weight:600;white-space:nowrap;">{{fmtSize($for.item.sizeBytes)}}</span>
400
+ </label>
401
+
402
+ <label class="item-row" ~for="inventory.datasets" style="cursor:pointer;">
403
+ <div class="row">
404
+ <input type="checkbox" :checked="selectedExportDatasets.includes($for.item.id)"
405
+ @change="toggleId('selectedExportDatasets', $for.item.id, $event.target.checked)">
406
+ <oda-icon icon="icons:archive" icon-size="18"></oda-icon>
407
+ <div><strong>Обучающий датасет: {{$for.item.id}}.jsonl</strong></div>
408
+ </div>
409
+ <span style="font-weight:600;white-space:nowrap;">{{fmtSize($for.item.sizeBytes)}}</span>
410
+ </label>
411
+
412
+ <label class="item-row" ~if="inventory.runtime?.present" style="cursor:pointer;">
413
+ <div class="row">
414
+ <input type="checkbox" :checked="exportIncludeRuntime"
415
+ @change="exportIncludeRuntime = $event.target.checked">
416
+ <oda-icon icon="carbon:chip" icon-size="18"></oda-icon>
417
+ <div><strong>Рантайм локального ИИ (#runtime: Bubo / ROCm)</strong></div>
418
+ </div>
419
+ <span style="font-weight:600;white-space:nowrap;">{{fmtSize(inventory.runtime.sizeBytes)}}</span>
420
+ </label>
421
+ </div>
422
+
423
+ <div class="row between" style="margin-top:4px;">
424
+ <label class="row" style="cursor:pointer;font-size:12px;" ~if="transport === 'disk'">
425
+ <input type="checkbox" :checked="exportOverwrite" @change="exportOverwrite = $event.target.checked">
426
+ <span>Перезаписывать модели, если они уже есть в папке назначения</span>
427
+ </label>
428
+ <span style="font-size:12.5px;">
429
+ Итого к переносу: <strong>{{fmtSize(exportSelectedBytes)}}</strong>
430
+ </span>
431
+ </div>
432
+
433
+ <div class="msg err" ~if="transport === 'disk' && exportInsufficientSpace">
434
+ Недостаточно свободного места на выбранном диске: нужно {{fmtSize(exportSelectedBytes)}}, свободно {{dirInfo?.freeGb}} ГБ.
435
+ </div>
436
+
437
+ <div class="row" style="justify-content:flex-end;margin-top:4px;">
438
+ <button type="button" class="btn primary" ~if="transport === 'disk'"
439
+ :disabled="!exportSelectedBytes || exportInsufficientSpace || !currentPath"
440
+ @tap="startExportDisk()">
441
+ <oda-icon icon="carbon:upload" icon-size="15"></oda-icon>
442
+ <span>Выгрузить на диск / флешку</span>
443
+ </button>
444
+ <button type="button" class="btn primary" ~if="transport === 'tar'"
445
+ :disabled="!exportSelectedBytes"
446
+ @tap="downloadTar()">
447
+ <oda-icon icon="carbon:download" icon-size="15"></oda-icon>
448
+ <span>Скачать архивом (.tar)</span>
449
+ </button>
450
+ </div>
451
+ </div>
452
+ </div>
453
+
454
+ <!-- РЕЖИМ 2: ЗАГРУЗКА (ИМПОРТ) -->
455
+ <div ~if="mode === 'import' && transport === 'disk'" style="display:flex;flex-direction:column;gap:10px;">
456
+ <div class="card">
457
+ <div class="row between">
458
+ <span class="sec-title">Найденные модели в выбранной папке</span>
459
+ <button type="button" class="btn" @tap="inspectSource(currentPath)">Проверить папку</button>
460
+ </div>
461
+
462
+ <div ~if="!sourceInfo" style="opacity:0.75;padding:6px 0;">
463
+ Выберите папку с резервной копией выше.
464
+ </div>
465
+
466
+ <div ~if="sourceInfo && !hasAnySourceItem" style="opacity:0.75;padding:6px 0;">
467
+ В «{{sourceInfo.sourceDir}}» не найдено моделей ИИ, адаптеров или датасетов.
468
+ </div>
469
+
470
+ <div ~if="sourceInfo && hasAnySourceItem" class="items-list">
471
+ <div class="row" style="font-size:12px;opacity:0.8;padding-bottom:2px;" ~if="sourceInfo.hasManifest">
472
+ <span>Манифест проверен ({{sourceInfo.sourceHost || 'локальный ПК'}})</span>
473
+ </div>
474
+
475
+ <label class="item-row" ~for="sourceInfo.models" style="cursor:pointer;">
476
+ <div class="row">
477
+ <input type="checkbox" :checked="selectedImportModels.includes($for.item.id)"
478
+ @change="toggleId('selectedImportModels', $for.item.id, $event.target.checked)">
479
+ <oda-icon :icon="$for.item.icon || 'ai:ollama'" icon-size="18"></oda-icon>
480
+ <div><strong>{{$for.item.label || $for.item.id}}</strong></div>
481
+ <span class="badge warn" ~if="$for.item.alreadyInstalled">Уже установлена</span>
482
+ <span class="badge ok" ~if="!$for.item.alreadyInstalled">Новая</span>
483
+ </div>
484
+ <span style="font-weight:600;white-space:nowrap;">{{fmtSize($for.item.sizeBytes)}}</span>
485
+ </label>
486
+
487
+ <label class="item-row" ~for="sourceInfo.adapters" style="cursor:pointer;">
488
+ <div class="row">
489
+ <input type="checkbox" :checked="selectedImportAdapters.includes($for.item.id)"
490
+ @change="toggleId('selectedImportAdapters', $for.item.id, $event.target.checked)">
491
+ <oda-icon icon="carbon:chip" icon-size="18"></oda-icon>
492
+ <div><strong>LoRA-адаптер: {{$for.item.label || $for.item.id}}</strong></div>
493
+ <span class="badge warn" ~if="$for.item.alreadyInstalled">Уже есть</span>
494
+ </div>
495
+ <span style="font-weight:600;white-space:nowrap;">{{fmtSize($for.item.sizeBytes)}}</span>
496
+ </label>
497
+
498
+ <label class="item-row" ~for="sourceInfo.datasets" style="cursor:pointer;">
499
+ <div class="row">
500
+ <input type="checkbox" :checked="selectedImportDatasets.includes($for.item.id)"
501
+ @change="toggleId('selectedImportDatasets', $for.item.id, $event.target.checked)">
502
+ <oda-icon icon="icons:archive" icon-size="18"></oda-icon>
503
+ <div><strong>Датасет: {{$for.item.id}}.jsonl</strong></div>
504
+ <span class="badge warn" ~if="$for.item.alreadyInstalled">Уже есть</span>
505
+ </div>
506
+ <span style="font-weight:600;white-space:nowrap;">{{fmtSize($for.item.sizeBytes)}}</span>
507
+ </label>
508
+
509
+ <label class="item-row" ~if="sourceInfo.runtime?.present" style="cursor:pointer;">
510
+ <div class="row">
511
+ <input type="checkbox" :checked="importIncludeRuntime"
512
+ @change="importIncludeRuntime = $event.target.checked">
513
+ <oda-icon icon="carbon:chip" icon-size="18"></oda-icon>
514
+ <div><strong>Рантайм (#runtime: Bubo / ROCm)</strong></div>
515
+ <span class="badge warn" ~if="sourceInfo.runtime.alreadyInstalled">Уже есть</span>
516
+ </div>
517
+ <span style="font-weight:600;white-space:nowrap;">{{fmtSize(sourceInfo.runtime.sizeBytes)}}</span>
518
+ </label>
519
+ </div>
520
+
521
+ <div class="row between" style="margin-top:4px;" ~if="sourceInfo && hasAnySourceItem">
522
+ <label class="row" style="cursor:pointer;font-size:12px;">
523
+ <input type="checkbox" :checked="importOverwrite" @change="importOverwrite = $event.target.checked">
524
+ <span>Перезаписывать уже установленные модели</span>
525
+ </label>
526
+ <span style="font-size:12.5px;">
527
+ Будет скопировано: <strong>{{fmtSize(importEffectiveBytes)}}</strong> (своб. {{sourceInfo.localFreeGb}} ГБ)
528
+ </span>
529
+ </div>
530
+
531
+ <div class="row" style="justify-content:flex-end;margin-top:4px;" ~if="sourceInfo && hasAnySourceItem">
532
+ <span ~if="importCopyCount === 0 && importHasAnythingToCopy" style="font-size:12px;opacity:0.75;">
533
+ Все выбранные элементы уже установлены — включите «Перезаписывать» или выберите новые.
534
+ </span>
535
+ <button type="button" class="btn primary" :disabled="importCopyCount === 0"
536
+ @tap="startImportDisk()">
537
+ <oda-icon icon="carbon:download" icon-size="15"></oda-icon>
538
+ <span>Загрузить в /MODELS/Local</span>
539
+ </button>
540
+ </div>
541
+ </div>
542
+ </div>
543
+
544
+ <!-- РЕЖИМ 2B: ЗАГРУЗКА .TAR ЧЕРЕЗ БРАУЗЕР -->
545
+ <div ~if="mode === 'import' && transport === 'tar'" class="card">
546
+ <div class="sec-title">Загрузить модели из архива .tar</div>
547
+ <div style="font-size:12.5px;opacity:0.85;">
548
+ Выберите ранее выгруженный файл <code>.tar</code> — сервер распакует его потоком с проверкой манифеста и автоматически зарегистрирует модели в <code>/MODELS/Local</code>.
549
+ </div>
550
+ <div class="row">
551
+ <input id="tarFileInput" type="file" accept=".tar,application/x-tar" @change="onTarFilePicked($event)">
552
+ </div>
553
+ <label class="row" style="cursor:pointer;font-size:12px;">
554
+ <input type="checkbox" :checked="importOverwrite" @change="importOverwrite = $event.target.checked">
555
+ <span>Перезаписывать уже установленные модели</span>
556
+ </label>
557
+ <div class="row" style="justify-content:flex-end;">
558
+ <button type="button" class="btn primary" :disabled="!tarFile || tarUploading" @tap="uploadTar()">
559
+ <oda-icon icon="carbon:upload" icon-size="15"></oda-icon>
560
+ <span>Загрузить .tar в /MODELS/Local</span>
561
+ </button>
562
+ </div>
563
+ </div>
564
+ `,
565
+
566
+ $item: null,
567
+ mode: 'export',
568
+ transport: 'disk',
569
+ roots: [],
570
+ dirInfo: null,
571
+ currentPath: '',
572
+ inventory: { models: [], adapters: [], datasets: [], runtime: { present: false } },
573
+ sourceInfo: null,
574
+ jobs: [],
575
+
576
+ selectedExportModels: [],
577
+ selectedExportAdapters: [],
578
+ selectedExportDatasets: [],
579
+ exportIncludeRuntime: true,
580
+ exportOverwrite: true,
581
+
582
+ selectedImportModels: [],
583
+ selectedImportAdapters: [],
584
+ selectedImportDatasets: [],
585
+ importIncludeRuntime: true,
586
+ importOverwrite: false,
587
+
588
+ tarFile: null,
589
+ tarUploading: false,
590
+ tarUploadProgress: 0,
591
+
592
+ notice: '',
593
+ error: '',
594
+ onComplete: null,
595
+ _pollTimer: null,
596
+ _hadRunning: false,
597
+
598
+ get activeJobs() {
599
+ return (this.jobs || []).filter(j => j.status === 'running');
600
+ },
601
+ get hasAnyExportItem() {
602
+ const inv = this.inventory || {};
603
+ return Boolean((inv.models?.length) || (inv.adapters?.length) || (inv.datasets?.length) || inv.runtime?.present);
604
+ },
605
+ get hasAnySourceItem() {
606
+ const s = this.sourceInfo || {};
607
+ return Boolean((s.models?.length) || (s.adapters?.length) || (s.datasets?.length) || s.runtime?.present);
608
+ },
609
+ get exportSelectedBytes() {
610
+ const inv = this.inventory || {};
611
+ let total = 0;
612
+ for (const m of inv.models || []) {
613
+ if (this.selectedExportModels.includes(m.id))
614
+ total += Number(m.sizeBytes) || 0;
615
+ }
616
+ for (const a of inv.adapters || []) {
617
+ if (this.selectedExportAdapters.includes(a.id))
618
+ total += Number(a.sizeBytes) || 0;
619
+ }
620
+ for (const d of inv.datasets || []) {
621
+ if (this.selectedExportDatasets.includes(d.id))
622
+ total += Number(d.sizeBytes) || 0;
623
+ }
624
+ if (this.exportIncludeRuntime && inv.runtime?.present)
625
+ total += Number(inv.runtime.sizeBytes) || 0;
626
+ return total;
627
+ },
628
+ get exportInsufficientSpace() {
629
+ const free = Number(this.dirInfo?.freeBytes) || 0;
630
+ return free > 0 && this.exportSelectedBytes > 0 && free < (this.exportSelectedBytes + 32 * 1024 * 1024);
631
+ },
632
+ get importEffectiveBytes() {
633
+ const s = this.sourceInfo || {};
634
+ let total = 0;
635
+ for (const m of s.models || []) {
636
+ if (this.selectedImportModels.includes(m.id) && (this.importOverwrite || !m.alreadyInstalled))
637
+ total += Number(m.sizeBytes) || 0;
638
+ }
639
+ for (const a of s.adapters || []) {
640
+ if (this.selectedImportAdapters.includes(a.id) && (this.importOverwrite || !a.alreadyInstalled))
641
+ total += Number(a.sizeBytes) || 0;
642
+ }
643
+ for (const d of s.datasets || []) {
644
+ if (this.selectedImportDatasets.includes(d.id) && (this.importOverwrite || !d.alreadyInstalled))
645
+ total += Number(d.sizeBytes) || 0;
646
+ }
647
+ if (this.importIncludeRuntime && s.runtime?.present && (this.importOverwrite || !s.runtime.alreadyInstalled))
648
+ total += Number(s.runtime.sizeBytes) || 0;
649
+ return total;
650
+ },
651
+ get importCopyCount() {
652
+ const s = this.sourceInfo || {};
653
+ let count = 0;
654
+ for (const m of s.models || []) {
655
+ if (this.selectedImportModels.includes(m.id) && (this.importOverwrite || !m.alreadyInstalled))
656
+ count++;
657
+ }
658
+ for (const a of s.adapters || []) {
659
+ if (this.selectedImportAdapters.includes(a.id) && (this.importOverwrite || !a.alreadyInstalled))
660
+ count++;
661
+ }
662
+ for (const d of s.datasets || []) {
663
+ if (this.selectedImportDatasets.includes(d.id) && (this.importOverwrite || !d.alreadyInstalled))
664
+ count++;
665
+ }
666
+ if (this.importIncludeRuntime && s.runtime?.present && (this.importOverwrite || !s.runtime.alreadyInstalled))
667
+ count++;
668
+ return count;
669
+ },
670
+ get importHasAnythingToCopy() {
671
+ return this.selectedImportModels.length > 0
672
+ || this.selectedImportAdapters.length > 0
673
+ || this.selectedImportDatasets.length > 0
674
+ || (this.importIncludeRuntime && this.sourceInfo?.runtime?.present);
675
+ },
676
+
677
+ fmtSize(b) { return fmtGb(b); },
678
+ fmtTime(s) { return fmtEta(s); },
679
+ isRootSelected(rootPath) {
680
+ if (!rootPath || !this.currentPath)
681
+ return false;
682
+ const a = String(rootPath).replace(/[\\/]+$/, '').toLowerCase();
683
+ const b = String(this.currentPath).replace(/[\\/]+$/, '').toLowerCase();
684
+ return b === a || b.startsWith(a + '\\') || b.startsWith(a + '/');
685
+ },
686
+
687
+ async _call(method, params = {}, post = undefined) {
688
+ this.error = '';
689
+ if (!this.$item)
690
+ return null;
691
+ try {
692
+ return await this.$item.fetch(method, params, post);
693
+ }
694
+ catch (e) {
695
+ this.error = String(e?.message || e);
696
+ return null;
697
+ }
698
+ },
699
+
700
+ async attached() {
701
+ await Promise.all([
702
+ this.loadInventory(),
703
+ this.loadRootsAndBrowse(),
704
+ this.refreshJobs(),
705
+ ]);
706
+ this._pollTimer = setInterval(() => {
707
+ if (this.activeJobs.length || this._hadRunning)
708
+ this.refreshJobs();
709
+ }, 800);
710
+ },
711
+ detached() {
712
+ if (this._pollTimer) {
713
+ clearInterval(this._pollTimer);
714
+ this._pollTimer = null;
715
+ }
716
+ },
717
+
718
+ async switchMode(m) {
719
+ this.mode = m;
720
+ this.error = '';
721
+ this.notice = '';
722
+ if (m === 'import' && this.currentPath && this.transport === 'disk') {
723
+ await this.inspectSource(this.currentPath);
724
+ }
725
+ },
726
+
727
+ async loadInventory() {
728
+ const inv = await this._call('trainer_transfer_inventory');
729
+ if (!inv)
730
+ return;
731
+ this.inventory = inv;
732
+ this.selectAllExport(true);
733
+ },
734
+
735
+ selectAllExport(on) {
736
+ const inv = this.inventory || {};
737
+ if (on) {
738
+ this.selectedExportModels = (inv.models || []).map(m => m.id);
739
+ this.selectedExportAdapters = (inv.adapters || []).map(a => a.id);
740
+ this.selectedExportDatasets = (inv.datasets || []).map(d => d.id);
741
+ this.exportIncludeRuntime = Boolean(inv.runtime?.present);
742
+ }
743
+ else {
744
+ this.selectedExportModels = [];
745
+ this.selectedExportAdapters = [];
746
+ this.selectedExportDatasets = [];
747
+ this.exportIncludeRuntime = false;
748
+ }
749
+ },
750
+
751
+ toggleId(listProp, id, checked) {
752
+ const set = new Set(this[listProp] || []);
753
+ if (checked)
754
+ set.add(id);
755
+ else
756
+ set.delete(id);
757
+ this[listProp] = [...set];
758
+ },
759
+
760
+ async loadRootsAndBrowse() {
761
+ const r = await this._call('trainer_transfer_roots');
762
+ if (r?.roots)
763
+ this.roots = r.roots;
764
+ await this.openDir('');
765
+ },
766
+
767
+ async openDir(targetPath) {
768
+ const info = await this._call('trainer_transfer_browse', targetPath ? { path: targetPath } : {});
769
+ if (!info)
770
+ return;
771
+ this.dirInfo = info;
772
+ this.currentPath = info.path;
773
+ if (this.mode === 'import' && info.hasBackup) {
774
+ await this.inspectSource(info.path);
775
+ }
776
+ else if (this.mode === 'import') {
777
+ this.sourceInfo = null;
778
+ }
779
+ },
780
+
781
+ async promptNewFolder() {
782
+ if (!this.currentPath)
783
+ return;
784
+ let name = '';
785
+ try {
786
+ name = await WORK.showPrompt('Имя новой папки', { placeholder: 'WORK-Models-Backup' });
787
+ }
788
+ catch {
789
+ return;
790
+ }
791
+ if (!name)
792
+ return;
793
+ const info = await this._call('trainer_transfer_mkdir', {}, { parentPath: this.currentPath, name });
794
+ if (info) {
795
+ this.dirInfo = info;
796
+ this.currentPath = info.path;
797
+ this.notice = `Создана папка «${info.path}»`;
798
+ }
799
+ },
800
+
801
+ async inspectSource(sourcePath) {
802
+ if (!sourcePath)
803
+ return;
804
+ const info = await this._call('trainer_transfer_inspect', { sourceDir: sourcePath });
805
+ if (!info)
806
+ return;
807
+ this.sourceInfo = info;
808
+ this.selectedImportModels = (info.models || []).map(m => m.id);
809
+ this.selectedImportAdapters = (info.adapters || []).map(a => a.id);
810
+ this.selectedImportDatasets = (info.datasets || []).map(d => d.id);
811
+ this.importIncludeRuntime = Boolean(info.runtime?.present);
812
+ },
813
+
814
+ async startExportDisk() {
815
+ this.notice = '';
816
+ const job = await this._call('trainer_transfer_export', {}, {
817
+ targetDir: this.currentPath,
818
+ modelIds: this.selectedExportModels,
819
+ adapterIds: this.selectedExportAdapters,
820
+ datasetIds: this.selectedExportDatasets,
821
+ includeRuntime: this.exportIncludeRuntime,
822
+ overwrite: this.exportOverwrite,
823
+ });
824
+ if (job) {
825
+ this._hadRunning = true;
826
+ this.notice = `Запущена выгрузка в «${this.currentPath}»…`;
827
+ await this.refreshJobs();
828
+ }
829
+ },
830
+
831
+ async startImportDisk() {
832
+ this.notice = '';
833
+ const job = await this._call('trainer_transfer_import', {}, {
834
+ sourceDir: this.currentPath,
835
+ modelIds: this.selectedImportModels,
836
+ adapterIds: this.selectedImportAdapters,
837
+ datasetIds: this.selectedImportDatasets,
838
+ includeRuntime: this.importIncludeRuntime,
839
+ overwrite: this.importOverwrite,
840
+ });
841
+ if (job) {
842
+ this._hadRunning = true;
843
+ this.notice = `Запущена загрузка моделей из «${this.currentPath}»…`;
844
+ await this.refreshJobs();
845
+ }
846
+ },
847
+
848
+ async cancelJob(jobId) {
849
+ await this._call('trainer_transfer_cancel', {}, { jobId });
850
+ await this.refreshJobs();
851
+ },
852
+
853
+ async refreshJobs() {
854
+ const res = await this._call('trainer_transfer_status');
855
+ if (!res?.jobs)
856
+ return;
857
+ this.jobs = res.jobs;
858
+ const stillRunning = this.activeJobs.length > 0;
859
+ if (this._hadRunning && !stillRunning) {
860
+ this._hadRunning = false;
861
+ const latest = this.jobs[0];
862
+ if (latest?.status === 'completed') {
863
+ this.notice = latest.type?.startsWith('import')
864
+ ? `Готово: загружено моделей — ${latest.imported?.models?.length || 0}, пропущено — ${latest.skipped?.length || 0}.`
865
+ : `Готово: выгружено моделей — ${latest.exported?.models?.length || 0} в «${latest.targetDir}».`;
866
+ await this.loadInventory();
867
+ if (this.dirInfo?.path)
868
+ await this.openDir(this.dirInfo.path);
869
+ await this.onComplete?.(latest);
870
+ }
871
+ else if (latest?.status === 'failed') {
872
+ this.error = latest.error || 'Ошибка переноса моделей';
873
+ }
874
+ else if (latest?.status === 'cancelled') {
875
+ this.notice = 'Перенос моделей отменён.';
876
+ }
877
+ }
878
+ },
879
+
880
+ downloadTar() {
881
+ if (!this.$item)
882
+ return;
883
+ const params = new URLSearchParams();
884
+ params.set('modelIds', this.selectedExportModels.join(','));
885
+ params.set('adapterIds', this.selectedExportAdapters.join(','));
886
+ params.set('datasetIds', this.selectedExportDatasets.join(','));
887
+ params.set('includeRuntime', String(Boolean(this.exportIncludeRuntime)));
888
+ const base = encodeURI(this.$item.short || '/MODELS/Local');
889
+ const link = document.createElement('a');
890
+ link.href = `${base}?trainer_transfer_export_tar&${params.toString()}`;
891
+ link.download = 'work-local-models.tar';
892
+ document.body.appendChild(link);
893
+ link.click();
894
+ link.remove();
895
+ this.notice = 'Начато скачивание архива .tar через браузер…';
896
+ },
897
+
898
+ onTarFilePicked(e) {
899
+ this.tarFile = e?.target?.files?.[0] || null;
900
+ },
901
+
902
+ async uploadTar() {
903
+ if (!this.tarFile || !this.$item)
904
+ return;
905
+ this.error = '';
906
+ this.notice = '';
907
+ this.tarUploading = true;
908
+ this.tarUploadProgress = 0;
909
+
910
+ try {
911
+ const url = encodeURI(this.$item.short || '/MODELS/Local')
912
+ + `?trainer_transfer_import_tar&overwrite=${this.importOverwrite ? 'true' : 'false'}`;
913
+ const result = await new Promise((resolve, reject) => {
914
+ const xhr = new XMLHttpRequest();
915
+ xhr.open('POST', url, true);
916
+ xhr.setRequestHeader('X-WORK-WSID', WORK.wsid || '');
917
+ xhr.setRequestHeader('Content-Type', 'application/x-tar');
918
+ xhr.upload.onprogress = (ev) => {
919
+ if (ev.lengthComputable && ev.total > 0)
920
+ this.tarUploadProgress = Math.min(99, Math.round((ev.loaded / ev.total) * 100));
921
+ };
922
+ xhr.onload = () => {
923
+ if (xhr.status >= 200 && xhr.status < 300) {
924
+ try { resolve(JSON.parse(xhr.responseText || '{}')); }
925
+ catch { resolve({ status: 'completed' }); }
926
+ }
927
+ else {
928
+ reject(new Error(xhr.responseText || `HTTP ${xhr.status}`));
929
+ }
930
+ };
931
+ xhr.onerror = () => reject(new Error('Сетевая ошибка при отправке .tar'));
932
+ xhr.send(this.tarFile);
933
+ });
934
+ this.tarUploadProgress = 100;
935
+ this.notice = `Архив .tar установлен: загружено моделей — ${result.imported?.models?.length || 0}, пропущено — ${result.skipped?.length || 0}.`;
936
+ await this.loadInventory();
937
+ await this.onComplete?.(result);
938
+ }
939
+ catch (err) {
940
+ this.error = String(err?.message || err);
941
+ }
942
+ finally {
943
+ this.tarUploading = false;
944
+ }
945
+ },
946
+ });
947
+
948
+ /**
949
+ * Открыть единый системный диалог выгрузки и загрузки локальных моделей (/MODELS/Local).
950
+ */
951
+ export async function openLocalModelsTransferDialog($item, { mode = 'export', onComplete = null } = {}) {
952
+ await customElements.whenDefined('item-local-models-transfer');
953
+ const targetItem = $item || await WORK.get_item('/MODELS/Local');
954
+ const el = ODA.createElement('item-local-models-transfer', {
955
+ $item: targetItem,
956
+ mode,
957
+ onComplete,
958
+ });
959
+ try {
960
+ await WORK.showDialog(el, {
961
+ allowClose: true,
962
+ width: 820,
963
+ TITLE: { label: 'Выгрузка и загрузка моделей (/MODELS/Local)', icon: 'carbon:usb' },
964
+ OK: null,
965
+ CANCEL: { label: 'Закрыть', icon: 'icons:close', colorMode: 'info' },
966
+ });
967
+ }
968
+ catch (err) {
969
+ if (!(err instanceof ODA.CancelError))
970
+ throw err;
971
+ }
972
+ }