odant-work 1.0.101 → 1.0.103

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 (83) hide show
  1. package/$server/$folder/$class/$structure/$department/ai/config.js +9 -0
  2. package/$server/$folder/$class/$structure/$department/ai/system.md +11 -0
  3. package/$server/$folder/$class/$structure/$department/class.js +9 -0
  4. package/$server/$folder/$class/$structure/$project/ai/config.js +9 -0
  5. package/$server/$folder/$class/$structure/$project/ai/system.md +12 -0
  6. package/$server/$folder/$class/$structure/$project/class.js +4 -1
  7. package/$server/$folder/$class/$structure/$project/handlers/pages/site/$handler/class.js +1 -1
  8. package/$server/$folder/$class/$structure/$server/ai/config.js +9 -0
  9. package/$server/$folder/$class/$structure/$server/ai/system.md +10 -0
  10. package/$server/$folder/$class/$structure/$server/class.js +2 -0
  11. package/$server/$folder/$class/$structure/$user/ai/config.js +9 -0
  12. package/$server/$folder/$class/$structure/$user/ai/system.md +8 -0
  13. package/$server/$folder/$class/$structure/$user/class.js +2 -0
  14. package/$server/$folder/$class/$structure/ai/system.md +1 -1
  15. package/$server/$folder/$class/$structure/class.js +4 -2
  16. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat-task.js +17 -6
  17. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/class.js +91 -22
  18. package/$server/$folder/$class/$structure/handlers/pages/form/system/agent/$handler/class.js +132 -3
  19. package/$server/$folder/$class/$structure/handlers/pages/form/system/staff/$handler/class.js +2 -2
  20. package/$server/$folder/$class/$structure/handlers/pages/site/$handler/class.js +2 -1
  21. package/$server/$folder/$class/ai/system.md +2 -2
  22. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/class.js +38 -8
  23. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/dock.js +22 -31
  24. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/util.js +32 -0
  25. package/$server/$folder/handlers/pages/form/$handler/class.js +47 -5
  26. package/$server/$folder/lib/chat-item/chat-item.js +14 -2
  27. package/$server/$folder/lib/consultant/consultant.js +81 -4
  28. package/$server/$folder/lib/explorer/explorer.js +20 -11
  29. package/$server/$folder/lib/icon/icon.js +1 -1
  30. package/$server/$folder/lib/node/node.js +3 -3
  31. package/$server/$folder/lib/site-loc/site-loc.js +8 -3
  32. package/$server/$folder/lib/tree/tree.js +8 -8
  33. package/AGENTS.md +3 -3
  34. package/autostart.bat +28 -0
  35. package/autostart.sh +17 -0
  36. package/package.json +1 -1
  37. package/run.mjs +19 -0
  38. package/scripts/autostart.mjs +281 -0
  39. package/scripts/import-bis.mjs +5 -5
  40. package/scripts/import-delovaya.mjs +5 -5
  41. package/scripts/watchdog.mjs +496 -0
  42. package/sources/client/class.js +1 -1
  43. package/sources/client.js +141 -8
  44. package/sources/data/api.js +1 -1
  45. package/sources/data/classes.js +2 -1
  46. package/sources/data/schema.js +2 -0
  47. package/sources/host/auth-methods.js +3 -1
  48. package/sources/host/auto-updater.js +23 -1
  49. package/sources/host/http-server.js +5 -3
  50. package/sources/host/push.js +43 -14
  51. package/sources/host/websocket.js +52 -3
  52. package/sources/modules/agent/index.js +38 -10
  53. package/sources/modules/agent/node-rules.js +353 -9
  54. package/sources/modules/agent/scheduler.js +7 -0
  55. package/sources/modules/agent/scope.js +8 -6
  56. package/sources/modules/agent/session.js +38 -8
  57. package/sources/modules/agent/tools/work/access.js +1 -1
  58. package/sources/modules/agent/tools/work/classes.js +1 -1
  59. package/sources/modules/agent/triggers.js +1 -1
  60. package/sources/modules/agent/twin-bus.js +2 -1
  61. package/sources/modules/notify/index.js +5 -2
  62. package/sources/modules/trainer/local-engine.js +3 -1
  63. package/sources/modules/user-profile/user-profile.js +129 -0
  64. package/sources/server/access/gateway.js +5 -3
  65. package/sources/server/access/links.js +9 -6
  66. package/sources/server/chat-threads.js +1 -1
  67. package/sources/server/class/base-template.js +3 -2
  68. package/sources/server/class/feed.js +36 -0
  69. package/sources/server/class/scaffold.js +137 -0
  70. package/sources/server/class/search.js +2 -2
  71. package/sources/server/class/security.js +1 -1
  72. package/sources/server/class.js +5 -3
  73. package/sources/server/folder.js +10 -6
  74. package/sources/server/logs.js +14 -0
  75. package/sources/server/node.js +1 -1
  76. package/sources/server/server.js +50 -1
  77. package/sources/server/user.js +45 -0
  78. package/sources/work.js +7 -0
  79. package/start.bat +25 -0
  80. package/start.sh +27 -0
  81. package/stop.bat +25 -0
  82. package/stop.sh +16 -0
  83. package/sw.js +3 -11
