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.
@@ -121,6 +121,13 @@ export function normalizeModelPath(modelPath) {
121
121
  }
122
122
 
123
123
  export function getUserPreferredModel() {
124
+ const serverModel = normalizeModelPath(
125
+ globalThis.WORK?.userSettings?.aiModel
126
+ || globalThis.WORK?.USER?.DATA?.settings?.aiModel
127
+ || ''
128
+ );
129
+ if (serverModel && !NON_CHAT_MODEL_RE.test(serverModel))
130
+ return serverModel;
124
131
  if (typeof localStorage === 'undefined')
125
132
  return '';
126
133
  try {
@@ -137,19 +144,23 @@ export function getUserPreferredModel() {
137
144
  }
138
145
  }
139
146
 
140
- export function setUserPreferredModel(modelPath) {
147
+ export function setUserPreferredModel(modelPath, { syncServer = true } = {}) {
141
148
  const clean = normalizeModelPath(modelPath);
142
- if (!clean || typeof localStorage === 'undefined')
143
- return;
144
- if (NON_CHAT_MODEL_RE.test(clean))
149
+ if (!clean || NON_CHAT_MODEL_RE.test(clean))
145
150
  return;
146
151
  try {
147
- localStorage.setItem(userAiStorageKey('model'), clean);
148
- localStorage.setItem('work.user.ai:default:model', clean);
152
+ if (typeof localStorage !== 'undefined') {
153
+ localStorage.setItem(userAiStorageKey('model'), clean);
154
+ localStorage.setItem('work.user.ai:default:model', clean);
155
+ }
149
156
  if (typeof BroadcastChannel !== 'undefined')
150
157
  new BroadcastChannel('work-user-ai-model').postMessage({ model: clean });
151
158
  }
152
159
  catch { /* ignore */ }
160
+ if (syncServer && globalThis.WORK?.uid && typeof globalThis.WORK?.saveUserSettings === 'function') {
161
+ if (normalizeModelPath(globalThis.WORK?.userSettings?.aiModel || '') !== clean)
162
+ globalThis.WORK.saveUserSettings({ aiModel: clean }).catch?.(() => {});
163
+ }
153
164
  }
154
165
 
155
166
  /**
@@ -71,10 +71,25 @@ ODA({
71
71
  this._modelBc = new BroadcastChannel('work-user-ai-model');
72
72
  this._modelBc.onmessage = ev => {
73
73
  const m = ev?.data?.model;
74
- if (m && m !== this.model) this.model = m;
74
+ if (m && m !== this.model) {
75
+ this._settingModelFromSync = true;
76
+ this.model = m;
77
+ this._settingModelFromSync = false;
78
+ }
75
79
  };
76
80
  } catch {/* ignore */}
77
81
  }
82
+ if (!this._onUserSettings && globalThis.WORK?.authEvents) {
83
+ this._onUserSettings = ev => {
84
+ const m = ev?.detail?.aiModel;
85
+ if (m && m !== this.model) {
86
+ this._settingModelFromSync = true;
87
+ this.model = m;
88
+ this._settingModelFromSync = false;
89
+ }
90
+ };
91
+ globalThis.WORK.authEvents.addEventListener('user-settings', this._onUserSettings);
92
+ }
78
93
  await this._hydrateModel();
