odant-work 1.0.96 → 1.0.97

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.
@@ -438,59 +438,6 @@ ODA({
438
438
  }
439
439
  </style>
440
440
  <div class="back"></div>
441
- <div class="feed-top-bar" ~if="showFeedModeToggle || ($item && $item.type !== '$user')">
442
- <div class="feed-mode-bar" ~if="showFeedModeToggle">
443
- <button type="button" class="feed-mode-btn" ~class="{ active: feedMode === 'dialog' }" @tap="setFeedMode('dialog')" title="Мой диалог и задачи с Агентом этого узла">Диалог</button>
444
- <button type="button" class="feed-mode-btn" ~class="{ active: feedMode === 'local' }" @tap="setFeedMode('local')" title="Местный лог открытой точки (доступно только BOSS)">Местный лог</button>
445
- <button type="button" class="feed-mode-btn" ~class="{ active: feedMode === 'audit' }" @tap="setFeedMode('audit')" title="Взаимодействия пользователей и клиентов с Агентом (доступно только BOSS)">Взаимодействия</button>
446
- </div>
447
- <div class="feed-mode-bar" ~if="$item && $item.type !== '$user'">
448
- <button type="button" class="feed-mode-btn" ~class="{ active: showParticipants }" @tap="toggleParticipants()" title="Участники и рабочие места подразделения">Участники ({{participantsCount}})</button>
449
- </div>
450
- </div>
451
- <div ~if="feedMode === 'audit' && showFeedModeToggle" class="audit-overlay">
452
- <div class="audit-sidebar">
453
- <div style="font-size:12px;font-weight:700;padding:4px 6px;color:var(--muted-color);">Диалоги с Агентом ({{auditThreads.length}})</div>
454
- <div ~if="!auditThreads.length" style="font-size:12.5px;color:var(--muted-color);padding:8px 6px;">Взаимодействий пока нет</div>
455
- <div ~for="auditThreads" @tap="openAuditThread($for.item)" ~class="{ active: auditSelectedId === $for.item.id }" style="padding:7px 9px;border-radius:7px;cursor:pointer;border:1px solid var(--subtle-border,transparent);background:var(--content-background,#fff);font-size:12.5px;">
456
- <div style="font-weight:600;display:flex;justify-content:space-between;gap:6px;">
457
- <span>{{$for.item.peerLabel}}</span>
458
- <span style="font-size:11px;opacity:0.7;">{{$for.item.messageCount}}</span>
459
- </div>
460
- <div ~if="$for.item.lastMessage" style="font-size:11.5px;color:var(--muted-color);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-top:2px;">{{$for.item.lastMessage.content || ($for.item.lastMessage.taskPath ? 'Задача' : 'Вложение')}}</div>
461
- </div>
462
- </div>
463
- <div class="audit-messages">
464
- <div ~if="!auditSelectedId" style="color:var(--muted-color);font-size:13px;margin:auto;">Выберите пользователя для просмотра истории взаимодействия с Агентом</div>
465
- <div ~for="auditMessages" style="padding:8px 11px;border-radius:8px;border:1px solid var(--subtle-border,#e2e8f0);background:var(--subtle-background,#f8fafc);font-size:13px;">
466
- <div style="font-size:11px;color:var(--muted-color);display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap;margin-bottom:3px;">
467
- <b>{{$for.item.sender === '$twin' ? 'Агент узла' : $for.item.sender}}</b>
468
- <span>{{new Date($for.item.created).toLocaleString()}}</span>
469
- </div>
470
- <div style="white-space:pre-wrap;word-break:break-word;">{{$for.item.content || ($for.item.taskPath ? 'Задача: ' + $for.item.taskPath : '')}}</div>
471
- <div ~if="$for.item.kind === 'approval'" style="display:flex;align-items:center;flex-wrap:wrap;gap:8px;margin-top:6px;">
472
- <span ~if="$for.item.meta?.status === 'approved'" style="font-size:11.5px;font-weight:700;color:#059669;">✓ Утверждено</span>
473
- <span ~if="$for.item.meta?.status === 'rejected'" style="font-size:11.5px;font-weight:700;color:#dc2626;">✕ Отклонено</span>
474
- <oda-button ~if="$for.item.meta?.status === 'pending'" icon="icons:check" info-invert @tap="resolveApprovalMsg($for.item, 'approve')">Утвердить</oda-button>
475
- <oda-button ~if="$for.item.meta?.status === 'pending'" icon="icons:close" @tap="resolveApprovalMsg($for.item, 'reject')">Отклонить</oda-button>
476
- </div>
477
- </div>
478
- </div>
479
- </div>
480
- <div ~if="showParticipants && $item && $item.type !== '$user'" class="participants-popover">
481
- <div style="display:flex;align-items:center;justify-content:space-between;font-weight:700;">
482
- <span>Участники ({{participantsCount}})</span>
483
- <oda-button icon="icons:close" :icon-size="14" @tap="showParticipants = false"></oda-button>
484
- </div>
485
- <div ~if="!participantsList.length" style="color:var(--muted-color);">Назначенных участников нет</div>
486
- <div ~for="participantsList" @tap="openParticipant($for.item)" style="display:flex;align-items:center;gap:8px;padding:5px 7px;border-radius:7px;cursor:pointer;border:1px solid var(--subtle-border,transparent);">
487
- <item-icon :$item="$for.item" icon-size="22" default="icons:person"></item-icon>
488
- <div style="flex:1;min-width:0;">
489
- <div style="font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">{{$for.item.label || $for.item.id}}</div>
490
- <div ~if="$for.item._placeLabel" style="font-size:11px;color:var(--muted-color);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">{{$for.item._placeLabel}}</div>
491
- </div>
492
- </div>
493
- </div>
494
441
  <chat-ribbon id="ribbon" :$item @chat-item-expanded="onCardExpanded($event)"></chat-ribbon>
495
442
  <div class="mover" vertical hidden>
496
443
  <oda-button :hidden="$('#ribbon').scrollTop < 0" content shadow icon="icons:chevron-right:270" @tap="$('#ribbon').scrollTop = -($('#ribbon').scrollHeight)"></oda-button>
@@ -801,7 +748,7 @@ ODA({
801
748
  window.execute(u);
802
749
  },
803
750
  get showFeedModeToggle() {
804
- return Boolean(this.$item && this.$item.type !== '$user' && this._canLocalFeed);
751
+ return false;
805
752
  },
806
753
  async _refreshCanLocalFeed(item = this.$item) {
807
754
  if (!item || item.type === '$user') {
@@ -2165,21 +2112,9 @@ ODA({
2165
2112
  }
2166
2113
  },
2167
2114
  get logsSource() {
2168
- // По умолчанию всегда показывается личный кабинет (/USERS/<uid>);
2169
- // местный лог точки (this.$pdp.$item) — только при явном включении режима local для BOSS.
2170
- const role = this.$pdp?.$item?.role || 'USER';
2171
- const uid = WORK.uid || '';
2172
- const local = this.$pdp?.isLocalFeed ? {
2173
- local: 1
2174
- } : {};
2175
- return Promise.resolve(this.$pdp.$item?.fetch?.('chatSource', {
2176
- role,
2177
- uid,
2178
- ...local
2179
- })).then(path => {
2180
- if (path && typeof path === 'string') return WORK.get_item(path);
2181
- return this.$pdp.$item;
2182
- });
2115
+ // Каждый узел хранит свою ленту (chatSource = this.path; серверный logs() сам вызывает _logSource),
2116
+ // поэтому берём прямо this.$pdp.$item без лишнего roundtrip и без сбоя get_item('/') на корне WORK.
2117
+ return this.$pdp?.$item || null;
2183
2118
  },
2184
2119
  get label() {
2185
2120
  let date = new Date(this.day);
@@ -275,7 +275,16 @@ ODA({
275
275
  $attr: true,
276
276
  },
277
277
  role: '',
278
- subViewPath: '',
278
+ subViewPath: {
279
+ $def: '',
280
+ set(n) {
281
+ if (!n || !this.tabs?.length)
282
+ return;
283
+ const [firstSeg, ...restSegs] = String(n).split('/').filter(Boolean);
284
+ if (firstSeg && this.activeId !== firstSeg && this.tabs.some(t => t.id === firstSeg))
285
+ this.selectTab(firstSeg, restSegs.join('/'));
286
+ }
287
+ },
279
288
  activeId: '',
280
289
  depth: 0,
281
290
  },
@@ -534,13 +543,13 @@ ODA({
534
543
  }
535
544
  else if (this.depth < 6 && (tab.layout || tab.DATA?.layout || (Array.isArray(tab.DATA?.items) && tab.DATA.items.length))) {
536
545
  el = ODA.createComponent('work-subview-container', {
537
- $handler: tab,
538
- $item: this.$item,
539
- $context: this.$item,
546
+ subViewPath: nestedSubView,
540
547
  layout: tab.layout || tab.DATA?.layout || 'sidebar',
541
548
  role: this.role,
542
- subViewPath: nestedSubView,
543
549
  depth: (this.depth || 0) + 1,
550
+ $handler: tab,
551
+ $item: this.$item,
552
+ $context: this.$item,
544
553
  });
545
554
  }
546
555
  if (!el)
@@ -568,6 +577,8 @@ ODA({
568
577
  const sub = nav.subView || nav.tab || '';
569
578
  if (!sub)
570
579
  return;
580
+ if (this._loadingPromise)
581
+ await this._loadingPromise.catch(() => {});
571
582
  const [firstSeg, ...restSegs] = String(sub).split('/').filter(Boolean);
572
583
  if (firstSeg && (this.tabs || []).some(t => t.id === firstSeg)) {
573
584
  await this.selectTab(firstSeg, restSegs.join('/'));
@@ -2190,6 +2201,11 @@ ODA({is: 'work-form',
2190
2201
  if (nav.view === 'objects' && nav.id) {
2191
2202
  nav.view = 'objects/object';
2192
2203
  }
2204
+ if (nav.view && String(nav.view).includes('/') && !nav.subView) {
2205
+ const [, ...navSubParts] = String(nav.view).split('/').filter(Boolean);
2206
+ if (navSubParts.length)
2207
+ nav.subView = navSubParts.join('/');
2208
+ }
2193
2209
  // Сохраним позицию прокрутки ленты чата до изменения полосы вкладок (formTabs)
2194
2210
  const curRib = this.view_control?.$?.('form-chat')?.$?.('oda-chat')?.$?.('#ribbon');
2195
2211
  if (curRib && curRib.clientHeight > 0 && !curRib._wasHidden) {
@@ -2419,14 +2435,15 @@ ODA({is: 'work-form',
2419
2435
  }
2420
2436
  else if (n.layout || n.DATA?.layout || (Array.isArray(n.DATA?.items) && n.DATA.items.length)) {
2421
2437
  el = ODA.createComponent('work-subview-container', {
2422
- $handler: n,
2423
- $item: tabItem,
2424
- $context: tabItem,
2425
- slot: 'main',
2438
+ subViewPath: nav?.subView || '',
2439
+ _initialNav: nav || null,
2426
2440
  layout: n.layout || n.DATA?.layout || 'sidebar',
2427
2441
  role: this.activeRole,
2428
- subViewPath: nav?.subView || '',
2429
2442
  depth: 0,
2443
+ slot: 'main',
2444
+ $handler: n,
2445
+ $item: tabItem,
2446
+ $context: tabItem,
2430
2447
  });
2431
2448
  }
2432
2449
  else {
@@ -737,13 +737,16 @@ export default {
737
737
  return;
738
738
  if ($item.type === '$handler') {
739
739
  const rawHPath = String($item.path || $item.short || '');
740
- const mForm = rawHPath.match(/^(.*?)\/(?:~|\$[^/]+(?:\/\$[^/]+)*)\/handlers\/pages\/form(?:\/([^/$]+))?/);
740
+ const mForm = rawHPath.match(/^(.*?)\/(?:~|\$[^/]+(?:\/\$[^/]+)*)\/handlers\/pages\/form(?:\/(.+?))?(?:\/\$handler)?$/);
741
741
  const rawSelf = $item[R]?.target || $item;
742
742
  const ctx = (Object.prototype.hasOwnProperty.call(rawSelf, '$context') || Object.prototype.hasOwnProperty.call($item, '$context'))
743
743
  ? await $item.$context
744
744
  : null;
745
745
  if (ctx && ctx.type !== '$handler') {
746
- const viewId = mForm?.[2] || ($item.id && $item.id !== 'form' ? $item.id : '');
746
+ const formView = mForm?.[2]
747
+ ? mForm[2].split('/').filter(s => s && s[0] !== '$').join('/')
748
+ : '';
749
+ const viewId = formView || ($item.id && $item.id !== 'form' ? $item.id : '');
747
750
  $item = ctx;
748
751
  if (viewId)
749
752
  nav = { ...(nav && typeof nav === 'object' ? nav : {}), view: viewId };
@@ -41,6 +41,14 @@ export default {
41
41
  }
42
42
  }
43
43
  }
44
+ .menu-loading {
45
+ @apply --horizontal;
46
+ align-items: center;
47
+ gap: 8px;
48
+ padding: 10px 12px;
49
+ font-size: 13px;
50
+ color: var(--muted-color);
51
+ }
44
52
  </style>
45
53
  <div ~if="showTools" class="tools-list">
46
54
  <div ~for="tools" :disabled="Boolean($for.item.disabled)" @pointerdown.stop.prevent="executeTool($for.item, $event)" class="tool">
@@ -49,6 +57,10 @@ export default {
49
57
  <span class="tool-shortcut" ~if="$for.item.shortcut">{{$for.item.shortcut}}</span>
50
58
  </div>
51
59
  </div>
60
+ <div ~if="showHandlers && !handlersRoot && _loadingHandlers" class="menu-loading">
61
+ <oda-icon icon="spinners:3-dots-scale" icon-size="16"></oda-icon>
62
+ <span>Загрузка…</span>
63
+ </div>
52
64
  <item-tree ~if="showHandlers" hide-files @resize :hide-tops :hide-roots :prefetch-deep="0" expander-order="1" expand-all :$item="handlersRoot" :allow-categories></item-tree>
53
65
  `,
54
66
  get $context(){
@@ -69,24 +81,53 @@ export default {
69
81
  get showHandlers() {
70
82
  return ['handlers', 'both'].includes(this.mode);
71
83
  },
72
- get handlersRoot() {
73
- const $item = this.$item;
74
- if (!$item)
75
- return null;
84
+ _loadingHandlers: false,
85
+ handlersRoot: null,
86
+ $item: {
87
+ $def: null,
88
+ set(n) {
89
+ this._loadHandlersRoot(n);
90
+ }
91
+ },
92
+ attached() {
93
+ if (this.$item && !this.handlersRoot && !this._loadingHandlers)
94
+ this._loadHandlersRoot(this.$item);
95
+ },
96
+ async _loadHandlersRoot($item = this.$item) {
97
+ if (!$item) {
98
+ this.handlersRoot = null;
99
+ return;
100
+ }
101
+ const seq = (this._handlersSeq = (this._handlersSeq || 0) + 1);
102
+ this._loadingHandlers = true;
76
103
  const stampContext = (node) => {
77
104
  if (!node || typeof node !== 'object')
78
105
  return node;
79
106
  node.$context = $item;
80
107
  if (Array.isArray(node.items)) {
81
108
  node.items = node.items
82
- .filter(ch => ch && !(ch.hidden || ch.DATA?.hidden))
109
+ .filter(ch => ch && !(ch.DATA?.hidden === true || (ch.type === '$handler' && ch.hidden === true)))
83
110
  .map(ch => stampContext(ch));
84
111
  }
85
112
  return node;
86
113
  };
87
- // роль должна быть известна до запроса: без неё фильтр по роли не сработает
88
- return Promise.resolve($item.ensureRole?.()).then(() =>
89
- $item.fetch('handlers', { path: this.path })).then(root => stampContext(root));
114
+ try {
115
+ // роль должна быть известна до запроса: без неё фильтр по роли не сработает
116
+ await Promise.resolve($item.ensureRole?.());
117
+ const root = await $item.fetch('handlers', { path: this.path });
118
+ if (seq !== this._handlersSeq)
119
+ return;
120
+ const stamped = stampContext(root);
121
+ this.handlersRoot = stamped;
122
+ const tree = this.$?.('item-tree');
123
+ if (tree && tree.$item !== stamped)
124
+ tree.$item = stamped;
125
+ this.async?.(() => this.parentElement?.layout?.(true), 30);
126
+ }
127
+ finally {
128
+ if (seq === this._handlersSeq)
129
+ this._loadingHandlers = false;
130
+ }
90
131
  },
91
132
  get tools(){
92
133
  return this.customTools || this.$item?.tools || [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.96",
3
+ "version": "1.0.97",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
@@ -65,8 +65,15 @@ export class $handler extends $class{
65
65
  get allowUse(){
66
66
  return this.DATA?.allowUse;
67
67
  }
68
+ _baseImportPath(item = this) {
69
+ const p = String(item?.path || '');
70
+ const s = String(item?.short || '');
71
+ if (p.startsWith('/$server/$folder/'))
72
+ return p;
73
+ return s || p;
74
+ }
68
75
  async import(path, is){
69
- path = (this.short || this.path) + '/~/' + (path || 'class.js');
76
+ path = this._baseImportPath(this) + '/~/' + (path || 'class.js');
70
77
  if(!path.endsWith('.js'))
71
78
  path += '.js';
72
79
  const module = await import(path);
@@ -83,7 +90,7 @@ export class $handler extends $class{
83
90
  }
84
91
  if (!comp || typeof comp !== 'object')
85
92
  return null;
86
- const rawPath = this.short || this.path || this.id;
93
+ const rawPath = this._baseImportPath(this) || this.id;
87
94
  const want = is || comp.is || rawExport.tag || makeViewTag(this.id, rawPath);
88
95
  // Клонируем описание компонента с сохранением дескрипторов (геттеры/сеттеры),
89
96
  // чтобы регистрация в WORK/ODA не мутировала кэшированный ES-модуль.
@@ -163,7 +170,7 @@ export class $handler extends $class{
163
170
  async getModule() {
164
171
  const $item = Reactor.activate(this);
165
172
  $item.$context = await $item.$context;
166
- const module = await import(`${$item.short || $item.path}/~/class.js`);
173
+ const module = await import(`${this._baseImportPath($item)}/~/class.js`);
167
174
  return module.default;
168
175
  }
169
176
  }
package/sources/client.js CHANGED
@@ -465,17 +465,22 @@ WORK.login = async function(force = false){
465
465
  try { sessionStorage.removeItem('work.pendingInviteToken'); } catch { /* ignore */ }
466
466
  }
467
467
  WORK.uid = uid;
468
+ WORK._anonExitSynced = false;
468
469
  await WORK.syncAuthUI();
469
470
  WORK.refreshChatUnread?.();
470
471
  WORK.notifyAuth?.({ uid, reason: 'login' });
471
472
  return res;
472
473
  }
474
+ const hadAuth = Boolean(WORK.uid);
473
475
  if (WORK.uid)
474
476
  await WORK.removeCurrentPushSubscription?.();
475
477
  WORK.uid = '';
476
478
  WORK.USER = undefined;
477
479
  WORK.chatUnread = { total: 0, byThread: {}, byNode: {}, byPeer: {} };
478
- await WORK.fetch("/", 'user_exit', {}, {}).catch(() => {});
480
+ if (hadAuth || !WORK._anonExitSynced) {
481
+ WORK._anonExitSynced = true;
482
+ await WORK.fetch("/", 'user_exit', {}, {}).catch(() => {});
483
+ }
479
484
  await WORK.syncAuthUI();
480
485
  WORK.notifyAuth?.({ uid: '', reason: 'logout' });
481
486
  })();
@@ -19,6 +19,21 @@ const UID_RE = /^[0-9A-F]{16}$/;
19
19
  /** Незавершённые входы: challengeId → { value, uid, expiresAt }. Одноразовые, со сроком. */
20
20
  const pendingLogins = new Map();
21
21
 
22
+ /** Незавершённые регистрации (до проверки кода): registrationId → { id, uid, email, code, at, attempts }. */
23
+ const pendingRegistrations = new Map();
24
+
25
+ /** Подтверждённые кодом регистрации (ожидание подписи ключа): registrationId → credentials. */
26
+ const pendingVerifiedRegistrations = new Map();
27
+
28
+ function prunePendingRegistrations(now = Date.now()) {
29
+ for (const [id, r] of pendingRegistrations)
30
+ if (!r?.at || now - r.at > REGISTER_CODE_TTL_MS)
31
+ pendingRegistrations.delete(id);
32
+ for (const [id, c] of pendingVerifiedRegistrations)
33
+ if (!c?.at || now - c.at > REGISTER_CODE_TTL_MS)
34
+ pendingVerifiedRegistrations.delete(id);
35
+ }
36
+
22
37
  /** Отправки кода по адресу: защита от почтовой бомбардировки и перебора. */
23
38
  const startsByEmail = new Map();
24
39
 
@@ -78,7 +93,7 @@ async function isFirstOrBossUser(uid) {
78
93
 
79
94
  export const authMethods = {
80
95
  async user_register_start(params = {}) {
81
- let { uid, email, inviteToken } = params.post || {};
96
+ let { uid, email, inviteToken, registrationId: postRegId } = params.post || {};
82
97
  if (!email || typeof email !== 'string')
83
98
  throw new Error("Не указан email");
84
99
  const expected = uidOfEmail(email);
@@ -87,8 +102,24 @@ export const authMethods = {
87
102
  uid = expected;
88
103
  let session = params.session;
89
104
  throttleStart(session, email);
105
+ const now = Date.now();
106
+ prunePendingRegistrations(now);
107
+ const rawRegId = postRegId ?? params.registrationId;
108
+ let regId;
109
+ if (rawRegId != null && rawRegId !== '') {
110
+ regId = String(rawRegId).trim();
111
+ if (regId.length > 64 || pendingRegistrations.has(regId) || pendingVerifiedRegistrations.has(regId))
112
+ throw new Error("Неверный registrationId");
113
+ }
114
+ else {
115
+ regId = crypto.randomUUID();
116
+ }
117
+ if (pendingRegistrations.size >= 10_000)
118
+ throw new Error("Слишком много незавершённых регистраций, повторите позже");
90
119
  let code = crypto.randomInt(0, 1_000_000).toString().padStart(6, '0');
91
- session.registration = { uid, email, code, at: Date.now(), attempts: 0 };
120
+ const reg = { id: regId, uid, email, code, at: now, attempts: 0 };
121
+ session.registration = reg;
122
+ pendingRegistrations.set(regId, reg);
92
123
  delete session.credentials;
93
124
  if (DEV_MODE) {
94
125
  console.log('[DEV] Registration code for', email, ':', code);
@@ -152,25 +183,38 @@ export const authMethods = {
152
183
  },
153
184
 
154
185
  async user_register_process(params = {}) {
155
- let { name, surname, patronymic } = params.post || {};
156
- let { code, session } = params;
157
- const reg = session.registration;
186
+ let { name, surname, patronymic, registrationId: postRegId } = params.post || {};
187
+ let { code, session, registrationId: queryRegId } = params;
188
+ const regId = String(queryRegId || postRegId || '').trim();
189
+ prunePendingRegistrations();
190
+ const reg = regId
191
+ ? (pendingRegistrations.get(regId) || (session.registration?.id === regId ? session.registration : null))
192
+ : session.registration;
158
193
  if (!reg || Date.now() - reg.at > REGISTER_CODE_TTL_MS) {
159
- delete session.registration;
194
+ if (reg?.id)
195
+ pendingRegistrations.delete(reg.id);
196
+ if (!reg || session.registration === reg)
197
+ delete session.registration;
160
198
  throw new Error("Срок действия проверочного кода истёк");
161
199
  }
162
200
  if (++reg.attempts > REGISTER_MAX_ATTEMPTS) {
163
- delete session.registration;
201
+ if (reg.id)
202
+ pendingRegistrations.delete(reg.id);
203
+ if (session.registration === reg)
204
+ delete session.registration;
164
205
  throw new Error("Превышено число попыток ввода кода, запросите новый");
165
206
  }
166
207
  if (!sameCode(reg.code, code)) {
167
208
  audit('register_code_fail', { email: reg.email, attempts: reg.attempts, params });
168
209
  throw new Error("Введен неверный проверочный код");
169
210
  }
170
- delete session.registration;
211
+ if (reg.id)
212
+ pendingRegistrations.delete(reg.id);
213
+ if (session.registration === reg)
214
+ delete session.registration;
171
215
  const { uid, email } = reg;
172
216
  let label = ((surname || '') + ' ' + (name || '') + ' ' + (patronymic || '')).trim() || email;
173
- session.credentials = {
217
+ const credentials = {
174
218
  uid,
175
219
  service: "WORK (Extensible Fractal File System)",
176
220
  origin: HOST,
@@ -180,14 +224,21 @@ export const authMethods = {
180
224
  challenge: crypto.randomUUID(),
181
225
  verified: true,
182
226
  };
227
+ session.credentials = credentials;
228
+ if (reg.id)
229
+ pendingVerifiedRegistrations.set(reg.id, { ...credentials, at: Date.now() });
183
230
  return session.credentials;
184
231
  },
185
232
 
186
233
  async user_register_finish(params = {}) {
187
- let { credentials: { uid: postUid, icon, surname, name, patronymic, publicKey, time } = {}, signature, inviteToken } = params.post || {};
234
+ let { credentials: { uid: postUid, icon, surname, name, patronymic, publicKey, time } = {}, signature, inviteToken, registrationId: postRegId } = params.post || {};
188
235
  let session = params.session;
189
- // uid и email — только из проверенной кодом регистрации этой сессии
190
- const verified = session.credentials?.verified ? session.credentials : null;
236
+ const regId = String(postRegId || params.registrationId || '').trim();
237
+ prunePendingRegistrations();
238
+ // uid и email — только из проверенной кодом регистрации (в сессии или по registrationId)
239
+ const pendingVerified = regId ? pendingVerifiedRegistrations.get(regId) : null;
240
+ const verified = (pendingVerified?.verified ? pendingVerified : null)
241
+ || (session.credentials?.verified ? session.credentials : null);
191
242
  if (!verified || !UID_RE.test(verified.uid))
192
243
  throw new Error("registration failed: адрес не подтверждён");
193
244
  const { uid, email } = verified;
@@ -204,7 +255,7 @@ export const authMethods = {
204
255
  { name: "RSASSA-PKCS1-v1_5" },
205
256
  PK,
206
257
  Buffer.from(signature, "base64"),
207
- new TextEncoder().encode(session.credentials.challenge)
258
+ new TextEncoder().encode(verified.challenge)
208
259
  );
209
260
  }
210
261
  catch {
@@ -212,9 +263,13 @@ export const authMethods = {
212
263
  }
213
264
  if (!isValid) {
214
265
  // Одноразовый challenge: после неверной подписи требуется заново подтвердить код
266
+ if (regId)
267
+ pendingVerifiedRegistrations.delete(regId);
215
268
  delete session.credentials;
216
269
  throw new Error("registration failed");
217
270
  }
271
+ if (regId)
272
+ pendingVerifiedRegistrations.delete(regId);
218
273
 
219
274
  let iconBytes = null;
220
275
  let base64Image = typeof icon === 'string' ? icon.split(';base64,').pop() : null;
@@ -411,9 +466,12 @@ export const authMethods = {
411
466
  const { session } = params;
412
467
  const uid = session?.uid;
413
468
  if (!uid) {
414
- this.constructor.clearSessionAuth(session);
469
+ // Анонимная сессия: не затираем незавершённую регистрацию (registration / credentials),
470
+ // чтобы фоновый user_exit при переподключении WebSocket или в другой вкладке не срывал ввод кода.
471
+ if (session)
472
+ delete session.challenge;
415
473
  const { time } = params.post || {};
416
- if (time)
474
+ if (time && session)
417
475
  delete session[time];
418
476
  return "Выход выполнен";
419
477
  }
@@ -27,8 +27,8 @@ export const CONFIG = {
27
27
  maxFileBytes: 20 * 1024 * 1024,
28
28
  maxTextChars: 400_000,
29
29
  /** Корневые папки и имена, которые не индексируются никогда. */
30
- excludeRoots: ['node_modules', 'sources', 'oda', 'tests', 'scripts', 'torus'],
31
- excludeNames: ['node_modules', '#secret', '#system', 'INDEX', '.git', '.svn', '.index', '.RAG', '.cursor', '.vscode'],
30
+ excludeRoots: ['node_modules', 'sources', 'oda', 'tests', 'scripts', 'torus', 'license-server'],
31
+ excludeNames: ['node_modules', '#secret', '#system', '#runtime', '#weights', '#datasets', '#adapters', '#cache', '#tmp', '#downloads', '#media', 'INDEX', '.git', '.svn', '.index', '.RAG', '.cursor', '.vscode'],
32
32
  /** Текст, извлекаемый как есть. */
33
33
  textExts: ['md', 'markdown', 'txt', 'csv', 'tsv', 'yaml', 'yml', 'skill', 'ai', 'chat', 'rst', 'adoc'],
34
34
  /** Документы, извлекаемые Kreuzberg / разбором таблиц. */
@@ -7,6 +7,9 @@ import { pipeline, env } from '@huggingface/transformers';
7
7
 
8
8
  // модели — вне дерева индексации и вне git; WORK_RAG_CACHE — общее хранилище (прогоны eval)
9
9
  env.cacheDir = process.env.WORK_RAG_CACHE || './.index/hf';
10
+ const ragThreads = Math.max(1, Math.min(2, Number(process.env.WORK_RAG_THREADS) || 2));
11
+ if (env.backends?.onnx?.wasm)
12
+ env.backends.onnx.wasm.numThreads = ragThreads;
10
13
 
11
14
  let extractor = null;
12
15
  let loadedKey = '';
@@ -14,7 +17,13 @@ let loadedKey = '';
14
17
  async function getExtractor(model, dtype) {
15
18
  const key = model + '|' + dtype;
16
19
  if (!extractor || loadedKey !== key) {
17
- extractor = await pipeline('feature-extraction', model, { dtype });
20
+ extractor = await pipeline('feature-extraction', model, {
21
+ dtype,
22
+ session_options: {
23
+ intraOpNumThreads: ragThreads,
24
+ interOpNumThreads: 1,
25
+ },
26
+ });
18
27
  loadedKey = key;
19
28
  }
20
29
  return extractor;
@@ -68,7 +68,7 @@ export function isExcluded(p, { allowHidden = false } = {}) {
68
68
  if (excludeRoots.has(segs[0]))
69
69
  return true;
70
70
  for (const s of segs) {
71
- if (excludeNames.has(s))
71
+ if (excludeNames.has(s) || s[0] === '#')
72
72
  return true;
73
73
  if (!allowHidden && s[0] === '.')
74
74
  return true;
@@ -87,6 +87,8 @@ export function kindOf(p) {
87
87
  if (name === 'class.js') {
88
88
  const meta = segs[segs.length - 2];
89
89
  const owner = segs[segs.length - 3];
90
+ if (meta === '$handler' || meta === '$method' || meta === '$trigger')
91
+ return null;
90
92
  if (meta?.[0] === '$' && (owner === undefined || owner[0] !== '$'))
91
93
  return 'class';
92
94
  return null;
@@ -79,8 +79,8 @@ async function drain() {
79
79
  failures++;
80
80
  note(p + ': ' + e.message);
81
81
  }
82
- // уступить циклу событий между документами, чтобы HTTP-запросы UI обслуживались без задержек
83
- await new Promise(r => setTimeout(r, 10));
82
+ // уступить циклу событий между документами, чтобы фоновая индексация не загружала систему
83
+ await new Promise(r => setTimeout(r, 50));
84
84
  }
85
85
  }
86
86
  finally {
@@ -234,7 +234,7 @@ export async function reconcile() {
234
234
  if (onDisk.has(p))
235
235
  continue;
236
236
  // снимки из лент индексируются принудительно и обходом не видны — проверяем наличие файла
237
- if (fs.existsSync(diskOf(p)))
237
+ if (!isExcluded(p) && kindOf(p) && fs.existsSync(diskOf(p)))
238
238
  continue;
239
239
  store.removeDocs(p);
240
240
  reconcileState.removed++;
@@ -347,8 +347,10 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
347
347
  case 'changed':
348
348
  case 'unregistered': {
349
349
  try {
350
- const regPayload = { ...this.params, ...(this.pendingInviteToken ? { inviteToken: this.pendingInviteToken } : {}) };
350
+ const registrationId = globalThis.crypto?.randomUUID?.() || WORK.genGUID?.() || (Date.now().toString(36) + Math.random().toString(36).slice(2));
351
+ const regPayload = { ...this.params, registrationId, ...(this.pendingInviteToken ? { inviteToken: this.pendingInviteToken } : {}) };
351
352
  const res = await WORK.fetch("/", 'user_register_start', {}, regPayload);
353
+ this._registrationId = registrationId;
352
354
  if (res && typeof res === 'object' && res.autoCode) {
353
355
  this.text = res.message || 'Идет процесс регистрации ключа безопасности...';
354
356
  await this._onCode({ detail: { value: res.autoCode } });
@@ -370,9 +372,10 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
370
372
  this.text = "Идет процесс регистрации ключа безопасности...";
371
373
  this.showCode = false;
372
374
  let code = await e.detail.value;
375
+ const regQuery = { code, ...(this._registrationId ? { registrationId: this._registrationId } : {}) };
373
376
 
374
377
  // 1. Проверяем код и получаем challenge
375
- let options = await WORK.fetch("/", 'user_register_process', { code }, this.params);
378
+ let options = await WORK.fetch("/", 'user_register_process', regQuery, this.params);
376
379
 
377
380
  // 2. Создаем ключи
378
381
  const keyPair = await window.crypto.subtle.generateKey({
@@ -391,8 +394,14 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
391
394
  // 3. Подписываем challenge
392
395
  let signature = await crypto.subtle.sign({ name: "RSASSA-PKCS1-v1_5" }, keyPair.privateKey, new TextEncoder().encode(options.challenge));
393
396
  signature = WORK.arrayBufferToBase64(signature);
394
- const finishPayload = { signature, credentials: this.params, ...(this.pendingInviteToken ? { inviteToken: this.pendingInviteToken } : {}) };
397
+ const finishPayload = {
398
+ signature,
399
+ credentials: this.params,
400
+ ...(this._registrationId ? { registrationId: this._registrationId } : {}),
401
+ ...(this.pendingInviteToken ? { inviteToken: this.pendingInviteToken } : {}),
402
+ };
395
403
  const resp = await WORK.fetch("/", 'user_register_finish', {}, finishPayload);
404
+ this._registrationId = '';
396
405
  if (this.pendingInviteToken) {
397
406
  try { sessionStorage.removeItem('work.pendingInviteToken'); } catch { /* ignore */ }
398
407
  this.pendingInviteToken = '';
@@ -414,6 +423,8 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
414
423
  this.isLogin = undefined;
415
424
  }
416
425
  catch (e) {
426
+ if (/неверный проверочный код/i.test(e?.message || ''))
427
+ this.showCode = true;
417
428
  this.text = e.message;
418
429
  }
419
430
  },