opencode-windows-scheduler 1.1.0 → 1.2.0

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 (84) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/README.md +13 -3
  3. package/README.ru.md +13 -3
  4. package/ROADMAP.md +20 -13
  5. package/dist/core/analytics.d.ts +10 -0
  6. package/dist/core/analytics.d.ts.map +1 -1
  7. package/dist/core/analytics.js +21 -0
  8. package/dist/core/dry-run.d.ts +13 -0
  9. package/dist/core/dry-run.d.ts.map +1 -1
  10. package/dist/core/dry-run.js +30 -0
  11. package/dist/core/matrix.d.ts.map +1 -1
  12. package/dist/core/matrix.js +10 -0
  13. package/dist/core/ps-wrapper.d.ts +32 -2
  14. package/dist/core/ps-wrapper.d.ts.map +1 -1
  15. package/dist/core/ps-wrapper.js +101 -3
  16. package/dist/core/schedule-gate.d.ts +2 -0
  17. package/dist/core/schedule-gate.d.ts.map +1 -0
  18. package/dist/core/schedule-gate.js +182 -0
  19. package/dist/core/schedule-v2.d.ts +88 -0
  20. package/dist/core/schedule-v2.d.ts.map +1 -0
  21. package/dist/core/schedule-v2.js +496 -0
  22. package/dist/core/scheduler/types.d.ts +15 -0
  23. package/dist/core/scheduler/types.d.ts.map +1 -1
  24. package/dist/core/scheduler/windows.d.ts.map +1 -1
  25. package/dist/core/scheduler/windows.js +13 -1
  26. package/dist/core/wrappers/bash.d.ts +15 -0
  27. package/dist/core/wrappers/bash.d.ts.map +1 -1
  28. package/dist/core/wrappers/bash.js +44 -1
  29. package/dist/db/history-repo.d.ts +8 -0
  30. package/dist/db/history-repo.d.ts.map +1 -1
  31. package/dist/db/history-repo.js +13 -0
  32. package/dist/db/schema.d.ts +1 -1
  33. package/dist/db/schema.d.ts.map +1 -1
  34. package/dist/db/schema.js +11 -0
  35. package/dist/index.d.ts +117 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +1010 -54
  38. package/dist/notifications.d.ts +112 -6
  39. package/dist/notifications.d.ts.map +1 -1
  40. package/dist/notifications.js +396 -34
  41. package/dist/profiles.d.ts +60 -0
  42. package/dist/profiles.d.ts.map +1 -0
  43. package/dist/profiles.js +209 -0
  44. package/dist/rpc.d.ts +511 -0
  45. package/dist/rpc.d.ts.map +1 -1
  46. package/dist/rpc.js +190 -2
  47. package/dist/server.d.ts.map +1 -1
  48. package/dist/server.js +5 -2
  49. package/dist/settings.d.ts +57 -0
  50. package/dist/settings.d.ts.map +1 -1
  51. package/dist/settings.js +118 -8
  52. package/dist/task-transfer.d.ts +13 -0
  53. package/dist/task-transfer.d.ts.map +1 -1
  54. package/dist/task-transfer.js +26 -0
  55. package/dist/types.d.ts.map +1 -1
  56. package/dist/types.js +3 -11
  57. package/dist/workspaces.d.ts +43 -0
  58. package/dist/workspaces.d.ts.map +1 -1
  59. package/dist/workspaces.js +174 -8
  60. package/docs/ARCHITECTURE.md +32 -12
  61. package/docs/FEATURES.md +86 -7
  62. package/gui-experimental.cjs +4 -2
  63. package/package.json +6 -2
  64. package/src/core/analytics.ts +36 -0
  65. package/src/core/dry-run.ts +42 -0
  66. package/src/core/matrix.ts +10 -0
  67. package/src/core/ps-wrapper.ts +117 -3
  68. package/src/core/schedule-gate.ts +213 -0
  69. package/src/core/schedule-v2.ts +533 -0
  70. package/src/core/scheduler/types.ts +15 -0
  71. package/src/core/scheduler/windows.ts +13 -1
  72. package/src/core/wrappers/bash.ts +60 -0
  73. package/src/db/history-repo.ts +23 -0
  74. package/src/db/schema.ts +14 -0
  75. package/src/gui.tsx +767 -22
  76. package/src/index.ts +1226 -52
  77. package/src/notifications.ts +516 -40
  78. package/src/profiles.ts +236 -0
  79. package/src/rpc.ts +201 -2
  80. package/src/server.ts +5 -2
  81. package/src/settings.ts +214 -9
  82. package/src/task-transfer.ts +44 -0
  83. package/src/types.ts +3 -13
  84. package/src/workspaces.ts +214 -8
package/src/gui.tsx CHANGED
@@ -26,11 +26,31 @@ interface MatrixConfig {
26
26
  overrides?: Record<string, MatrixOverrideFields>
27
27
  }
28
28
 
29
- /** Настройки уведомлений (webhook). */
29
+ /** Настройки уведомлений (webhook, шаблоны, фильтры, матрицы, дайджест — Спринт 20). */
30
30
  interface NotificationSettings {
31
31
  enabled: boolean
32
32
  onlyOnError: boolean
33
- webhook?: { enabled: boolean; url: string }
33
+ webhook?: {
34
+ enabled: boolean
35
+ url: string
36
+ timeoutMs?: number
37
+ retryCount?: number
38
+ retryDelayMs?: number
39
+ }
40
+ templates?: { success: string; error: string }
41
+ filters?: { include: string[]; exclude: string[] }
42
+ matrix?: {
43
+ enabled: boolean
44
+ onPartial: boolean
45
+ onAllFailed: boolean
46
+ stuckAfterMinutes: number
47
+ }
48
+ digest?: {
49
+ enabled: boolean
50
+ frequency: "daily" | "weekly"
51
+ time: string
52
+ lastSentAt?: string | null
53
+ }
34
54
  }
35
55
 
36
56
  /** Настройки ретеншна истории (Спринт 18). 0 — соответствующее ограничение выключено. */
@@ -45,6 +65,12 @@ interface Job {
45
65
  name: string
46
66
  schedule: string
47
67
  status: JobStatus
68
+ /** Всего запусков именно этой задачи (не общий итог по всем). */
69
+ runsTotal?: number
70
+ /** Успешных запусков этой задачи. */
71
+ runsSuccess?: number
72
+ /** Неуспешных запусков этой задачи. */
73
+ runsError?: number
48
74
  nextRun?: string
49
75
  paused?: boolean
50
76
  retryCount?: number
@@ -88,6 +114,14 @@ interface Job {
88
114
  status: string
89
115
  message: string
90
116
  } | null
117
+ /** IANA-часовой пояс задачи (Спринт 19); null — системный. */
118
+ timezone?: string | null
119
+ /** Окно запуска: начало "HH:MM" (Спринт 19). */
120
+ notBefore?: string | null
121
+ /** Окно запуска: конец "HH:MM" (может быть меньше notBefore). */
122
+ notAfter?: string | null
123
+ /** Пауза до даты (ISO) — задача включится автоматически. */
124
+ pausedUntil?: string | null
91
125
  }
92
126
 
93
127
  /** Пользовательский шаблон, сохранённый в templates.json. */
@@ -123,9 +157,22 @@ interface Workspace {
123
157
  gitRemote?: string | null
124
158
  gitBranch?: string | null
125
159
  color?: string | null
160
+ /** Env-переменные workspace (Спринт 21); секреты приходят замаскированными. */
161
+ env?: Record<string, string> | null
162
+ /** Путь к .env-файлу workspace (Спринт 21). */
163
+ envFile?: string | null
126
164
  createdAt: string
127
165
  }
128
166
 
