odant-work 1.0.98 → 1.0.100

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 (31) hide show
  1. package/#system/package-manifest.json +32 -33
  2. package/$server/$folder/$class/$data/handlers/pages/form/objects/$handler/class.js +26 -4
  3. package/$server/$folder/$class/$data/handlers/pages/form/objects/object/$handler/class.js +7 -2
  4. package/$server/$folder/$class/$domain/class.js +1 -0
  5. package/$server/$folder/$class/$module/handlers/pages/form/system/modules/$handler/class.js +1 -1
  6. package/$server/$folder/$class/$structure/$project/class.js +1 -0
  7. package/$server/$folder/$class/$structure/{handlers → $project/handlers}/pages/form/system/modules/$handler/class.js +21 -4
  8. package/$server/$folder/$class/$structure/$server/class.js +1 -0
  9. package/$server/$folder/$class/$structure/$server/handlers/pages/form/system/license/$handler/class.js +1 -1
  10. package/$server/$folder/$class/$structure/$user/class.js +1 -0
  11. package/$server/$folder/$class/$structure/handlers/pages/data/$handler/class.js +14 -1
  12. package/$server/$folder/$class/$structure/handlers/pages/form/email/$handler/class.js +34 -5
  13. package/$server/$folder/$class/$structure/handlers/pages/form/system/agent/$handler/class.js +28 -4
  14. package/$server/$folder/$class/$structure/handlers/pages/form/system/database/$handler/class.js +10 -6
  15. package/$server/$folder/$class/$structure/handlers/pages/form/system/messengers/$handler/class.js +41 -10
  16. package/$server/$folder/$class/$structure/handlers/pages/form/system/skills/$handler/class.js +27 -16
  17. package/$server/$folder/$class/$structure/handlers/pages/form/system/staff/$handler/class.js +19 -6
  18. package/$server/$folder/$class/ai/system.md +1 -1
  19. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/feed.js +7 -1
  20. package/$server/$folder/lib/consultant/consultant.js +6 -1
  21. package/$server/$folder/lib/explorer/explorer.js +53 -8
  22. package/$server/$folder/lib/messenger-settings/messenger-settings.js +63 -21
  23. package/$server/$folder/lib/prompt-bar/prompt-bar.js +15 -1
  24. package/AGENTS.md +1 -1
  25. package/PROJECTS/$domain/readme.md +2 -2
  26. package/package.json +1 -1
  27. package/sources/client/handler.js +17 -5
  28. package/sources/modules/agent/node-rules.js +5 -0
  29. package/sources/server/class/base-template.js +19 -81
  30. package/sources/server/class/security.js +19 -1
  31. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/modules/$handler/class.js +0 -3
