odant-work 1.0.108 → 1.0.109

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.
@@ -0,0 +1,293 @@
1
+ export default {
2
+ label: 'SMS / Контакты',
3
+ title: 'SMS-шлюз и публичный контакт администратора',
4
+ description: 'Настройка SMS / Flash-Call провайдера для входа и приглашений по телефону, а также контакт для экрана отключённой учётной записи',
5
+ icon: 'communication:textsms',
6
+ order: 86,
7
+ group: 'infra',
8
+ roles: ['BOSS'],
9
+ component: {
10
+ imports: 'oda//button, oda//icon',
11
+ template: /* html */`
12
+ <style>
13
+ :host {
14
+ @apply --vertical;
15
+ @apply --flex;
16
+ overflow: auto;
17
+ padding: 20px;
18
+ gap: 16px;
19
+ box-sizing: border-box;
20
+ background: var(--body-background, #f6f8fb);
21
+ color: var(--content-color, #1e293b);
22
+ }
23
+ .wrap {
24
+ max-width: 820px;
25
+ width: 100%;
26
+ margin: 0 auto;
27
+ display: flex;
28
+ flex-direction: column;
29
+ gap: 16px;
30
+ }
31
+ .card {
32
+ background: var(--content-background, #ffffff);
33
+ border: 1px solid var(--subtle-border, #e2e8f0);
34
+ border-radius: 12px;
35
+ padding: 18px 20px;
36
+ display: flex;
37
+ flex-direction: column;
38
+ gap: 12px;
39
+ }
40
+ .card-head {
41
+ display: flex;
42
+ align-items: center;
43
+ justify-content: space-between;
44
+ gap: 10px;
45
+ flex-wrap: wrap;
46
+ }
47
+ .card-title {
48
+ font-size: 16px;
49
+ font-weight: 700;
50
+ display: flex;
51
+ align-items: center;
52
+ gap: 8px;
53
+ }
54
+ .badge {
55
+ padding: 4px 10px;
56
+ border-radius: 999px;
57
+ font-size: 12px;
58
+ font-weight: 600;
59
+ background: rgba(148, 163, 184, 0.16);
60
+ color: #475569;
61
+ }
62
+ .badge.ok {
63
+ background: rgba(16, 185, 129, 0.15);
64
+ color: #059669;
65
+ }
66
+ .grid {
67
+ display: grid;
68
+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
69
+ gap: 12px;
70
+ }
71
+ .field {
72
+ display: flex;
73
+ flex-direction: column;
74
+ gap: 4px;
75
+ }
76
+ .field label {
77
+ font-size: 12px;
78
+ font-weight: 600;
79
+ color: var(--muted-color, #64748b);
80
+ }
81
+ .field input, .field select, .field textarea {
82
+ padding: 8px 10px;
83
+ border-radius: 8px;
84
+ border: 1px solid var(--subtle-border, #cbd5e1);
85
+ background: var(--content-background, #fff);
86
+ color: var(--content-color, #1e293b);
87
+ font: inherit;
88
+ font-size: 13.5px;
89
+ box-sizing: border-box;
90
+ width: 100%;
91
+ }
92
+ .actions {
93
+ display: flex;
94
+ align-items: center;
95
+ gap: 10px;
96
+ flex-wrap: wrap;
97
+ }
98
+ .hint {
99
+ font-size: 12.5px;
100
+ color: var(--muted-color, #64748b);
101
+ line-height: 1.45;
102
+ }
103
+ .msg {
104
+ font-size: 13px;
105
+ font-weight: 500;
106
+ color: #059669;
107
+ }
108
+ .msg.err {
109
+ color: #dc2626;
110
+ }
111
+ </style>
112
+ <div class="wrap">
113
+ <div class="card">
114
+ <div class="card-head">
115
+ <div class="card-title">
116
+ <oda-icon icon="communication:textsms" icon-size="20"></oda-icon>
117
+ <span>Локальный SMS / Flash-Call шлюз</span>
118
+ </div>
119
+ <span class="badge" ~class="{ ok: connected }">{{connected ? 'Подключён' : 'Не настроен'}}</span>
120
+ </div>
121
+ <div class="hint">
122
+ Если локальный шлюз не настроен, лицензированный сервер WORK автоматически отправляет коды входа по телефону через сервер поддержки (<code>license.odant.org</code>), а для уже привязанных пользователей — через Telegram / MAX.
123
+ </div>
124
+ <div class="grid">
125
+ <div class="field">
126
+ <label>Провайдер</label>
127
+ <select ::value="form.provider">
128
+ <option value="none">Отключён (использовать хаб / мессенджеры)</option>
129
+ <option value="smsru">SMS.ru (SMS и Flash-Call)</option>
130
+ <option value="smsc">SMSC.ru (SMS и Flash-Call)</option>
131
+ <option value="webhook">Универсальный HTTP Webhook</option>
132
+ </select>
133
+ </div>
134
+ <div class="field" ~if="form.provider !== 'none'">
135
+ <label>Режим доставки</label>
136
+ <select ::value="form.mode">
137
+ <option value="sms">SMS-сообщение</option>
138
+ <option value="flashcall">Flash-Call (звонок-сброс, дешевле)</option>
139
+ </select>
140
+ </div>
141
+ <div class="field" ~if="form.provider === 'smsru'">
142
+ <label>API ID (SMS.ru)</label>
143
+ <input type="text" placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" ::value="form.apiKey">
144
+ </div>
145
+ <div class="field" ~if="form.provider === 'smsc'">
146
+ <label>Логин (SMSC.ru)</label>
147
+ <input type="text" placeholder="login" ::value="form.login">
148
+ </div>
149
+ <div class="field" ~if="form.provider === 'smsc'">
150
+ <label>Пароль или API-ключ (SMSC.ru)</label>
151
+ <input type="password" placeholder="••••••••" ::value="form.password">
152
+ </div>
153
+ <div class="field" ~if="form.provider === 'webhook'">
154
+ <label>URL HTTP Webhook (POST JSON)</label>
155
+ <input type="url" placeholder="https://sms-gateway.example/send" ::value="form.webhookUrl">
156
+ </div>
157
+ <div class="field" ~if="form.provider === 'webhook'">
158
+ <label>Bearer-токен Webhook (необязательно)</label>
159
+ <input type="password" placeholder="••••••••" ::value="form.webhookToken">
160
+ </div>
161
+ <div class="field" ~if="form.provider !== 'none'">
162
+ <label>Имя отправителя (Sender ID, необязательно)</label>
163
+ <input type="text" placeholder="ODANT-WORK" ::value="form.sender">
164
+ </div>
165
+ </div>
166
+ <div class="actions" ~if="form.provider !== 'none'">
167
+ <input type="tel" placeholder="+79991234567" ::value="testPhone" style="padding:7px 10px;border-radius:8px;border:1px solid var(--subtle-border,#cbd5e1);font:inherit;width:190px;">
168
+ <oda-button icon="communication:call" label="Отправить тест" @tap="sendTest" :disabled="busy || !testPhone"></oda-button>
169
+ </div>
170
+ </div>
171
+
172
+ <div class="card">
173
+ <div class="card-head">
174
+ <div class="card-title">
175
+ <oda-icon icon="icons:contact-support" icon-size="20"></oda-icon>
176
+ <span>Публичный контакт администратора (экран блокировки)</span>
177
+ </div>
178
+ </div>
179
+ <div class="hint">
180
+ Показывается отключённым пользователям на экране входа. По умолчанию скрыт (личные адреса BOSS публично не отдаются). Заполняйте только контакты, которые можно показывать на странице входа.
181
+ </div>
182
+ <div class="grid">
183
+ <div class="field">
184
+ <label>Название / Имя службы</label>
185
+ <input type="text" placeholder="Служба поддержки ИТ" ::value="form.supportContact.label">
186
+ </div>
187
+ <div class="field">
188
+ <label>Публичный Email</label>
189
+ <input type="email" placeholder="support@company.ru" ::value="form.supportContact.email">
190
+ </div>
191
+ <div class="field">
192
+ <label>Публичный телефон</label>
193
+ <input type="tel" placeholder="+7 (495) 000-00-00" ::value="form.supportContact.phone">
194
+ </div>
195
+ </div>
196
+ <div class="field">
197
+ <label>Дополнительный комментарий</label>
198
+ <textarea rows="2" placeholder="Например: время работы поддержки Пн–Пт 9:00–18:00" ::value="form.supportContact.note"></textarea>
199
+ </div>
200
+ <div class="actions">
201
+ <oda-button primary icon="icons:save" label="Сохранить настройки" @tap="saveSettings" :disabled="busy"></oda-button>
202
+ <span ~if="statusMsg" class="msg" ~class="{ err: statusErr }">{{statusMsg}}</span>
203
+ </div>
204
+ </div>
205
+ </div>
206
+ `,
207
+ $item: {
208
+ $def: null,
209
+ set(n) {
210
+ if (n) this.reload();
211
+ }
212
+ },
213
+ connected: false,
214
+ busy: false,
215
+ testPhone: '',
216
+ statusMsg: '',
217
+ statusErr: false,
218
+ form: {
219
+ provider: 'none',
220
+ mode: 'sms',
221
+ apiKey: '',
222
+ login: '',
223
+ password: '',
224
+ sender: '',
225
+ webhookUrl: '',
226
+ webhookToken: '',
227
+ supportContact: { label: '', email: '', phone: '', note: '' }
228
+ },
229
+ attached() {
230
+ if (this.$item) this.reload();
231
+ },
232
+ async reload() {
233
+ if (!this.$item) return;
234
+ try {
235
+ const res = await this.$item.fetch('sms_settings_get');
236
+ if (res && typeof res === 'object') {
237
+ this.connected = Boolean(res.connected);
238
+ this.form = {
239
+ provider: res.provider || 'none',
240
+ mode: res.mode || 'sms',
241
+ apiKey: res.apiKey || '',
242
+ login: res.login || '',
243
+ password: res.password || '',
244
+ sender: res.sender || '',
245
+ webhookUrl: res.webhookUrl || '',
246
+ webhookToken: res.webhookToken || '',
247
+ supportContact: {
248
+ label: res.supportContact?.label || '',
249
+ email: res.supportContact?.email || '',
250
+ phone: res.supportContact?.phone || '',
251
+ note: res.supportContact?.note || ''
252
+ }
253
+ };
254
+ }
255
+ } catch (err) {
256
+ this.statusErr = true;
257
+ this.statusMsg = err?.message || String(err);
258
+ }
259
+ },
260
+ async saveSettings() {
261
+ if (!this.$item || this.busy) return;
262
+ this.busy = true;
263
+ this.statusMsg = '';
264
+ this.statusErr = false;
265
+ try {
266
+ const res = await this.$item.fetch('sms_settings_save', {}, this.form);
267
+ this.connected = Boolean(res?.connected);
268
+ this.statusMsg = 'Настройки сохранены в #system/sms.json';
269
+ } catch (err) {
270
+ this.statusErr = true;
271
+ this.statusMsg = err?.message || String(err);
272
+ } finally {
273
+ this.busy = false;
274
+ }
275
+ },
276
+ async sendTest() {
277
+ if (!this.$item || this.busy) return;
278
+ this.busy = true;
279
+ this.statusMsg = '';
280
+ this.statusErr = false;
281
+ try {
282
+ await this.$item.fetch('sms_settings_save', {}, this.form);
283
+ const res = await this.$item.fetch('sms_settings_test', {}, { phone: this.testPhone });
284
+ this.statusMsg = `Тест отправлен (${res?.provider || ''} · ${res?.mode || ''})`;
285
+ } catch (err) {
286
+ this.statusErr = true;
287
+ this.statusMsg = err?.message || String(err);
288
+ } finally {
289
+ this.busy = false;
290
+ }
291
+ }
292
+ }
293
+ };
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Приглашение нового или существующего пользователя на рабочее место активной структуры ($structure) для BOSS.
3
+ */
4
+ export default {
5
+ icon: 'icons:person-add',
6
+ label: 'Пригласить',
7
+ roles: ['BOSS'],
8
+ isButton: true,
9
+ order: 5,
10
+ allowUse($context) {
11
+ return Boolean($context && !$context.DATA?.isUser && !$context.DATA?.usersContainer);
12
+ },
13
+ async execute() {
14
+ const target = await (this.$context || this.$item?.$context || this.$item);
15
+ if (!target)
16
+ return;
17
+ await import('/$server/$folder/lib/invite/invite.js');
18
+ const el = ODA.createComponent('work-invite-dialog', { $item: target });
19
+ try {
20
+ await WORK.showDialog(el, {
21
+ allowClose: true,
22
+ TITLE: { label: 'Пригласить пользователя', icon: 'icons:person-add' },
23
+ CANCEL: { label: 'Закрыть', icon: 'icons:close' },
24
+ });
25
+ }
26
+ catch (err) {
27
+ if (!(err instanceof WORK.CancelError))
28
+ console.warn('[invite]', err);
29
+ }
30
+ },
31
+ };
@@ -1332,8 +1332,12 @@ export default {
1332
1332
  <oda-icon ~if="canEdit" class="chev" icon="icons:chevron-right:90" icon-size="14"></oda-icon>
1333
1333
  </div>
1334
1334
 
1335
- <div ~if="canEdit && canManageRoles" class="row-actions">
1336
- <button type="button" class="icon-btn add-role-btn" @tap="promptAddRole('')">
1335
+ <div ~if="canEdit" class="row-actions">
1336
+ <button type="button" class="icon-btn add-role-btn" @tap="openInviteDialog()">
1337
+ <oda-icon icon="icons:person-add" icon-size="15"></oda-icon>
1338
+ <span>Пригласить</span>
1339
+ </button>
1340
+ <button ~if="canManageRoles" type="button" class="icon-btn add-role-btn" @tap="promptAddRole('')">
1337
1341
  <oda-icon icon="icons:add" icon-size="15"></oda-icon>
1338
1342
  <span>Роль</span>
1339
1343
  </button>
@@ -2017,6 +2021,25 @@ export default {
2017
2021
  }
2018
2022
  return node;
2019
2023
  },