167
+ /** Описание профиля плагина (Спринт 21). */
168
+ interface ProfileInfo {
169
+ name: string
170
+ dir: string
171
+ port: number | null
172
+ isDefault: boolean
173
+ active: boolean
174
+ }
175
+
129
176
  function statusColor(status: JobStatus): string {
130
177
  switch (status) {
131
178
  case "running": return "#f5a623"
@@ -196,6 +243,37 @@ export default Plugin.define({
196
243
  const [workspaceFilter, setWorkspaceFilter] = createSignal("all")
197
244
  const [workspaceBusy, setWorkspaceBusy] = createSignal(false)
198
245
  const [workspaceId, setWorkspaceId] = createSignal("")
246
+ // Профили плагина (Спринт 21): отдельные БД/настройки/порт дашборда.
247
+ const [profiles, setProfiles] = createSignal<ProfileInfo[]>([])
248
+ const [profileCurrent, setProfileCurrent] = createSignal("default")
249
+ const [profilePinned, setProfilePinned] = createSignal(false)
250
+ const [profilesOpen, setProfilesOpen] = createSignal(false)
251
+ const [profileBusy, setProfileBusy] = createSignal(false)
252
+ // Собственный текстовый prompt: в Electron/WebView window.prompt не работает
253
+ // (возвращает null), из-за чего «+ Создать» в профилях молча ничего не делал.
254
+ const [promptOpen, setPromptOpen] = createSignal(false)
255
+ const [promptTitle, setPromptTitle] = createSignal("")
256
+ const [promptValue, setPromptValue] = createSignal("")
257
+ let promptResolve: ((value: string | null) => void) | null = null
258
+
259
+ /** Модальный ввод строки. Возвращает null при отмене/Escape/клике по фону. */
260
+ function askText(title: string, initial = ""): Promise<string | null> {
261
+ // Предыдущий незакрытый запрос отменяем, чтобы не потерять промис.
262
+ promptResolve?.(null)
263
+ return new Promise((resolve) => {
264
+ promptResolve = resolve
265
+ setPromptTitle(title)
266
+ setPromptValue(initial)
267
+ setPromptOpen(true)
268
+ })
269
+ }
270
+
271
+ function answerPrompt(value: string | null) {
272
+ const resolve = promptResolve
273
+ promptResolve = null
274
+ setPromptOpen(false)
275
+ resolve?.(value)
276
+ }
199
277
  const [logs, setLogs] = createSignal("")
200
278
  const [logsTask, setLogsTask] = createSignal<string | null>(null)
201
279
  const [busy, setBusy] = createSignal(false)
@@ -245,6 +323,23 @@ export default Plugin.define({
245
323
  const [webhookUrl, setWebhookUrl] = createSignal("")
246
324
  const [notificationsCollapsed, setNotificationsCollapsed] = createSignal(true)
247
325
  const [testNotificationBusy, setTestNotificationBusy] = createSignal(false)
326
+ // Спринт 20: webhook-ретраи, шаблоны, фильтры, матрицы и дайджест.
327
+ const [webhookTimeoutMs, setWebhookTimeoutMs] = createSignal(10000)
328
+ const [webhookRetryCount, setWebhookRetryCount] = createSignal(2)
329
+ const [webhookRetryDelayMs, setWebhookRetryDelayMs] = createSignal(1000)
330
+ const [templateSuccess, setTemplateSuccess] = createSignal("")
331
+ const [templateError, setTemplateError] = createSignal("")
332
+ const [filterInclude, setFilterInclude] = createSignal("")
333
+ const [filterExclude, setFilterExclude] = createSignal("")
334
+ const [matrixNotifyEnabled, setMatrixNotifyEnabled] = createSignal(true)
335
+ const [matrixNotifyPartial, setMatrixNotifyPartial] = createSignal(true)
336
+ const [matrixNotifyAllFailed, setMatrixNotifyAllFailed] = createSignal(true)
337
+ const [matrixStuckMinutes, setMatrixStuckMinutes] = createSignal(60)
338
+ const [digestEnabled, setDigestEnabled] = createSignal(false)
339
+ const [digestFrequency, setDigestFrequency] = createSignal<"daily" | "weekly">("daily")
340
+ const [digestTime, setDigestTime] = createSignal("09:00")
341
+ const [digestLastSentAt, setDigestLastSentAt] = createSignal<string | null>(null)
342
+ const [digestBusy, setDigestBusy] = createSignal(false)
248
343
 
249
344
  // Настройки ретеншна истории (Спринт 18): очистка старых записей.
250
345
  const [historyRetentionDays, setHistoryRetentionDays] = createSignal(30)
@@ -274,16 +369,35 @@ export default Plugin.define({
274
369
  }
275
370
  }
276
371
 
372
+ /** Разложить настройки уведомлений по сигналам формы (Спринт 20). */
373
+ function applyNotificationSettings(n: NotificationSettings | undefined) {
374
+ setNotificationsEnabled(Boolean(n?.enabled))
375
+ setOnlyOnError(n?.onlyOnError !== false)
376
+ setWebhookEnabled(Boolean(n?.webhook?.enabled))
377
+ setWebhookUrl(n?.webhook?.url ?? "")
378
+ setWebhookTimeoutMs(Number(n?.webhook?.timeoutMs ?? 10000))
379
+ setWebhookRetryCount(Number(n?.webhook?.retryCount ?? 2))
380
+ setWebhookRetryDelayMs(Number(n?.webhook?.retryDelayMs ?? 1000))
381
+ setTemplateSuccess(n?.templates?.success ?? "")
382
+ setTemplateError(n?.templates?.error ?? "")
383
+ setFilterInclude((n?.filters?.include ?? []).join(", "))
384
+ setFilterExclude((n?.filters?.exclude ?? []).join(", "))
385
+ setMatrixNotifyEnabled(n?.matrix?.enabled !== false)
386
+ setMatrixNotifyPartial(n?.matrix?.onPartial !== false)
387
+ setMatrixNotifyAllFailed(n?.matrix?.onAllFailed !== false)
388
+ setMatrixStuckMinutes(Number(n?.matrix?.stuckAfterMinutes ?? 60))
389
+ setDigestEnabled(Boolean(n?.digest?.enabled))
390
+ setDigestFrequency(n?.digest?.frequency === "weekly" ? "weekly" : "daily")
391
+ setDigestTime(n?.digest?.time ?? "09:00")
392
+ setDigestLastSentAt(n?.digest?.lastSentAt ?? null)
393
+ }
394
+
277
395
  async function loadSettingsGui() {
278
396
  try {
279
397
  const s = await rpc.get_settings({})
280
398
  setMaxConcurrent(s.maxConcurrent ?? 1)
281
399
  setWinterMode(Boolean(s.winterMode))
282
- const n = s.notifications
283
- setNotificationsEnabled(Boolean(n?.enabled))
284
- setOnlyOnError(n?.onlyOnError !== false)
285
- setWebhookEnabled(Boolean(n?.webhook?.enabled))
286
- setWebhookUrl(n?.webhook?.url ?? "")
400
+ applyNotificationSettings(s.notifications)
287
401
  const h = s.history
288
402
  setHistoryRetentionDays(Number(h?.retentionDays ?? 30))
289
403
  setHistoryMaxRecords(Number(h?.maxRecords ?? 5000))
@@ -296,10 +410,44 @@ export default Plugin.define({
296
410
 
297
411
  /** Текущие настройки уведомлений из сигналов формы. */
298
412
  function currentNotificationSettings(): NotificationSettings {
413
+ const splitList = (value: string) =>
414
+ value
415
+ .split(",")
416
+ .map((item) => item.trim())
417
+ .filter((item) => item.length > 0)
299
418
  return {
300
419
  enabled: notificationsEnabled(),
301
420
  onlyOnError: onlyOnError(),
302
- webhook: { enabled: webhookEnabled(), url: (webhookUrl() || "").trim() },
421
+ webhook: {
422
+ enabled: webhookEnabled(),
423
+ url: (webhookUrl() || "").trim(),
424
+ timeoutMs: Math.max(1000, Math.min(120000, Math.floor(Number(webhookTimeoutMs()) || 10000))),
425
+ retryCount: Math.max(0, Math.min(5, Math.floor(Number(webhookRetryCount()) || 0))),
426
+ retryDelayMs: Math.max(100, Math.min(60000, Math.floor(Number(webhookRetryDelayMs()) || 1000))),
427
+ },
428
+ templates: {
429
+ success: templateSuccess().trim(),
430
+ error: templateError().trim(),
431
+ },
432
+ filters: {
433
+ include: splitList(filterInclude()),
434
+ exclude: splitList(filterExclude()),
435
+ },
436
+ matrix: {
437
+ enabled: matrixNotifyEnabled(),
438
+ onPartial: matrixNotifyPartial(),
439
+ onAllFailed: matrixNotifyAllFailed(),
440
+ stuckAfterMinutes: Math.max(
441
+ 0,
442
+ Math.min(10080, Math.floor(Number(matrixStuckMinutes()) || 0))
443
+ ),
444
+ },
445
+ digest: {
446
+ enabled: digestEnabled(),
447
+ frequency: digestFrequency(),
448
+ time: (digestTime() || "09:00").trim(),
449
+ lastSentAt: digestLastSentAt(),
450
+ },
303
451
  }
304
452
  }
305
453
 
@@ -324,11 +472,7 @@ export default Plugin.define({
324
472
  if (patch.maxConcurrent !== undefined) setMaxConcurrent(s.maxConcurrent)
325
473
  if (patch.winterMode !== undefined) setWinterMode(Boolean(s.winterMode))
326
474
  if (patch.notifications !== undefined) {
327
- const n = s.notifications
328
- setNotificationsEnabled(Boolean(n?.enabled))
329
- setOnlyOnError(n?.onlyOnError !== false)
330
- setWebhookEnabled(Boolean(n?.webhook?.enabled))
331
- setWebhookUrl(n?.webhook?.url ?? "")
475
+ applyNotificationSettings(s.notifications)
332
476
  }
333
477
  if (patch.history !== undefined) {
334
478
  const h = s.history
@@ -408,6 +552,30 @@ export default Plugin.define({
408
552
  }
409
553
  }
410
554
 
555
+ /** Кнопка «📊 Отправить дайджест сейчас» (Спринт 20). */
556
+ async function handleSendDigest() {
557
+ setDigestBusy(true)
558
+ try {
559
+ // Сначала фиксируем настройки формы — дайджест читает settings.json.
560
+ await saveNotificationSettings()
561
+ const result = await rpc.send_digest({})
562
+ ctx.toast.show({
563
+ title: result.success ? "Дайджест отправлен" : "Дайджест не отправлен",
564
+ variant: result.success ? "success" : "error",
565
+ description: result.message,
566
+ })
567
+ } catch (err: any) {
568
+ console.error("RPC Error (send_digest):", err)
569
+ ctx.toast.show({
570
+ title: "Дайджест не отправлен",
571
+ variant: "error",
572
+ description: errorMessage(err),
573
+ })
574
+ } finally {
575
+ setDigestBusy(false)
576
+ }
577
+ }
578
+
411
579
  async function saveSettingsGui(val: number) {
412
580
  setMaxConcurrent(val)
413
581
  await persistSettings({ maxConcurrent: val })
@@ -450,6 +618,10 @@ export default Plugin.define({
450
618
  // Триггеры (cron / file / mcp-event) и рабочая директория
451
619
  const [triggerType, setTriggerType] = createSignal<"cron" | "file" | "mcp-event">("cron")
452
620
  const [watchPath, setWatchPath] = createSignal("")
621
+ // Часовой пояс и окно запуска (Спринт 19). Пусто = системный пояс / без окна.
622
+ const [timezone, setTimezone] = createSignal("")
623
+ const [notBefore, setNotBefore] = createSignal("")
624
+ const [notAfter, setNotAfter] = createSignal("")
453
625
  const [mcpServer, setMcpServer] = createSignal("")
454
626
  const [mcpEventName, setMcpEventName] = createSignal("")
455
627
  const [mcpFilter, setMcpFilter] = createSignal("")
@@ -670,10 +842,144 @@ export default Plugin.define({
670
842
  /** Активный workspace выбранной задачи (для dry-run подсказки). */
671
843
  const selectedWorkspace = () => workspaces().find((w) => w.id === workspaceId())
672
844
 
845
+ // ---- Профили (Спринт 21) ----
846
+
847
+ async function loadProfilesGui() {
848
+ try {
849
+ const result = await rpc.get_profiles({})
850
+ const list = Array.isArray(result?.profiles) ? (result.profiles as ProfileInfo[]) : []
851
+ setProfiles(list)
852
+ if (result?.current) setProfileCurrent(result.current)
853
+ setProfilePinned(Boolean(result?.pinnedByEnv))
854
+ } catch (err: any) {
855
+ console.error("RPC Error (get_profiles):", err)
856
+ }
857
+ }
858
+
859
+ async function handleSwitchProfile(name: string) {
860
+ if (!name || name === profileCurrent()) return
861
+ setProfileBusy(true)
862
+ try {
863
+ const result = await rpc.set_profile({ name })
864
+ if (!result.success) {
865
+ ctx.toast.show({ title: "Не удалось переключить профиль", variant: "error", description: result.message ?? "Неизвестная ошибка" })
866
+ return
867
+ }
868
+ setProfileCurrent(result.current ?? name)
869
+ ctx.toast.show({ title: "Профиль переключён", variant: "success", description: result.message })
870
+ await loadProfilesGui()
871
+ } catch (err: any) {
872
+ console.error("RPC Error (set_profile):", err)
873
+ ctx.toast.show({ title: "Ошибка переключения профиля", variant: "error", description: shortError(errorMessage(err)) })
874
+ } finally {
875
+ setProfileBusy(false)
876
+ }
877
+ }
878
+
879
+ async function handleCreateProfile() {
880
+ const name = ((await askText("Имя нового профиля (латиница, цифры, - и _)", "")) ?? "").trim()
881
+ if (!name) return
882
+ setProfileBusy(true)
883
+ try {
884
+ const result = await rpc.create_profile({ name })
885
+ if (!result.success) {
886
+ ctx.toast.show({ title: "Не удалось создать профиль", variant: "error", description: result.message ?? "Неизвестная ошибка" })
887
+ return
888
+ }
889
+ await loadProfilesGui()
890
+ ctx.toast.show({ title: "Профиль создан", variant: "success", description: result.message })
891
+ } catch (err: any) {
892
+ console.error("RPC Error (create_profile):", err)
893
+ ctx.toast.show({ title: "Ошибка создания профиля", variant: "error", description: shortError(errorMessage(err)) })
894
+ } finally {
895
+ setProfileBusy(false)
896
+ }
897
+ }
898
+
899
+ async function handleDeleteProfile(name: string) {
900
+ if (!name || name === "default") return
901
+ if (!window.confirm(`Удалить профиль "${name}" вместе с его БД, настройками и логами?`)) return
902
+ setProfileBusy(true)
903
+ try {
904
+ const result = await rpc.delete_profile({ name })
905
+ if (!result.success) {
906
+ ctx.toast.show({ title: "Не удалось удалить профиль", variant: "error", description: result.message ?? "Неизвестная ошибка" })
907
+ return
908
+ }
909
+ await loadProfilesGui()
910
+ ctx.toast.show({ title: "Профиль удалён", variant: "success" })
911
+ } catch (err: any) {
912
+ console.error("RPC Error (delete_profile):", err)
913
+ ctx.toast.show({ title: "Ошибка удаления профиля", variant: "error", description: shortError(errorMessage(err)) })
914
+ } finally {
915
+ setProfileBusy(false)
916
+ }
917
+ }
918
+
919
+ // ---- Env-переменные workspace (Спринт 21) ----
920
+
921
+ /** Строки `KEY=VALUE` из объекта env (для textarea). */
922
+ function envToText(env?: Record<string, string> | null): string {
923
+ if (!env) return ""
924
+ return Object.entries(env).map(([key, value]) => `${key}=${value}`).join("\n")
925
+ }
926
+
927
+ /** Разбирает textarea `KEY=VALUE`: возвращает пары или null при ошибке. */
928
+ function parseEnvText(text: string): Record<string, string> | null {
929
+ const result: Record<string, string> = {}
930
+ for (const raw of text.split(/\r?\n/)) {
931
+ const line = raw.trim()
932
+ if (!line || line.startsWith("#")) continue
933
+ const eq = line.indexOf("=")
934
+ if (eq <= 0) return null
935
+ const key = line.slice(0, eq).trim()
936
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) return null
937
+ result[key] = line.slice(eq + 1).trim()
938
+ }
939
+ return result
940
+ }
941
+
942
+ async function handleEditWorkspaceEnv(workspace: Workspace) {
943
+ const envText = await askText(
944
+ "Env-переменные workspace, по одной в строке KEY=VALUE\n(пустое поле — очистить)",
945
+ envToText(workspace.env)
946
+ )
947
+ if (envText === null) return
948
+ const env = parseEnvText(envText)
949
+ if (!env) {
950
+ ctx.toast.show({ title: "Неверный формат env", variant: "error", description: "Нужны строки KEY=VALUE, имя — латиница/цифры/_" })
951
+ return
952
+ }
953
+ const envFile = await askText(
954
+ "Путь к .env-файлу workspace (необязательно, пусто — без файла)",
955
+ workspace.envFile ?? ""
956
+ )
957
+ if (envFile === null) return
958
+ setWorkspaceBusy(true)
959
+ try {
960
+ const result = await rpc.update_workspace({
961
+ id: workspace.id,
962
+ env: Object.keys(env).length ? env : null,
963
+ envFile: envFile.trim() || null,
964
+ })
965
+ if (!result.success) {
966
+ ctx.toast.show({ title: "Не удалось сохранить env", variant: "error", description: result.error ?? "Неизвестная ошибка" })
967
+ return
968
+ }
969
+ await loadWorkspacesGui()
970
+ ctx.toast.show({ title: "Env-переменные сохранены", variant: "success", description: "Секреты маскируются в логах" })
971
+ } catch (err: any) {
972
+ console.error("RPC Error (update_workspace env):", err)
973
+ ctx.toast.show({ title: "Ошибка сохранения env", variant: "error", description: shortError(errorMessage(err)) })
974
+ } finally {
975
+ setWorkspaceBusy(false)
976
+ }
977
+ }
978
+
673
979
  async function handleAddWorkspace() {
674
- const workspacePath = (window.prompt("Путь к git-репозиторию (workspace)", "") ?? "").trim()
980
+ const workspacePath = ((await askText("Путь к git-репозиторию (workspace)", "")) ?? "").trim()
675
981
  if (!workspacePath) return
676
- const workspaceName = (window.prompt("Название workspace (необязательно)", "") ?? "").trim()
982
+ const workspaceName = ((await askText("Название workspace (необязательно)", "")) ?? "").trim()
677
983
  setWorkspaceBusy(true)
678
984
  try {
679
985
  const result = await rpc.add_workspace({
@@ -696,9 +1002,9 @@ export default Plugin.define({
696
1002
  }
697
1003
 
698
1004
  async function handleEditWorkspace(workspace: Workspace) {
699
- const nextPath = (window.prompt("Путь к git-репозиторию", workspace.path) ?? "").trim()
1005
+ const nextPath = ((await askText("Путь к git-репозиторию", workspace.path)) ?? "").trim()
700
1006
  if (!nextPath) return
701
- const nextName = (window.prompt("Название workspace", workspace.name) ?? "").trim()
1007
+ const nextName = ((await askText("Название workspace", workspace.name)) ?? "").trim()
702
1008
  setWorkspaceBusy(true)
703
1009
  try {
704
1010
  const result = await rpc.update_workspace({
@@ -776,6 +1082,9 @@ export default Plugin.define({
776
1082
  : "cron"
777
1083
  )
778
1084
  setWatchPath(t.watchPath ?? "")
1085
+ setTimezone(t.timezone ?? "")
1086
+ setNotBefore(t.notBefore ?? "")
1087
+ setNotAfter(t.notAfter ?? "")
779
1088
  setMcpServer(t.mcpEvent?.server ?? "")
780
1089
  setMcpEventName(t.mcpEvent?.event ?? "")
781
1090
  setMcpFilter(t.mcpEvent?.filter ?? "")
@@ -816,7 +1125,7 @@ export default Plugin.define({
816
1125
  return
817
1126
  }
818
1127
 
819
- const templateName = (window.prompt("Название шаблона", "") ?? "").trim()
1128
+ const templateName = ((await askText("Название шаблона", "")) ?? "").trim()
820
1129
  if (!templateName) return
821
1130
 
822
1131
  try {
@@ -834,6 +1143,9 @@ export default Plugin.define({
834
1143
  afterScript: (afterScript() || "").trim(),
835
1144
  dependsOn: dependsOn(),
836
1145
  triggerType: triggerType(),
1146
+ timezone: (timezone() || "").trim() || undefined,
1147
+ notBefore: (notBefore() || "").trim() || undefined,
1148
+ notAfter: (notAfter() || "").trim() || undefined,
837
1149
  mcpEvent:
838
1150
  triggerType() === "mcp-event"
839
1151
  ? {
@@ -907,6 +1219,9 @@ export default Plugin.define({
907
1219
  name: t.name,
908
1220
  schedule: t.schedule,
909
1221
  status: (t.status as JobStatus) ?? "unknown",
1222
+ runsTotal: typeof t.runsTotal === "number" ? t.runsTotal : 0,
1223
+ runsSuccess: typeof t.runsSuccess === "number" ? t.runsSuccess : 0,
1224
+ runsError: typeof t.runsError === "number" ? t.runsError : 0,
910
1225
  nextRun: t.nextRun ?? undefined,
911
1226
  paused: t.status?.toLowerCase().includes("disabled"),
912
1227
  retryCount: t.retryCount ?? 0,
@@ -920,6 +1235,10 @@ export default Plugin.define({
920
1235
  triggerType: (t.triggerType ?? "cron") as "cron" | "file" | "mcp-event",
921
1236
  mcpEvent: t.mcpEvent ?? undefined,
922
1237
  watchPath: t.watchPath ?? undefined,
1238
+ timezone: t.timezone ?? undefined,
1239
+ notBefore: t.notBefore ?? undefined,
1240
+ notAfter: t.notAfter ?? undefined,
1241
+ pausedUntil: t.pausedUntil ?? undefined,
923
1242
  workingDirectory: t.workingDirectory ?? undefined,
924
1243
  workspaceId: t.workspaceId ?? undefined,
925
1244
  workspaceName: t.workspaceName ?? undefined,
@@ -954,7 +1273,7 @@ export default Plugin.define({
954
1273
  async function fetchHistory(taskName: string) {
955
1274
  setHistoryOpen(taskName)
956
1275
  try {
957
- const result = await rpc.get_history({ limit: 10 })
1276
+ const result = await rpc.get_history({ limit: 10, taskName })
958
1277
  setHistory(result.records ?? [])
959
1278
  } catch (err: any) {
960
1279
  console.error("RPC Error (get_history):", err)
@@ -1002,6 +1321,9 @@ export default Plugin.define({
1002
1321
  afterScript: (afterScript() || "").trim(),
1003
1322
  dependsOn: dependsOn(),
1004
1323
  triggerType: triggerType(),
1324
+ timezone: (timezone() || "").trim() || undefined,
1325
+ notBefore: (notBefore() || "").trim() || undefined,
1326
+ notAfter: (notAfter() || "").trim() || undefined,
1005
1327
  mcpEvent:
1006
1328
  triggerType() === "mcp-event"
1007
1329
  ? {
@@ -1043,6 +1365,9 @@ export default Plugin.define({
1043
1365
  setAfterScript("")
1044
1366
  setTriggerType("cron")
1045
1367
  setWatchPath("")
1368
+ setTimezone("")
1369
+ setNotBefore("")
1370
+ setNotAfter("")
1046
1371
  setMcpServer("")
1047
1372
  setMcpEventName("")
1048
1373
  setMcpFilter("")
@@ -1250,6 +1575,9 @@ export default Plugin.define({
1250
1575
  afterScript: (afterScript() || "").trim(),
1251
1576
  dependsOn: dependsOn(),
1252
1577
  triggerType: triggerType(),
1578
+ timezone: (timezone() || "").trim() || undefined,
1579
+ notBefore: (notBefore() || "").trim() || undefined,
1580
+ notAfter: (notAfter() || "").trim() || undefined,
1253
1581
  mcpEvent:
1254
1582
  triggerType() === "mcp-event"
1255
1583
  ? {
@@ -1284,6 +1612,9 @@ export default Plugin.define({
1284
1612
  setAfterScript("")
1285
1613
  setTriggerType("cron")
1286
1614
  setWatchPath("")
1615
+ setTimezone("")
1616
+ setNotBefore("")
1617
+ setNotAfter("")
1287
1618
  setMcpServer("")
1288
1619
  setMcpEventName("")
1289
1620
  setMcpFilter("")
@@ -1321,6 +1652,9 @@ export default Plugin.define({
1321
1652
  setAfterScript(job.afterScript ?? "")
1322
1653
  setTriggerType(job.triggerType ?? "cron")
1323
1654
  setWatchPath(job.watchPath ?? "")
1655
+ setTimezone(job.timezone ?? "")
1656
+ setNotBefore(job.notBefore ?? "")
1657
+ setNotAfter(job.notAfter ?? "")
1324
1658
  setMcpServer(job.mcpEvent?.server ?? "")
1325
1659
  setMcpEventName(job.mcpEvent?.event ?? "")
1326
1660
  setMcpFilter(job.mcpEvent?.filter ?? "")
@@ -1350,6 +1684,7 @@ export default Plugin.define({
1350
1684
  // Автообновление списка задач каждые 5 секунд
1351
1685
  loadJobs()
1352
1686
  loadWorkspacesGui()
1687
+ loadProfilesGui()
1353
1688
  loadSettingsGui()
1354
1689
  loadPlatformGui()
1355
1690
  loadTemplatesGui()
@@ -1461,6 +1796,15 @@ export default Plugin.define({
1461
1796
  {job.watchPath && (
1462
1797
  <span title={`Отслеживание файла: ${job.watchPath}`} style="font-size:13px;flex-shrink:0;cursor:help">👁️</span>
1463
1798
  )}
1799
+ {job.timezone && (
1800
+ <span title={`Часовой пояс задачи: ${job.timezone}`} style="font-size:11px;font-weight:600;flex-shrink:0;cursor:help;white-space:nowrap;padding:2px 7px;border-radius:999px;border:1px solid #64d2ff;color:#64d2ff;background:rgba(100,210,255,0.12)">🌍 {job.timezone}</span>
1801
+ )}
1802
+ {job.notBefore && job.notAfter && (
1803
+ <span title={`Окно запуска: ${job.notBefore}–${job.notAfter}. Вне окна запуск переносится на его открытие.`} style="font-size:11px;font-weight:600;flex-shrink:0;cursor:help;white-space:nowrap;padding:2px 7px;border-radius:999px;border:1px solid #bf5af2;color:#bf5af2;background:rgba(191,90,242,0.12)">🪟 {job.notBefore}–{job.notAfter}</span>
1804
+ )}
1805
+ {job.pausedUntil && (
1806
+ <span title={`Пауза до ${new Date(job.pausedUntil).toLocaleString()} — задача включится автоматически.`} style="font-size:11px;font-weight:600;flex-shrink:0;cursor:help;white-space:nowrap;padding:2px 7px;border-radius:999px;border:1px solid #ffd60a;color:#ffd60a;background:rgba(255,214,10,0.12)">⏸ до {new Date(job.pausedUntil).toLocaleDateString()}</span>
1807
+ )}
1464
1808
  {(job.beforeScript || job.afterScript) && (
1465
1809
  <span
1466
1810
  title={`Lifecycle hooks: ${[job.beforeScript ? `pre: ${job.beforeScript}` : "", job.afterScript ? `post: ${job.afterScript}` : ""].filter(Boolean).join(" · ")}`}
@@ -1506,8 +1850,11 @@ export default Plugin.define({
1506
1850
  </span>
1507
1851
  </div>
1508
1852
  )}
1509
- <div style="font-size:12px;color:#a0a0a6;margin-top:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">
1510
- 📊 Всего: {metrics().total} | ✅ {metrics().success} | ❌ {metrics().error}
1853
+ <div
1854
+ title="Запуски именно этой задачи (успешные / с ошибкой)"
1855
+ style="font-size:12px;color:#a0a0a6;margin-top:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"
1856
+ >
1857
+ 📊 Всего: {job.runsTotal ?? 0} | ✅ {job.runsSuccess ?? 0} | ❌ {job.runsError ?? 0}
1511
1858
  </div>
1512
1859
  {(job.schedule || job.nextRun) && (
1513
1860
  <div style="display:flex;align-items:center;gap:8px;font-size:12px;color:#a0a0a6;margin-top:2px">
@@ -1748,6 +2095,12 @@ export default Plugin.define({
1748
2095
  <div style="margin-top:5px;font-size:11px;font-weight:600;letter-spacing:1.2px;text-transform:uppercase;color:#8e8e93">
1749
2096
  Local AI CI/CD Orchestrator
1750
2097
  </div>
2098
+ <div
2099
+ title="Суммарные метрики по всем задачам (включая архивные записи метрик)"
2100
+ style="margin-top:4px;font-size:11px;color:#8e8e93"
2101
+ >
2102
+ 📊 Всего по всем задачам: {metrics().total} · ✅ {metrics().success} · ❌ {metrics().error}
2103
+ </div>
1751
2104
  </div>
1752
2105
  <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
1753
2106
  <select
@@ -1762,6 +2115,15 @@ export default Plugin.define({
1762
2115
  ))}
1763
2116
  <option value="none">Без workspace</option>
1764
2117
  </select>
2118
+ <button
2119
+ onClick={() => setProfilesOpen((v) => !v)}
2120
+ title={profilePinned()
2121
+ ? "Профиль задан переменной окружения OPENCODE_SCHEDULER_PROFILE — переключение в GUI недоступно"
2122
+ : "Профили: отдельные БД, настройки и порт дашборда"}
2123
+ style={`display:flex;align-items:center;gap:6px;padding:6px 12px;border-radius:999px;cursor:pointer;font-size:12px;user-select:none;white-space:nowrap;border:1px solid ${profilesOpen() ? "#bf5af2" : "#333"};background:${profilesOpen() ? "rgba(191,90,242,0.12)" : "#1e1e1e"};color:${profilesOpen() ? "#bf5af2" : "#e0e0e0"}`}
2124
+ >
2125
+ 👤 {profileCurrent()}{profilePinned() ? " 🔒" : ""}
2126
+ </button>
1765
2127
  <button
1766
2128
  onClick={async () => {
1767
2129
  // Открываем окно сразу (внутри клика), чтобы не сработал блокировщик попапов.
@@ -1801,6 +2163,62 @@ export default Plugin.define({
1801
2163
  </div>
1802
2164
  </div>
1803
2165
 
2166
+ {profilesOpen() && (
2167
+ <div style="background:#1e1e1e;border:1px solid #333;border-radius:10px;padding:12px 14px;display:flex;flex-direction:column;gap:8px">
2168
+ <div style="display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap">
2169
+ <div style="font-size:12px;font-weight:600;color:#e0e0e0">👤 Профили</div>
2170
+ <button
2171
+ onClick={() => void handleCreateProfile()}
2172
+ disabled={profileBusy()}
2173
+ style={`padding:4px 10px;border-radius:6px;border:1px solid #333;background:#262626;color:#e0e0e0;font-size:11px;cursor:${profileBusy() ? "not-allowed" : "pointer"}`}
2174
+ >
2175
+ + Создать
2176
+ </button>
2177
+ </div>
2178
+ {profilePinned() && (
2179
+ <div style="font-size:11px;color:#ffd60a">
2180
+ Профиль задан переменной OPENCODE_SCHEDULER_PROFILE. Переключение в GUI недоступно.
2181
+ </div>
2182
+ )}
2183
+ <div style="display:flex;flex-direction:column;gap:6px">
2184
+ {profiles().map((profile) => (
2185
+ <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:12px">
2186
+ <span style={`font-weight:${profile.active ? 700 : 400};color:${profile.active ? "#bf5af2" : "#e0e0e0"}`}>
2187
+ {profile.name}{profile.isDefault ? " (по умолчанию)" : ""}
2188
+ </span>
2189
+ <span style="font-size:11px;color:#8e8e93">
2190
+ {profile.port ? `порт ${profile.port}` : "порт по умолчанию"}
2191
+ </span>
2192
+ <span style="font-size:11px;color:#8e8e93;overflow:hidden;text-overflow:ellipsis;max-width:340px" title={profile.dir}>{profile.dir}</span>
2193
+ {profile.active ? (
2194
+ <span style="font-size:11px;color:#34c759">активен</span>
2195
+ ) : (
2196
+ <button
2197
+ onClick={() => void handleSwitchProfile(profile.name)}
2198
+ disabled={profileBusy() || profilePinned()}
2199
+ style={`padding:2px 8px;border-radius:6px;border:1px solid #333;background:#262626;color:#e0e0e0;font-size:11px;cursor:${profileBusy() || profilePinned() ? "not-allowed" : "pointer"};opacity:${profilePinned() ? 0.5 : 1}`}
2200
+ >
2201
+ Переключить
2202
+ </button>
2203
+ )}
2204
+ {!profile.isDefault && !profile.active && (
2205
+ <button
2206
+ onClick={() => void handleDeleteProfile(profile.name)}
2207
+ disabled={profileBusy()}
2208
+ style={`padding:2px 8px;border-radius:6px;border:1px solid rgba(255,59,48,0.4);background:rgba(255,59,48,0.12);color:#ff3b30;font-size:11px;cursor:${profileBusy() ? "not-allowed" : "pointer"}`}
2209
+ >
2210
+ Удалить
2211
+ </button>
2212
+ )}
2213
+ </div>
2214
+ ))}
2215
+ </div>
2216
+ <div style="font-size:11px;color:#8e8e93">
2217
+ У каждого профиля своя БД, настройки, логи и порт дашборда. После переключения перезапустите OpenCode.
2218
+ </div>
2219
+ </div>
2220
+ )}
2221
+
1804
2222
  <div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:8px">
1805
2223
  <button
1806
2224
  onClick={handleExport}
@@ -1904,6 +2322,206 @@ export default Plugin.define({
1904
2322
  <div style="font-size:11px;color:#8e8e93">
1905
2323
  POST с JSON {"{ content, text }"} — совместимо с Discord и Slack.
1906
2324
  </div>
2325
+ <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:11px;color:#b0b0b0">
2326
+ <span>Таймаут, мс:</span>
2327
+ <input
2328
+ type="number"
2329
+ min="1000"
2330
+ max="120000"
2331
+ step="1000"
2332
+ value={webhookTimeoutMs()}
2333
+ disabled={!notificationsEnabled() || !webhookEnabled()}
2334
+ onInput={(e) => setWebhookTimeoutMs(Number(e.currentTarget.value) || 10000)}
2335
+ onChange={() => void saveNotificationSettings()}
2336
+ style="width:80px;padding:4px 6px;background:#1e1e1e;border:1px solid #333;border-radius:4px;color:#fff;font-size:12px;outline:none"
2337
+ />
2338
+ <span>повторов:</span>
2339
+ <input
2340
+ type="number"
2341
+ min="0"
2342
+ max="5"
2343
+ value={webhookRetryCount()}
2344
+ disabled={!notificationsEnabled() || !webhookEnabled()}
2345
+ onInput={(e) => setWebhookRetryCount(Number(e.currentTarget.value) || 0)}
2346
+ onChange={() => void saveNotificationSettings()}
2347
+ style="width:56px;padding:4px 6px;background:#1e1e1e;border:1px solid #333;border-radius:4px;color:#fff;font-size:12px;outline:none"
2348
+ />
2349
+ <span>пауза, мс:</span>
2350
+ <input
2351
+ type="number"
2352
+ min="100"
2353
+ max="60000"
2354
+ step="100"
2355
+ value={webhookRetryDelayMs()}
2356
+ disabled={!notificationsEnabled() || !webhookEnabled()}
2357
+ onInput={(e) => setWebhookRetryDelayMs(Number(e.currentTarget.value) || 1000)}
2358
+ onChange={() => void saveNotificationSettings()}
2359
+ style="width:80px;padding:4px 6px;background:#1e1e1e;border:1px solid #333;border-radius:4px;color:#fff;font-size:12px;outline:none"
2360
+ />
2361
+ </div>
2362
+ <div style="font-size:11px;color:#8e8e93">
2363
+ Повтор при сетевой ошибке, таймауте, 5xx и 429 (экспоненциальная пауза).
2364
+ </div>
2365
+ </div>
2366
+
2367
+ {/* Фильтры по задачам (Спринт 20) */}
2368
+ <div style="border-top:1px solid #333;padding-top:10px;display:flex;flex-direction:column;gap:8px">
2369
+ <div style="font-size:12px;color:#e0e0e0;font-weight:600">Фильтры по задачам</div>
2370
+ <input
2371
+ type="text"
2372
+ value={filterInclude() || ""}
2373
+ disabled={!notificationsEnabled()}
2374
+ onInput={(e) => setFilterInclude(e.currentTarget.value)}
2375
+ onChange={() => void saveNotificationSettings()}
2376
+ placeholder="Только эти задачи (через запятую, * — маска)"
2377
+ style={`display:block;width:100%;box-sizing:border-box;padding:8px;background:#1e1e1e;border:1px solid #333;border-radius:6px;color:#fff;font-size:13px;outline:none;opacity:${notificationsEnabled() ? 1 : 0.5}`}
2378
+ />
2379
+ <input
2380
+ type="text"
2381
+ value={filterExclude() || ""}
2382
+ disabled={!notificationsEnabled()}
2383
+ onInput={(e) => setFilterExclude(e.currentTarget.value)}
2384
+ onChange={() => void saveNotificationSettings()}
2385
+ placeholder="Исключить задачи (через запятую, * — маска)"
2386
+ style={`display:block;width:100%;box-sizing:border-box;padding:8px;background:#1e1e1e;border:1px solid #333;border-radius:6px;color:#fff;font-size:13px;outline:none;opacity:${notificationsEnabled() ? 1 : 0.5}`}
2387
+ />
2388
+ <div style="font-size:11px;color:#8e8e93">
2389
+ Пустой список «только» = все задачи. Исключения важнее включений.
2390
+ </div>
2391
+ </div>
2392
+
2393
+ {/* Шаблоны сообщений (Спринт 20) */}
2394
+ <div style="border-top:1px solid #333;padding-top:10px;display:flex;flex-direction:column;gap:8px">
2395
+ <div style="font-size:12px;color:#e0e0e0;font-weight:600">Шаблоны сообщений</div>
2396
+ <input
2397
+ type="text"
2398
+ value={templateSuccess() || ""}
2399
+ disabled={!notificationsEnabled()}
2400
+ onInput={(e) => setTemplateSuccess(e.currentTarget.value)}
2401
+ onChange={() => void saveNotificationSettings()}
2402
+ placeholder={'✅ Задача "{task}" выполнена ({duration})'}
2403
+ style={`display:block;width:100%;box-sizing:border-box;padding:8px;background:#1e1e1e;border:1px solid #333;border-radius:6px;color:#fff;font-size:12px;outline:none;opacity:${notificationsEnabled() ? 1 : 0.5}`}
2404
+ />
2405
+ <input
2406
+ type="text"
2407
+ value={templateError() || ""}
2408
+ disabled={!notificationsEnabled()}
2409
+ onInput={(e) => setTemplateError(e.currentTarget.value)}
2410
+ onChange={() => void saveNotificationSettings()}
2411
+ placeholder={'❌ Задача "{task}" упала ({duration}){error}'}
2412
+ style={`display:block;width:100%;box-sizing:border-box;padding:8px;background:#1e1e1e;border:1px solid #333;border-radius:6px;color:#fff;font-size:12px;outline:none;opacity:${notificationsEnabled() ? 1 : 0.5}`}
2413
+ />
2414
+ <div style="font-size:11px;color:#8e8e93">
2415
+ Плейсхолдеры: {"{task} {status} {duration} {error} {emoji}"}. Пусто = шаблон по умолчанию.
2416
+ </div>
2417
+ </div>
2418
+
2419
+ {/* Уведомления о матрицах (Спринт 20) */}
2420
+ <div style="border-top:1px solid #333;padding-top:10px;display:flex;flex-direction:column;gap:8px">
2421
+ <div style="font-size:12px;color:#e0e0e0;font-weight:600">Матрицы</div>
2422
+ <label style={`display:flex;align-items:center;gap:8px;font-size:12px;cursor:pointer;opacity:${notificationsEnabled() ? 1 : 0.5}`}>
2423
+ <input
2424
+ type="checkbox"
2425
+ checked={matrixNotifyEnabled()}
2426
+ disabled={!notificationsEnabled()}
2427
+ onChange={(e) => {
2428
+ setMatrixNotifyEnabled(e.currentTarget.checked)
2429
+ void saveNotificationSettings()
2430
+ }}
2431
+ style="accent-color:#5ac8fa;cursor:pointer;margin:0"
2432
+ />
2433
+ Уведомлять о завершении матриц
2434
+ </label>
2435
+ <div style={`display:flex;align-items:center;gap:10px;flex-wrap:wrap;font-size:12px;color:#b0b0b0;opacity:${notificationsEnabled() && matrixNotifyEnabled() ? 1 : 0.5}`}>
2436
+ <label style="display:flex;align-items:center;gap:6px;cursor:pointer">
2437
+ <input
2438
+ type="checkbox"
2439
+ checked={matrixNotifyPartial()}
2440
+ disabled={!notificationsEnabled() || !matrixNotifyEnabled()}
2441
+ onChange={(e) => {
2442
+ setMatrixNotifyPartial(e.currentTarget.checked)
2443
+ void saveNotificationSettings()
2444
+ }}
2445
+ style="accent-color:#5ac8fa;cursor:pointer;margin:0"
2446
+ />
2447
+ partial
2448
+ </label>
2449
+ <label style="display:flex;align-items:center;gap:6px;cursor:pointer">
2450
+ <input
2451
+ type="checkbox"
2452
+ checked={matrixNotifyAllFailed()}
2453
+ disabled={!notificationsEnabled() || !matrixNotifyEnabled()}
2454
+ onChange={(e) => {
2455
+ setMatrixNotifyAllFailed(e.currentTarget.checked)
2456
+ void saveNotificationSettings()
2457
+ }}
2458
+ style="accent-color:#5ac8fa;cursor:pointer;margin:0"
2459
+ />
2460
+ все упали
2461
+ </label>
2462
+ <span>зависший клон, мин:</span>
2463
+ <input
2464
+ type="number"
2465
+ min="0"
2466
+ max="10080"
2467
+ value={matrixStuckMinutes()}
2468
+ disabled={!notificationsEnabled() || !matrixNotifyEnabled()}
2469
+ onInput={(e) => setMatrixStuckMinutes(Number(e.currentTarget.value) || 0)}
2470
+ onChange={() => void saveNotificationSettings()}
2471
+ style="width:72px;padding:4px 6px;background:#1e1e1e;border:1px solid #333;border-radius:4px;color:#fff;font-size:12px;outline:none"
2472
+ />
2473
+ </div>
2474
+ <div style="font-size:11px;color:#8e8e93">
2475
+ Клон, выполняющийся дольше указанного времени, уведомляется один раз. 0 — выключить.
2476
+ </div>
2477
+ </div>
2478
+
2479
+ {/* Дайджест (Спринт 20) */}
2480
+ <div style="border-top:1px solid #333;padding-top:10px;display:flex;flex-direction:column;gap:8px">
2481
+ <div style="font-size:12px;color:#e0e0e0;font-weight:600">Дайджест</div>
2482
+ <label style={`display:flex;align-items:center;gap:8px;font-size:12px;cursor:pointer;opacity:${notificationsEnabled() ? 1 : 0.5}`}>
2483
+ <input
2484
+ type="checkbox"
2485
+ checked={digestEnabled()}
2486
+ disabled={!notificationsEnabled()}
2487
+ onChange={(e) => {
2488
+ setDigestEnabled(e.currentTarget.checked)
2489
+ void saveNotificationSettings()
2490
+ }}
2491
+ style="accent-color:#5ac8fa;cursor:pointer;margin:0"
2492
+ />
2493
+ Отправлять дайджест
2494
+ </label>
2495
+ <div style={`display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:12px;color:#b0b0b0;opacity:${notificationsEnabled() && digestEnabled() ? 1 : 0.5}`}>
2496
+ <select
2497
+ value={digestFrequency()}
2498
+ disabled={!notificationsEnabled() || !digestEnabled()}
2499
+ onChange={(e) => {
2500
+ setDigestFrequency(e.currentTarget.value === "weekly" ? "weekly" : "daily")
2501
+ void saveNotificationSettings()
2502
+ }}
2503
+ style="padding:4px 6px;background:#1e1e1e;border:1px solid #333;border-radius:4px;color:#fff;font-size:12px;outline:none"
2504
+ >
2505
+ <option value="daily">ежедневно</option>
2506
+ <option value="weekly">еженедельно (Пн)</option>
2507
+ </select>
2508
+ <input
2509
+ type="time"
2510
+ value={digestTime()}
2511
+ disabled={!notificationsEnabled() || !digestEnabled()}
2512
+ onInput={(e) => setDigestTime(e.currentTarget.value)}
2513
+ onChange={() => void saveNotificationSettings()}
2514
+ style="padding:4px 6px;background:#1e1e1e;border:1px solid #333;border-radius:4px;color:#fff;font-size:12px;outline:none"
2515
+ />
2516
+ <span style="font-size:11px;color:#8e8e93">
2517
+ {digestLastSentAt()
2518
+ ? `последняя отправка: ${new Date(digestLastSentAt()!).toLocaleString()}`
2519
+ : "ещё не отправлялся"}
2520
+ </span>
2521
+ </div>
2522
+ <div style="font-size:11px;color:#8e8e93">
2523
+ Запуски, success rate, стоимость и топ ошибок за сутки/неделю.
2524
+ </div>
1907
2525
  </div>
1908
2526
 
1909
2527
  <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
@@ -1914,6 +2532,13 @@ export default Plugin.define({
1914
2532
  >
1915
2533
  {testNotificationBusy() ? "Отправка..." : "🧪 Тестовое уведомление"}
1916
2534
  </button>
2535
+ <button
2536
+ onClick={() => void handleSendDigest()}
2537
+ disabled={digestBusy() || !webhookEnabled()}
2538
+ style={`padding:6px 12px;background:#2d7d46;color:white;border:none;border-radius:6px;cursor:${digestBusy() || !webhookEnabled() ? "not-allowed" : "pointer"};font-size:12px;font-weight:500;opacity:${digestBusy() || !webhookEnabled() ? 0.6 : 1}`}
2539
+ >
2540
+ {digestBusy() ? "Отправка..." : "📊 Отправить дайджест сейчас"}
2541
+ </button>
1917
2542
  <span style="font-size:11px;color:#8e8e93">
1918
2543
  ntfy.sh не используется — только webhook.
1919
2544
  </span>
@@ -2026,8 +2651,17 @@ export default Plugin.define({
2026
2651
  <span style="font-size:10px;color:#a0a0a6;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">
2027
2652
  git: {workspace.gitBranch || "—"} · {workspace.gitRemote || "remote не задан"}
2028
2653
  </span>
2654
+ <span style="font-size:10px;color:#8e8e93;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">
2655
+ env: {workspace.env ? `${Object.keys(workspace.env).length} перем.` : "—"}{workspace.envFile ? " · .env-файл" : ""}
2656
+ </span>
2029
2657
  </div>
2030
2658
  <div style="display:flex;gap:4px;flex-shrink:0">
2659
+ <button
2660
+ onClick={() => void handleEditWorkspaceEnv(workspace)}
2661
+ disabled={workspaceBusy()}
2662
+ title="Env-переменные workspace (секреты маскируются в логах)"
2663
+ style="background:transparent;border:none;color:#a0a0a6;cursor:pointer;font-size:14px;padding:2px"
2664
+ >🔑</button>
2031
2665
  <button
2032
2666
  onClick={() => void handleEditWorkspace(workspace)}
2033
2667
  disabled={workspaceBusy()}
@@ -2446,6 +3080,53 @@ export default Plugin.define({
2446
3080
  {cronError() && (
2447
3081
  <div style="display:block;max-height:80px;overflow-y:auto;margin-top:8px;padding:8px;background:#2a1113;border:1px solid #5a1d21;border-radius:6px;font-size:11px;line-height:1.4;color:#ff6b6b;white-space:pre-wrap;word-break:break-word">{cronError()}</div>
2448
3082
  )}
3083
+ <div style="display:block;width:100%;margin-top:12px">
3084
+ <label style="display:block;margin-bottom:8px;font-size:12px;color:#b0b0b0;font-weight:500">Часовой пояс (IANA)</label>
3085
+ <input
3086
+ type="text"
3087
+ list="iana-timezones"
3088
+ value={timezone() || ""}
3089
+ onInput={(e) => setTimezone(e.currentTarget.value)}
3090
+ placeholder="Пусто — системный пояс"
3091
+ style="display:block;width:100%;box-sizing:border-box;padding:8px;background:#1e1e1e;border:1px solid #333;border-radius:6px;color:#fff;font-size:13px;outline:none"
3092
+ />
3093
+ <datalist id="iana-timezones">
3094
+ <option value="Europe/Moscow" />
3095
+ <option value="Europe/London" />
3096
+ <option value="Europe/Berlin" />
3097
+ <option value="America/New_York" />
3098
+ <option value="America/Los_Angeles" />
3099
+ <option value="Asia/Almaty" />
3100
+ <option value="Asia/Tokyo" />
3101
+ <option value="UTC" />
3102
+ </datalist>
3103
+ <div style="display:block;margin-top:6px;font-size:11px;color:#808080">
3104
+ Другая зона — задача будится каждую минуту, cron проверяется с учётом пояса.
3105
+ </div>
3106
+ </div>
3107
+ <div style="display:block;width:100%;margin-top:12px">
3108
+ <label style="display:block;margin-bottom:8px;font-size:12px;color:#b0b0b0;font-weight:500">Окно запуска (необязательно)</label>
3109
+ <div style="display:flex;gap:8px;align-items:center">
3110
+ <input
3111
+ type="time"
3112
+ value={notBefore() || ""}
3113
+ onInput={(e) => setNotBefore(e.currentTarget.value)}
3114
+ title="Начало окна"
3115
+ style="display:block;flex:1;box-sizing:border-box;padding:8px;background:#1e1e1e;border:1px solid #333;border-radius:6px;color:#fff;font-size:13px;outline:none"
3116
+ />
3117
+ <span style="color:#808080;font-size:12px">—</span>
3118
+ <input
3119
+ type="time"
3120
+ value={notAfter() || ""}
3121
+ onInput={(e) => setNotAfter(e.currentTarget.value)}
3122
+ title="Конец окна (может быть меньше начала)"
3123
+ style="display:block;flex:1;box-sizing:border-box;padding:8px;background:#1e1e1e;border:1px solid #333;border-radius:6px;color:#fff;font-size:13px;outline:none"
3124
+ />
3125
+ </div>
3126
+ <div style="display:block;margin-top:6px;font-size:11px;color:#808080">
3127
+ Вне окна запуск переносится на его открытие, а не пропускается. Например 22:00 — 06:00.
3128
+ </div>
3129
+ </div>
2449
3130
  </div>
2450
3131
 
2451
3132
  <div style="display:block;width:100%;margin-bottom:12px">
@@ -2747,7 +3428,7 @@ export default Plugin.define({
2747
3428
  </button>
2748
3429
  {isEditing && (
2749
3430
  <button
2750
- onClick={() => { setEditingJob(null); setName(""); setSchedule("* * * * *"); setPrompt(""); setModel(""); setPriority(DEFAULT_PRIORITY); setRetryCount(0); setRetryDelay(60); setQualityGate(""); setDependsOn([]); setBeforeScript(""); setAfterScript(""); setTriggerType("cron"); setWatchPath(""); setMcpServer(""); setMcpEventName(""); setMcpFilter(""); setWorkingDirectory(""); setWorkspaceId(""); setAllowedTools([]); setDeniedTools([]); resetMatrixForm(); setCronPreset("* * * * *"); setCronError("") }}
3431
+ onClick={() => { setEditingJob(null); setName(""); setSchedule("* * * * *"); setPrompt(""); setModel(""); setPriority(DEFAULT_PRIORITY); setRetryCount(0); setRetryDelay(60); setQualityGate(""); setDependsOn([]); setBeforeScript(""); setAfterScript(""); setTriggerType("cron"); setWatchPath(""); setTimezone(""); setNotBefore(""); setNotAfter(""); setMcpServer(""); setMcpEventName(""); setMcpFilter(""); setWorkingDirectory(""); setWorkspaceId(""); setAllowedTools([]); setDeniedTools([]); resetMatrixForm(); setCronPreset("* * * * *"); setCronError("") }}
2751
3432
  style="background:transparent;border:1px solid #333;border-radius:6px;padding:8px 16px;color:#ff3b30;cursor:pointer;font-size:13px;width:100%"
2752
3433
  >
2753
3434
  Отмена
@@ -2812,6 +3493,70 @@ export default Plugin.define({
2812
3493
  }
2813
3494
  </div>
2814
3495
 
3496
+ {/* Модальный текстовый ввод (замена неработающего в Electron window.prompt) */}
3497
+ {promptOpen() && (
3498
+ <div
3499
+ style="position:fixed;inset:0;background:rgba(0,0,0,0.55);display:flex;align-items:center;justify-content:center;z-index:2000;padding:20px"
3500
+ onClick={() => answerPrompt(null)}
3501
+ >
3502
+ <div
3503
+ onClick={(e) => e.stopPropagation()}
3504
+ style="width:min(540px,100%);background:#1e1e1e;border:1px solid #444;border-radius:10px;padding:16px;display:flex;flex-direction:column;gap:12px;box-shadow:0 12px 40px rgba(0,0,0,0.6)"
3505
+ >
3506
+ <div style="font-size:13px;font-weight:600;color:#e0e0e0;white-space:pre-wrap">{promptTitle()}</div>
3507
+ {promptTitle().includes("KEY=VALUE") ? (
3508
+ <textarea
3509
+ autofocus
3510
+ rows={6}
3511
+ value={promptValue()}
3512
+ onInput={(e) => setPromptValue(e.currentTarget.value)}
3513
+ onKeyDown={(e) => {
3514
+ if (e.key === "Escape") answerPrompt(null)
3515
+ if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
3516
+ e.preventDefault()
3517
+ answerPrompt(promptValue())
3518
+ }
3519
+ e.stopPropagation()
3520
+ }}
3521
+ style="width:100%;box-sizing:border-box;resize:vertical;padding:8px 10px;border-radius:8px;border:1px solid #3a3a3a;background:#141414;color:#e0e0e0;font-family:Menlo, Monaco, 'Courier New', monospace;font-size:12px;outline:none"
3522
+ />
3523
+ ) : (
3524
+ <input
3525
+ autofocus
3526
+ value={promptValue()}
3527
+ onInput={(e) => setPromptValue(e.currentTarget.value)}
3528
+ onKeyDown={(e) => {
3529
+ if (e.key === "Escape") answerPrompt(null)
3530
+ if (e.key === "Enter") {
3531
+ e.preventDefault()
3532
+ answerPrompt(promptValue())
3533
+ }
3534
+ e.stopPropagation()
3535
+ }}
3536
+ style="width:100%;box-sizing:border-box;padding:8px 10px;border-radius:8px;border:1px solid #3a3a3a;background:#141414;color:#e0e0e0;font-size:13px;outline:none"
3537
+ />
3538
+ )}
3539
+ <div style="display:flex;justify-content:flex-end;gap:8px">
3540
+ <button
3541
+ onClick={() => answerPrompt(null)}
3542
+ style="padding:6px 14px;border-radius:6px;border:1px solid #3a3a3a;background:#262626;color:#e0e0e0;font-size:12px;cursor:pointer"
3543
+ >
3544
+ Отмена
3545
+ </button>
3546
+ <button
3547
+ onClick={() => answerPrompt(promptValue())}
3548
+ style="padding:6px 14px;border-radius:6px;border:1px solid #0a84ff;background:#0a84ff;color:#fff;font-size:12px;font-weight:600;cursor:pointer"
3549
+ >
3550
+ ОК
3551
+ </button>
3552
+ </div>
3553
+ {promptTitle().includes("KEY=VALUE") && (
3554
+ <div style="font-size:11px;color:#8e8e93">Ctrl+Enter — сохранить, Escape — отмена</div>
3555
+ )}
3556
+ </div>
3557
+ </div>
3558
+ )}
3559
+
2815
3560
  {/* Панель логов */}
2816
3561
  {logsTask() && (
2817
3562
  <div style="position:fixed;bottom:16px;left:16px;right:16px;background:#1e1e1e;border:1px solid #333;border-radius:8px;padding:0;max-height:300px;overflow:hidden;display:flex;flex-direction:column;z-index:1000">