@@ -550,10 +550,6 @@ export default {
550
550
  </div>
551
551
  <div class="top-right">
552
552
  <oda-tabs variant="pills" compact :allow-list="false" :items="dbModeTabItems" :focused-index="dbModeTabIndex" @tab-select="onDbModeTabSelect($event)"></oda-tabs>
553
- <button class="btn" @tap="reloadAll()" :disabled="loading">
554
- <oda-icon icon="icons:refresh" :icon-size="16"></oda-icon>
555
- <span>Обновить</span>
556
- </button>
557
553
  </div>
558
554
  </div>
559
555
 
@@ -912,8 +908,13 @@ export default {
912
908
  $public: {
913
909
  $item: {
914
910
  $def: null,
915
- set(n) {
916
- if (n) this.initForItem();
911
+ set(n, o) {
912
+ if (o && this._onChanged) o.unlisten?.('changed', this._onChanged);
913
+ if (n) {
914
+ this._onChanged ??= () => this.debounce?.('db-reload', () => this.reloadAll(), 250) ?? this.reloadAll();
915
+ n.listen?.('changed', this._onChanged);
916
+ this.initForItem();
917
+ }
917
918
  }
918
919
  },
919
920
  databases: {
@@ -1525,6 +1526,9 @@ export default {
1525
1526
  } catch {
1526
1527
  return '';
1527
1528
  }
1529
+ },
1530
+ detached() {
1531
+ if (this.$item && this._onChanged) this.$item.unlisten?.('changed', this._onChanged);
1528
1532
  }
1529
1533
  }
1530
1534
  };
@@ -167,7 +167,6 @@ export default {
167
167
  <span ~if="!effectiveBot" class="badge warn">
168
168
  Бот не задан (работает браузерный Web-Push)
169
169
  </span>
170
- <oda-button icon="icons:refresh" label="Обновить" title="Обновить статус и проверить коды привязки" @tap="pollAndReload()"></oda-button>
171
170
  </div>
172
171
  </div>
173
172
 
@@ -217,9 +216,8 @@ export default {
217
216
  </div>
218
217
 
219
218
  <div ~if="linkCodeInfo && linkCodeInfo.target === 'group'" class="code-box">
220
- <span>Добавьте бота в групповой чат подразделения и отправьте туда команду:</span>
219
+ <span>Добавьте бота в групповой чат подразделения и отправьте туда команду (привязка определится автоматически):</span>
221
220
  <span class="code-mono">{{linkCodeInfo.command}}</span>
222
- <oda-button icon="icons:check" label="Я отправил код — проверить" @tap="pollAndReload()"></oda-button>
223
221
  </div>
224
222
 
225
223
  <div class="row">
@@ -261,10 +259,9 @@ export default {
261
259
  </div>
262
260
 
263
261
  <div ~if="linkCodeInfo && linkCodeInfo.target === 'user'" class="code-box">
264
- <span>Отправьте боту {{linkCodeInfo.bot?.username ? '@' + linkCodeInfo.bot.username : (linkCodeInfo.bot?.label || 'мессенджера')}} команду:</span>
262
+ <span>Отправьте боту {{linkCodeInfo.bot?.username ? '@' + linkCodeInfo.bot.username : (linkCodeInfo.bot?.label || 'мессенджера')}} команду (привязка определится автоматически):</span>
265
263
  <span class="code-mono">{{linkCodeInfo.command}}</span>
266
264
  <a ~if="linkCodeInfo.deepLink" class="deep-link" :href="linkCodeInfo.deepLink" target="_blank" rel="noopener">Открыть бота</a>
267
- <oda-button icon="icons:check" label="Я отправил код — проверить" @tap="pollAndReload()"></oda-button>
268
265
  </div>
269
266
  </div>
270
267
 
@@ -283,6 +280,16 @@ export default {
283
280
  </div>
284
281
  </div>
285
282
  `,
283
+ $item: {
284
+ $def: null,
285
+ set(n, o) {
286
+ if (o && this._onChanged) o.unlisten?.('changed', this._onChanged);
287
+ if (n) {
288
+ this._onChanged ??= () => this.debounce?.('msg-reload', () => this.reload(), 200) ?? this.reload();
289
+ n.listen?.('changed', this._onChanged);
290
+ }
291
+ }
292
+ },
286
293
  $form: null,
287
294
  allowSave: true,
288
295
  _savedSnap: '',
@@ -337,6 +344,26 @@ export default {
337
344
  async attached() {
338
345
  await this.reload();
339
346
  },
347
+ detached() {
348
+ this._stopLinkPolling();
349
+ if (this.$item && this._onChanged) this.$item.unlisten?.('changed', this._onChanged);
350
+ },
351
+ _startLinkPolling() {
352
+ this._stopLinkPolling();
353
+ this._pollTimer = setInterval(() => {
354
+ if (!this.isConnected || !this.linkCodeInfo) {
355
+ this._stopLinkPolling();
356
+ return;
357
+ }
358
+ this.pollAndReload(true);
359
+ }, 3000);
360
+ },
361
+ _stopLinkPolling() {
362
+ if (this._pollTimer) {
363
+ clearInterval(this._pollTimer);
364
+ this._pollTimer = null;
365
+ }
366
+ },
340
367
  get hasPersonalLink() {
341
368
  return Boolean(this.currentUser?.telegram || this.currentUser?.max);
342
369
  },
@@ -447,24 +474,28 @@ export default {
447
474
  }
448
475
  });
449
476
  this.linkCodeInfo = info;
477
+ if (info) this._startLinkPolling();
450
478
  } catch (e) {
451
479
  this.error = String(e?.message || e);
452
480
  }
453
481
  },
454
- async pollAndReload() {
455
- this.error = '';
456
- this.notice = '';
482
+ async pollAndReload(silent = false) {
483
+ if (!silent) {
484
+ this.error = '';
485
+ this.notice = '';
486
+ }
457
487
  try {
458
488
  const st = await this.$item.fetch('messenger_poll');
459
489
  this.applyStatus(st);
460
490
  if (Array.isArray(st?.matched) && st.matched.length) {
461
491
  this.linkCodeInfo = null;
492
+ this._stopLinkPolling();
462
493
  this.notice = `Привязка выполнена (${st.matched.map(m => m.type === 'group' ? 'группа ' + m.chatTitle : 'пользователь ' + m.uid).join(', ')})`;
463
- } else {
494
+ } else if (!silent) {
464
495
  this.notice = 'Статус обновлён';
465
496
  }
466
497
  } catch (e) {
467
- this.error = String(e?.message || e);
498
+ if (!silent) this.error = String(e?.message || e);
468
499
  }
469
500
  },
470
501
  async unbind(target = 'user', channel = '') {
@@ -58,6 +58,7 @@ export default {
58
58
  padding: 6px 12px; border-radius: 8px; font-size: 12px; font-weight: 500;
59
59
  cursor: pointer; display: inline-flex; align-items: center; gap: 6px;
60
60
  }
61
+ .btn:disabled { opacity: 0.45; cursor: default; }
61
62
  .btn-primary { background: var(--accent-color, #2563eb); color: #fff; border-color: transparent; }
62
63
  .form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px; }
63
64
  .field { display: flex; flex-direction: column; gap: 4px; }
@@ -85,7 +86,6 @@ export default {
85
86
  <p>Навыки <span class="code-chip">ai/skills/</span> наследуются вниз по ветке структур; вызываются через <span class="code-chip">@имя</span></p>
86
87
  </div>
87
88
  </div>
88
- <button class="btn" @tap="reload">↻ Обновить</button>
89
89
  </div>
90
90
 
91
91
  <div ~if="noticeText" class="notice" :error="noticeError">{{noticeText}}</div>
@@ -111,7 +111,7 @@ export default {
111
111
  <div class="cmd-box">{{$for.item.filePath}}</div>
112
112
  <div class="btn-row">
113
113
  <button class="btn btn-primary" @tap="importHostSkill($for.item)">
114
- {{$for.item.installedInWork ? '↻ Обновить в WORK' : '⬇ Импортировать в WORK'}}
114
+ {{$for.item.installedInWork ? '⬇ Перезаписать с ПК' : '⬇ Импортировать в WORK'}}
115
115
  </button>
116
116
  </div>
117
117
  </div>
@@ -137,7 +137,7 @@ export default {
137
137
  <textarea :value="skillContentInput" @input="skillContentInput = $event.target.value" placeholder="---\nname: my-skill\ndescription: Когда применять навык\n---\n\nИнструкция..."></textarea>
138
138
  </div>
139
139
  <div class="btn-row">
140
- <button class="btn btn-primary" @tap="installCustomSkill">⚡ Сохранить навык</button>
140
+ <button class="btn btn-primary" :disabled="!canSaveCustomSkill" @tap="installCustomSkill">⚡ Сохранить навык</button>
141
141
  </div>
142
142
  </div>
143
143
 
@@ -166,23 +166,34 @@ export default {
166
166
  </div>
167
167
  </div>
168
168
  `,
169
- props: {
170
- $item: null,
171
- skills: { type: Array, default: () => [] },
172
- hostSkills: { type: Array, default: () => [] },
173
- expandedSkillId: '',
174
- noticeText: '',
175
- noticeError: false,
176
- skillUrlInput: '',
177
- skillIdInput: '',
178
- skillContentInput: '',
169
+ $item: {
170
+ $def: null,
171
+ set(n, o) {
172
+ if (o && this._onChanged) o.unlisten?.('changed', this._onChanged);
173
+ if (n) {
174
+ this._onChanged ??= () => this.debounce?.('skills-reload', () => this.reload(), 150) ?? this.reload();
175
+ n.listen?.('changed', this._onChanged);
176
+ this.reload();
177
+ }
178
+ },
179
+ },
180
+ skills: [],
181
+ hostSkills: [],
182
+ expandedSkillId: '',
183
+ noticeText: '',
184
+ noticeError: false,
185
+ skillUrlInput: '',
186
+ skillIdInput: '',
187
+ skillContentInput: '',
188
+ get canSaveCustomSkill() {
189
+ return Boolean(String(this.skillUrlInput || '').trim() || String(this.skillContentInput || '').trim());
179
190
  },
180
- observers: [function onItem($item) {
181
- if ($item) this.reload();
182
- }],
183
191
  attached() {
184
192
  this.reload();
185
193
  },
194
+ detached() {
195
+ if (this.$item && this._onChanged) this.$item.unlisten?.('changed', this._onChanged);
196
+ },
186
197
  showNotice(text, isError = false) {
187
198
  this.noticeText = String(text || '');
188
199
  this.noticeError = Boolean(isError);
@@ -1331,7 +1331,7 @@ export default {
1331
1331
  <oda-icon ~if="canEdit" class="chev" icon="icons:chevron-right:90" icon-size="14"></oda-icon>
1332
1332
  </div>
1333
1333
 
1334
- <div ~if="canEdit" class="row-actions">
1334
+ <div ~if="canEdit && canManageRoles" class="row-actions">
1335
1335
  <button type="button" class="icon-btn add-role-btn" @tap="promptAddRole('')">
1336
1336
  <oda-icon icon="icons:add" icon-size="15"></oda-icon>
1337
1337
  <span>Роль</span>
@@ -1339,9 +1339,9 @@ export default {
1339
1339
  </div>
1340
1340
  </div>
1341
1341
 
1342
- <div ~if="!rootRoles.length" class="muted" style="padding:16px;">Ролей пока нет</div>
1342
+ <div ~if="canManageRoles && !rootRoles.length" class="muted" style="padding:16px;">Ролей пока нет</div>
1343
1343
 
1344
- <staff-role-node ~for="rootRoles"
1344
+ <staff-role-node ~if="canManageRoles" ~for="rootRoles"
1345
1345
  :role="$for.item"
1346
1346
  :prefix="''"
1347
1347
  :depth="0"
@@ -1358,10 +1358,18 @@ export default {
1358
1358
  `,
1359
1359
  $item: {
1360
1360
  $def: null,
1361
- set(n) {
1362
- if (n) this.reload();
1361
+ set(n, o) {
1362
+ if (o && this._onChanged) o.unlisten?.('changed', this._onChanged);
1363
+ if (n) {
1364
+ this._onChanged ??= () => this.debounce?.('staff-reload', () => this.reload(), 200) ?? this.reload();
1365
+ n.listen?.('changed', this._onChanged);
1366
+ this.reload();
1367
+ }
1363
1368
  }
1364
1369
  },
1370
+ get canManageRoles() {
1371
+ return this.$item?.DATA?.allowRoles !== false;
1372
+ },
1365
1373
  security: null,
1366
1374
  allUsers: [],
1367
1375
  usersTree: [],
@@ -1389,6 +1397,9 @@ export default {
1389
1397
  async attached() {
1390
1398
  if (this.$item) await this.reload();
1391
1399
  },
1400
+ detached() {
1401
+ if (this.$item && this._onChanged) this.$item.unlisten?.('changed', this._onChanged);
1402
+ },
1392
1403
  async applyNav(nav = {}) {
1393
1404
  if (nav.place) this.focusedTrail = String(nav.place);
1394
1405
  await this.reload();
@@ -1935,6 +1946,7 @@ export default {
1935
1946
  },
1936
1947
  async setBoss(uid) {
1937
1948
  const sec = JSON.parse(JSON.stringify(this.security || {}));
1949
+ if (!this.canManageRoles) delete sec.ROLES;
1938
1950
  const cleanUid = String(uid || '').trim();
1939
1951
  sec.BOSS = cleanUid ? [cleanUid] : [];
1940
1952
  const label = cleanUid ? this.userLabel(cleanUid) : 'наследуется сверху';
@@ -1962,7 +1974,7 @@ export default {
1962
1974
  if (uid) await this.setBoss(uid);
1963
1975
  },
1964
1976
  async onRoleDrop(e, trail) {
1965
- if (!this.canEdit) return;
1977
+ if (!this.canEdit || !this.canManageRoles) return;
1966
1978
  e.preventDefault();
1967
1979
  const dropped = parseDroppedItem(e);
1968
1980
  if (!dropped) return;
@@ -2005,6 +2017,7 @@ export default {
2005
2017
  return node;
2006
2018
  },
2007
2019
  async promptAddRole(parentTrail = '') {
2020
+ if (!this.canManageRoles) return;
2008
2021
  const raw = window.prompt(parentTrail ? 'Добавить подроль' : 'Добавить роль', 'Название');
2009
2022
  const label = String(raw || '').trim();
2010
2023
  if (!label || label === 'Название') return;
@@ -23,7 +23,7 @@
23
23
 
24
24
  - **Дерево и типы:** всё — папка или файл единого дерева; адрес узла — его путь. Папка с метапапкой `$тип` — класс: `class.js` (свойства), `readme.md` (контракт), `handlers/`. Ветки типов: `$structure` (кто действует: `$server`, `$project`, `$structure`, `$user`), `$module` (что установлено, в т. ч. `$mcp` и `$provider` с моделями `$ai`), `$data` (где хранятся объекты); `$class` абстрактен. `/X/~/…` отдаёт собранное по слоям: `/X/~/class.js`, `/X/~/readme.md`, `/X/~/handlers/…`.
25
25
  - **Ссылки:** только `ancestor` (узел продолжает другой) и `types` (примеси) в `class.js`; из пути ничего не вычисляется.
26
- - **Роли:** встроенная одна — `BOSS` (владелец узла и поддерева, наследуется вниз). Остальные — записи `#security.ROLES` структуры (`assign`, права `LINKS` `read`/`write`, маркеры `USERS`/`GUESTS`), а не дочерние классы.
26
+ - **Роли:** встроенная одна — `BOSS` (единственный владелец узла и поддерева на `$server`, `$project` и `$structure`, наследуется вниз). Остальные — записи `#security.ROLES` только подразделений `$structure` (`USERS`, права `LINKS`, маркер `external`), а не дочерние классы.
27
27
  - **Учёт:** `$catalog` (листья хранят объекты, группы агрегируют), `$virtual` (`turnover`/`balance` + `OVERLAY`), `$struct` (`table: true` — таблица), `$operation` — двойная запись (Дебет + Кредит в `$account` + `logs`); проведённое исправляется только сторно; поля справочника-аналитики — субаналитики.
28
28
  - **Ядро и дерево:** ядро (`sources/`, `oda/`, `run.mjs`, `#system/`) меняется только по явной задаче доработки движка через `developer`-контур (тесты, отложенный перезапуск). Остальное — дерево, включая системный типизатор `/$server/$folder`; оно меняется штатно, без git. Правки типизатора и модулей уровня WORK — только извне проектов, с подтверждением, проверкой последствий и сбросом кэша.
29
29
  - **Арены инструментов:** дерево — WORK-инструментами (`ls/read/find/write/edit/delete`, `create_class/update_class/move_class/delete_class`), файлы ОС вне WORK — `os_*`; `shell` не служит обходом WORK-ограничений.
@@ -443,7 +443,7 @@ ODA({ is: 'microchat-tool',
443
443
  </div>
444
444
  <div class="why" ~if="connectMsg">{{connectMsg}}</div>
445
445
  <div class="btns">
446
- <oda-button hide-icon accent-invert :label="data.connect.provider === 'token' ? 'Сохранить' : 'Войти в ' + (data.connect.label || '')" @tap="connect()"></oda-button>
446
+ <oda-button hide-icon accent-invert :disabled="!canConnect" :label="data.connect.provider === 'token' ? 'Сохранить' : 'Войти в ' + (data.connect.label || '')" @tap="connect()"></oda-button>
447
447
  <oda-button hide-icon class="ghost danger" label="Не подключать" @tap="approve(false)"></oda-button>
448
448
  </div>
449
449
  </div>
@@ -552,6 +552,12 @@ ODA({ is: 'microchat-tool',
552
552
  openExternal() { window.open(this.data?.page?.url, '_blank'); },
553
553
  openUrl(u) { window.open(u, '_blank'); },
554
554
  get needClient() { return !!this.data?.connect?.need_client && this.data.connect.provider !== 'token'; },
555
+ get canConnect() {
556
+ const p = this.data?.connect?.provider;
557
+ if (p === 'token') return Boolean(String(this.cred?.token || '').trim());
558
+ if (this.needClient) return Boolean(String(this.cred?.client_id || '').trim() && String(this.cred?.client_secret || '').trim());
559
+ return true;
560
+ },
555
561
  get redirectUri() { return location.origin + '/oauth/callback'; },
556
562
  cred: {},
557
563
  connectMsg: '',
@@ -871,9 +871,14 @@ ODA({
871
871
  async _hydrateModel() {
872
872
  try {
873
873
  const uid = globalThis.WORK?.uid || globalThis.WORK?.USER?.id || globalThis.WORK?.credentials?.uid || 'default';
874
- const userModel = localStorage.getItem(`work.user.ai:${uid}:model`)
874
+ const rawUserModel = localStorage.getItem(`work.user.ai:${uid}:model`)
875
875
  || localStorage.getItem('work.user.ai:default:model')
876
876
  || '';
877
+ const trimmed = rawUserModel.trim();
878
+ const modelsBase = ['MODULES', 'Модели'].join('/');
879
+ const userModel = /^\/?MODELS(?:\/|$)/i.test(trimmed)
880
+ ? '/' + modelsBase + (trimmed.startsWith('/') ? trimmed : '/' + trimmed).slice('/MODELS'.length)
881
+ : rawUserModel;
877
882
  if (userModel && !/(flux|sdxl|stable-?diffusion|z-image|embedding|bge-|rerank|whisper|\basr\b|\btts\b|\bstt\b|voice|kokoro|musicgen|wan2|ltx-video)/i.test(userModel)) {
878
883
  this.model = userModel;
879
884
  return;
@@ -3,7 +3,7 @@ export default {
3
3
  imports: 'oda//app-layout.js, oda//tabs.js, oda//icon, oda//button, ~/lib//tree.js, ~/lib//node-explorer.js, ~/lib//consultant.js, ~/lib//class-picker.js, ~/lib//support.js',
4
4
  extends: 'oda-app-layout',
5
5
  template: /*html*/`
6
- <item-tree order="0" slot='left-panel' :clean-structure="cleanStructure" :items-selector :show-size show-status show-users allow-focus :hide-roots :hide-tops :$item style="height: 0"></item-tree>
6
+ <item-tree order="0" slot='left-panel' :clean-structure="cleanStructure" :items-selector :show-size show-status show-users allow-focus :hide-roots :hide-tops :$item="treeRootItem" style="height: 0"></item-tree>
7
7
  <item-consultant order="3" slot='left-panel' id="consultant" label="ИИ" icon="bootstrap:robot" :$item hidden style="height: 0"></item-consultant>
8
8
  <div flex vertical slot='main' style="overflow: hidden; position: relative;">
9
9
  <call-form ~if="showCall" id="callForm"></call-form>
@@ -255,6 +255,43 @@ export default {
255
255
  hideRoots: 2,
256
256
  hideTops: 0,
257
257
  itemsSelector: 'items',
258
+ _treeScopeUser: null,
259
+ get treeRootItem() {
260
+ return this._treeScopeUser || this.$item;
261
+ },
262
+ async _syncExplorerTreeScope() {
263
+ if (!this.$item)
264
+ return;
265
+ if (WORK.DEV_MODE || !WORK.uid) {
266
+ this._treeScopeUser = null;
267
+ this.hideRoots = 2;
268
+ this.hideTops = 0;
269
+ return;
270
+ }
271
+ if (this.$item.type === '$server') {
272
+ try {
273
+ const isAdm = await this.$item.isBoss;
274
+ if (isAdm) {
275
+ this._treeScopeUser = null;
276
+ this.hideRoots = 2;
277
+ this.hideTops = 0;
278
+ return;
279
+ }
280
+ const info = await WORK.fetch(location.origin + '/', 'info', { deep: 1, tree: 'main' }).catch(() => null);
281
+ if (Array.isArray(info?.items) && info.items.length === 0 && WORK.USER) {
282
+ this._treeScopeUser = WORK.USER;
283
+ this.hideRoots = 0;
284
+ this.hideTops = 0;
285
+ }
286
+ else {
287
+ this._treeScopeUser = null;
288
+ this.hideRoots = 2;
289
+ this.hideTops = 1;
290
+ }
291
+ }
292
+ catch { /* ignore */ }
293
+ }
294
+ },
258
295
 
259
296
  _bookmarksStorageKey() {
260
297
  const root = this.$item?.short || this.$item?.path || '/';
@@ -672,6 +709,7 @@ export default {
672
709
  url.searchParams.delete('invite');
673
710
  history.replaceState(null, '', url.pathname + url.search + url.hash);
674
711
  if (res?.consumed) {
712
+ await this._syncExplorerTreeScope();
675
713
  this.$('item-tree')?.refreshTree?.();
676
714
  const p = await WORK.get_item(res.pointPath).catch(() => null);
677
715
  if (p)
@@ -692,15 +730,13 @@ export default {
692
730
  if(this.left_drawer)
693
731
  this.left_drawer.closed = true;
694
732
  }
695
- if (this.$item?.type === '$server' && !WORK.DEV_MODE) {
696
- try {
697
- const isAdm = await this.$item.isBoss;
698
- this.hideTops = isAdm ? 0 : 1;
699
- }
700
- catch { /* ignore */ }
701
- }
733
+ await this._syncExplorerTreeScope();
702
734
  })
703
735
  window.explorer = this;
736
+ if (this.$item?.listen && !this._onRootChanged) {
737
+ this._onRootChanged = () => this.debounce?.('explorer-scope', () => this._syncExplorerTreeScope(), 250);
738
+ this.$item.listen('changed', this._onRootChanged);
739
+ }
704
740
  if (!this._dirtyMsgBound && typeof window !== 'undefined') {
705
741
  this._dirtyMsgBound = true;
706
742
  window.addEventListener('message', (ev) => {
@@ -730,6 +766,7 @@ export default {
730
766
  this._refreshLeftButtons();
731
767
  this._initTopLicenseBanner();
732
768
  this._refreshSupportBadge();
769
+ this._syncExplorerTreeScope();
733
770
  this.render?.();
734
771
  });
735
772
  window.execute = async ($item, nav) => {
@@ -868,6 +905,14 @@ export default {
868
905
  }
869
906
  catch { /* ignore */ }
870
907
  },
908
+ detached() {
909
+ if (this.$item?.unlisten && this._onRootChanged)
910
+ this.$item.unlisten('changed', this._onRootChanged);
911
+ if (this._supportBadgeTimer) {
912
+ clearInterval(this._supportBadgeTimer);
913
+ this._supportBadgeTimer = null;
914
+ }
915
+ },
871
916
  }
872
917
 
873
918
  ODA({ is: 'item-hexagon-layout', imports: 'oda//hexagon-layout.js', extends: 'oda-hexagon-layout',
@@ -161,7 +161,6 @@ export const MESSENGER_SETTINGS_DEF = {
161
161
  <span ~if="!effectiveBot" class="badge warn">
162
162
  Бот не задан (работает браузерный Web-Push)
163
163
  </span>
164
- <oda-button icon="icons:refresh" title="Обновить и проверить коды привязки" @tap="pollAndReload()"></oda-button>
165
164
  </div>
166
165
  </div>
167
166
 
@@ -195,10 +194,9 @@ export const MESSENGER_SETTINGS_DEF = {
195
194
  </div>
196
195
 
197
196
  <div ~if="linkCodeInfo && linkCodeInfo.target === 'user'" class="code-box">
198
- <span>Отправьте боту {{linkCodeInfo.bot?.username ? '@' + linkCodeInfo.bot.username : (linkCodeInfo.bot?.label || 'мессенджера')}} команду:</span>
197
+ <span>Отправьте боту {{linkCodeInfo.bot?.username ? '@' + linkCodeInfo.bot.username : (linkCodeInfo.bot?.label || 'мессенджера')}} команду (привязка определится автоматически):</span>
199
198
  <span class="code-mono">{{linkCodeInfo.command}}</span>
200
199
  <a ~if="linkCodeInfo.deepLink" class="deep-link" :href="linkCodeInfo.deepLink" target="_blank" rel="noopener">Открыть бота</a>
201
- <oda-button icon="icons:check" label="Я отправил код — проверить" @tap="pollAndReload()"></oda-button>
202
200
  </div>
203
201
  </div>
204
202
 
@@ -245,9 +243,8 @@ export const MESSENGER_SETTINGS_DEF = {
245
243
  </div>
246
244
 
247
245
  <div ~if="linkCodeInfo && linkCodeInfo.target === 'group'" class="code-box">
248
- <span>Добавьте бота в групповой чат подразделения и отправьте туда:</span>
246
+ <span>Добавьте бота в групповой чат подразделения и отправьте туда (привязка определится автоматически):</span>
249
247
  <span class="code-mono">{{linkCodeInfo.command}}</span>
250
- <oda-button icon="icons:check" label="Проверить привязку группы" @tap="pollAndReload()"></oda-button>
251
248
  </div>
252
249
 
253
250
  <div class="row">
@@ -259,7 +256,7 @@ export const MESSENGER_SETTINGS_DEF = {
259
256
 
260
257
  <div class="row" style="justify-content: flex-end; gap: 8px;">
261
258
  <oda-button ~if="effectiveBot" icon="communication:Send" label="Проверить общую рассылку точки" @tap="testDelivery('department')"></oda-button>
262
- <oda-button icon="icons:save" label="Сохранить настройки точки" @tap="saveConfig()"></oda-button>
259
+ <oda-button icon="icons:save" :disabled="!isChanged" label="Сохранить настройки точки" @tap="saveConfig()"></oda-button>
263
260
  </div>
264
261
  </div>
265
262
 
@@ -278,11 +275,20 @@ export const MESSENGER_SETTINGS_DEF = {
278
275
  </div>
279
276
  </div>
280
277
  `,
281
- props: {
282
- $item: { type: Object },
283
- canEdit: { type: Boolean, default: false },
284
- userMap: { type: Object, default: () => ({}) },
278
+ $item: {
279
+ $def: null,
280
+ set(n, o) {
281
+ if (o && this._onChanged) o.unlisten?.('changed', this._onChanged);
282
+ if (n) {
283
+ this._onChanged ??= () => this.debounce?.('ms-reload', () => this.reload(), 200) ?? this.reload();
284
+ n.listen?.('changed', this._onChanged);
285
+ this.reload();
286
+ }
287
+ },
285
288
  },
289
+ canEdit: false,
290
+ userMap: {},
291
+ _savedSnap: '',
286
292
  pointLabel: '',
287
293
  ownBot: null,
288
294
  effectiveBot: null,
@@ -299,16 +305,45 @@ export const MESSENGER_SETTINGS_DEF = {
299
305
  linkCodeInfo: null,
300
306
  notice: '',
301
307
  error: '',
302
- observers: [
303
- function watchItem($item) {
304
- if ($item)
305
- this.reload();
306
- },
307
- ],
308
+ _currentSnap() {
309
+ return JSON.stringify({
310
+ k: this.draftBotKind || 'telegram',
311
+ l: this.draftBotLabel || '',
312
+ t: this.draftBotToken || '',
313
+ u: this.draftBotUsername || '',
314
+ g: this.draftGroupChatId || '',
315
+ gt: this.draftGroupTitle || '',
316
+ b: Boolean(this.draftBroadcastToMembers),
317
+ });
318
+ },
319
+ get isChanged() {
320
+ if (!this._savedSnap) return false;
321
+ return this._currentSnap() !== this._savedSnap;
322
+ },
308
323
  attached() {
309
324
  if (this.$item)
310
325
  this.reload();
311
326
  },
327
+ detached() {
328
+ this._stopLinkPolling();
329
+ if (this.$item && this._onChanged) this.$item.unlisten?.('changed', this._onChanged);
330
+ },
331
+ _startLinkPolling() {
332
+ this._stopLinkPolling();
333
+ this._pollTimer = setInterval(() => {
334
+ if (!this.isConnected || !this.linkCodeInfo) {
335
+ this._stopLinkPolling();
336
+ return;
337
+ }
338
+ this.pollAndReload(true);
339
+ }, 3000);
340
+ },
341
+ _stopLinkPolling() {
342
+ if (this._pollTimer) {
343
+ clearInterval(this._pollTimer);
344
+ this._pollTimer = null;
345
+ }
346
+ },
312
347
  get hasPersonalLink() {
313
348
  return Boolean(this.currentUser?.telegram || this.currentUser?.max);
314
349
  },
@@ -330,6 +365,7 @@ export const MESSENGER_SETTINGS_DEF = {
330
365
  this.draftGroupChatId = st.groupChatId || '';
331
366
  this.draftGroupTitle = st.groupTitle || '';
332
367
  this.draftBroadcastToMembers = st.broadcastToMembers !== false;
368
+ this._savedSnap = this._currentSnap();
333
369
  },
334
370
  async reload() {
335
371
  this.error = '';
@@ -403,27 +439,33 @@ export const MESSENGER_SETTINGS_DEF = {
403
439
  post: { target, channel: this.effectiveBot?.kind || this.draftBotKind || 'telegram' },
404
440
  });
405
441
  this.linkCodeInfo = info;
442
+ if (info)
443
+ this._startLinkPolling();
406
444
  }
407
445
  catch (e) {
408
446
  this.error = String(e?.message || e);
409
447
  }
410
448
  },
411
- async pollAndReload() {
412
- this.error = '';
413
- this.notice = '';
449
+ async pollAndReload(silent = false) {
450
+ if (!silent) {
451
+ this.error = '';
452
+ this.notice = '';
453
+ }
414
454
  try {
415
455
  const st = await this.$item.fetch('messenger_poll');
416
456
  this.applyStatus(st);
417
457
  if (Array.isArray(st?.matched) && st.matched.length) {
418
458
  this.linkCodeInfo = null;
459
+ this._stopLinkPolling();
419
460
  this.notice = `Привязка выполнена (${st.matched.map(m => m.type === 'group' ? 'группа ' + m.chatTitle : 'пользователь ' + m.uid).join(', ')})`;
420
461
  }
421
- else {
462
+ else if (!silent) {
422
463
  this.notice = 'Статус обновлён';
423
464
  }
424
465
  }
425
466
  catch (e) {
426
- this.error = String(e?.message || e);
467
+ if (!silent)
468
+ this.error = String(e?.message || e);
427
469
  }
428
470
  },
429
471
  async unbind(target = 'user', channel = '') {
@@ -43,13 +43,26 @@ function userAiStorageKey(suffix = 'model') {
43
43
  return `work.user.ai:${uid}:${suffix}`;
44
44
  }
45
45
 
46
+ function normalizeModelPath(modelPath) {
47
+ const s = String(modelPath || '').trim().replace(/\\/g, '/');
48
+ if (!s)
49
+ return '';
50
+ if (/^\/?MODELS(?:\/|$)/i.test(s)) {
51
+ const clean = s.startsWith('/') ? s : '/' + s;
52
+ const modelsBase = ['MODULES', 'Модели'].join('/');
53
+ return '/' + modelsBase + clean.slice('/MODELS'.length);
54
+ }
55
+ return s;
56
+ }
57
+
46
58
  export function getUserPreferredModel() {
47
59
  if (typeof localStorage === 'undefined')
48
60
  return '';
49
61
  try {
50
- const val = localStorage.getItem(userAiStorageKey('model'))
62
+ const raw = localStorage.getItem(userAiStorageKey('model'))
51
63
  || localStorage.getItem('work.user.ai:default:model')
52
64
  || '';
65
+ const val = normalizeModelPath(raw);
53
66
  if (val && /(flux|sdxl|stable-?diffusion|z-image|embedding|bge-|rerank|whisper|\basr\b|\btts\b|\bstt\b|voice|kokoro|musicgen|wan2|ltx-video)/i.test(val))
54
67
  return '';
55
68
  return val;
@@ -60,6 +73,7 @@ export function getUserPreferredModel() {
60
73
  }
61
74
 
62
75
  export function setUserPreferredModel(modelPath) {
76
+ modelPath = normalizeModelPath(modelPath);
63
77
  if (!modelPath || typeof localStorage === 'undefined')
64
78
  return;
65
79
  if (/(flux|sdxl|stable-?diffusion|z-image|embedding|bge-|rerank|whisper|\basr\b|\btts\b|\bstt\b|voice|kokoro|musicgen|wan2|ltx-video)/i.test(modelPath))