package/sources/client.js CHANGED
@@ -438,6 +438,8 @@ WORK.login = async function(force = false){
438
438
  WORK.credentials = window.top.WORK.credentials;
439
439
  WORK.uid = window.top.WORK.uid || '';
440
440
  WORK.USER = window.top.WORK.USER;
441
+ WORK.userSettings = window.top.WORK.userSettings || WORK.userSettings;
442
+ WORK._userSettingsLoaded = Boolean(window.top.WORK._userSettingsLoaded);
441
443
  WORK._loginError = null;
442
444
  return res;
443
445
  }
@@ -478,27 +480,41 @@ WORK.login = async function(force = false){
478
480
  if (pendingInviteToken) {
479
481
  try { sessionStorage.removeItem('work.pendingInviteToken'); } catch { /* ignore */ }
480
482
  }
483
+ const prevUid = WORK.uid || '';
484
+ const authChanged = !WORK._authNotifiedOnce || prevUid !== uid;
481
485
  WORK.uid = uid;
482
486
  WORK._loginError = null;
483
487
  WORK._anonExitSynced = false;
484
- await WORK.syncAuthUI();
488
+ if (authChanged || !WORK.USER)
489
+ await WORK.syncAuthUI();
490
+ await WORK.loadUserSettings?.();
485
491
  WORK.refreshChatUnread?.();
486
- WORK.notifyAuth?.({ uid, reason: 'login' });
492
+ if (authChanged) {
493
+ WORK._authNotifiedOnce = true;
494
+ WORK.notifyAuth?.({ uid, reason: 'login' });
495
+ }
487
496
  return res;
488
497
  }
489
498
  const hadAuth = Boolean(WORK.uid);
499
+ const authChanged = !WORK._authNotifiedOnce || hadAuth;
490
500
  if (WORK.uid)
491
501
  await WORK.removeCurrentPushSubscription?.();
492
502
  WORK.uid = '';
503
+ WORK._pushSyncedUid = '';
493
504
  WORK._loginError = null;
494
505
  WORK.USER = undefined;
506
+ WORK.userSettings = { chatSound: true, aiModel: '' };
507
+ WORK._userSettingsLoaded = false;
495
508
  WORK.chatUnread = { total: 0, byThread: {}, byNode: {}, byPeer: {} };
496
509
  if (hadAuth || !WORK._anonExitSynced) {
497
510
  WORK._anonExitSynced = true;
498
511
  await WORK.fetch("/", 'user_exit', {}, {}).catch(() => {});
499
512
  }
500
- await WORK.syncAuthUI();
501
- WORK.notifyAuth?.({ uid: '', reason: 'logout' });
513
+ if (authChanged) {
514
+ await WORK.syncAuthUI();
515
+ WORK._authNotifiedOnce = true;
516
+ WORK.notifyAuth?.({ uid: '', reason: 'logout' });
517
+ }
502
518
  }
