odant-work 1.0.79 → 1.0.80

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.
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "packageName": "odant-work",
3
- "version": "1.0.79",
3
+ "version": "1.0.80",
4
4
  "createdAt": 1795100682741,
5
- "updatedAt": 1795617066093,
5
+ "updatedAt": 1795679116239,
6
6
  "files": {
7
7
  "run.mjs": "f8918c612e8641e9beee06221be6680aa6fd21f25468451f2ac857fd51772266",
8
- "package.json": "50131a77dc0d102c13d6f0f308193d43f70766fccb37dcd1c2cf24da56ec81a7",
9
- "package-lock.json": "8f755207ab52da7f0680ddb16cb61acc6fd97689a78e8f8493f9f6893c8ee5c6",
8
+ "package.json": "9c78ed13db73f012082612fd1961df4f1cb3b43bdde951bc34566c229bda8cde",
9
+ "package-lock.json": "e345cb23161a7e41c3ceeaef497f421678df83c9ca64bd82639584c9188effa6",
10
10
  "sources/client/class.js": "c3fb8f143fc83aaa2df1ddeddd412d2d4dfe88656578095babe2df34fb3b3922",
11
11
  "sources/client/field.js": "ffdd50fa8b6ec515cc42da5fca96658ff2b20e274601a1f926e0031372467a19",
12
12
  "sources/client/file.js": "667101d75fa30840370d5be232e518aaac7c1fd52ca05a12da560eef6c0848b0",
13
- "sources/client/folder.js": "691f16dbebe9b908fc3b5c32244afda16f7436e5aee8f4726cf42b2678517de1",
13
+ "sources/client/folder.js": "e9d7e0a8b429401afeddd9a0740d4a5e506149588b4c865104f99d89117142d9",
14
14
  "sources/client/handler.js": "8c19284248fbe61272ef9e59c72e5beaf5cfd3cfab1ee03d0796901d95679b6c",
15
15
  "sources/client/index.js": "037ff635b149a617adf1219d34f0ba9dd936d5f60cea59e62d276a49468c3dc3",
16
16
  "sources/client/readme.md": "a50aa4aa3a90606b2f446e2d29166aa26175ae87539901299e9347322ae4a2fe",
@@ -36,7 +36,7 @@
36
36
  "sources/data/time.js": "cb34c1137685e83265938bb007859dfc1fca3548588d1663ee01e1affc87a09a",
37
37
  "sources/data/workspace.js": "afbc007c16a26e86de2753794e0e7387218e97aba378047a5f37ea7961e3e921",
38
38
  "sources/host/auth-methods.js": "d3373f072a0b31f1c689beffba144c334c848cb4a0a0a3a74f6146ff8e1292d0",
39
- "sources/host/auto-updater.js": "fbab9f06c508e079a8c055a1ca7a9fd61bba22ba396f5f85204883cbe19b79e9",
39
+ "sources/host/auto-updater.js": "be3d3d17f11ab5aeb39db178eef92b7829095557bd35eb0df592f6650293a877",
40
40
  "sources/host/babel-merge.js": "11d5b65cae03aeabd09f06f65bee78f6fd0131eab125cc87c0dcaaf2d10e08a5",
41
41
  "sources/host/config.js": "f41058d2ef46afc0ac5e262a0f31064d3288ab3794c4d45c0761498e775f60ae",
42
42
  "sources/host/email-utils.js": "b15c9dadad3529f48ec9da2312394d321777ed8ec8ce1cb5c4b7946617070fcf",
@@ -203,7 +203,7 @@
203
203
  "sources/reactor.js": "fa132f59bac51e0d7b05a109b83100046eacddfc84576bef6115c2605b57ebf6",
204
204
  "sources/readme.md": "045fa4d63779731d4c535deefa7bfb2956b021ab25a4d86b8dc41d6f964386f2",
205
205
  "sources/server/access/audit.js": "b3e2cf891faf4ce97f7e8eb96a8482727ed1ad25d0ed5d6cc4e30eb922917952",
206
- "sources/server/access/gateway.js": "f3ec5b454ab3a546e0b84c73daa30c0d1feaee64aad204a162a2a701cb67625c",
206
+ "sources/server/access/gateway.js": "a376781fd02408dc92cf1be36b0691ba75ee44820c4b2a9242cb3bd69b9678ac",
207
207
  "sources/server/access/index.js": "c98fd2acc4164e299334ab865a12a07218a81c6197e1021eecb155f0096688b7",
208
208
  "sources/server/access/invites.js": "0a500a191eb58c575e31b5d594059aedf8abcf189ba8b36f600564c19f9127aa",
209
209
  "sources/server/access/links.js": "6adb41bd50057f28a6298054458611765aafb4336bd28166de129c30c0e36ddc",
@@ -232,12 +232,12 @@
232
232
  "sources/server/node.js": "c1aba780ddaa077ffcd63cd3387d1a5b96d67396651badfd39c5e65382f3a94d",
233
233
  "sources/server/readme.md": "171ab173184008c748d8062f2473e8630b53ebc6a76b220a2547d5ae8bbd4999",
234
234
  "sources/server/safe-node-name.js": "8ab1be33347050b09d7b76f0beb02a81e590216116c24096db4d061e9e1de54b",
235
- "sources/server/server.js": "497e26c5ca3d6427cde3fad1eaf6a51cad4157425ece90f34ee05e4caba41e21",
235
+ "sources/server/server.js": "34e23e5492f31b24e60867d9bcadc2debbbf3f93354a8c920d6958db6b0baf27",
236
236
  "sources/server/upload-mark.js": "8cf8da3e3935b98132485a26a467b072e31a08b14a36e91a5e26c683918286d2",
237
237
  "sources/server/user.js": "638a159ab5be43c1b42da48e8643f5dd849de6740b951868285413f9a0e5a3f4",
238
238
  "sources/server/zip-guard.js": "c377e9c0ca779764b64614cc0e32a435483c55261a73f144209306be3c15e76c",
239
239
  "sources/tester.html": "69ed1c6c68586cb32da9f7939305a1570ddc919a3e6f8d19b74ecfcd13f98f10",
240
- "sources/work.js": "7ea712fc13743d0ec15126667940321d350e293b4f52b2aa578595524ae524bd",
240
+ "sources/work.js": "e649c43ae62b657b06bfb457a31349373c4095755ed7eb644411c2c1f17aa8a8",
241
241
  "oda/benchmarks/dbmon/index.html": "f7215c6ae05491250f9b628001a5eb85361bf4738224870eda7b992f0aa6aec8",
242
242
  "oda/benchmarks/dbmon/lib/ENV.js": "968c7162a59f3fa3e8a90afafdbd81aeda02ee6459edc0eca5438192fbb140c5",
243
243
  "oda/benchmarks/dbmon/lib/ga.js": "7f32f81f7d505d1ebf21d1d6fc4c6e5fba58893a567c9caa176d32f79f3c9278",
@@ -814,7 +814,7 @@
814
814
  "$server/$folder/lib/menu/progress.md": "f88ee7fde608ec00a9f2459e11b28328c0c6003f1b365b919c3dd9004296c86a",
815
815
  "$server/$folder/lib/menu/readme.md": "2fcd2b1b905ac9cd25264da2cef02d53d181e97b9d02c16772770de82b756eba",
816
816
  "$server/$folder/lib/messenger-settings/messenger-settings.js": "0e6237d9724ae4fd33327f9a521b26e698d7b40074d39402d1f4812ad2fbe085",
817
- "$server/$folder/lib/node/node.js": "5299d9935cbfbe77fe3758426652952533c5096b4b28e58e0a4be6e533972626",
817
+ "$server/$folder/lib/node/node.js": "d22fb78361403156053ed3e6f40a60237a6fb14a7ec9ab256225d6e04131d2e6",
818
818
  "$server/$folder/lib/node/progress.md": "eaada60a7d4f72a913369fda6cdad0abb3c8156215eec4d6bd9211f1ccc441ba",
819
819
  "$server/$folder/lib/node/readme.md": "ea9b82dc0db4af289b08d2e41399124310cee089cfab5d2107663ee314a23741",
820
820
  "$server/$folder/lib/node-explorer/node-explorer.js": "7f30a60186e5aa81d93ceabade522656403066320f3fa439f6a490049270269e",
@@ -1,5 +1,107 @@
1
1
  import { isLinkNode } from '../tree/link-nodes.js';
2
2
 
3
+ const VERSION_CHECK_INTERVAL_MS = 10 * 60_000;
4
+
5
+ async function waitServerRestart() {
6
+ const probe = async () => {
7
+ try {
8
+ const res = await fetch(window.location.origin, { method: 'HEAD', cache: 'no-store' });
9
+ return Boolean(res);
10
+ }
11
+ catch {
12
+ return false;
13
+ }
14
+ };
15
+ const until = async (wantUp, tries, delay) => {
16
+ for (let i = 0; i < tries; i++) {
17
+ if (await probe() === wantUp)
18
+ return true;
19
+ await new Promise(r => setTimeout(r, delay));
20
+ }
21
+ return false;
22
+ };
23
+ await until(false, 150, 200);
24
+ if (!await until(true, 600, 500))
25
+ throw new Error('Сервер не поднялся — проверьте work-restart.log и обновите страницу вручную');
26
+ }
27
+
28
+ function getWorkVersionStore() {
29
+ const host = globalThis.WORK || globalThis;
30
+ if (host.__workVersionStore)
31
+ return host.__workVersionStore;
32
+ const store = {
33
+ state: null,
34
+ busyLabel: '',
35
+ error: '',
36
+ events: new EventTarget(),
37
+ _rootItem: null,
38
+ _timer: null,
39
+ _inFlight: null,
40
+ _lastFetchAt: 0,
41
+ _visBound: false,
42
+ emit() {
43
+ this.events.dispatchEvent(new Event('change'));
44
+ },
45
+ setBusy(label) {
46
+ this.busyLabel = label || '';
47
+ this.emit();
48
+ },
49
+ ensureStarted(item) {
50
+ if (!item || typeof item.fetch !== 'function')
51
+ return;
52
+ const changedItem = this._rootItem !== item;
53
+ this._rootItem = item;
54
+ if (changedItem || !this.state)
55
+ this.refresh(item, { check: false });
56
+ if (!this._timer) {
57
+ this._timer = setInterval(() => {
58
+ if (this._rootItem)
59
+ this.refresh(this._rootItem, { check: false });
60
+ }, VERSION_CHECK_INTERVAL_MS);
61
+ }
62
+ if (!this._visBound && typeof document !== 'undefined') {
63
+ this._visBound = true;
64
+ document.addEventListener('visibilitychange', () => {
65
+ if (document.visibilityState === 'visible' && this._rootItem && (Date.now() - this._lastFetchAt) >= VERSION_CHECK_INTERVAL_MS)
66
+ this.refresh(this._rootItem, { check: false });
67
+ });
68
+ }
69
+ },
70
+ async refresh(item, { check = false } = {}) {
71
+ if (!item || typeof item.fetch !== 'function')
72
+ return this.state;
73
+ if (this._inFlight && !check)
74
+ return this._inFlight;
75
+ const req = (async () => {
76
+ try {
77
+ const res = await item.fetch('version_status', check ? { check: 1 } : {});
78
+ if (res && typeof res === 'object' && res.runningVersion) {
79
+ this.state = res;
80
+ this.error = res.checkError || '';
81
+ this._lastFetchAt = Date.now();
82
+ this.emit();
83
+ }
84
+ return this.state;
85
+ }
86
+ catch (err) {
87
+ this.error = String(err?.message || err);
88
+ this.emit();
89
+ return this.state;
90
+ }
91
+ finally {
92
+ if (this._inFlight === req)
93
+ this._inFlight = null;
94
+ }
95
+ })();
96
+ if (!check)
97
+ this._inFlight = req;
98
+ return req;
99
+ },
100
+ };
101
+ host.__workVersionStore = store;
102
+ return store;
103
+ }
104
+
3
105
  export default {
4
106
  imports: '~/lib//icon, ~/lib//users',
5
107
  extends: 'item-icon',
@@ -117,6 +219,37 @@ export default {
117
219
  align-self: center;
118
220
  margin-right: 4px;
119
221
  }
222
+ .work-ver{
223
+ @apply --no-flex;
224
+ font-size: 11px;
225
+ font-family: monospace;
226
+ line-height: 1.25;
227
+ padding: 2px 7px;
228
+ margin-left: 6px;
229
+ border-radius: 999px;
230
+ border: 1px solid light-dark(rgba(100, 116, 139, 0.28), rgba(148, 163, 184, 0.28));
231
+ background: light-dark(rgba(100, 116, 139, 0.08), rgba(148, 163, 184, 0.12));
232
+ color: var(--muted-color, light-dark(#64748b, #94a3b8));
233
+ white-space: nowrap;
234
+ align-self: center;
235
+ user-select: none;
236
+ }
237
+ .work-ver.clickable{
238
+ cursor: pointer;
239
+ }
240
+ .work-ver.clickable:hover{
241
+ filter: brightness(0.95);
242
+ }
243
+ .work-ver.has-update{
244
+ border-color: light-dark(rgba(22, 163, 74, 0.45), rgba(74, 222, 128, 0.45));
245
+ background: light-dark(#dcfce7, rgba(22, 163, 74, 0.24));
246
+ color: light-dark(#15803d, #86efac);
247
+ font-weight: 700;
248
+ }
249
+ .work-ver.busy{
250
+ opacity: .75;
251
+ cursor: wait;
252
+ }
120
253
  </style>
121
254
  <div horizontal flex style="align-items: center; min-width: 0; width: 100%;">
122
255
  <div vertical flex style="min-width: 0;">
@@ -127,6 +260,10 @@ export default {
127
260
  <span class="history-time" ~if="historyTime" ~show="!hideLabel">{{historyTime}}</span>
128
261
  </div>
129
262
  </div>
263
+ <span class="work-ver" ~if="showWorkVersion"
264
+ ~class="{ 'has-update': workVersionHasUpdate, clickable: workVersionClickable, busy: workVersionBusy }"
265
+ :title="workVersionTitle"
266
+ @tap.stop="onWorkVersionTap($event)">{{workVersionText}}</span>
130
267
  <span class="unread-badge" ~if="unreadCount > 0">{{unreadCount > 99 ? '99+' : unreadCount}}</span>
131
268
  <span class="obj-count" ~if="objectCount">{{objectCount}}</span>
132
269
  <span class="size" ~if="showSize && !($item instanceof CORE.$class) && !isPlace" ~show="$item?.size">{{$item?.size}}</span>
@@ -272,7 +409,9 @@ export default {
272
409
  }
273
410
  },
274
411
  showStatus: false,
412
+ isExplorer: false,
275
413
  _unreadVer: 0,
414
+ _workVerTick: 0,
276
415
  attached() {
277
416
  if (!this._onChatUnreadEvt && globalThis.WORK) {
278
417
  globalThis.WORK.chatEvents ??= new EventTarget();
@@ -280,6 +419,13 @@ export default {
280
419
  globalThis.WORK.chatEvents.addEventListener('chat:message', this._onChatUnreadEvt);
281
420
  globalThis.WORK.chatEvents.addEventListener('chat:read', this._onChatUnreadEvt);
282
421
  }
422
+ const store = getWorkVersionStore();
423
+ if (!this._onWorkVerEvt) {
424
+ this._onWorkVerEvt = () => { this._workVerTick++; };
425
+ store.events.addEventListener('change', this._onWorkVerEvt);
426
+ }
427
+ if (this.isWorkServerNode)
428
+ store.ensureStarted(this.$item);
283
429
  },
284
430
  detached() {
285
431
  if (this._onChatUnreadEvt && globalThis.WORK?.chatEvents) {
@@ -287,6 +433,126 @@ export default {
287
433
  globalThis.WORK.chatEvents.removeEventListener('chat:read', this._onChatUnreadEvt);
288
434
  this._onChatUnreadEvt = null;
289
435
  }
436
+ if (this._onWorkVerEvt) {
437
+ getWorkVersionStore().events.removeEventListener('change', this._onWorkVerEvt);
438
+ this._onWorkVerEvt = null;
439
+ }
440
+ },
441
+ get isWorkServerNode() {
442
+ const it = this.$item;
443
+ if (!it || this.isLink || this.hideLabel || this.isExplorer || this.hasAttribute?.('is-explorer'))
444
+ return false;
445
+ const p = String(it.path || it.short || '/').replace(/\/+$/, '') || '/';
446
+ return it.type === '$server' && p === '/';
447
+ },
448
+ get _workVerInfo() {
449
+ void this._workVerTick;
450
+ if (!this.isWorkServerNode)
451
+ return null;
452
+ const store = getWorkVersionStore();
453
+ if (store._rootItem !== this.$item)
454
+ store.ensureStarted(this.$item);
455
+ return store.state ? { ...store.state, busyLabel: store.busyLabel, error: store.error } : null;
456
+ },
457
+ get showWorkVersion() {
458
+ const info = this._workVerInfo;
459
+ return Boolean(info && (info.runningVersion || info.busyLabel));
460
+ },
461
+ get workVersionHasUpdate() {
462
+ return Boolean(this._workVerInfo?.updateAvailable);
463
+ },
464
+ get workVersionBusy() {
465
+ return Boolean(this._workVerInfo?.busyLabel);
466
+ },
467
+ get workVersionClickable() {
468
+ const info = this._workVerInfo;
469
+ return Boolean(info && info.canUpdate && !info.busyLabel);
470
+ },
471
+ get workVersionText() {
472
+ const info = this._workVerInfo;
473
+ if (!info)
474
+ return '';
475
+ if (info.busyLabel)
476
+ return info.busyLabel;
477
+ if (info.updateAvailable && info.latestVersion)
478
+ return `v${info.runningVersion} ↑ ${info.latestVersion}`;
479
+ return `v${info.runningVersion}`;
480
+ },
481
+ get workVersionTitle() {
482
+ const info = this._workVerInfo;
483
+ if (!info)
484
+ return '';
485
+ if (info.busyLabel)
486
+ return info.busyLabel;
487
+ if (info.updateAvailable && info.latestVersion) {
488
+ return info.canUpdate
489
+ ? `Доступна новая версия ${info.latestVersion} (текущая ${info.runningVersion}) — нажмите, чтобы обновить и перезапустить`
490
+ : `Доступна новая версия ${info.latestVersion} (текущая ${info.runningVersion})`;
491
+ }
492
+ const errPart = info.error ? `\nОшибка проверки: ${info.error}` : '';
493
+ return info.canUpdate
494
+ ? `Версия WORK ${info.runningVersion} — нажмите для проверки обновлений${errPart}`
495
+ : `Версия WORK ${info.runningVersion}${errPart}`;
496
+ },
497
+ async _confirmAndUpdateWork(store, info) {
498
+ if (!info?.updateAvailable || !info?.canUpdate || store.busyLabel)
499
+ return;
500
+ const msg = `Доступна новая версия WORK ${info.latestVersion} (текущая ${info.runningVersion}). Обновить и перезапустить сервер?`;
501
+ let ok = false;
502
+ try {
503
+ if (typeof globalThis.WORK?.showConfirm === 'function')
504
+ ok = await globalThis.WORK.showConfirm(msg);
505
+ else
506
+ ok = window.confirm(msg);
507
+ }
508
+ catch {
509
+ return;
510
+ }
511
+ if (!ok)
512
+ return;
513
+ store.setBusy('Обновление…');
514
+ try {
515
+ const res = await this.$item.fetch('version_update_restart');
516
+ if (!res?.restarted) {
517
+ store.setBusy('');
518
+ await store.refresh(this.$item, { check: false });
519
+ return;
520
+ }
521
+ store.setBusy('Перезапуск…');
522
+ await waitServerRestart();
523
+ window.location.reload();
524
+ }
525
+ catch (err) {
526
+ store.setBusy('');
527
+ store.error = String(err?.message || err);
528
+ store.emit();
529
+ try {
530
+ if (typeof globalThis.WORK?.showToast === 'function')
531
+ globalThis.WORK.showToast(`Не удалось обновить сервер: ${store.error}`, 'error');
532
+ }
533
+ catch { /* ignore */ }
534
+ }
535
+ },
536
+ async onWorkVersionTap(e) {
537
+ e?.stopPropagation?.();
538
+ const store = getWorkVersionStore();
539
+ const info = this._workVerInfo;
540
+ if (!info || !info.canUpdate || store.busyLabel)
541
+ return;
542
+ if (info.updateAvailable) {
543
+ await this._confirmAndUpdateWork(store, info);
544
+ return;
545
+ }
546
+ store.setBusy('Проверка…');
547
+ try {
548
+ const next = await store.refresh(this.$item, { check: true });
549
+ store.setBusy('');
550
+ if (next?.updateAvailable)
551
+ await this._confirmAndUpdateWork(store, { ...next, busyLabel: '' });
552
+ }
553
+ catch {
554
+ store.setBusy('');
555
+ }
290
556
  },
291
557
  get unreadCount() {
292
558
  void this._unreadVer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.79",
3
+ "version": "1.0.80",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
@@ -277,6 +277,9 @@ export class $folder extends $item {
277
277
  || method.startsWith('agent_')
278
278
  || method === 'security_update'
279
279
  || method === 'export_distro'
280
+ || method === 'version_status'
281
+ || method === 'version_update_restart'
282
+ || method === 'restart_server'
280
283
  ))
281
284
  || (method === 'logs' && params.mode && params.mode !== 'folder' && params.mode !== 'files');
282
285
  return WORK.fetch?.(this.short || '/', method, params, post_data).then(res => {
@@ -21,10 +21,11 @@ import { spawn } from 'node:child_process';
21
21
 
22
22
  export const PACKAGE_NAME = 'odant-work';
23
23
  export const DEFAULT_NPM_REGISTRY = process.env.WORK_NPM_REGISTRY || 'https://registry.npmjs.org';
24
- export const DEFAULT_CHECK_INTERVAL_MS = 6 * 3600_000; // каждые 6 часов
24
+ export const DEFAULT_CHECK_INTERVAL_MS = 10 * 60_000; // каждые 10 минут
25
25
 
26
26
  const MANIFEST_REL_PATH = '#system/package-manifest.json';
27
27
  const STATE_REL_PATH = '#system/auto-update.json';
28
+ const RUNNING_VERSIONS = new Map();
28
29
 
29
30
  /**
30
31
  * Сравнить две semver-версии (например, "1.0.4" и "1.0.3").
@@ -279,7 +280,7 @@ export function loadAutoUpdateState(rootDir = '.') {
279
280
  enabled: true,
280
281
  packageName: PACKAGE_NAME,
281
282
  registryUrl: DEFAULT_NPM_REGISTRY,
282
- checkIntervalHours: 6,
283
+ checkIntervalMinutes: 10,
283
284
  lastCheckAt: null,
284
285
  lastUpdateAt: null,
285
286
  lastVersionFrom: null,
@@ -314,6 +315,48 @@ export function saveAutoUpdateState(patch = {}, rootDir = '.') {
314
315
  return next;
315
316
  }
316
317
 
318
+ /**
319
+ * Запомнить (при первом обращении) и вернуть версию пакета, с которой стартовал текущий процесс.
320
+ */
321
+ export function getRunningVersion(rootDir = '.') {
322
+ const absRoot = path.resolve(rootDir);
323
+ if (!RUNNING_VERSIONS.has(absRoot))
324
+ RUNNING_VERSIONS.set(absRoot, readLocalPackageVersion(absRoot));
325
+ return RUNNING_VERSIONS.get(absRoot);
326
+ }
327
+
328
+ /**
329
+ * Текущий статус версий (без сетевого запроса):
330
+ * запущенная в памяти, версия на диске и последняя известная из npm.
331
+ */
332
+ export function getVersionStatus({ rootDir = '.' } = {}) {
333
+ const absRoot = path.resolve(rootDir);
334
+ const runningVersion = getRunningVersion(absRoot);
335
+ const diskVersion = readLocalPackageVersion(absRoot);
336
+ const state = loadAutoUpdateState(absRoot);
337
+ const npmVersion = state.latestAvailableVersion ? String(state.latestAvailableVersion) : '';
338
+
339
+ let latestVersion = runningVersion;
340
+ if (compareSemver(diskVersion, latestVersion) > 0)
341
+ latestVersion = diskVersion;
342
+ if (npmVersion && compareSemver(npmVersion, latestVersion) > 0)
343
+ latestVersion = npmVersion;
344
+
345
+ const updateAvailable = compareSemver(latestVersion, runningVersion) > 0;
346
+ const needsDownload = Boolean(npmVersion && compareSemver(npmVersion, diskVersion) > 0);
347
+ return {
348
+ packageName: state.packageName || PACKAGE_NAME,
349
+ runningVersion,
350
+ diskVersion,
351
+ latestVersion,
352
+ npmVersion: npmVersion || null,
353
+ updateAvailable,
354
+ needsDownload,
355
+ checkedAt: state.lastCheckAt || null,
356
+ lastError: state.lastError || null,
357
+ };
358
+ }
359
+
317
360
  /**
318
361
  * Проверить наличие более свежей версии пакета odant-work в npm registry.
319
362
  */
@@ -323,40 +366,50 @@ export async function checkForNpmUpdates({
323
366
  packageName,
324
367
  fetchImpl = globalThis.fetch,
325
368
  } = {}) {
326
- const state = loadAutoUpdateState(rootDir);
369
+ const absRoot = path.resolve(rootDir);
370
+ const runningVersion = getRunningVersion(absRoot);
371
+ const state = loadAutoUpdateState(absRoot);
327
372
  const pkgName = packageName || state.packageName || PACKAGE_NAME;
328
373
  const regUrl = String(registryUrl || state.registryUrl || DEFAULT_NPM_REGISTRY).replace(/\/+$/, '');
329
- const currentVersion = readLocalPackageVersion(rootDir);
374
+ const currentVersion = readLocalPackageVersion(absRoot);
330
375
  const now = Date.now();
331
376
 
332
377
  const metaUrl = `${regUrl}/${encodeURIComponent(pkgName)}/latest`;
333
378
  const res = await fetchImpl(metaUrl, {
334
- headers: { 'Accept': 'application/json' },
379
+ headers: { 'Accept': 'application/json', 'Cache-Control': 'no-cache' },
335
380
  });
336
381
  if (!res.ok) {
337
382
  const errText = await res.text().catch(() => '');
338
383
  const errMsg = `npm registry (${metaUrl}) ответил HTTP ${res.status}: ${errText.slice(0, 160)}`;
339
- saveAutoUpdateState({ lastCheckAt: now, lastError: errMsg }, rootDir);
384
+ saveAutoUpdateState({ lastCheckAt: now, lastError: errMsg }, absRoot);
340
385
  throw new Error(errMsg);
341
386
  }
342
387
 
343
388
  const meta = await res.json();
344
- const latestVersion = String(meta.version || currentVersion);
345
- const updateAvailable = compareSemver(latestVersion, currentVersion) > 0;
389
+ const npmVersion = String(meta.version || currentVersion);
390
+ let latestVersion = npmVersion;
391
+ if (compareSemver(currentVersion, latestVersion) > 0)
392
+ latestVersion = currentVersion;
393
+ const diskNeedsUpdate = compareSemver(npmVersion, currentVersion) > 0;
394
+ const updateAvailable = compareSemver(latestVersion, runningVersion) > 0 || diskNeedsUpdate;
346
395
  const tarballUrl = String(meta.dist?.tarball || '');
347
396
  const shasum = String(meta.dist?.shasum || '');
348
397
 
349
398
  const updatedState = saveAutoUpdateState({
350
399
  lastCheckAt: now,
351
- latestAvailableVersion: latestVersion,
400
+ latestAvailableVersion: npmVersion,
352
401
  updateAvailable,
353
402
  lastError: null,
354
- }, rootDir);
403
+ }, absRoot);
355
404
 
356
405
  return {
357
406
  packageName: pkgName,
407
+ runningVersion,
358
408
  currentVersion,
409
+ diskVersion: currentVersion,
359
410
  latestVersion,
411
+ npmVersion,
412
+ diskNeedsUpdate,
360
413
  updateAvailable,
361
414
  tarballUrl,
362
415
  shasum,
@@ -751,7 +804,14 @@ export async function checkAndApplyNpmUpdate({
751
804
  installDeps = false,
752
805
  } = {}) {
753
806
  const check = await checkForNpmUpdates({ rootDir, registryUrl, packageName, fetchImpl });
754
- if (!check.updateAvailable) {
807
+ if (!check.diskNeedsUpdate) {
808
+ if (compareSemver(check.latestVersion, check.runningVersion) > 0) {
809
+ return {
810
+ updated: true,
811
+ alreadyOnDisk: true,
812
+ ...check,
813
+ };
814
+ }
755
815
  return {
756
816
  updated: false,
757
817
  ...check,
@@ -810,14 +870,16 @@ export async function checkAndApplyNpmUpdate({
810
870
  let updateTimer = null;
811
871
 
812
872
  /**
813
- * Запустить фоновую периодическую проверку и автообновление из npm.
873
+ * Запустить фоновую периодическую проверку обновлений из npm (по умолчанию каждые 10 мин, только проверка).
814
874
  */
815
875
  export function startAutoUpdateDaemon({
816
876
  rootDir = '.',
817
877
  intervalMs,
818
878
  runOnStart = true,
879
+ autoApply = process.env.WORK_AUTO_APPLY === '1',
819
880
  fetchImpl = globalThis.fetch,
820
881
  } = {}) {
882
+ getRunningVersion(rootDir);
821
883
  ensurePackageManifest(rootDir);
822
884
  const state = loadAutoUpdateState(rootDir);
823
885
  if (updateTimer) {
@@ -828,7 +890,10 @@ export function startAutoUpdateDaemon({
828
890
  try {
829
891
  const cur = loadAutoUpdateState(rootDir);
830
892
  if (!cur.enabled) return;
831
- await checkAndApplyNpmUpdate({ rootDir, fetchImpl, installDeps: true });
893
+ if (autoApply)
894
+ await checkAndApplyNpmUpdate({ rootDir, fetchImpl, installDeps: true });
895
+ else
896
+ await checkForNpmUpdates({ rootDir, fetchImpl });
832
897
  }
833
898
  catch (err) {
834
899
  console.warn('[auto-updater]', err?.message || err);
@@ -838,7 +903,7 @@ export function startAutoUpdateDaemon({
838
903
  const bootTimer = setTimeout(runCheck, 5_000);
839
904
  bootTimer.unref?.();
840
905
  }
841
- const period = Number(intervalMs || (state.checkIntervalHours || 6) * 3600_000 || DEFAULT_CHECK_INTERVAL_MS);
906
+ const period = Number(intervalMs || (state.checkIntervalMinutes ? state.checkIntervalMinutes * 60_000 : DEFAULT_CHECK_INTERVAL_MS));
842
907
  updateTimer = setInterval(runCheck, period);
843
908
  updateTimer.unref?.();
844
909
  return updateTimer;
@@ -85,10 +85,10 @@ export const MEMBERS = Object.freeze({
85
85
  ...Object.fromEntries(Object.entries(KLADR_METHODS).map(([name, m]) => [name, m.level])),
86
86
  remove_push_subscription: L.WRITE, send_push_notification: L.WRITE,
87
87
  // администрирование
88
- delete: L.ADMIN, npm: L.ADMIN, restart_normal: L.ADMIN, read_secret: L.ADMIN,
88
+ delete: L.ADMIN, npm: L.ADMIN, restart_normal: L.ADMIN, restart_server: L.ADMIN, read_secret: L.ADMIN,
89
89
  save_secret: L.ADMIN, clear_rag: L.ADMIN, security_log: L.ADMIN, agent_panel: L.ADMIN,
90
90
  set_enabled: L.ADMIN, export_archive: L.READ, import_archive: L.ADMIN, delete_log_entry: L.WRITE,
91
- distro_info: L.READ, export_distro: L.READ,
91
+ distro_info: L.READ, export_distro: L.READ, version_status: L.READ, version_update_restart: L.ADMIN,
92
92
  });
93
93
 
94
94
  /** Никогда не вызываются снаружи, даже если объявлены в class.js. */
@@ -1,6 +1,7 @@
1
1
  import * as http from "node:http";
2
2
  import * as https from "node:https";
3
3
  import * as fs from "node:fs";
4
+ import * as path from "node:path";
4
5
  import { createHash, randomBytes } from "node:crypto";
5
6
  import * as mime from "mime-types";
6
7
  import * as fsp from "node:fs/promises";
@@ -721,21 +722,84 @@ export class $server extends $class {
721
722
  }
722
723
 
723
724
  /**
724
- * Отложенный штатный перезапуск процесса WORK (например после правки ядра sources/).
725
- * Работает как в DEV_MODE, так и в обычном режиме; доступен только BOSS корневого WORK.
725
+ * Получить статус версии WORK (запущенная, на диске, последняя в npm).
726
+ * Если передан check=1 и пользователь — BOSS корня, выполняет мгновенную проверку npm.
726
727
  */
727
- async restart_server(params = {}) {
728
+ async version_status(params = {}) {
729
+ const rootDir = this.dir || process.cwd();
730
+ const uid = $class.resolveUid(params);
731
+ const roles = uid ? await this.roles(params).catch(() => []) : [];
732
+ const canUpdate = Boolean(DEV_MODE || roles.includes('BOSS'));
733
+ const { checkForNpmUpdates, getVersionStatus } = await import('../host/auto-updater.js');
734
+ let checkError = null;
735
+ if (params.check && params.check !== '0' && params.check !== 'false' && canUpdate) {
736
+ try {
737
+ await checkForNpmUpdates({ rootDir });
738
+ }
739
+ catch (err) {
740
+ checkError = String(err?.message || err);
741
+ }
742
+ }
743
+ const status = getVersionStatus({ rootDir });
744
+ return {
745
+ ...status,
746
+ canUpdate,
747
+ ...(checkError ? { checkError } : {}),
748
+ };
749
+ }
750
+
751
+ /**
752
+ * При наличии новой версии скачать и применить её из npm (с сохранением данных и правок),
753
+ * затем перезапустить сервер уже в новой версии. Доступно только BOSS корневого WORK.
754
+ */
755
+ async version_update_restart(params = {}) {
728
756
  const uid = $class.resolveUid(params);
729
757
  if (!uid)
730
758
  throw new Error('Доступ запрещён');
731
759
  const roles = await this.roles(params).catch(() => []);
732
760
  if (!roles.includes('BOSS'))
733
761
  throw new Error('Доступ запрещён');
762
+
763
+ const rootDir = path.resolve(this.dir || process.cwd());
764
+ const { checkAndApplyNpmUpdate, getVersionStatus } = await import('../host/auto-updater.js');
765
+ const before = getVersionStatus({ rootDir });
766
+ let applyResult = null;
767
+ if (before.needsDownload || !before.updateAvailable) {
768
+ applyResult = await checkAndApplyNpmUpdate({ rootDir, installDeps: true });
769
+ }
770
+ const after = getVersionStatus({ rootDir });
771
+ if (!after.updateAvailable && !applyResult?.updated) {
772
+ return {
773
+ restarted: false,
774
+ updated: false,
775
+ status: after,
776
+ };
777
+ }
778
+
779
+ const localRunMjs = path.join(rootDir, 'run.mjs');
780
+ const extraArgs = process.argv.slice(2);
781
+ const entryArgs = fs.existsSync(localRunMjs)
782
+ ? [localRunMjs, ...extraArgs]
783
+ : (process.argv.slice(1).length ? process.argv.slice(1) : ['run.mjs']);
784
+ const delayMs = await this._scheduleProcessRestart({ cwd: rootDir, entryArgs, delayMs: params.delayMs });
785
+ return {
786
+ restarted: true,
787
+ updated: true,
788
+ fromVersion: before.runningVersion,
789
+ toVersion: after.latestVersion,
790
+ delayMs,
791
+ status: after,
792
+ };
793
+ }
794
+
795
+ async _scheduleProcessRestart({ cwd = process.cwd(), entryArgs, delayMs: rawDelay } = {}) {
734
796
  const { spawn } = await import('node:child_process');
735
797
  const env = { ...process.env };
736
798
  delete env.NODE_OPTIONS;
737
- const entryArgs = process.argv.slice(1).length ? process.argv.slice(1) : ['run.mjs'];
738
- const delayMs = Math.max(1500, Math.min(10000, Number(params.delayMs) || 2500));
799
+ const args = Array.isArray(entryArgs) && entryArgs.length
800
+ ? entryArgs
801
+ : (process.argv.slice(1).length ? process.argv.slice(1) : ['run.mjs']);
802
+ const delayMs = Math.max(1500, Math.min(10000, Number(rawDelay) || 2500));
739
803
  const helper = `
740
804
  const fs = await import('node:fs');
741
805
  const path = await import('node:path');
@@ -756,10 +820,25 @@ export class $server extends $class {
756
820
  child.unref();
757
821
  `;
758
822
  spawn(process.execPath, ['--input-type=module', '-e', helper,
759
- String(process.pid), process.cwd(), JSON.stringify(env), JSON.stringify(entryArgs)], {
823
+ String(process.pid), cwd, JSON.stringify(env), JSON.stringify(args)], {
760
824
  detached: true, stdio: 'ignore', env,
761
825
  }).unref();
762
826
  setTimeout(() => process.exit(0), delayMs).unref?.();
827
+ return delayMs;
828
+ }
829
+
830
+ /**
831
+ * Отложенный штатный перезапуск процесса WORK (например после правки ядра sources/).
832
+ * Работает как в DEV_MODE, так и в обычном режиме; доступен только BOSS корневого WORK.
833
+ */
834
+ async restart_server(params = {}) {
835
+ const uid = $class.resolveUid(params);
836
+ if (!uid)
837
+ throw new Error('Доступ запрещён');
838
+ const roles = await this.roles(params).catch(() => []);
839
+ if (!roles.includes('BOSS'))
840
+ throw new Error('Доступ запрещён');
841
+ const delayMs = await this._scheduleProcessRestart({ delayMs: params.delayMs });
763
842
  return { scheduled: true, delayMs };
764
843
  }
765
844
  }
package/sources/work.js CHANGED
@@ -119,12 +119,17 @@ if (process.env.WORK_SWEEP !== '0') {
119
119
  }, 2 * 60_000).unref?.();
120
120
  }
121
121
 
122
- // Автообновление из npm (с сохранением пользовательских баз, классов, файлов и настроек)
122
+ // Автообновление из npm (проверка каждые 10 мин; применение и перезапуск — по клику на ноде WORK)
123
123
  // и периодическая синхронизация лицензий по привязанному токену владельца (#system/owner-token.json)
124
+ import('./host/auto-updater.js')
125
+ .then(m => {
126
+ m.getRunningVersion('.');
127
+ if (process.env.WORK_AUTO_UPDATE !== '0' && !process.env.WORK_TEST)
128
+ m.startAutoUpdateDaemon();
129
+ })
130
+ .catch(e => console.warn('[auto-updater]', e?.message || e));
131
+
124
132
  if (process.env.WORK_AUTO_UPDATE !== '0' && !process.env.WORK_TEST) {
125
- import('./host/auto-updater.js')
126
- .then(m => m.startAutoUpdateDaemon())
127
- .catch(e => console.warn('[auto-updater]', e?.message || e));
128
133
 
129
134
  // Первичная и адаптивная автосинхронизация лицензий (Q10):
130
135
  // через 5 с после старта; каждые 30 с пока базовая лицензия ожидает активации, затем каждые 15 мин.