79
94
  if (this._initialNav) {
80
95
  const nav = this._initialNav;
@@ -107,6 +122,10 @@ ODA({
107
122
  this._modelBc?.close?.();
108
123
  this._modelBc = null;
109
124
  } catch {/* ignore */}
125
+ if (this._onUserSettings) {
126
+ globalThis.WORK?.authEvents?.removeEventListener?.('user-settings', this._onUserSettings);
127
+ this._onUserSettings = null;
128
+ }
110
129
  },
111
130
  last: {
112
131
  $def: 0,
@@ -115,13 +134,16 @@ ODA({
115
134
  model: {
116
135
  $def: '',
117
136
  set(n) {
118
- if (n) setUserPreferredModel(n);
137
+ if (n) setUserPreferredModel(n, { syncServer: !this._settingModelFromSync });
119
138
  }
120
139
  },
121
140
  get $saveKey() {
122
141
  return this.$item?.short;
123
142
  },
124
143
  async _hydrateModel() {
144
+ if (WORK?.uid && !WORK._userSettingsLoaded && typeof WORK.loadUserSettings === 'function') {
145
+ await WORK.loadUserSettings().catch(() => {});
146
+ }
125
147
  let userModel = getUserPreferredModel();
126
148
  if (userModel && typeof WORK?.get_item === 'function') {
127
149
  const existing = await WORK.get_item(userModel).catch(() => null);
@@ -12,7 +12,7 @@ import './ui/dock.js';
12
12
  import './ui/voice-ui.js';
13
13
  import { VoiceController } from './ui/voice.js';
14
14
  import { collectDocs, computeStats, stableDocs, activityOf, taskFiles, computerUse, realPathOfSnapshot } from './ui/docs.js';
15
- import { pathOfWorkHref, workHref } from './ui/util.js';
15
+ import { pathOfWorkHref, workHref, playTaskCompletionClick } from './ui/util.js';
16
16
 
17
17
  /**
18
18
  * Клик по WORK-ссылке в markdown (событие md-link от oda-markdown-viewer):
@@ -146,19 +146,33 @@ export default {
146
146
  this.computerChecked = false;
147
147
  }
148
148
  this._bound = n || null;
149
+ this._hasActiveRun = false;
149
150
  if (!n) return;
150
151
  this._h = {
151
152
  'changed': () => this._reload(),
152
153
  'task.delta': e => this._onDelta(e.detail?.value),
154
+ 'chat.start': () => {
155
+ this._hasActiveRun = true;
156
+ },
153
157
  'task.state': e => {
154
158
  const s = e.detail?.value?.status;
155
159
  if (s) {
160
+ const prevStatus = this.status;
156
161
  this.status = s;
157
162
  this._lastDelta = Date.now();
163
+ if (s === 'running') this._hasActiveRun = true;
164
+ else if (s === 'waiting' && (this._hasActiveRun || prevStatus === 'running') && this._isOnScreen()) {
165
+ this._hasActiveRun = false;
166
+ playTaskCompletionClick();
167
+ }
158
168
  }
159
169
  },
160
170
  'task.moved': e => this._handleTaskMoved(e.detail?.value || e.detail),
161
- 'chat.done': () => this._reload()
171
+ 'chat.done': () => {
172
+ if (this._hasActiveRun && this._isOnScreen()) playTaskCompletionClick();
173
+ this._hasActiveRun = false;
174
+ this._reload();
175
+ }
162
176
  };
163
177
  for (const [k, fn] of Object.entries(this._h)) n.listen(k, fn);
164
178
  this._reload();
@@ -183,7 +197,7 @@ export default {
183
197
  */
184
198
  _watchPresence() {
185
199
  this._presenceIO ??= new IntersectionObserver(entries => {
186
- if (entries.some(e => e.isIntersecting)) this._notifyPresence();
200
+ this._notifyPresence(entries.some(e => e.isIntersecting));
187
201
  });
188
202
  this._presenceIO.observe(this);
189
203
  this._presenceOnVis = () => this._notifyPresence();
@@ -192,10 +206,11 @@ export default {
192
206
  // (в чате адрес не содержит путь задачи — сравнивать URL недостаточно)
193
207
  this._presenceOnSw = e => {
194
208
  const msg = e?.data;
209
+ const port = e?.ports?.[0] || msg?.port;
195
210
  const mine = this._bound?.path || this.$item?.path;
196
- if (msg?.type !== 'work:is-task-visible' || !msg.port || !mine || msg.path !== mine) return;
211
+ if (msg?.type !== 'work:is-task-visible' || !port || !mine || msg.path !== mine) return;
197
212
  if (this._isOnScreen()) try {
198
- msg.port.postMessage({
213
+ port.postMessage({
199
214
  visible: true
200
215
  });
201
216
  } catch {/* порт закрыт */}
@@ -204,6 +219,8 @@ export default {
204
219
  this.async(() => this._notifyPresence(), 150);
205
220
  },
206
221
  _unwatchPresence() {
222
+ const p = this._bound?.path || this.$item?.path;
223
+ if (p) globalThis.WORK?.setTaskPresence?.(p, false);
207
224
  this._presenceIO?.disconnect();
208
225
  this._presenceIO = null;
209
226
  if (this._presenceOnVis) document.removeEventListener('visibilitychange', this._presenceOnVis);
@@ -220,9 +237,12 @@ export default {
220
237
  h = window.innerHeight || 0;
221
238
  return r.bottom > 0 && r.right > 0 && r.top < h && r.left < w;
222
239
  },
223
- _notifyPresence() {
240
+ _notifyPresence(intersecting) {
224
241
  const path = this._bound?.path || this.$item?.path;
225
- if (!path || document.visibilityState !== 'visible') return;
242
+ if (!path) return;
243
+ const visible = intersecting === false ? false : this._isOnScreen();
244
+ globalThis.WORK?.setTaskPresence?.(path, visible);
245
+ if (!visible) return;
226
246
  try {
227
247
  navigator.serviceWorker?.ready?.then(reg => reg.active?.postMessage({
228
248
  type: 'work:task-visible',
@@ -496,6 +516,7 @@ export default {
496
516
  }
497
517
  };
498
518
  this._lastDelta = Date.now();
519
+ this._hasActiveRun = true;
499
520
  if (this.status !== 'running') this.status = 'running';
500
521
  if (/^(?:computer_|sandbox_)/.test(String(d.name || '')) && d.name !== 'computer_destroy') this._openMonitorOnce();
501
522
  this._stick();
@@ -544,6 +565,7 @@ export default {
544
565
  const prevComputerUsed = Boolean(this._cu?.used);
545
566
  this.data = data;
546
567
  this.status = data.status || 'idle';
568
+ if (this.status === 'running') this._hasActiveRun = true;
547
569
  this._lastDelta = Date.now();
548
570
  this._noticeDocs(before);
549
571
  if (this.computer.used) {
@@ -672,6 +694,7 @@ export default {
672
694
  };
673
695
  this.pinned = true;
674
696
  this.status = 'running';
697
+ this._hasActiveRun = true;
675
698
  this._stick();
676
699
  },
677
700
  toast(text) {
@@ -689,7 +712,7 @@ export default {
689
712
  try {
690
713
  navigator.serviceWorker.controller.postMessage({
691
714
  type: 'work:task-visible',
692
- task: this.$item.path
715
+ path: this.$item.path
693
716
  });
694
717
  } catch {/* ignore */}
695
718
  }
@@ -546,3 +546,35 @@ export function resultMarkdown(t) {
546
546
  return r;
547
547
  return '```\n' + r.replace(/```/g, '``\u200b`') + '\n```';
548
548
  }
549
+
550
+ let _clickAudioCtx = null;
551
+ /** Тихий короткий звуковой щелчок по завершении ответа или переходе в ожидание при открытом чате. */
552
+ export function playTaskCompletionClick() {
553
+ try {
554
+ if (globalThis.WORK?.userSettings?.chatSound === false)
555
+ return false;
556
+ const AC = globalThis.AudioContext || globalThis.webkitAudioContext;
557
+ if (!AC)
558
+ return false;
559
+ const ctx = _clickAudioCtx ??= new AC();
560
+ if (ctx.state === 'suspended')
561
+ ctx.resume?.().catch(() => {});
562
+ const now = ctx.currentTime;
563
+ const osc = ctx.createOscillator();
564
+ const gain = ctx.createGain();
565
+ osc.type = 'triangle';
566
+ osc.frequency.setValueAtTime(920, now);
567
+ osc.frequency.exponentialRampToValueAtTime(420, now + 0.032);
568
+ gain.gain.setValueAtTime(0.001, now);
569
+ gain.gain.linearRampToValueAtTime(0.055, now + 0.004);
570
+ gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.038);
571
+ osc.connect(gain);
572
+ gain.connect(ctx.destination);
573
+ osc.start(now);
574
+ osc.stop(now + 0.042);
575
+ return true;
576
+ }
577
+ catch {
578
+ return false;
579
+ }
580
+ }
@@ -18,6 +18,7 @@ let _pathOfWorkHref = null;
18
18
  let _resolveClientLocation = null;
19
19
  let _dotStateOfTask = null;
20
20
  let _VoiceController = null;
21
+ let _playTaskCompletionClick = null;
21
22
 
22
23
  function ensureConsultantUI() {
23
24
  return _uiLoaded ??= Promise.all([
@@ -28,6 +29,7 @@ function ensureConsultantUI() {
28
29
  import('/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/util.js').then(m => {
29
30
  _pathOfWorkHref = m.pathOfWorkHref;
30
31
  _resolveClientLocation = m.resolveClientLocation;
32
+ _playTaskCompletionClick = m.playTaskCompletionClick;
31
33
  _resolveClientLocation?.(0)?.catch?.(() => {});
32
34
  }),
33
35
  import('/$server/$folder/lib/dot/dot.js'),
@@ -773,8 +775,10 @@ ODA({
773
775
  if (col)
774
776
  this._ro.observe(col);
775
777
  }, 50);
778
+ this._watchPresence();
776
779
  },
777
780
  detached() {
781
+ this._unwatchPresence();
778
782
  this._unbindTask();
779
783
  this._voice?.disable();
780
784
  this.voiceOn = false;
@@ -1152,26 +1156,99 @@ ODA({
1152
1156
  }
1153
1157
  },
1154
1158
 
1159
+ _watchPresence() {
1160
+ this._presenceIO ??= new IntersectionObserver(entries => {
1161
+ this._notifyPresence(entries.some(e => e.isIntersecting));
1162
+ });
1163
+ this._presenceIO.observe(this);
1164
+ this._presenceOnVis = () => this._notifyPresence();
1165
+ document.addEventListener('visibilitychange', this._presenceOnVis);
1166
+ this._presenceOnSw = e => {
1167
+ const msg = e?.data;
1168
+ const port = e?.ports?.[0] || msg?.port;
1169
+ const mine = this.taskItem?.path;
1170
+ if (msg?.type !== 'work:is-task-visible' || !port || !mine || msg.path !== mine)
1171
+ return;
1172
+ if (this._isOnScreen()) {
1173
+ try { port.postMessage({ visible: true }); } catch { /* ignore */ }
1174
+ }
1175
+ };
1176
+ navigator.serviceWorker?.addEventListener?.('message', this._presenceOnSw);
1177
+ this.async(() => this._notifyPresence(), 150);
1178
+ },
1179
+ _unwatchPresence() {
1180
+ const p = this.taskItem?.path;
1181
+ if (p) globalThis.WORK?.setTaskPresence?.(p, false);
1182
+ this._presenceIO?.disconnect();
1183
+ this._presenceIO = null;
1184
+ if (this._presenceOnVis) document.removeEventListener('visibilitychange', this._presenceOnVis);
1185
+ this._presenceOnVis = null;
1186
+ if (this._presenceOnSw) navigator.serviceWorker?.removeEventListener?.('message', this._presenceOnSw);
1187
+ this._presenceOnSw = null;
1188
+ },
1189
+ _isOnScreen() {
1190
+ if (document.visibilityState !== 'visible' || !this.isConnected)
1191
+ return false;
1192
+ const r = this.getBoundingClientRect?.();
1193
+ if (!r || r.width < 2 || r.height < 2)
1194
+ return false;
1195
+ const w = window.innerWidth || 0;
1196
+ const h = window.innerHeight || 0;
1197
+ return r.bottom > 0 && r.right > 0 && r.top < h && r.left < w;
1198
+ },
1199
+ _notifyPresence(intersecting) {
1200
+ const path = this.taskItem?.path;
1201
+ if (!path) return;
1202
+ const visible = intersecting === false ? false : this._isOnScreen();
1203
+ globalThis.WORK?.setTaskPresence?.(path, visible);
1204
+ if (!visible) return;
1205
+ try {
1206
+ navigator.serviceWorker?.ready?.then(reg => reg.active?.postMessage({ type: 'work:task-visible', path })).catch(() => {});
1207
+ } catch { /* ignore */ }
1208
+ },
1155
1209
  _bindTask(task) {
1210
+ const prevPath = this.taskItem?.path;
1211
+ if (prevPath && prevPath !== task?.path)
1212
+ globalThis.WORK?.setTaskPresence?.(prevPath, false);
1156
1213
  this._unbindTask();
1157
1214
  this.taskItem = task || null;
1215
+ this._hasActiveRun = false;
1158
1216
  if (!task)
1159
1217
  return;
1160
1218
  this._taskHandlers = {
1161
1219
  'changed': () => this._reloadTask(),
1162
- 'task.delta': e => this._onDelta(e.detail?.value),
1220
+ 'task.delta': e => {
1221
+ this._hasActiveRun = true;
1222
+ this._onDelta(e.detail?.value);
1223
+ },
1224
+ 'chat.start': () => {
1225
+ this._hasActiveRun = true;
1226
+ },
1163
1227
  'task.state': e => {
1164
1228
  const s = e.detail?.value?.status;
1165
1229
  if (s) {
1230
+ const prev = this.status;
1166
1231
  this.status = s;
1167
1232
  this._lastDelta = Date.now();
1233
+ if (s === 'running')
1234
+ this._hasActiveRun = true;
1235
+ else if (s === 'waiting' && (this._hasActiveRun || prev === 'running') && this._isOnScreen()) {
1236
+ this._hasActiveRun = false;
1237
+ _playTaskCompletionClick?.();
1238
+ }
1168
1239
  }
1169
1240
  },
1170
- 'chat.done': () => this._reloadTask(),
1241
+ 'chat.done': () => {
1242
+ if (this._hasActiveRun && this._isOnScreen())
1243
+ _playTaskCompletionClick?.();
1244
+ this._hasActiveRun = false;
1245
+ this._reloadTask();
1246
+ },
1171
1247
  };
1172
1248
  for (const [k, fn] of Object.entries(this._taskHandlers))
1173
1249
  task.listen?.(k, fn);
1174
1250
  this._reloadTask();
1251
+ this._notifyPresence();
1175
1252
  },
1176
1253
 
1177
1254
  _unbindTask() {
@@ -1286,7 +1363,7 @@ ODA({
1286
1363
  this.toast(res.error || 'Не удалось отправить ответ');
1287
1364
  else if (this.taskItem?.path && navigator.serviceWorker?.controller) {
1288
1365
  try {
1289
- navigator.serviceWorker.controller.postMessage({ type: 'work:task-visible', task: this.taskItem.path });
1366
+ navigator.serviceWorker.controller.postMessage({ type: 'work:task-visible', path: this.taskItem.path });
1290
1367
  }
1291
1368
  catch { /* ignore */ }
1292
1369
  }
@@ -892,7 +892,7 @@ ODA({is: 'oda-tree-node',
892
892
  },
893
893
  get isToggleableUser() {
894
894
  const it = this.$item;
895
- if (!it || isLinkNode(it) || it.type !== '$user')
895
+ if (!it || isLinkNode(it) || it.type !== '$user' || it.DATA?.usersContainer === true)
896
896
  return false;
897
897
  if (globalThis.WORK?.uid && it.id === globalThis.WORK.uid)
898
898
  return false;
@@ -900,7 +900,7 @@ ODA({is: 'oda-tree-node',
900
900
  return Boolean(globalThis.WORK?.DEV_MODE || tree?._isRootBoss);
901
901
  },
902
902
  get isModuleBlocked() {
903
- if (!this.isModule && this.$item?.type !== '$user')
903
+ if (!this.isModule && (this.$item?.type !== '$user' || this.$item?.DATA?.usersContainer === true))
904
904
  return false;
905
905
  this.$item.__version;
906
906
  if (this.$item?.type === '$user')
package/autostart.bat ADDED
@@ -0,0 +1,28 @@
1
+ @echo off
2
+ setlocal
3
+ set "WORK_DIR=%~dp0"
4
+ if "%WORK_DIR:~-1%"=="\" set "WORK_DIR=%WORK_DIR:~0,-1%"
5
+ pushd "%WORK_DIR%" >nul
6
+
7
+ where node >nul 2>nul
8
+ if errorlevel 1 (
9
+ echo [WORK] Node.js не найден в PATH.
10
+ popd >nul
11
+ exit /b 1
12
+ )
13
+
14
+ set "AS_SCRIPT=%WORK_DIR%\scripts\autostart.mjs"
15
+ if not exist "%AS_SCRIPT%" set "AS_SCRIPT=%WORK_DIR%\node_modules\odant-work\scripts\autostart.mjs"
16
+ if not exist "%AS_SCRIPT%" (
17
+ echo [WORK] Не найден scripts\autostart.mjs
18
+ popd >nul
19
+ exit /b 1
20
+ )
21
+
22
+ set "ACTION=%~1"
23
+ if "%ACTION%"=="" set "ACTION=install"
24
+
25
+ node "%AS_SCRIPT%" "%ACTION%" "--root=%WORK_DIR%"
26
+ set "RC=%ERRORLEVEL%"
27
+ popd >nul
28
+ exit /b %RC%
package/autostart.sh ADDED
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env sh
2
+ set -eu
3
+ WORK_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
4
+ cd "$WORK_DIR"
5
+
6
+ if ! command -v node >/dev/null 2>&1; then
7
+ echo "[WORK] Node.js не найден в PATH." >&2
8
+ exit 1
9
+ fi
10
+
11
+ AS_SCRIPT="$WORK_DIR/scripts/autostart.mjs"
12
+ if [ ! -f "$AS_SCRIPT" ]; then
13
+ AS_SCRIPT="$WORK_DIR/node_modules/odant-work/scripts/autostart.mjs"
14
+ fi
15
+
16
+ ACTION="${1:-install}"
17
+ exec node "$AS_SCRIPT" "$ACTION" "--root=$WORK_DIR"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.102",
3
+ "version": "1.0.103",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
package/run.mjs CHANGED
@@ -80,6 +80,25 @@ if (!isPackageActual()) {
80
80
  const workRoot = path.resolve(process.cwd());
81
81
  const pkgRoot = path.resolve(currentDirectory);
82
82
 
83
+ const cliArgs = process.argv.slice(2);
84
+ const autostartArg = cliArgs.find(a => a === '--autostart' || a.startsWith('--autostart='));
85
+ if (autostartArg) {
86
+ const action = autostartArg.includes('=') ? (autostartArg.split('=')[1] || 'install') : 'install';
87
+ const { runAutostartCommand } = await import('./scripts/autostart.mjs');
88
+ await runAutostartCommand(action, { workRoot });
89
+ process.exit(0);
90
+ }
91
+ if (cliArgs.includes('--stop')) {
92
+ const { stopWork } = await import('./scripts/watchdog.mjs');
93
+ const ok = await stopWork({ workRoot });
94
+ process.exit(ok ? 0 : 1);
95
+ }
96
+ if (cliArgs.includes('--status')) {
97
+ const { printStatus } = await import('./scripts/watchdog.mjs');
98
+ await printStatus({ workRoot });
99
+ process.exit(0);
100
+ }
101
+
83
102
  /**
84
103
  * Если запуск выполнен через `npx odant-work` или из `node_modules/odant-work` в рабочей папке (например, D:\WORK),
85
104
  * автоматически разворачиваем или безопасно обновляем рабочую директорию из установленного пакета.