odant-work 1.0.78 → 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,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.78",
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;