odant-work 1.0.102 → 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.
@@ -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');
@@ -278,16 +278,15 @@ export async function llmWithFallback(primaryPath, fallbackPaths = []) {
278
278
  }
279
279
  const CLASSIFIER_MODEL_RE = /(классификатор|classifier|rerank|0\.6b)/i;
280
280
 
281
- /** Первая доступная чат-модель в /MODULES/Модели (приоритетно default:true и основная LLM, не классификатор). */
282
- export async function findFirstAvailableChatModel() {
281
+ /** Список доступных чат-моделей (используется в настройках профиля и автовыборе по умолчанию). */
282
+ export async function listAvailableChatModels() {
283
283
  const root = await WORK.get_item('/MODULES/Модели').catch(() => null);
284
- let firstAny = '';
285
- let firstActive = '';
286
- let firstPrimary = '';
284
+ const out = [];
287
285
  for (const provider of (await root?.items) || []) {
288
286
  await provider?.init?.catch?.(() => {});
289
287
  if (provider?.DATA?.enabled === false)
290
288
  continue;
289
+ const provLabel = String(provider.DATA?.label || provider.label || provider.id || '');
291
290
  for (const m of (await provider.items) || []) {
292
291
  await m.init?.catch?.(() => {});
293
292
  if (m?.DATA?.enabled === false)
@@ -297,18 +296,31 @@ export async function findFirstAvailableChatModel() {
297
296
  continue;
298
297
  const active = (m.aiActive ?? m.DATA?.aiActive) !== false;
299
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
300
  const isPrimary = active && !CLASSIFIER_MODEL_RE.test(name);
301
- if (!firstAny)
302
- firstAny = m.path;
303
- if (active && !firstActive)
304
- firstActive = m.path;
305
- if (active && m.DATA?.default === true)
306
- return m.path;
307
- if (isPrimary && !firstPrimary)
308
- firstPrimary = m.path;
301
+ out.push({
302
+ path: m.path,
303
+ label: provLabel ? `${label} (${provLabel})` : label,
304
+ active,
305
+ default: m.DATA?.default === true,
306
+ isPrimary,
307
+ });
309
308
  }
310
309
  }
311
- return firstPrimary || firstActive || 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 || '';
312
324
  }
313
325
  /** Найти активную локальную модель в /MODULES/Модели/Local по capabilities (или id). */
314
326
  async function findActiveLocalModel({ caps = [], ids = [], method = '' } = {}) {
@@ -254,25 +254,49 @@ export function pushMessageOf(s, kind, text, detail = {}) {
254
254
  };
255
255
  }
256
256
 
257
+ /**
258
+ * Считать ли завершение хода «выполненной задачей» для отправки push/мессенджера:
259
+ * только если работа шла не быстрее PUSH_DONE_MIN_MS И были реальные действия
260
+ * (вызовы инструментов агента или фоновый/плановый запуск), чтобы обычный диалог
261
+ * вроде «привет» (даже при долгом прогреве локальной модели) не слал пуши.
262
+ */
263
+ export function shouldNotifyTaskDone(s, session, startItemCount = 0, now = Date.now()) {
264
+ const started = Number(s?.runStartedAt || s?.startedAt || 0);
265
+ if (!started || now - started < PUSH_DONE_MIN_MS)
266
+ return false;
267
+ if (session?.scheduled || session?.background || s?.body?.childAgent)
268
+ return true;
269
+ const from = Number.isFinite(s?.runStartItemCount) ? s.runStartItemCount : startItemCount;
270
+ const items = Array.isArray(s?.body?.items) ? s.body.items.slice(Math.max(0, from)) : [];
271
+ return items.some(it => Array.isArray(it?.tools) && it.tools.length > 0);
272
+ }
273
+
257
274
  /**
258
275
  * Push пользователю: задача ждёт его / закончила долгую работу / упала.
259
276
  * Показывать ли — решает service worker: если эта задача уже открыта на экране (в видимой
260
- * вкладке — в проводнике или отдельной страницей), уведомление не показывается; открытый
261
- * и сфокусированный проводник тоже подавляет push.
277
+ * вкладке — в проводнике или отдельной страницей), уведомление не показывается.
262
278
  * 9.7: ожидающее разрешение — с кнопками «Разрешить/Отклонить» прямо в уведомлении.
263
279
  */
264
280
  async function pushNotify(s, session, kind, text, detail = {}) {
265
281
  const uid = session?.uid;
266
282
  if (!uid || process.env.WORK_TEST)
267
283
  return;
284
+ let visibleOnScreen = false;
268
285
  try {
269
- const { sendPushNotification, removePushSubscription } = await import('../../host/push.js');
270
- await sendPushNotification({ receivers: [uid], message: pushMessageOf(s, kind, text, detail) }, removePushSubscription);
286
+ const { isTaskVisibleToUser } = await import('../../host/websocket.js');
287
+ visibleOnScreen = isTaskVisibleToUser(uid, s.file?.path);
271
288
  }
272
- catch (e) {
273
- console.warn('[task push]', e.message);
289
+ catch { /* ignore */ }
290
+ if (!visibleOnScreen) {
291
+ try {
292
+ const { sendPushNotification, removePushSubscription } = await import('../../host/push.js');
293
+ await sendPushNotification({ receivers: [uid], message: pushMessageOf(s, kind, text, detail) }, removePushSubscription);
294
+ }
295
+ catch (e) {
296
+ console.warn('[task push]', e.message);
297
+ }
274
298
  }
275
- if (!(session?.scheduled && kind === 'done')) {
299
+ if (!(session?.scheduled && kind === 'done') && !visibleOnScreen) {
276
300
  try {
277
301
  const { notifyTaskEvent } = await import('../notify/index.js');
278
302
  await notifyTaskEvent({ file: s.file, uid, kind, text, detail });
@@ -502,6 +526,10 @@ function start(s, session, file, licenseOpts = {}) {
502
526
  s.movedAway = false;
503
527
  s.controller = new AbortController();
504
528
  s.startedAt = Date.now();
529
+ if (!s.runStartedAt) {
530
+ s.runStartedAt = s.startedAt;
531
+ s.runStartItemCount = Array.isArray(body.items) ? body.items.length : 0;
532
+ }
505
533
  setStatus(s, session, 'running');
506
534
  send(s, session, { type: 'chat.start' });
507
535
  const host = makeHost(s, session);
@@ -605,8 +633,10 @@ function start(s, session, file, licenseOpts = {}) {
605
633
  await publishTaskResults(file, session).catch(e => console.warn('[task publish]', e?.message || e));
606
634
  if (!aborted && body.status === 'error')
607
635
  pushNotify(s, session, 'error', [...body.items].reverse().find(i => i.type === 'error' || i.error)?.content);
608
- else if (!aborted && body.status === 'idle' && Date.now() - s.startedAt >= PUSH_DONE_MIN_MS)
636
+ else if (!aborted && body.status === 'idle' && shouldNotifyTaskDone(s, session))
609
637
  pushNotify(s, session, 'done', lastAnswer(body));
638
+ s.runStartedAt = 0;
639
+ s.runStartItemCount = undefined;
610
640
  })();
611
641
  return s.running;
612
642
  }
@@ -49,6 +49,49 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
49
49
  border-radius: 8px;
50
50
  padding: 6px 8px;
51
51
  }
52
+ .settings-card {
53
+ gap: 10px;
54
+ border: 1px solid var(--border-color, #cbd5e1);
55
+ border-radius: 10px;
56
+ padding: 12px 14px;
57
+ background: var(--content-background, #fff);
58
+ box-sizing: border-box;
59
+ }
60
+ .settings-title {
61
+ font-weight: 600;
62
+ font-size: 15px;
63
+ }
64
+ .settings-field {
65
+ gap: 4px;
66
+ font-size: 14px;
67
+ }
68
+ .settings-field select {
69
+ border: 1px solid gray;
70
+ padding: 8px;
71
+ border-radius: 8px;
72
+ font-size: 14px;
73
+ width: 100%;
74
+ box-sizing: border-box;
75
+ background: inherit;
76
+ color: inherit;
77
+ }
78
+ .settings-toggle {
79
+ gap: 8px;
80
+ align-items: center;
81
+ font-size: 14px;
82
+ cursor: pointer;
83
+ }
84
+ .settings-toggle input {
85
+ width: 18px;
86
+ height: 18px;
87
+ margin: 0;
88
+ flex-shrink: 0;
89
+ cursor: pointer;
90
+ }
91
+ .settings-hint {
92
+ font-size: 12px;
93
+ color: #10b981;
94
+ }
52
95
  </style>
53
96
  <div no-flex vertical class="profile-wrap">
54
97
  <div ~if="pendingInvite?.valid" style="padding:10px 12px;border-radius:8px;border:1px solid #10b981;background:rgba(16,185,129,0.1);font-size:small;line-height:1.4;text-align:center;">
@@ -70,6 +113,21 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
70
113
  </div>
71
114
  <div flex style="text-align: center;" ~html="state.legend"></div>
72
115
  <div flex style="text-align: center;" :error="!!error" @tap="fill_code">{{text}}</div>
116
+ <div class="settings-card" vertical ~if="!isOtherUser && isLogin">
117
+ <div class="settings-title">Личные настройки</div>
118
+ <label class="settings-field" vertical>
119
+ <span>Главная модель ИИ</span>
120
+ <select :value="settingModel" @change="_onSettingModelChange($event)">
121
+ <option value="">По умолчанию системы</option>
122
+ <option ~for="m in chatModels" :value="m.path" :selected="m.path === settingModel">{{m.label}}</option>
123
+ </select>
124
+ </label>
125
+ <label class="settings-toggle" horizontal>
126
+ <input type="checkbox" :checked="settingChatSound" @change="_onSettingChatSoundChange($event)">
127
+ <span>Звуковой щелчок по завершении ответа в открытом чате</span>
128
+ </label>
129
+ <div class="settings-hint" ~if="settingsStatus">{{settingsStatus}}</div>
130
+ </div>
73
131
  </div>
74
132
  `,
75
133
  $item: {
@@ -81,6 +139,10 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
81
139
  error: null,
82
140
  text: '',
83
141
  isLoggingIn: false,
142
+ chatModels: [],
143
+ settingModel: '',
144
+ settingChatSound: true,
145
+ settingsStatus: '',
84
146
  get isOtherUser() {
85
147
  return Boolean(this.$item?.id && WORK?.uid && this.$item.id !== WORK.uid);
86
148
  },
@@ -206,6 +268,7 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
206
268
  attached() {
207
269
  this._syncFromItem(this.$item);
208
270
  this._loadPendingInvite();
271
+ this._loadSettingsAndModels();
209
272
  this._onAuthState = () => {
210
273
  if (this.isOtherUser)
211
274
  return;
@@ -217,18 +280,84 @@ ODA({ is: 'user-profile', imports: 'oda//otp.js',
217
280
  else if (this.isLogin) {
218
281
  this.error = null;
219
282
  this.text = '';
283
+ this._loadSettingsAndModels();
220
284
  }
221
285
  this.isLogin = undefined;
222
286
  this.render?.();
223
287
  };
288
+ this._onUserSettings = () => {
289
+ if (this.isOtherUser)
290
+ return;
291
+ this._applyLocalUserSettings();
292
+ };
224
293
  WORK.authEvents?.addEventListener?.('auth', this._onAuthState);
225
294
  WORK.authEvents?.addEventListener?.('login-state', this._onAuthState);
295
+ WORK.authEvents?.addEventListener?.('user-settings', this._onUserSettings);
226
296
  },
227
297
  detached() {
228
298
  if (this._onAuthState) {
229
299
  WORK.authEvents?.removeEventListener?.('auth', this._onAuthState);
230
300
  WORK.authEvents?.removeEventListener?.('login-state', this._onAuthState);
231
301
  }
302
+ if (this._onUserSettings) {
303
+ WORK.authEvents?.removeEventListener?.('user-settings', this._onUserSettings);
304
+ }
305
+ },
306
+ _applyLocalUserSettings() {
307
+ const s = WORK.userSettings || this.$item?.DATA?.settings || {};
308
+ this.settingModel = typeof s.aiModel === 'string' ? s.aiModel : '';
309
+ this.settingChatSound = s.chatSound !== false;
310
+ },
311
+ async _loadSettingsAndModels() {
312
+ if (this.isOtherUser || !this.isLogin)
313
+ return;
314
+ this._applyLocalUserSettings();
315
+ try {
316
+ if (typeof WORK.loadUserSettings === 'function') {
317
+ await WORK.loadUserSettings();
318
+ this._applyLocalUserSettings();
319
+ }
320
+ if (typeof WORK.fetch === 'function') {
321
+ const list = await WORK.fetch('/', 'agent_chat_models').catch(() => []);
322
+ if (Array.isArray(list))
323
+ this.chatModels = list;
324
+ }
325
+ }
326
+ catch { /* ignore */ }
327
+ },
328
+ async _saveProfileSetting(patch) {
329
+ this.settingsStatus = '';
330
+ try {
331
+ if (typeof WORK.saveUserSettings === 'function')
332
+ await WORK.saveUserSettings(patch);
333
+ if (patch && 'aiModel' in patch && patch.aiModel && typeof BroadcastChannel !== 'undefined') {
334
+ try { new BroadcastChannel('work-user-ai-model').postMessage({ model: patch.aiModel }); } catch {}
335
+ }
336
+ this._applyLocalUserSettings();
337
+ this.settingsStatus = 'Сохранено';
338
+ clearTimeout(this._settingsTimer);
339
+ this._settingsTimer = setTimeout(() => { this.settingsStatus = ''; }, 2000);
340
+ }
341
+ catch (err) {
342
+ this.settingsStatus = err?.message || 'Ошибка сохранения';
343
+ }
344
+ },
345
+ _onSettingModelChange(e) {
346
+ const val = String(e?.target?.value || '');
347
+ this.settingModel = val;
348
+ if (!val && typeof localStorage !== 'undefined') {
349
+ try {
350
+ const uid = WORK.uid || this.$item?.id || 'default';
351
+ localStorage.removeItem(`work.user.ai:${uid}:model`);
352
+ localStorage.removeItem('work.user.ai:default:model');
353
+ } catch {}
354
+ }
355
+ this._saveProfileSetting({ aiModel: val });
356
+ },
357
+ _onSettingChatSoundChange(e) {
358
+ const checked = Boolean(e?.target?.checked);
359
+ this.settingChatSound = checked;
360
+ this._saveProfileSetting({ chatSound: checked });
232
361
  },
233
362
  async _syncFromItem(item) {
234
363
  if (item?.id && WORK?.uid && item.id !== WORK.uid) {
@@ -65,7 +65,8 @@ export const MEMBERS = Object.freeze({
65
65
  types: L.READ, system_types: L.READ, allowed_child_types: L.READ,
66
66
  // вошедший
67
67
  proxy: L.AUTH, node_grants: L.AUTH, mcp_token_create: L.AUTH, mcp_token_list: L.AUTH, mcp_token_revoke: L.AUTH,
68
- store_push_subscription: L.AUTH, remove_push_subscription: L.AUTH, agent_default_model: L.AUTH,
68
+ store_push_subscription: L.AUTH, remove_push_subscription: L.AUTH, agent_default_model: L.AUTH, agent_chat_models: L.AUTH,
69
+ user_settings_get: L.AUTH, user_settings_save: L.AUTH,
69
70
  // сеть WORK
70
71
  network_graph: L.READ, remote: L.WRITE, node_add: L.BOSS, node_refresh: L.BOSS,
71
72
  // запись (точное право — внутри метода)
@@ -206,6 +206,12 @@ export const classFeedMethods = {
206
206
  return listNodeRules(this, params);
207
207
  },
208
208
 
209
+ /** Список доступных чат-моделей для профиля и выбора модели по умолчанию. */
210
+ async agent_chat_models() {
211
+ const { listAvailableChatModels } = await import('../../modules/agent/index.js');
212
+ return listAvailableChatModels();
213
+ },
214
+
209
215
  /** Безопасный выбор модели по умолчанию для чата нового пользователя. */
210
216
  async agent_default_model(params = {}) {
211
217
  const { loadConfig } = await import('../../modules/agent/resources.js');
@@ -284,6 +284,41 @@ export class $server extends $class {
284
284
  throw new Error('push: требуется вход');
285
285
  }
286
286
 
287
+ async _resolveSelfUserItem(params = {}) {
288
+ const uid = $class.resolveUid(params);
289
+ if (!uid)
290
+ throw new Error('Требуется вход');
291
+ const usersRoot = await this.$users;
292
+ const list = await usersRoot?.items;
293
+ const found = Array.isArray(list) ? list.find(u => u?.id === uid) : null;
294
+ return found || await usersRoot?.get_item?.(uid).catch(() => null) || null;
295
+ }
296
+
297
+ async user_settings_get(params = {}) {
298
+ const uItem = await this._resolveSelfUserItem(params);
299
+ if (!uItem)
300
+ return { chatSound: true, aiModel: '' };
301
+ await uItem.init;
302
+ const raw = uItem.DATA?.settings;
303
+ return {
304
+ chatSound: raw?.chatSound !== false,
305
+ aiModel: typeof raw?.aiModel === 'string' ? raw.aiModel : '',
306
+ ...(raw && typeof raw === 'object' ? raw : {}),
307
+ ...(raw?.chatSound === undefined ? { chatSound: true } : {}),
308
+ };
309
+ }
310
+
311
+ async user_settings_save(params = {}) {
312
+ const uItem = await this._resolveSelfUserItem(params);
313
+ if (!uItem || typeof uItem.writeOwnSettings !== 'function')
314
+ throw new Error('Профиль пользователя не найден');
315
+ const patch = (params.post && typeof params.post === 'object' && !Array.isArray(params.post)) ? params.post : {};
316
+ const nextSettings = await uItem.writeOwnSettings(patch);
317
+ const { broadcastUserSettings } = await import('../host/websocket.js');
318
+ broadcastUserSettings(uItem.id, nextSettings);
319
+ return nextSettings;
320
+ }
321
+
287
322
  get pageHTML() {
288
323
  return fs.readFileSync('./sources/page.html', {encoding: 'utf-8'});
289
324
  }
@@ -692,6 +727,13 @@ export class $server extends $class {
692
727
  throw new Error('Доступ запрещён');
693
728
  if (!DEV_MODE)
694
729
  throw new Error('Сервер уже работает в обычном режиме');
730
+ if (process.env.WORK_WATCHDOG === '1') {
731
+ const reqFile = path.join(this.dir || process.cwd(), '#system', 'restart-request.json');
732
+ fs.mkdirSync(path.dirname(reqFile), { recursive: true });
733
+ fs.writeFileSync(reqFile, JSON.stringify({ env: { WORK_DEV: 'false' }, reason: 'restart_normal', time: Date.now() }), 'utf8');
734
+ setTimeout(() => process.exit(75), 1000).unref?.();
735
+ return true;
736
+ }
695
737
  const { spawn } = await import('node:child_process');
696
738
  const env = { ...process.env, WORK_DEV: 'false' };
697
739
  // отладочные флаги не должны пережить перезапуск
@@ -794,13 +836,20 @@ export class $server extends $class {
794
836
  }
795
837
 
796
838
  async _scheduleProcessRestart({ cwd = process.cwd(), entryArgs, delayMs: rawDelay } = {}) {
839
+ const delayMs = Math.max(1500, Math.min(10000, Number(rawDelay) || 2500));
840
+ if (process.env.WORK_WATCHDOG === '1') {
841
+ const reqFile = path.join(cwd, '#system', 'restart-request.json');
842
+ fs.mkdirSync(path.dirname(reqFile), { recursive: true });
843
+ fs.writeFileSync(reqFile, JSON.stringify({ reason: 'server_restart', time: Date.now() }), 'utf8');
844
+ setTimeout(() => process.exit(75), delayMs).unref?.();
845
+ return delayMs;
846
+ }
797
847
  const { spawn } = await import('node:child_process');
798
848
  const env = { ...process.env };
799
849
  delete env.NODE_OPTIONS;
800
850
  const args = Array.isArray(entryArgs) && entryArgs.length
801
851
  ? entryArgs
802
852
  : (process.argv.slice(1).length ? process.argv.slice(1) : ['run.mjs']);
803
- const delayMs = Math.max(1500, Math.min(10000, Number(rawDelay) || 2500));
804
853
  const helper = `
805
854
  const fs = await import('node:fs');
806
855
  const path = await import('node:path');