503
519
  catch (err) {
504
520
  WORK._loginError = err;
@@ -581,12 +597,117 @@ WORK.getPublicVapid = async function () {
581
597
  key = WORK.urlBase64ToUint8Array(key);
582
598
  return WORK.arrayBufferToBase64(key);
583
599
  }
600
+ function getPushDeviceId() {
601
+ try {
602
+ let id = globalThis.localStorage?.getItem('work.push.deviceId') || '';
603
+ if (!id) {
604
+ id = globalThis.crypto?.randomUUID?.() || (Date.now().toString(36) + '-' + Math.random().toString(36).slice(2));
605
+ globalThis.localStorage?.setItem('work.push.deviceId', id);
606
+ }
607
+ return id;
608
+ }
609
+ catch {
610
+ return '';
611
+ }
612
+ }
584
613
  WORK.storePushSubscription = function (subscription) {
585
- return WORK.fetch("/", 'store_push_subscription', {}, subscription);
614
+ const sub = typeof subscription?.toJSON === 'function' ? subscription.toJSON() : { ...(subscription || {}) };
615
+ const deviceId = getPushDeviceId();
616
+ let replaceEndpoint = '';
617
+ try { replaceEndpoint = globalThis.localStorage?.getItem('work.push.endpoint') || ''; } catch {}
618
+ const payload = {
619
+ ...sub,
620
+ ...(deviceId ? { deviceId } : {}),
621
+ ...(replaceEndpoint && replaceEndpoint !== sub.endpoint ? { replaceEndpoint } : {}),
622
+ };
623
+ try {
624
+ if (sub.endpoint)
625
+ globalThis.localStorage?.setItem('work.push.endpoint', sub.endpoint);
626
+ } catch {}
627
+ return WORK.fetch("/", 'store_push_subscription', {}, payload);
586
628
  }
587
629
  WORK.removePushSubscription = function (subscription) {
588
- return WORK.fetch("/", 'remove_push_subscription', {}, subscription);
630
+ const sub = typeof subscription?.toJSON === 'function' ? subscription.toJSON() : { ...(subscription || {}) };
631
+ const deviceId = getPushDeviceId();
632
+ try { globalThis.localStorage?.removeItem('work.push.endpoint'); } catch {}
633
+ return WORK.fetch("/", 'remove_push_subscription', {}, { ...sub, ...(deviceId ? { deviceId } : {}) });
589
634
  }
635
+ WORK.userSettings = { chatSound: true, aiModel: '' };
636
+ WORK._userSettingsLoaded = false;
637
+ WORK._applyUserSettings = function (next, { broadcast = false } = {}) {
638
+ if (!next || typeof next !== 'object')
639
+ return WORK.userSettings;
640
+ WORK.userSettings = {
641
+ ...WORK.userSettings,
642
+ ...next,
643
+ chatSound: next.chatSound !== false,
644
+ aiModel: typeof next.aiModel === 'string' ? next.aiModel : (WORK.userSettings?.aiModel || ''),
645
+ };
646
+ if (WORK.USER?.DATA)
647
+ WORK.USER.DATA.settings = { ...WORK.userSettings };
648
+ if (broadcast) {
649
+ try { WORK._settingsChannel?.postMessage?.(WORK.userSettings); } catch {}
650
+ }
651
+ try {
652
+ WORK.authEvents?.dispatchEvent?.(new CustomEvent('user-settings', { detail: WORK.userSettings }));
653
+ } catch {}
654
+ return WORK.userSettings;
655
+ };
656
+ if (typeof BroadcastChannel !== 'undefined') {
657
+ try {
658
+ WORK._settingsChannel ??= new BroadcastChannel('work-user-settings');
659
+ WORK._settingsChannel.addEventListener('message', (e) => {
660
+ if (e.data && typeof e.data === 'object')
661
+ WORK._applyUserSettings(e.data, { broadcast: false });
662
+ });
663
+ } catch {}
664
+ }
665
+ WORK.loadUserSettings = async function () {
666
+ if (!WORK.uid || typeof WORK.fetch !== 'function')
667
+ return WORK.userSettings;
668
+ try {
669
+ const res = await WORK.fetch('/', 'user_settings_get');
670
+ if (res && typeof res === 'object') {
671
+ WORK._userSettingsLoaded = true;
672
+ WORK._applyUserSettings(res, { broadcast: false });
673
+ }
674
+ }
675
+ catch { /* ignore */ }
676
+ return WORK.userSettings;
677
+ };
678
+ WORK.saveUserSettings = async function (patch = {}) {
679
+ if (!patch || typeof patch !== 'object')
680
+ return WORK.userSettings;
681
+ WORK._applyUserSettings(patch, { broadcast: true });
682
+ if (!WORK.uid || typeof WORK.fetch !== 'function')
683
+ return WORK.userSettings;
684
+ try {
685
+ const saved = await WORK.fetch('/', 'user_settings_save', {}, patch);
686
+ if (saved && typeof saved === 'object') {
687
+ WORK._userSettingsLoaded = true;
688
+ WORK._applyUserSettings(saved, { broadcast: true });
689
+ }
690
+ }
691
+ catch (err) {
692
+ console.warn('[user-settings] save', err?.message || err);
693
+ }
694
+ return WORK.userSettings;
695
+ };
696
+ WORK._visibleTasks = new Set();
697
+ WORK.setTaskPresence = function (taskPath, visible) {
698
+ const p = String(taskPath || '').replace(/\/+$/, '');
699
+ if (!p)
700
+ return;
701
+ if (visible)
702
+ WORK._visibleTasks.add(p);
703
+ else
704
+ WORK._visibleTasks.delete(p);
705
+ try {
706
+ if (WORK._ws?.readyState === 1)
707
+ WORK._ws.send(JSON.stringify({ type: 'task.presence', path: p, visible: Boolean(visible) }));
708
+ }
709
+ catch { /* ignore */ }
710
+ };
590
711
  /** Перед выходом убрать подписку у прежнего uid, иначе следующий пользователь получит его push. */
591
712
  WORK.removeCurrentPushSubscription = async function () {
592
713
  if (!WORK.uid || !navigator.serviceWorker || typeof Notification === 'undefined' || Notification.permission !== 'granted')
@@ -639,11 +760,17 @@ class WebSocketEvents {
639
760
  }
640
761
  }
641
762
  onopen(e) {
763
+ WORK._ws = this;
642
764
  this.send(JSON.stringify(Object.keys(CORE.$item.ITEMS)));
765
+ for (const tp of WORK._visibleTasks || []) {
766
+ try { this.send(JSON.stringify({ type: 'task.presence', path: tp, visible: true })); } catch {}
767
+ }
643
768
  WORK.connected = true;
644
769
  WORK.login().catch(() => {});
645
770
  }
646
771
  onclose(e) {
772
+ if (WORK._ws === this)
773
+ WORK._ws = null;
647
774
  WORK.connected = false;
648
775
  WORK.wsid = '';
649
776
  WORK._loginPromise = null;
@@ -669,6 +796,10 @@ class WebSocketEvents {
669
796
  case 'connect':{
670
797
  WORK.wsid = this.id = data.wsid
671
798
  } break;
799
+ case 'user-settings': {
800
+ if (data.settings && (!WORK.uid || data.uid === WORK.uid))
801
+ WORK._applyUserSettings?.(data.settings, { broadcast: false });
802
+ } break;
672
803
  case 'auth-changed': {
673
804
  WORK.onAuthChanged(data);
674
805
  } break;
@@ -824,16 +955,18 @@ if (WORK.top === window) {
824
955
  }
825
956
  // Даже действующую подписку привязываем к текущему uid после входа/рестарта.
826
957
  await WORK.storePushSubscription(subscription);
958
+ WORK._pushSyncedUid = WORK.uid;
827
959
  return true;
828
960
  }
829
961
  catch (err) { console.warn('[push] subscription', err); return false; }
830
962
  };
831
963
  setTimeout(() => {
832
- WORK.enableTaskNotifications(false);
964
+ if (WORK.uid && WORK._pushSyncedUid !== WORK.uid)
965
+ WORK.enableTaskNotifications(false);
833
966
  RTCCaller.init();
834
967
  }, 3000);
835
968
  WORK.authEvents?.addEventListener('auth', e => {
836
- if (e.detail?.uid)
969
+ if (e.detail?.uid && WORK._pushSyncedUid !== e.detail.uid)
837
970
  WORK.enableTaskNotifications(false);
838
971
  });
839
972
  }