2024
+ async openInviteDialog() {
2025
+ if (!this.$item || !this.canEdit) return;
2026
+ await import('/$server/$folder/lib/invite/invite.js');
2027
+ const el = ODA.createComponent('work-invite-dialog', { $item: this.$item });
2028
+ const onAssigned = () => this.reload();
2029
+ el.addEventListener('assigned', onAssigned);
2030
+ try {
2031
+ await WORK.showDialog(el, {
2032
+ allowClose: true,
2033
+ TITLE: { label: 'Пригласить пользователя', icon: 'icons:person-add' },
2034
+ CANCEL: { label: 'Закрыть', icon: 'icons:close' },
2035
+ });
2036
+ } catch (err) {
2037
+ if (!(err instanceof WORK.CancelError))
2038
+ console.warn('[staff.invite]', err);
2039
+ } finally {
2040
+ el.removeEventListener('assigned', onAssigned);
2041
+ }
2042
+ },
2020
2043
  async promptAddRole(parentTrail = '') {
2021
2044
  if (!this.canManageRoles) return;
2022
2045
  const raw = window.prompt(parentTrail ? 'Добавить подроль' : 'Добавить роль', 'Название');
@@ -1576,11 +1576,18 @@ ODA({is: 'work-form',
1576
1576
  get currentItem() {
1577
1577
  return this.activeItem || this.$item;
1578
1578
  },
1579
+ _formViewsKey($item = this.currentItem, role = this.activeRole) {
1580
+ return ($item?.short || $item?.path || '') + '::' + (role || '');
1581
+ },
1579
1582
  get formViews() {
1580
1583
  const $item = this.currentItem;
1581
1584
  const role = this.activeRole;
1582
1585
  if (!$item)
1583
1586
  return [];
1587
+ const key = this._formViewsKey($item, role);
1588
+ const cached = this._formViewsCache?.get?.(key);
1589
+ if (Array.isArray(cached))
1590
+ return cached;
1584
1591
  return this.loadFormViews($item, role);
1585
1592
  },
1586
1593
  _myScope: null,
@@ -1591,49 +1598,84 @@ ODA({is: 'work-form',
1591
1598
  return Boolean(isUsr && item.id && globalThis.WORK?.uid && item.id !== globalThis.WORK.uid);
1592
1599
  },
1593
1600
  get visibleFormViews() {
1594
- const views = this.formViews;
1595
- if (!Array.isArray(views))
1601
+ const cur = this.currentItem;
1602
+ const raw = this.formViews;
1603
+ const itemKey = cur?.short || cur?.path || '';
1604
+ const views = Array.isArray(raw)
1605
+ ? raw
1606
+ : (this._lastFormViewsByItem?.get?.(itemKey) || []);
1607
+ if (!Array.isArray(views) || !views.length)
1596
1608
  return [];
1597
- if (this._isForeignUserItem(this.currentItem)) {
1598
- return views.filter(v => v?.id === 'chat');
1599
- }
1600
- const hideSystemForUnassigned = Boolean(
1601
- this._myScope?.isUnassigned
1602
- && (this.currentItem?.DATA?.isUser || this.currentItem?.isUser)
1603
- && !this.currentItem?.DATA?.usersContainer
1604
- );
1605
- return views.filter(v => {
1606
- if (hideSystemForUnassigned && v?.id === 'system')
1607
- return false;
1608
- return !(v?.DATA?.hidden || v?.hidden) || v?.id === this.view?.id;
1609
- });
1609
+ let filtered;
1610
+ if (this._isForeignUserItem(cur)) {
1611
+ filtered = views.filter(v => v?.id === 'chat');
1612
+ }
1613
+ else {
1614
+ const hideSystemForUnassigned = Boolean(
1615
+ this._myScope?.isUnassigned
1616
+ && (cur?.DATA?.isUser || cur?.isUser)
1617
+ && !cur?.DATA?.usersContainer
1618
+ );
1619
+ const activeViewId = this.view?.id;
1620
+ filtered = views.filter(v => {
1621
+ if (hideSystemForUnassigned && v?.id === 'system')
1622
+ return false;
1623
+ return !(v?.DATA?.hidden || v?.hidden) || v?.id === activeViewId;
1624
+ });
1625
+ }
1626
+ // Сохраняем ссылку на тот же массив, если состав представлений не изменился — исключает мигание ~for
1627
+ const prev = this._stableVisibleFormViews;
1628
+ if (Array.isArray(prev) && prev.length === filtered.length && prev.every((v, i) => v === filtered[i] || (v?.id && v.id === filtered[i]?.id)))
1629
+ return prev;
1630
+ this._stableVisibleFormViews = filtered;
1631
+ return filtered;
1610
1632
  },
1611
1633
  async loadFormViews($item, role) {
1612
- try {
1613
- const root = await $item.fetch('handlers', { path: '//form', ...(role ? { role } : {}) });
1614
- let views = (root?.items || []).filter(item => {
1615
- if (!item || item.type !== '$handler' || item.enabled === false || item.usable === false || item.allowUse === false)
1616
- return false;
1617
- if ((item.layout || item.DATA?.layout) && Array.isArray(item.items)) {
1618
- const hasChild = item.items.some(ch => ch && ch.type === '$handler' && ch.enabled !== false && ch.usable !== false && ch.allowUse !== false);
1619
- if (!hasChild)
1634
+ if (!$item || typeof $item.fetch !== 'function')
1635
+ return [];
1636
+ const cacheKey = this._formViewsKey($item, role);
1637
+ const itemKey = $item?.short || $item?.path || '';
1638
+ this._formViewsCache ??= new Map();
1639
+ this._lastFormViewsByItem ??= new Map();
1640
+ this._formViewsInflight ??= new Map();
1641
+ if (this._formViewsCache.has(cacheKey))
1642
+ return this._formViewsCache.get(cacheKey);
1643
+ if (this._formViewsInflight.has(cacheKey))
1644
+ return this._formViewsInflight.get(cacheKey);
1645
+ const req = (async () => {
1646
+ try {
1647
+ const root = await $item.fetch('handlers', { path: '//form', ...(role ? { role } : {}) });
1648
+ let views = (root?.items || []).filter(item => {
1649
+ if (!item || item.type !== '$handler' || item.enabled === false || item.usable === false || item.allowUse === false)
1620
1650
  return false;
1651
+ if ((item.layout || item.DATA?.layout) && Array.isArray(item.items)) {
1652
+ const hasChild = item.items.some(ch => ch && ch.type === '$handler' && ch.enabled !== false && ch.usable !== false && ch.allowUse !== false);
1653
+ if (!hasChild)
1654
+ return false;
1655
+ }
1656
+ return true;
1657
+ });
1658
+ views.sort((a, b) => (a.order ?? a.DATA?.order ?? 99) - (b.order ?? b.DATA?.order ?? 99));
1659
+ const ext = $item?.ext;
1660
+ for (const v of views) {
1661
+ v.$context = $item;
1662
+ if (v.id === 'file' && ext && v.DATA) {
1663
+ v.DATA.icon = 'files-color:s-' + ext;
1664
+ }
1621
1665
  }
1622
- return true;
1623
- });
1624
- views.sort((a, b) => (a.order ?? a.DATA?.order ?? 99) - (b.order ?? b.DATA?.order ?? 99));
1625
- const ext = $item?.ext;
1626
- for (const v of views) {
1627
- v.$context = $item;
1628
- if (v.id === 'file' && ext && v.DATA) {
1629
- v.DATA.icon = 'files-color:s-' + ext;
1630
- }
1666
+ this._formViewsCache.set(cacheKey, views);
1667
+ if (itemKey)
1668
+ this._lastFormViewsByItem.set(itemKey, views);
1669
+ return views;
1670
+ } catch (err) {
1671
+ console.error(err);
1672
+ return [];
1673
+ } finally {
1674
+ this._formViewsInflight.delete(cacheKey);
1631
1675
  }
1632
- return views;
1633
- } catch (err) {
1634
- console.error(err);
1635
- return [];
1636
- }
1676
+ })();
1677
+ this._formViewsInflight.set(cacheKey, req);
1678
+ return req;
1637
1679
  },
1638
1680
  async resolveView(name, targetItem = this.currentItem) {
1639
1681
  const $item = targetItem || this.currentItem;
@@ -834,6 +834,8 @@ ODA({
834
834
  this._watchPresence();
835
835
  },
836
836
  detached() {
837
+ clearInterval(this._runPollTimer);
838
+ this._runPollTimer = null;
837
839
  this._unwatchPresence();
838
840
  this._unbindTask();
839
841
  this._voice?.disable();
@@ -1270,25 +1272,37 @@ ODA({
1270
1272
  this._unbindTask();
1271
1273
  this.taskItem = task || null;
1272
1274
  this._hasActiveRun = false;
1273
- if (!task)
1275
+ if (!task) {
1276
+ clearInterval(this._runPollTimer);
1277
+ this._runPollTimer = null;
1274
1278
  return;
1279
+ }
1280
+ globalThis.WORK?._subscribeWsPath?.(task.short || task.path);
1275
1281
  this._taskHandlers = {
1276
- 'changed': () => this._reloadTask(),
1282
+ 'changed': () => { this._lastWsEvent = Date.now(); this._reloadTask(); },
1277
1283
  'task.delta': e => {
1284
+ this._lastWsEvent = Date.now();
1278
1285
  this._hasActiveRun = true;
1279
1286
  this._onDelta(e.detail?.value);
1280
1287
  },
1281
1288
  'chat.start': () => {
1289
+ this._lastWsEvent = Date.now();
1282
1290
  this._hasActiveRun = true;
1291
+ if (this.status !== 'running')
1292
+ this.status = 'running';
1293
+ this._ensureRunPoll();
1283
1294
  },
1284
1295
  'task.state': e => {
1296
+ this._lastWsEvent = Date.now();
1285
1297
  const s = e.detail?.value?.status;
1286
1298
  if (s) {
1287
1299
  const prev = this.status;
1288
1300
  this.status = s;
1289
1301
  this._lastDelta = Date.now();
1290
- if (s === 'running')
1302
+ if (s === 'running') {
1291
1303
  this._hasActiveRun = true;
1304
+ this._ensureRunPoll();
1305
+ }
1292
1306
  else if (s === 'waiting' && (this._hasActiveRun || prev === 'running') && this._isOnScreen()) {
1293
1307
  this._hasActiveRun = false;
1294
1308
  _playTaskCompletionClick?.();
@@ -1296,6 +1310,7 @@ ODA({
1296
1310
  }
1297
1311
  },
1298
1312
  'chat.done': () => {
1313
+ this._lastWsEvent = Date.now();
1299
1314
  if (this._hasActiveRun && this._isOnScreen())
1300
1315
  _playTaskCompletionClick?.();
1301
1316
  this._hasActiveRun = false;
@@ -1305,10 +1320,34 @@ ODA({
1305
1320
  for (const [k, fn] of Object.entries(this._taskHandlers))
1306
1321
  task.listen?.(k, fn);
1307
1322
  this._reloadTask();
1323
+ this._ensureRunPoll();
1308
1324
  this._notifyPresence();
1309
1325
  },
1310
1326
 
1327
+ _ensureRunPoll() {
1328
+ if (this._runPollTimer)
1329
+ return;
1330
+ this._runPollTimer = setInterval(() => {
1331
+ if (!this.taskItem) {
1332
+ clearInterval(this._runPollTimer);
1333
+ this._runPollTimer = null;
1334
+ return;
1335
+ }
1336
+ const active = this.status === 'running' || Boolean(this.optimistic) || this.starting;
1337
+ if (!active) {
1338
+ clearInterval(this._runPollTimer);
1339
+ this._runPollTimer = null;
1340
+ return;
1341
+ }
1342
+ const sinceWs = Date.now() - (this._lastWsEvent || 0);
1343
+ if (sinceWs >= 1500)
1344
+ this._reloadTask();
1345
+ }, 1800);
1346
+ },
1347
+
1311
1348
  _unbindTask() {
1349
+ clearInterval(this._runPollTimer);
1350
+ this._runPollTimer = null;
1312
1351
  const t = this.taskItem;
1313
1352
  if (t && this._taskHandlers) {
1314
1353
  for (const [k, fn] of Object.entries(this._taskHandlers))
@@ -1359,8 +1398,11 @@ ODA({
1359
1398
  do {
1360
1399
  this._again = false;
1361
1400
  try {
1362
- const raw = await this.taskItem?.load();
1401
+ const stateRes = await this.taskItem?.fetch?.('state').catch(() => null);
1402
+ const isLiveObj = Boolean(stateRes && typeof stateRes === 'object' && 'body' in stateRes);
1403
+ const raw = isLiveObj ? stateRes.body : await this.taskItem?.load();
1363
1404
  const data = typeof raw === 'string' ? JSON.parse(raw || '{}') : (raw || {});
1405
+ const isRunning = isLiveObj ? Boolean(stateRes.running) : (data.status === 'running');
1364
1406
  const done = new Set((data.items || []).filter(i => i.type === 'assistant' && (i.durationMs || i.stopped || i.interrupted)).map(i => i.id));
1365
1407
  if (Object.keys(this.streams).some(id => done.has(id))) {
1366
1408
  const s = {};
@@ -1371,10 +1413,20 @@ ODA({
1371
1413
  this.streams = s;
1372
1414
  }
1373
1415
  this.data = data;
1416
+ const hasAssistant = (data.items || []).some(i => i.type === 'assistant');
1374
1417
  if (this.items.length)
1375
1418
  this.optimistic = null;
1376
- // Пока новая задача только что создана (items ещё пуст и висит optimistic), сохраняем статус 'running' до старта цикла на сервере
1377
- this.status = data.status || (this.optimistic ? 'running' : 'idle');
1419
+ // Пока задача активна на сервере или только что создана (нет ответа и < 15с), не сбрасываем в idle
1420
+ const recentStart = Boolean(data.created && (Date.now() - (+data.created || 0) < 15000) && !hasAssistant);
1421
+ this.status = isRunning
1422
+ ? (data.status === 'waiting' ? 'waiting' : 'running')
1423
+ : (data.status && data.status !== 'idle'
1424
+ ? data.status
1425
+ : ((this.optimistic || (recentStart && data.status !== 'error' && data.status !== 'stopped')) ? 'running' : (data.status || 'idle')));
1426
+ if (this.status === 'running') {
1427
+ this._hasActiveRun = true;
1428
+ this._ensureRunPoll();
1429
+ }
1378
1430
  this._lastDelta = Date.now();
1379
1431
  this._stick();
1380
1432
  this._voice?.onData({ ...data, status: this.status });