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.
- package/#system/package-manifest.json +37 -24
- package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +21 -2
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/file.js +58 -0
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/readme.md +2 -2
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/feed.js +2 -11
- package/$server/$folder/lib/chat-item/chat-item.js +17 -1
- package/$server/$folder/lib/local-models-transfer/local-models-transfer.js +972 -0
- package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +408 -111
- package/MODELS/Local/$provider/handlers/methods/transfer/$handler/class.js +41 -0
- package/logo.png +0 -0
- package/package.json +1 -1
- package/rules/threats.md +117 -116
- package/sources/client.js +1 -0
- package/sources/data/progress.md +15 -0
- package/sources/host/auto-updater.js +6 -2
- package/sources/host/http-server.js +23 -0
- package/sources/host/websocket.js +127 -120
- package/sources/modules/agent/index.js +6 -1
- package/sources/modules/agent/readme.md +217 -216
- package/sources/modules/agent/session.js +43 -8
- package/sources/modules/agent/tools/chrome.js +263 -0
- package/sources/modules/bridge/chrome.js +673 -0
- package/sources/modules/bridge/hub.js +395 -361
- package/sources/modules/chrome-extension/background.js +299 -0
- package/sources/modules/chrome-extension/manifest.json +25 -0
- package/sources/modules/chrome-extension/options.html +48 -0
- package/sources/modules/chrome-extension/options.js +104 -0
- package/sources/modules/chrome-extension/popup.html +25 -0
- package/sources/modules/chrome-extension/popup.js +32 -0
- package/sources/modules/trainer/huggingface.js +412 -65
- package/sources/modules/trainer/index.js +288 -1
- package/sources/modules/trainer/tar-stream.js +458 -0
- package/sources/modules/trainer/transfer.js +1570 -0
- package/sources/modules/user-profile/user-profile.js +34 -10
- package/sources/modules/user-profile/user-token.js +168 -0
- package/sw.js +85 -9
|
@@ -1005,9 +1005,73 @@ export default ${JSON.stringify(meta, null, 4)};
|
|
|
1005
1005
|
};
|
|
1006
1006
|
}
|
|
1007
1007
|
|
|
1008
|
+
const DOWNLOAD_STATE_FILE = 'download-state.json';
|
|
1009
|
+
const RETRYABLE_HTTP_STATUSES = new Set([408, 425, 429, 500, 502, 503, 504]);
|
|
1010
|
+
|
|
1011
|
+
function isRetryableDownloadError(err) {
|
|
1012
|
+
if (!err)
|
|
1013
|
+
return false;
|
|
1014
|
+
if (err.httpStatus && RETRYABLE_HTTP_STATUSES.has(err.httpStatus))
|
|
1015
|
+
return true;
|
|
1016
|
+
if (err.httpStatus && err.httpStatus >= 400 && err.httpStatus < 500)
|
|
1017
|
+
return false;
|
|
1018
|
+
const msg = String(err?.message || err);
|
|
1019
|
+
if (/Unexpected URL|Некорректн|отменена/i.test(msg))
|
|
1020
|
+
return false;
|
|
1021
|
+
return err.retryable === true
|
|
1022
|
+
|| /ECONNRESET|ETIMEDOUT|EPIPE|EAI_AGAIN|ENOTFOUND|network|fetch failed|terminated|aborted|socket|premature/i.test(msg);
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
async function writeDownloadStateSafe(stagingDir, job, extra = {}) {
|
|
1026
|
+
try {
|
|
1027
|
+
await fsp.mkdir(stagingDir, { recursive: true });
|
|
1028
|
+
const payload = {
|
|
1029
|
+
repoId: job.repoId,
|
|
1030
|
+
label: job.label,
|
|
1031
|
+
modality: job.modality,
|
|
1032
|
+
capabilities: job.capabilities,
|
|
1033
|
+
revision: job.revision,
|
|
1034
|
+
providerFolder: job.providerFolder,
|
|
1035
|
+
folderName: job.folderName,
|
|
1036
|
+
registerInWork: extra.registerInWork !== false,
|
|
1037
|
+
nodeMeta: extra.nodeMeta || null,
|
|
1038
|
+
files: (job.files || []).map(f => ({ name: f.name, size: Number(f.size) || 0 })),
|
|
1039
|
+
totalBytes: Number(job.totalBytes) || 0,
|
|
1040
|
+
downloadedBytes: Number(job.downloadedBytes) || 0,
|
|
1041
|
+
status: job.status,
|
|
1042
|
+
error: job.error || null,
|
|
1043
|
+
updatedAt: Date.now(),
|
|
1044
|
+
};
|
|
1045
|
+
const tmp = path.join(stagingDir, `${DOWNLOAD_STATE_FILE}.tmp`);
|
|
1046
|
+
await fsp.writeFile(tmp, JSON.stringify(payload, null, 2), 'utf-8');
|
|
1047
|
+
await fsp.rename(tmp, path.join(stagingDir, DOWNLOAD_STATE_FILE));
|
|
1048
|
+
}
|
|
1049
|
+
catch { /* ignore state write error */ }
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
function waitAbortable(ms, signal) {
|
|
1053
|
+
if (ms <= 0)
|
|
1054
|
+
return Promise.resolve();
|
|
1055
|
+
return new Promise((resolve, reject) => {
|
|
1056
|
+
if (signal?.aborted) {
|
|
1057
|
+
reject(new Error('Загрузка приостановлена пользователем'));
|
|
1058
|
+
return;
|
|
1059
|
+
}
|
|
1060
|
+
const timer = setTimeout(() => {
|
|
1061
|
+
signal?.removeEventListener('abort', onAbort);
|
|
1062
|
+
resolve();
|
|
1063
|
+
}, ms);
|
|
1064
|
+
const onAbort = () => {
|
|
1065
|
+
clearTimeout(timer);
|
|
1066
|
+
reject(new Error('Загрузка приостановлена пользователем'));
|
|
1067
|
+
};
|
|
1068
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
1069
|
+
});
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1008
1072
|
/**
|
|
1009
1073
|
* Запустить прямую загрузку модели с Hugging Face в `MODELS/Local/<Имя>/#weights/`
|
|
1010
|
-
* с поддержкой докачки (`Range`),
|
|
1074
|
+
* с поддержкой докачки (`Range`), авто-ретраев при обрывах, паузы без потери скачанного и авто-созданием узла `$ai`.
|
|
1011
1075
|
*/
|
|
1012
1076
|
export async function startHuggingFaceDownload({
|
|
1013
1077
|
repoId,
|
|
@@ -1021,6 +1085,8 @@ export async function startHuggingFaceDownload({
|
|
|
1021
1085
|
nodeMeta = null,
|
|
1022
1086
|
registerInWork = true,
|
|
1023
1087
|
waitForCompletion = false,
|
|
1088
|
+
maxRetries = 20,
|
|
1089
|
+
retryBaseDelayMs = 3000,
|
|
1024
1090
|
fetchImpl = globalThis.fetch,
|
|
1025
1091
|
} = {}) {
|
|
1026
1092
|
const cleanId = validateRepoId(repoId);
|
|
@@ -1057,9 +1123,44 @@ export async function startHuggingFaceDownload({
|
|
|
1057
1123
|
|
|
1058
1124
|
await fsp.mkdir(stagingDir, { recursive: true });
|
|
1059
1125
|
|
|
1126
|
+
// Убираем старые завершённые/паузовые записи для той же папки из памяти
|
|
1127
|
+
for (const [k, entry] of _downloads.entries()) {
|
|
1128
|
+
if (entry.job.status !== 'downloading' && entry.job.providerFolder === safeProvider && entry.job.folderName === folderName)
|
|
1129
|
+
_downloads.delete(k);
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
const jobFiles = [];
|
|
1133
|
+
for (const f of selected) {
|
|
1134
|
+
const size = Number(f.size) || 0;
|
|
1135
|
+
const stagedFile = path.join(stagingDir, path.basename(f.name));
|
|
1136
|
+
const partFile = stagedFile + '.part';
|
|
1137
|
+
let downloaded = 0;
|
|
1138
|
+
let done = false;
|
|
1139
|
+
try {
|
|
1140
|
+
const stDone = await fsp.stat(stagedFile);
|
|
1141
|
+
if (stDone.isFile() && stDone.size > 0 && (!size || stDone.size === size)) {
|
|
1142
|
+
downloaded = stDone.size;
|
|
1143
|
+
done = true;
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
catch { /* ещё не завершён */ }
|
|
1147
|
+
if (!done) {
|
|
1148
|
+
try {
|
|
1149
|
+
const stPart = await fsp.stat(partFile);
|
|
1150
|
+
if (stPart.isFile())
|
|
1151
|
+
downloaded = stPart.size;
|
|
1152
|
+
}
|
|
1153
|
+
catch { /* .part ещё нет */ }
|
|
1154
|
+
}
|
|
1155
|
+
jobFiles.push({ name: f.name, size: size || (done ? downloaded : 0), downloaded, done });
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1060
1158
|
const jobId = 'hf_' + crypto.randomUUID().slice(0, 8);
|
|
1061
|
-
const totalBytes =
|
|
1159
|
+
const totalBytes = jobFiles.reduce((acc, f) => acc + (Number(f.size) || 0), 0);
|
|
1160
|
+
const initialDownloaded = jobFiles.reduce((acc, f) => acc + (Number(f.downloaded) || 0), 0);
|
|
1161
|
+
const initialProgress = totalBytes > 0 ? Math.min(99, Math.round((initialDownloaded / totalBytes) * 100)) : 0;
|
|
1062
1162
|
const controller = new AbortController();
|
|
1163
|
+
let keepFilesOnAbort = true;
|
|
1063
1164
|
|
|
1064
1165
|
const job = {
|
|
1065
1166
|
id: jobId,
|
|
@@ -1070,87 +1171,177 @@ export async function startHuggingFaceDownload({
|
|
|
1070
1171
|
revision: String(revision || 'main'),
|
|
1071
1172
|
providerFolder: safeProvider,
|
|
1072
1173
|
folderName,
|
|
1174
|
+
rootDir,
|
|
1175
|
+
stagingDir,
|
|
1073
1176
|
weightsDir,
|
|
1074
1177
|
status: 'downloading',
|
|
1075
|
-
files:
|
|
1076
|
-
currentFile:
|
|
1077
|
-
downloadedBytes:
|
|
1178
|
+
files: jobFiles,
|
|
1179
|
+
currentFile: (jobFiles.find(f => !f.done) || jobFiles[0])?.name || '',
|
|
1180
|
+
downloadedBytes: initialDownloaded,
|
|
1078
1181
|
totalBytes,
|
|
1079
|
-
progress:
|
|
1182
|
+
progress: initialProgress,
|
|
1080
1183
|
speedMBs: 0,
|
|
1184
|
+
etaSeconds: null,
|
|
1185
|
+
retryAttempt: 0,
|
|
1186
|
+
retryError: '',
|
|
1081
1187
|
startedAt: Date.now(),
|
|
1082
1188
|
finishedAt: null,
|
|
1083
1189
|
modelPath: `/MODELS/${safeProvider}/${folderName}`,
|
|
1084
1190
|
error: null,
|
|
1085
1191
|
};
|
|
1086
|
-
|
|
1192
|
+
const entryMeta = {
|
|
1193
|
+
job,
|
|
1194
|
+
controller,
|
|
1195
|
+
nodeMeta,
|
|
1196
|
+
registerInWork,
|
|
1197
|
+
setKeepFiles: (v) => { keepFilesOnAbort = Boolean(v); },
|
|
1198
|
+
};
|
|
1199
|
+
_downloads.set(jobId, entryMeta);
|
|
1200
|
+
await writeDownloadStateSafe(stagingDir, job, { nodeMeta, registerInWork });
|
|
1087
1201
|
|
|
1088
1202
|
const runPromise = (async () => {
|
|
1089
1203
|
const t0 = Date.now();
|
|
1204
|
+
let sessionDownloadedBytes = 0;
|
|
1205
|
+
const updateMetrics = () => {
|
|
1206
|
+
job.downloadedBytes = job.files.reduce((acc, f) => acc + (Number(f.downloaded) || 0), 0);
|
|
1207
|
+
if (job.totalBytes > 0)
|
|
1208
|
+
job.progress = Math.min(99, Math.round((job.downloadedBytes / job.totalBytes) * 100));
|
|
1209
|
+
const elapsedSec = Math.max(0.2, (Date.now() - t0) / 1000);
|
|
1210
|
+
const bytesPerSec = sessionDownloadedBytes / elapsedSec;
|
|
1211
|
+
job.speedMBs = +(bytesPerSec / (1024 * 1024)).toFixed(2);
|
|
1212
|
+
if (job.totalBytes > 0 && bytesPerSec > 1024) {
|
|
1213
|
+
const remaining = Math.max(0, job.totalBytes - job.downloadedBytes);
|
|
1214
|
+
job.etaSeconds = Math.round(remaining / bytesPerSec);
|
|
1215
|
+
}
|
|
1216
|
+
};
|
|
1217
|
+
|
|
1090
1218
|
try {
|
|
1091
1219
|
for (const fileEntry of job.files) {
|
|
1092
1220
|
if (controller.signal.aborted)
|
|
1093
|
-
throw new Error('Загрузка
|
|
1221
|
+
throw new Error('Загрузка приостановлена пользователем');
|
|
1222
|
+
if (fileEntry.done)
|
|
1223
|
+
continue;
|
|
1224
|
+
|
|
1094
1225
|
job.currentFile = fileEntry.name;
|
|
1095
1226
|
const stagedFile = path.join(stagingDir, path.basename(fileEntry.name));
|
|
1096
1227
|
const partFile = stagedFile + '.part';
|
|
1097
|
-
|
|
1098
|
-
let existingSize = 0;
|
|
1099
|
-
try {
|
|
1100
|
-
const st = await fsp.stat(partFile);
|
|
1101
|
-
existingSize = st.size;
|
|
1102
|
-
}
|
|
1103
|
-
catch { /* файла ещё нет */ }
|
|
1104
|
-
|
|
1105
1228
|
const encodedPath = fileEntry.name.split('/').map(encodeURIComponent).join('/');
|
|
1106
1229
|
const url = `${HF_ORIGIN}/${cleanId}/resolve/${encodeURIComponent(job.revision)}/${encodedPath}`;
|
|
1107
|
-
const headers = hfHeaders(token);
|
|
1108
|
-
if (existingSize > 0)
|
|
1109
|
-
headers.Range = `bytes=${existingSize}-`;
|
|
1110
|
-
|
|
1111
|
-
const res = await fetchImpl(url, { headers, signal: controller.signal });
|
|
1112
|
-
if (!res.ok && res.status !== 206 && res.status !== 416)
|
|
1113
|
-
throw new Error(`Ошибка загрузки ${fileEntry.name}: HTTP ${res.status}`);
|
|
1114
|
-
|
|
1115
|
-
const isPartial = res.status === 206;
|
|
1116
|
-
if (!isPartial && res.status !== 416)
|
|
1117
|
-
existingSize = 0;
|
|
1118
|
-
|
|
1119
|
-
const contentLen = Number(res.headers?.get?.('content-length') || 0);
|
|
1120
|
-
if (!fileEntry.size && contentLen > 0) {
|
|
1121
|
-
fileEntry.size = existingSize + contentLen;
|
|
1122
|
-
job.totalBytes = job.files.reduce((acc, f) => acc + (Number(f.size) || 0), 0);
|
|
1123
|
-
}
|
|
1124
1230
|
|
|
1125
|
-
|
|
1231
|
+
let attempt = 0;
|
|
1232
|
+
while (true) {
|
|
1233
|
+
if (controller.signal.aborted)
|
|
1234
|
+
throw new Error('Загрузка приостановлена пользователем');
|
|
1235
|
+
|
|
1236
|
+
let existingSize = 0;
|
|
1237
|
+
try {
|
|
1238
|
+
const st = await fsp.stat(partFile);
|
|
1239
|
+
if (st.isFile())
|
|
1240
|
+
existingSize = st.size;
|
|
1241
|
+
}
|
|
1242
|
+
catch { /* файла ещё нет */ }
|
|
1243
|
+
|
|
1244
|
+
if (fileEntry.size > 0 && existingSize >= fileEntry.size) {
|
|
1245
|
+
await fsp.rename(partFile, stagedFile);
|
|
1246
|
+
fileEntry.downloaded = fileEntry.size;
|
|
1247
|
+
fileEntry.done = true;
|
|
1248
|
+
updateMetrics();
|
|
1249
|
+
break;
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
try {
|
|
1253
|
+
const headers = hfHeaders(token);
|
|
1254
|
+
if (existingSize > 0)
|
|
1255
|
+
headers.Range = `bytes=${existingSize}-`;
|
|
1256
|
+
|
|
1257
|
+
const res = await fetchImpl(url, { headers, signal: controller.signal });
|
|
1258
|
+
if (res.status === 416) {
|
|
1259
|
+
if (existingSize > 0 && (!fileEntry.size || existingSize >= fileEntry.size)) {
|
|
1260
|
+
await fsp.rename(partFile, stagedFile);
|
|
1261
|
+
fileEntry.size = fileEntry.size || existingSize;
|
|
1262
|
+
fileEntry.downloaded = existingSize;
|
|
1263
|
+
fileEntry.done = true;
|
|
1264
|
+
updateMetrics();
|
|
1265
|
+
break;
|
|
1266
|
+
}
|
|
1267
|
+
await fsp.rm(partFile, { force: true }).catch(() => {});
|
|
1268
|
+
existingSize = 0;
|
|
1269
|
+
const err416 = new Error(`Сбой Range для ${fileEntry.name}: HTTP 416`);
|
|
1270
|
+
err416.retryable = true;
|
|
1271
|
+
throw err416;
|
|
1272
|
+
}
|
|
1273
|
+
if (!res.ok && res.status !== 206) {
|
|
1274
|
+
const errHttp = new Error(`Ошибка загрузки ${fileEntry.name}: HTTP ${res.status}`);
|
|
1275
|
+
errHttp.httpStatus = res.status;
|
|
1276
|
+
throw errHttp;
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
const isPartial = res.status === 206;
|
|
1280
|
+
if (!isPartial)
|
|
1281
|
+
existingSize = 0;
|
|
1282
|
+
|
|
1283
|
+
const contentLen = Number(res.headers?.get?.('content-length') || 0);
|
|
1284
|
+
if (!fileEntry.size && contentLen > 0) {
|
|
1285
|
+
fileEntry.size = existingSize + contentLen;
|
|
1286
|
+
job.totalBytes = job.files.reduce((acc, f) => acc + (Number(f.size) || 0), 0);
|
|
1287
|
+
}
|
|
1126
1288
|
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1289
|
+
fileEntry.downloaded = existingSize;
|
|
1290
|
+
job.retryAttempt = 0;
|
|
1291
|
+
job.retryError = '';
|
|
1292
|
+
updateMetrics();
|
|
1293
|
+
|
|
1294
|
+
if (res.body) {
|
|
1295
|
+
const flags = isPartial ? 'a' : 'w';
|
|
1296
|
+
const out = fs.createWriteStream(partFile, { flags });
|
|
1297
|
+
try {
|
|
1298
|
+
for await (const chunk of res.body) {
|
|
1299
|
+
if (controller.signal.aborted)
|
|
1300
|
+
throw new Error('Загрузка приостановлена пользователем');
|
|
1301
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
1302
|
+
if (!out.write(buf))
|
|
1303
|
+
await new Promise(r => out.once('drain', r));
|
|
1304
|
+
fileEntry.downloaded += buf.length;
|
|
1305
|
+
sessionDownloadedBytes += buf.length;
|
|
1306
|
+
updateMetrics();
|
|
1307
|
+
}
|
|
1308
|
+
await new Promise((resolve, reject) => {
|
|
1309
|
+
out.end();
|
|
1310
|
+
out.once('finish', resolve);
|
|
1311
|
+
out.once('error', reject);
|
|
1312
|
+
});
|
|
1313
|
+
}
|
|
1314
|
+
catch (streamErr) {
|
|
1315
|
+
await new Promise((resolve) => {
|
|
1316
|
+
out.once('finish', resolve);
|
|
1317
|
+
out.once('error', resolve);
|
|
1318
|
+
out.once('close', resolve);
|
|
1319
|
+
try { out.end(); } catch { resolve(); }
|
|
1320
|
+
});
|
|
1321
|
+
if (!controller.signal.aborted && !streamErr.httpStatus)
|
|
1322
|
+
streamErr.retryable = true;
|
|
1323
|
+
throw streamErr;
|
|
1324
|
+
}
|
|
1134
1325
|
}
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1326
|
+
|
|
1327
|
+
await fsp.rename(partFile, stagedFile);
|
|
1328
|
+
fileEntry.done = true;
|
|
1329
|
+
updateMetrics();
|
|
1330
|
+
break;
|
|
1331
|
+
}
|
|
1332
|
+
catch (err) {
|
|
1333
|
+
if (controller.signal.aborted)
|
|
1334
|
+
throw err;
|
|
1335
|
+
if (!isRetryableDownloadError(err) || attempt >= maxRetries)
|
|
1336
|
+
throw err;
|
|
1337
|
+
attempt++;
|
|
1338
|
+
job.retryAttempt = attempt;
|
|
1339
|
+
job.retryError = String(err?.message || err);
|
|
1340
|
+
await writeDownloadStateSafe(stagingDir, job, { nodeMeta, registerInWork });
|
|
1341
|
+
const delay = Math.min(30000, retryBaseDelayMs * attempt);
|
|
1342
|
+
await waitAbortable(delay, controller.signal);
|
|
1144
1343
|
}
|
|
1145
|
-
await new Promise((resolve, reject) => {
|
|
1146
|
-
out.end();
|
|
1147
|
-
out.once('finish', resolve);
|
|
1148
|
-
out.once('error', reject);
|
|
1149
|
-
});
|
|
1150
1344
|
}
|
|
1151
|
-
|
|
1152
|
-
await fsp.rename(partFile, stagedFile);
|
|
1153
|
-
fileEntry.done = true;
|
|
1154
1345
|
}
|
|
1155
1346
|
|
|
1156
1347
|
// Переносим готовые файлы из скрытой папки #downloads в целевую папку модели #weights
|
|
@@ -1200,6 +1391,7 @@ export async function startHuggingFaceDownload({
|
|
|
1200
1391
|
}
|
|
1201
1392
|
|
|
1202
1393
|
job.progress = 100;
|
|
1394
|
+
job.etaSeconds = 0;
|
|
1203
1395
|
job.status = 'completed';
|
|
1204
1396
|
job.finishedAt = Date.now();
|
|
1205
1397
|
try {
|
|
@@ -1211,12 +1403,22 @@ export async function startHuggingFaceDownload({
|
|
|
1211
1403
|
catch { /* ignore */ }
|
|
1212
1404
|
}
|
|
1213
1405
|
catch (err) {
|
|
1214
|
-
job.status = controller.signal.aborted ? 'cancelled' : 'failed';
|
|
1215
|
-
job.error = String(err?.message || err);
|
|
1216
|
-
job.finishedAt = Date.now();
|
|
1217
1406
|
if (controller.signal.aborted) {
|
|
1407
|
+
job.status = keepFilesOnAbort ? 'paused' : 'cancelled';
|
|
1408
|
+
job.error = keepFilesOnAbort ? null : String(err?.message || err);
|
|
1409
|
+
}
|
|
1410
|
+
else {
|
|
1411
|
+
job.status = 'failed';
|
|
1412
|
+
job.error = String(err?.message || err);
|
|
1413
|
+
}
|
|
1414
|
+
job.etaSeconds = null;
|
|
1415
|
+
job.finishedAt = Date.now();
|
|
1416
|
+
if (controller.signal.aborted && !keepFilesOnAbort) {
|
|
1218
1417
|
await fsp.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
|
|
1219
1418
|
}
|
|
1419
|
+
else {
|
|
1420
|
+
await writeDownloadStateSafe(stagingDir, job, { nodeMeta, registerInWork });
|
|
1421
|
+
}
|
|
1220
1422
|
}
|
|
1221
1423
|
})();
|
|
1222
1424
|
|
|
@@ -1231,16 +1433,161 @@ export function getHuggingFaceDownload(jobId) {
|
|
|
1231
1433
|
return entry ? { ...entry.job } : null;
|
|
1232
1434
|
}
|
|
1233
1435
|
|
|
1234
|
-
export function listHuggingFaceDownloads() {
|
|
1235
|
-
|
|
1436
|
+
export function listHuggingFaceDownloads(rootDir = process.cwd()) {
|
|
1437
|
+
const inMemory = [..._downloads.values()].map(e => ({ ...e.job }));
|
|
1438
|
+
const seenFolders = new Set(inMemory.map(j => `${j.providerFolder}:${j.folderName}`));
|
|
1439
|
+
|
|
1440
|
+
// Подхватываем недокачанные папки из MODELS/Local/#downloads/* (включая оставшиеся после рестарта)
|
|
1441
|
+
const downloadsRoot = path.join(rootDir, 'MODELS', 'Local', '#downloads');
|
|
1442
|
+
if (fs.existsSync(downloadsRoot)) {
|
|
1443
|
+
try {
|
|
1444
|
+
const entries = fs.readdirSync(downloadsRoot, { withFileTypes: true });
|
|
1445
|
+
for (const e of entries) {
|
|
1446
|
+
if (!e.isDirectory() || e.name.startsWith('.') || e.name.startsWith('_import_') || e.name.startsWith('_tar_import_'))
|
|
1447
|
+
continue;
|
|
1448
|
+
if (seenFolders.has(`Local:${e.name}`))
|
|
1449
|
+
continue;
|
|
1450
|
+
const folderDir = path.join(downloadsRoot, e.name);
|
|
1451
|
+
const stateFile = path.join(folderDir, DOWNLOAD_STATE_FILE);
|
|
1452
|
+
let state = {};
|
|
1453
|
+
if (fs.existsSync(stateFile)) {
|
|
1454
|
+
try { state = JSON.parse(fs.readFileSync(stateFile, 'utf-8')); }
|
|
1455
|
+
catch { /* ignore */ }
|
|
1456
|
+
}
|
|
1457
|
+
const dirFiles = fs.readdirSync(folderDir, { withFileTypes: true });
|
|
1458
|
+
let diskBytes = 0;
|
|
1459
|
+
const parsedFiles = [];
|
|
1460
|
+
for (const f of dirFiles) {
|
|
1461
|
+
if (!f.isFile() || f.name === DOWNLOAD_STATE_FILE || f.name.endsWith('.tmp'))
|
|
1462
|
+
continue;
|
|
1463
|
+
try {
|
|
1464
|
+
const st = fs.statSync(path.join(folderDir, f.name));
|
|
1465
|
+
diskBytes += st.size || 0;
|
|
1466
|
+
parsedFiles.push({
|
|
1467
|
+
name: f.name.replace(/\.part$/, ''),
|
|
1468
|
+
size: st.size || 0,
|
|
1469
|
+
downloaded: st.size || 0,
|
|
1470
|
+
done: !f.name.endsWith('.part'),
|
|
1471
|
+
});
|
|
1472
|
+
}
|
|
1473
|
+
catch { /* ignore */ }
|
|
1474
|
+
}
|
|
1475
|
+
if (diskBytes <= 0 && !state.repoId)
|
|
1476
|
+
continue;
|
|
1477
|
+
const totalBytes = Number(state.totalBytes) || 0;
|
|
1478
|
+
const progress = totalBytes > 0 ? Math.min(99, Math.round((diskBytes / totalBytes) * 100)) : 0;
|
|
1479
|
+
inMemory.push({
|
|
1480
|
+
id: `disk_${e.name}`,
|
|
1481
|
+
repoId: state.repoId || '',
|
|
1482
|
+
label: state.label || e.name,
|
|
1483
|
+
modality: state.modality || 'llm',
|
|
1484
|
+
capabilities: state.capabilities || ['chat'],
|
|
1485
|
+
revision: state.revision || 'main',
|
|
1486
|
+
providerFolder: 'Local',
|
|
1487
|
+
folderName: e.name,
|
|
1488
|
+
status: state.status === 'failed' ? 'failed' : 'paused',
|
|
1489
|
+
files: Array.isArray(state.files) && state.files.length ? state.files : parsedFiles,
|
|
1490
|
+
currentFile: parsedFiles[0]?.name || '',
|
|
1491
|
+
downloadedBytes: diskBytes,
|
|
1492
|
+
totalBytes,
|
|
1493
|
+
progress,
|
|
1494
|
+
speedMBs: 0,
|
|
1495
|
+
etaSeconds: null,
|
|
1496
|
+
startedAt: state.updatedAt || Date.now(),
|
|
1497
|
+
finishedAt: state.updatedAt || Date.now(),
|
|
1498
|
+
modelPath: `/MODELS/Local/${e.name}`,
|
|
1499
|
+
error: state.error || null,
|
|
1500
|
+
nodeMeta: state.nodeMeta || null,
|
|
1501
|
+
canResume: true,
|
|
1502
|
+
onDiskOnly: true,
|
|
1503
|
+
});
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
catch { /* ignore */ }
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
return inMemory.sort((a, b) => (b.startedAt || 0) - (a.startedAt || 0));
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
export function pauseHuggingFaceDownload(jobId) {
|
|
1513
|
+
const entry = _downloads.get(String(jobId || ''));
|
|
1514
|
+
if (!entry)
|
|
1515
|
+
return null;
|
|
1516
|
+
entry.setKeepFiles?.(true);
|
|
1517
|
+
entry.controller.abort();
|
|
1518
|
+
entry.job.status = 'paused';
|
|
1519
|
+
entry.job.etaSeconds = null;
|
|
1520
|
+
entry.job.finishedAt = Date.now();
|
|
1521
|
+
return { ...entry.job };
|
|
1522
|
+
}
|
|
1523
|
+
|
|
1524
|
+
export async function discardHuggingFaceDownload({ jobId = '', folderName = '', rootDir = process.cwd() } = {}) {
|
|
1525
|
+
const key = String(jobId || '');
|
|
1526
|
+
const entry = key ? _downloads.get(key) : null;
|
|
1527
|
+
let targetFolder = String(folderName || entry?.job?.folderName || '').replace(/[<>:"/\\|?*]/g, '').trim();
|
|
1528
|
+
if (entry) {
|
|
1529
|
+
entry.setKeepFiles?.(false);
|
|
1530
|
+
if (entry.job.status === 'downloading')
|
|
1531
|
+
entry.controller.abort();
|
|
1532
|
+
entry.job.status = 'cancelled';
|
|
1533
|
+
_downloads.delete(key);
|
|
1534
|
+
}
|
|
1535
|
+
if (!targetFolder && key.startsWith('disk_'))
|
|
1536
|
+
targetFolder = key.slice(5);
|
|
1537
|
+
if (targetFolder) {
|
|
1538
|
+
const stagingDir = path.join(rootDir, 'MODELS', 'Local', '#downloads', targetFolder);
|
|
1539
|
+
await fsp.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
|
|
1540
|
+
}
|
|
1541
|
+
return { ok: true, discarded: targetFolder || key };
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
export async function resumeHuggingFaceDownload({
|
|
1545
|
+
jobId = '',
|
|
1546
|
+
folderName = '',
|
|
1547
|
+
repoId = '',
|
|
1548
|
+
quant = 'Q8_0',
|
|
1549
|
+
token = '',
|
|
1550
|
+
nodeMeta = null,
|
|
1551
|
+
rootDir = process.cwd(),
|
|
1552
|
+
fetchImpl = globalThis.fetch,
|
|
1553
|
+
} = {}) {
|
|
1554
|
+
const key = String(jobId || '');
|
|
1555
|
+
const entry = key ? _downloads.get(key) : null;
|
|
1556
|
+
const cleanFolder = String(folderName || entry?.job?.folderName || (key.startsWith('disk_') ? key.slice(5) : '')).trim();
|
|
1557
|
+
let state = {};
|
|
1558
|
+
if (cleanFolder) {
|
|
1559
|
+
const stateFile = path.join(rootDir, 'MODELS', 'Local', '#downloads', cleanFolder, DOWNLOAD_STATE_FILE);
|
|
1560
|
+
if (fs.existsSync(stateFile)) {
|
|
1561
|
+
try { state = JSON.parse(await fsp.readFile(stateFile, 'utf-8')); }
|
|
1562
|
+
catch { /* ignore */ }
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
const resolvedRepo = repoId || entry?.job?.repoId || state.repoId;
|
|
1566
|
+
if (!resolvedRepo)
|
|
1567
|
+
throw new Error(`Не удалось определить репозиторий Hugging Face для докачки «${cleanFolder || key}»`);
|
|
1568
|
+
|
|
1569
|
+
return startHuggingFaceDownload({
|
|
1570
|
+
repoId: resolvedRepo,
|
|
1571
|
+
quant,
|
|
1572
|
+
revision: entry?.job?.revision || state.revision || 'main',
|
|
1573
|
+
token,
|
|
1574
|
+
rootDir,
|
|
1575
|
+
providerFolder: entry?.job?.providerFolder || state.providerFolder || 'Local',
|
|
1576
|
+
targetNodeName: cleanFolder,
|
|
1577
|
+
nodeMeta: nodeMeta || entry?.nodeMeta || state.nodeMeta || null,
|
|
1578
|
+
registerInWork: entry?.registerInWork ?? state.registerInWork ?? true,
|
|
1579
|
+
fetchImpl,
|
|
1580
|
+
});
|
|
1236
1581
|
}
|
|
1237
1582
|
|
|
1238
|
-
export function cancelHuggingFaceDownload(jobId) {
|
|
1583
|
+
export function cancelHuggingFaceDownload(jobId, { keepFiles = false } = {}) {
|
|
1239
1584
|
const entry = _downloads.get(String(jobId || ''));
|
|
1240
1585
|
if (!entry)
|
|
1241
1586
|
return null;
|
|
1587
|
+
entry.setKeepFiles?.(Boolean(keepFiles));
|
|
1242
1588
|
entry.controller.abort();
|
|
1243
|
-
entry.job.status = 'cancelled';
|
|
1589
|
+
entry.job.status = keepFiles ? 'paused' : 'cancelled';
|
|
1590
|
+
entry.job.etaSeconds = null;
|
|
1244
1591
|
entry.job.finishedAt = Date.now();
|
|
1245
1592
|
return { ...entry.job };
|
|
1246
1593
|
}
|