@@ -144,7 +144,7 @@ function getDbSummary(db) {
144
144
  countFor(clsPath, clsType = '') {
145
145
  const cls = getClass(db, clsPath);
146
146
  const type = cls?.type || clsType;
147
- if (!type || type === '$project' || type === '$project' || type === '$structure' || type === '$domain')
147
+ if (!type || cls?.own?.isStructure || type === '$project' || type === '$structure' || type === '$domain')
148
148
  return 0;
149
149
  const key = `${type}:${cls?.cid || clsPath}`;
150
150
  if (subtreeCounts.has(key))
@@ -14,12 +14,13 @@ import fsp from 'node:fs/promises';
14
14
  import path from 'node:path';
15
15
  import { pathToFileURL } from 'node:url';
16
16
  import { tx } from './db.js';
17
+ import { structureSubtypesSync } from '../server/class/scaffold.js';
17
18
 
18
19
  /** Типы прикладных классов данных. */
19
20
  export const DATA_TYPES = Object.freeze(['$catalog', '$virtual', '$struct', '$operation', '$account', '$register']);
20
21
 
21
22
  /** Типы классов орг-структуры (подразделения), проектов, доменов и модулей. */
22
- export const STRUCTURE_TYPES = Object.freeze(['$structure', '$project']);
23
+ export const STRUCTURE_TYPES = Object.freeze([...new Set(['$structure', '$project', ...structureSubtypesSync()])]);
23
24
  export const MODULE_TYPES = Object.freeze(['$module', '$provider', '$mcp']);
24
25
  export const DOMAIN_TYPES = Object.freeze(['$domain']);
25
26
 
@@ -20,6 +20,7 @@
20
20
  import { getClass, ancestors, descendants, isLeaf, classesGeneration } from './classes.js';
21
21
  import { compile, BUILTIN_FUNCTIONS } from './expr.js';
22
22
  import { formatFio } from './fio.js';
23
+ import { structureSubtypesSync } from '../server/class/scaffold.js';
23
24
 
24
25
  /** Семейство типа класса: схема наследуется внутри семейства. */
25
26
  export const FAMILY = Object.freeze({
@@ -27,6 +28,7 @@ export const FAMILY = Object.freeze({
27
28
  $struct: 'struct',
28
29
  $operation: 'operation',
29
30
  $account: 'account', $register: 'account',
31
+ ...Object.fromEntries(structureSubtypesSync().map(t => [t, 'structure'])),
30
32
  $structure: 'structure', $project: 'structure',
31
33
  $module: 'module',
32
34
  });
@@ -300,13 +300,15 @@ export const authMethods = {
300
300
  let $user_item = await $users._get_next_item(uid, CORE.$user);
301
301
  credentials.keys = $user_item.keys || {};
302
302
  credentials.keys[time] = publicKey;
303
+ if ($user_item.DATA?.settings && typeof $user_item.DATA.settings === 'object')
304
+ credentials.settings = $user_item.DATA.settings;
303
305
 
304
306
  if (iconBytes)
305
307
  credentials.icon = '/USERS//' + uid + '/$user/icon.png';
306
308
 
307
309
  let post = CORE.$class.toScript(credentials);
308
310
 
309
- let res = await $user_item.save({ filename: 'class.js', post, session: { $user: WORK } });
311
+ let res = await $user_item.save({ filename: 'class.js', post, session: { $user: WORK }, ignore_save_logs: true });
310
312
  let u = await this.$users;
311
313
  (await u.children)?.forEach?.(ch => ch.children = undefined);
312
314
  u.children = undefined;
@@ -138,9 +138,23 @@ export function isProtectedUserPath(relPath) {
138
138
  * Проверить, является ли файл частью системного ядра (движок сервера и фреймворк ODA),
139
139
  * которое должно обновляться до новой версии релиза всегда.
140
140
  */
141
+ const CORE_ROOT_SCRIPTS = new Set([
142
+ 'run.mjs',
143
+ 'package.json',
144
+ 'package-lock.json',
145
+ 'start.bat',
146
+ 'stop.bat',
147
+ 'autostart.bat',
148
+ 'start.sh',
149
+ 'stop.sh',
150
+ 'autostart.sh',
151
+ 'scripts/watchdog.mjs',
152
+ 'scripts/autostart.mjs',
153
+ ]);
154
+
141
155
  export function isCoreEnginePath(relPath) {
142
156
  const rel = normalizeRelPath(relPath);
143
- if (rel === 'run.mjs' || rel === 'package.json' || rel === 'package-lock.json')
157
+ if (CORE_ROOT_SCRIPTS.has(rel))
144
158
  return true;
145
159
  if (rel.startsWith('sources/') || rel.startsWith('oda/') || rel.startsWith('vendor/'))
146
160
  return true;
@@ -154,6 +168,14 @@ const TRACKED_ROOTS = [
154
168
  'run.mjs',
155
169
  'package.json',
156
170
  'package-lock.json',
171
+ 'start.bat',
172
+ 'stop.bat',
173
+ 'autostart.bat',
174
+ 'start.sh',
175
+ 'stop.sh',
176
+ 'autostart.sh',
177
+ 'scripts/watchdog.mjs',
178
+ 'scripts/autostart.mjs',
157
179
  'sources',
158
180
  'oda',
159
181
  '$server',
@@ -181,15 +181,17 @@ function onListenError(port, err) {
181
181
  }
182
182
 
183
183
  export function shouldAutoOpenBrowser(env = process.env, execArgv = process.execArgv, argv = process.argv) {
184
- if (env.WORK_OPEN_BROWSER === '1' || env.WORK_OPEN_BROWSER === 'true')
185
- return true;
186
184
  if (env.WORK_NO_BROWSER === '1' || env.WORK_OPEN_BROWSER === '0' || env.WORK_TEST || env.CI || env.NODE_TEST_CONTEXT)
187
185
  return false;
188
186
  if (Array.isArray(execArgv) && execArgv.some(a => a === '--test' || a.startsWith('--test-')))
189
187
  return false;
190
188
  if (Array.isArray(argv) && argv.some(a => /[\\/]tests[\\/]/i.test(String(a)) || /\.test\.m?js$/i.test(String(a))))
191
189
  return false;
192
- return true;
190
+ if (env.WORK_OPEN_BROWSER === '1' || env.WORK_OPEN_BROWSER === 'true')
191
+ return true;
192
+ if (Array.isArray(argv) && argv.includes('--open'))
193
+ return true;
194
+ return false;
193
195
  }
194
196
 
195
197
  export function openBrowser(url) {
@@ -32,25 +32,49 @@ export async function storePushSubscription(params) {
32
32
  if (!params.session?.uid) {
33
33
  throw new Error('No user id on store_push_subscription');
34
34
  }
35
- const subscription = params.post;
35
+ const raw = params.post || {};
36
+ const endpoint = String(raw.endpoint || '');
37
+ const replaceEndpoint = String(raw.replaceEndpoint || '');
38
+ const deviceId = String(raw.deviceId || '').slice(0, 128);
39
+ const subscription = {
40
+ endpoint,
41
+ ...(raw.expirationTime !== undefined ? { expirationTime: raw.expirationTime } : {}),
42
+ ...(raw.keys ? { keys: raw.keys } : {}),
43
+ ...(deviceId ? { deviceId } : {}),
44
+ };
36
45
  const subscriptions = await loadPushSubscriptions(params.session.uid);
37
- const idx = subscriptions.findIndex(s => s.endpoint === subscription.endpoint);
38
- if (idx > -1) {
39
- Object.assign(subscriptions[idx], subscription);
40
- } else {
41
- subscriptions.push(subscription);
42
- }
43
- await savePushSubscriptions(params.session.uid, subscriptions);
46
+ const filtered = subscriptions.filter(s => {
47
+ if (!s?.endpoint)
48
+ return false;
49
+ if (s.endpoint === endpoint)
50
+ return false;
51
+ if (replaceEndpoint && s.endpoint === replaceEndpoint)
52
+ return false;
53
+ if (deviceId && s.deviceId && s.deviceId === deviceId)
54
+ return false;
55
+ return true;
56
+ });
57
+ filtered.push(subscription);
58
+ await savePushSubscriptions(params.session.uid, filtered);
44
59
  return true;
45
60
  }
46
61
 
47
62
  export async function removePushSubscription(params) {
48
- const subscription = params.post;
63
+ const raw = params.post || {};
64
+ const endpoint = String(raw.endpoint || '');
65
+ const deviceId = String(raw.deviceId || '').slice(0, 128);
49
66
  const subscriptions = await loadPushSubscriptions(params.session.uid);
50
- const idx = subscriptions.findIndex(s => s.endpoint === subscription.endpoint);
51
- if (idx > -1) {
52
- subscriptions.splice(idx, 1);
53
- await savePushSubscriptions(params.session.uid, subscriptions);
67
+ const next = subscriptions.filter(s => {
68
+ if (!s?.endpoint)
69
+ return false;
70
+ if (endpoint && s.endpoint === endpoint)
71
+ return false;
72
+ if (deviceId && s.deviceId && s.deviceId === deviceId)
73
+ return false;
74
+ return true;
75
+ });
76
+ if (next.length !== subscriptions.length) {
77
+ await savePushSubscriptions(params.session.uid, next);
54
78
  }
55
79
  return true;
56
80
  }
@@ -69,7 +93,12 @@ export async function sendPushNotification(params, removeFn) {
69
93
  const subscriptions = await loadPushSubscriptions(uid);
70
94
  return Promise.all(subscriptions.map(async s => {
71
95
  try {
72
- await webPush.sendNotification(s, message);
96
+ const sub = {
97
+ endpoint: s.endpoint,
98
+ ...(s.expirationTime !== undefined ? { expirationTime: s.expirationTime } : {}),
99
+ ...(s.keys ? { keys: s.keys } : {}),
100
+ };
101
+ await webPush.sendNotification(sub, message);
73
102
  }
74
103
  catch (err) {
75
104
  console.warn(err);
@@ -24,6 +24,8 @@ export function sameOrigin(req) {
24
24
  }
25
25
  }
26
26
 
27
+ const allSessions = () => Object.values($server?.sessions || {});
28
+
27
29
  /** Уведомить сессии о смене presence пользователя (online).
28
30
  * F24: анонимным сессиям (без вошедшего) местоположение людей не рассылаем.
29
31
  * Экспортировано для теста фильтра. */
@@ -31,7 +33,7 @@ export function broadcastUserPath($user) {
31
33
  if (!$user?.short)
32
34
  return;
33
35
  const message = JSON.stringify({ path: $user.short, initiator: $user.id });
34
- for (const session of Object.values($server.sessions)) {
36
+ for (const session of allSessions()) {
35
37
  if (!session?.$user)
36
38
  continue; // анонимная сессия — без присутствия
37
39
  for (const sock of Object.values(session.sockets || {})) {
@@ -52,7 +54,7 @@ export function broadcastChatEvent(uids, payload) {
52
54
  if (!targets.size || !payload || typeof payload !== 'object')
53
55
  return;
54
56
  const raw = JSON.stringify(payload);
55
- for (const session of Object.values($server.sessions || {})) {
57
+ for (const session of allSessions()) {
56
58
  const uid = session?.$user?.id;
57
59
  if (!uid || !targets.has(uid))
58
60
  continue;
@@ -71,6 +73,37 @@ function notifyUserOnline(session) {
71
73
  broadcastUserPath(session.$user);
72
74
  }
73
75
 
76
+ export function isTaskVisibleToUser(uid, taskPath) {
77
+ if (!uid || !taskPath)
78
+ return false;
79
+ const norm = String(taskPath).replace(/\/+$/, '');
80
+ for (const session of allSessions()) {
81
+ if (session?.uid !== uid)
82
+ continue;
83
+ for (const sock of Object.values(session.sockets || {})) {
84
+ if (sock?.ws?.readyState !== 1)
85
+ continue;
86
+ if (sock.visibleTasks?.has?.(norm))
87
+ return true;
88
+ }
89
+ }
90
+ return false;
91
+ }
92
+
93
+ export function broadcastUserSettings(uid, settings) {
94
+ if (!uid || !settings || typeof settings !== 'object')
95
+ return;
96
+ const raw = JSON.stringify({ type: 'user-settings', uid, settings });
97
+ for (const session of allSessions()) {
98
+ if (session?.uid !== uid)
99
+ continue;
100
+ for (const sock of Object.values(session.sockets || {})) {
101
+ if (sock?.ws?.readyState === 1)
102
+ sock.ws.send(raw);
103
+ }
104
+ }
105
+ }
106
+
74
107
  export function onWebSocketConnect(ws, request) {
75
108
  // Настоящий Chrome пользователя через расширение MV3: авторизуется токеном wmcp. (без cookies)
76
109
  if (String(request?.url || '').split('?')[0] === '/~chrome') {
@@ -97,13 +130,29 @@ export function onWebSocketConnect(ws, request) {
97
130
  const cookies = parseCookies(request);
98
131
  let session = $server.get_session(cookies.ssid);
99
132
  let wsid = $server.genGUID();
100
- session.sockets[wsid] = { ws, events: [] };
133
+ session.sockets[wsid] = { ws, events: [], visibleTasks: new Set() };
101
134
  ws.send(JSON.stringify({ type: 'connect', wsid }));
102
135
  notifyUserOnline(session);
103
136
  ws.on('message', async (message) => {
104
137
  try {
105
138
  let str = new TextDecoder('utf-8').decode(message);
106
139
  let events = JSON.parse(str);
140
+ if (events && typeof events === 'object' && !Array.isArray(events)) {
141
+ if (events.type === 'task.presence') {
142
+ const sock = session.sockets[wsid];
143
+ if (sock) {
144
+ sock.visibleTasks ??= new Set();
145
+ const p = typeof events.path === 'string' ? events.path.replace(/\/+$/, '').slice(0, 2048) : '';
146
+ if (p && events.visible)
147
+ sock.visibleTasks.add(p);
148
+ else if (p)
149
+ sock.visibleTasks.delete(p);
150
+ else if (!events.visible)
151
+ sock.visibleTasks.clear();
152
+ }
153
+ }
154
+ return;
155
+ }
107
156
  if (!Array.isArray(events))
108
157
  return;
109
158
  const { assertPathProps, canRead } = await import('../server/access/gateway.js');
@@ -276,23 +276,51 @@ export async function llmWithFallback(primaryPath, fallbackPaths = []) {
276
276
  };
277
277
  return adapter;
278
278
  }
279
- /** Первая доступная чат-модель в /MODULES/Модели (активная приоритетно), когда дефолтная модель отсутствует. */
280
- async function findFirstAvailableChatModel() {
279
+ const CLASSIFIER_MODEL_RE = /(классификатор|classifier|rerank|0\.6b)/i;
280
+
281
+ /** Список доступных чат-моделей (используется в настройках профиля и автовыборе по умолчанию). */
282
+ export async function listAvailableChatModels() {
281
283
  const root = await WORK.get_item('/MODULES/Модели').catch(() => null);
282
- let firstAny = '';
284
+ const out = [];
283
285
  for (const provider of (await root?.items) || []) {
286
+ await provider?.init?.catch?.(() => {});
287
+ if (provider?.DATA?.enabled === false)
288
+ continue;
289
+ const provLabel = String(provider.DATA?.label || provider.label || provider.id || '');
284
290
  for (const m of (await provider.items) || []) {
285
- await m.init;
291
+ await m.init?.catch?.(() => {});
292
+ if (m?.DATA?.enabled === false)
293
+ continue;
286
294
  const caps = Array.isArray(m.capabilities) ? m.capabilities : String(m.capabilities || '').split(/[\s,]+/);
287
295
  if (!caps.includes('chat') || typeof m.streamChat !== 'function')
288
296
  continue;
289
- if (!firstAny)
290
- firstAny = m.path;
291
- if ((m.aiActive ?? m.DATA?.aiActive) !== false)
292
- return m.path;
297
+ const active = (m.aiActive ?? m.DATA?.aiActive) !== false;
298
+ const name = String(m.id || m.DATA?.label || m.label || m.path || '');
299
+ const label = String(m.DATA?.label || m.label || m.id || m.path || '');
300
+ const isPrimary = active && !CLASSIFIER_MODEL_RE.test(name);
301
+ out.push({
302
+ path: m.path,
303
+ label: provLabel ? `${label} (${provLabel})` : label,
304
+ active,
305
+ default: m.DATA?.default === true,
306
+ isPrimary,
307
+ });
293
308
  }
294
309
  }
295
- return firstAny;
310
+ return out;
311
+ }
312
+
313
+ /** Первая доступная чат-модель в /MODULES/Модели (приоритетно default:true и основная LLM, не классификатор). */
314
+ export async function findFirstAvailableChatModel() {
315
+ const list = await listAvailableChatModels();
316
+ const def = list.find(m => m.active && m.default);
317
+ if (def)
318
+ return def.path;
319
+ const primary = list.find(m => m.isPrimary);
320
+ if (primary)
321
+ return primary.path;
322
+ const active = list.find(m => m.active);
323
+ return (active || list[0])?.path || '';
296
324
  }
297
325
  /** Найти активную локальную модель в /MODULES/Модели/Local по capabilities (или id). */
298
326
  async function findActiveLocalModel({ caps = [], ids = [], method = '' } = {}) {
@@ -661,7 +689,7 @@ async function placeBlock(place, session, location, contextPath) {
661
689
  const label = place.DATA?.label || place.label || place.id || place.path || 'WORK';
662
690
  const cone = contextConeOf(contextPath || place.path);
663
691
  const pt = place.type;
664
- if (pt === '$structure') {
692
+ if (place.DATA?.isDepartment || pt === '$structure') {
665
693
  const orgName = cone?.[1] || '';
666
694
  lines.push(`- Твоя идентичность (субъект): ты — цифровой двойник подразделения «${label}»${orgName ? ` (организация «${orgName}»)` : ''}, путь ${place.path}. Отвечай и действуй от первого лица этого подразделения.`);
667
695
  }