opencode-windows-scheduler 1.5.0 → 1.5.1
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.
- package/CHANGELOG.md +37 -1
- package/LICENSE +21 -21
- package/README.md +24 -2
- package/ROADMAP-STRATEGY.md +16 -16
- package/ROADMAP.md +410 -141
- package/dist/core/dry-run.d.ts +10 -0
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +55 -34
- package/dist/core/git-trigger.d.ts.map +1 -1
- package/dist/core/git-trigger.js +15 -9
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +48 -22
- package/dist/core/schedule-v2.d.ts.map +1 -1
- package/dist/core/schedule-v2.js +29 -17
- package/dist/core/scheduler/types.d.ts +6 -0
- package/dist/core/scheduler/types.d.ts.map +1 -1
- package/dist/core/scheduler/windows.d.ts +6 -2
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +25 -10
- package/dist/core/telegram.d.ts.map +1 -1
- package/dist/core/telegram.js +13 -10
- package/dist/i18n.d.ts +52 -0
- package/dist/i18n.d.ts.map +1 -0
- package/dist/i18n.js +292 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +781 -179
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +74 -40
- package/dist/rpc.d.ts +15 -2
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +6 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +89 -48
- package/dist/settings.d.ts +3 -0
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +20 -8
- package/dist/task-transfer.d.ts +13 -0
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +11 -0
- package/dist/types.d.ts +11 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +32 -0
- package/docs/ARCHITECTURE.md +36 -1
- package/docs/FEATURES.md +19 -0
- package/docs/README.ru.md +17 -1
- package/gui-experimental.cjs +9 -9
- package/locales/en.json +695 -0
- package/locales/ru.json +695 -0
- package/package.json +6 -3
- package/scripts/test-locale.mjs +44 -0
- package/src/core/dry-run.ts +76 -38
- package/src/core/git-trigger.ts +15 -9
- package/src/core/matrix.ts +52 -26
- package/src/core/schedule-v2.ts +47 -17
- package/src/core/scheduler/types.ts +6 -0
- package/src/core/scheduler/windows.ts +25 -10
- package/src/core/telegram.ts +16 -10
- package/src/gui.tsx +575 -480
- package/src/i18n.ts +339 -0
- package/src/index.ts +943 -191
- package/src/notifications.ts +83 -42
- package/src/rpc.ts +6 -2
- package/src/server.ts +89 -48
- package/src/settings.ts +38 -10
- package/src/task-transfer.ts +24 -0
- package/src/types.ts +37 -0
package/src/index.ts
CHANGED
|
@@ -6,8 +6,16 @@ import { existsSync } from "node:fs";
|
|
|
6
6
|
import fs from "node:fs/promises";
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import { LockManager } from "./core/lock.js";
|
|
9
|
-
import {
|
|
10
|
-
|
|
9
|
+
import {
|
|
10
|
+
LOCK_DIR,
|
|
11
|
+
LOG_DIR,
|
|
12
|
+
PLUGIN_DIR,
|
|
13
|
+
STALE_LOCK_MAX_AGE_MS,
|
|
14
|
+
WRAPPER_DIR,
|
|
15
|
+
sanitizeName,
|
|
16
|
+
validateTaskName,
|
|
17
|
+
} from "./types.js";
|
|
18
|
+
import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun, nextRun as cronNextRun, normalizeActiveDays, activeWindowState, nextWindowOpenDelayMs } from "./core/schedule-v2.js";
|
|
11
19
|
import {
|
|
12
20
|
buildLaunchdOneShotCleanup,
|
|
13
21
|
normalizeOneShotRunAt,
|
|
@@ -39,6 +47,7 @@ import {
|
|
|
39
47
|
import { SchedulerRpc } from "./rpc.js";
|
|
40
48
|
import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
|
|
41
49
|
import { loadSettings, saveSettings } from "./settings.js";
|
|
50
|
+
import { setLocale, t, type Locale } from "./i18n.js";
|
|
42
51
|
import type {
|
|
43
52
|
AuditSettings,
|
|
44
53
|
HistorySettings,
|
|
@@ -89,7 +98,7 @@ import {
|
|
|
89
98
|
import { closeDb, initDb } from "./db/index.js";
|
|
90
99
|
import { migrateJsonToDb } from "./db/migrate.js";
|
|
91
100
|
import { checkJsonBackups, recoverInterruptedRuns } from "./db/recovery.js";
|
|
92
|
-
import { getTask, listMatrixClones, saveTask } from "./db/tasks-repo.js";
|
|
101
|
+
import { getTask, listMatrixClones, listTasks as listTaskDefinitions, saveTask } from "./db/tasks-repo.js";
|
|
93
102
|
import {
|
|
94
103
|
addWorkspace,
|
|
95
104
|
deleteWorkspace,
|
|
@@ -211,7 +220,11 @@ export const matrixSchema = z.object({
|
|
|
211
220
|
|
|
212
221
|
/** Zod-схема аргументов schedule_task */
|
|
213
222
|
export const scheduleTaskSchema = z.object({
|
|
214
|
-
name: z
|
|
223
|
+
name: z
|
|
224
|
+
.string()
|
|
225
|
+
.describe(
|
|
226
|
+
"Unique task name (the plugin prefix is applied automatically). Allowed: letters (including Cyrillic), digits, space, dot, underscore and hyphen."
|
|
227
|
+
),
|
|
215
228
|
schedule: z
|
|
216
229
|
.string()
|
|
217
230
|
.optional()
|
|
@@ -412,6 +425,12 @@ export const scheduleTaskSchema = z.object({
|
|
|
412
425
|
.describe(
|
|
413
426
|
"Role-scoped tool deny-list (takes precedence over allowedTools). Metadata-only."
|
|
414
427
|
),
|
|
428
|
+
runWhenLoggedOff: z
|
|
429
|
+
.boolean()
|
|
430
|
+
.optional()
|
|
431
|
+
.describe(
|
|
432
|
+
"Windows only: run the task even when no user is logged on (/ru SYSTEM). The task runs in session 0 without the user's profile, mapped drives or saved credentials, so tasks that need the user's environment may fail. Creating such a task usually requires an elevated shell. Default false: interactive only — the task runs only while the user is logged on."
|
|
433
|
+
),
|
|
415
434
|
matrix: matrixSchema
|
|
416
435
|
.optional()
|
|
417
436
|
.describe(
|
|
@@ -423,7 +442,7 @@ export const scheduleTaskSchema = z.object({
|
|
|
423
442
|
ctx.addIssue({
|
|
424
443
|
code: z.ZodIssueCode.custom,
|
|
425
444
|
path: ["schedule"],
|
|
426
|
-
message: "
|
|
445
|
+
message: t("tool.error.cronSchedule"),
|
|
427
446
|
});
|
|
428
447
|
}
|
|
429
448
|
if (
|
|
@@ -434,21 +453,21 @@ export const scheduleTaskSchema = z.object({
|
|
|
434
453
|
ctx.addIssue({
|
|
435
454
|
code: z.ZodIssueCode.custom,
|
|
436
455
|
path: ["runAt"],
|
|
437
|
-
message: "
|
|
456
|
+
message: t("tool.error.onceSchedule"),
|
|
438
457
|
});
|
|
439
458
|
}
|
|
440
459
|
if (trigger === "once" && value.matrix) {
|
|
441
460
|
ctx.addIssue({
|
|
442
461
|
code: z.ZodIssueCode.custom,
|
|
443
462
|
path: ["matrix"],
|
|
444
|
-
message: "
|
|
463
|
+
message: t("tool.error.onceMatrixSchema"),
|
|
445
464
|
});
|
|
446
465
|
}
|
|
447
466
|
if (trigger !== "once" && (value.runAt || value.delaySeconds !== undefined)) {
|
|
448
467
|
ctx.addIssue({
|
|
449
468
|
code: z.ZodIssueCode.custom,
|
|
450
469
|
path: ["runAt"],
|
|
451
|
-
message: "
|
|
470
|
+
message: t("tool.error.onceFields"),
|
|
452
471
|
});
|
|
453
472
|
}
|
|
454
473
|
});
|
|
@@ -520,6 +539,12 @@ export const updateTaskSchema = z.object({
|
|
|
520
539
|
.enum(["skip", "postpone", "run"])
|
|
521
540
|
.optional()
|
|
522
541
|
.describe("New behaviour outside the window: postpone (default), skip or run."),
|
|
542
|
+
runWhenLoggedOff: z
|
|
543
|
+
.boolean()
|
|
544
|
+
.optional()
|
|
545
|
+
.describe(
|
|
546
|
+
"Windows only: true runs the task without a logged-on user (/ru SYSTEM, session 0 without the user profile, mapped drives or saved credentials; usually requires an elevated shell). false/omitted keeps the task interactive-only."
|
|
547
|
+
),
|
|
523
548
|
watchGlobs: z
|
|
524
549
|
.array(z.string())
|
|
525
550
|
.optional()
|
|
@@ -629,14 +654,14 @@ export const updateTaskSchema = z.object({
|
|
|
629
654
|
ctx.addIssue({
|
|
630
655
|
code: z.ZodIssueCode.custom,
|
|
631
656
|
path: ["runAt"],
|
|
632
|
-
message: "
|
|
657
|
+
message: t("tool.error.onceFields"),
|
|
633
658
|
});
|
|
634
659
|
}
|
|
635
660
|
if (value.triggerType === "once" && value.matrix) {
|
|
636
661
|
ctx.addIssue({
|
|
637
662
|
code: z.ZodIssueCode.custom,
|
|
638
663
|
path: ["matrix"],
|
|
639
|
-
message: "
|
|
664
|
+
message: t("tool.error.onceMatrixUpdate"),
|
|
640
665
|
});
|
|
641
666
|
}
|
|
642
667
|
});
|
|
@@ -700,13 +725,13 @@ const manageWorkspacesSchema = z.object({
|
|
|
700
725
|
.nullable()
|
|
701
726
|
.optional()
|
|
702
727
|
.describe(
|
|
703
|
-
"
|
|
728
|
+
"Workspace environment variables (key → value). Override envFile values; secrets are masked in logs (add/update)."
|
|
704
729
|
),
|
|
705
730
|
envFile: z
|
|
706
731
|
.string()
|
|
707
732
|
.nullable()
|
|
708
733
|
.optional()
|
|
709
|
-
.describe("
|
|
734
|
+
.describe("Path to the workspace .env file (add/update, null clears it)."),
|
|
710
735
|
});
|
|
711
736
|
|
|
712
737
|
export const matrixControlSchema = z.object({
|
|
@@ -770,6 +795,12 @@ export const manageSettingsSchema = z.object({
|
|
|
770
795
|
.max(16)
|
|
771
796
|
.optional()
|
|
772
797
|
.describe("How many task runs may execute at the same time."),
|
|
798
|
+
locale: z
|
|
799
|
+
.enum(["ru", "en"])
|
|
800
|
+
.optional()
|
|
801
|
+
.describe(
|
|
802
|
+
"Interface language: ru (default) or en. Applies without restart."
|
|
803
|
+
),
|
|
773
804
|
winterMode: z
|
|
774
805
|
.boolean()
|
|
775
806
|
.optional()
|
|
@@ -950,6 +981,90 @@ function wrapExecute<Args>(
|
|
|
950
981
|
};
|
|
951
982
|
}
|
|
952
983
|
|
|
984
|
+
/**
|
|
985
|
+
* Спринт 27.5.2: ближайший запуск по определению задачи, без чтения ОС.
|
|
986
|
+
*
|
|
987
|
+
* - `once` → `runAt` (запланированный момент);
|
|
988
|
+
* - пауза (`paused` или будущий `pausedUntil`) → null;
|
|
989
|
+
* - `cron` → ближайшее совпадение cron с учётом окна и дней недели:
|
|
990
|
+
* * `run` — окно игнорируется;
|
|
991
|
+
* * `skip` — ищем следующее совпадение внутри окна;
|
|
992
|
+
* * `postpone` (по умолчанию) — перенос на открытие окна, как в schedule-gate;
|
|
993
|
+
* - `file`/`git`/`mcp-event` → null (расписания нет).
|
|
994
|
+
*/
|
|
995
|
+
function computeTaskNextRun(
|
|
996
|
+
def:
|
|
997
|
+
| Pick<
|
|
998
|
+
TaskDefinition,
|
|
999
|
+
| "schedule"
|
|
1000
|
+
| "triggerType"
|
|
1001
|
+
| "runAt"
|
|
1002
|
+
| "timezone"
|
|
1003
|
+
| "notBefore"
|
|
1004
|
+
| "notAfter"
|
|
1005
|
+
| "activeDays"
|
|
1006
|
+
| "windowPolicy"
|
|
1007
|
+
| "pausedUntil"
|
|
1008
|
+
>
|
|
1009
|
+
| undefined,
|
|
1010
|
+
options: { paused?: boolean; now?: Date } = {}
|
|
1011
|
+
): string | null {
|
|
1012
|
+
if (!def) return null;
|
|
1013
|
+
if (options.paused) return null;
|
|
1014
|
+
|
|
1015
|
+
const now = options.now ?? new Date();
|
|
1016
|
+
if (def.pausedUntil) {
|
|
1017
|
+
const until = Date.parse(def.pausedUntil);
|
|
1018
|
+
if (Number.isFinite(until) && until > now.getTime()) return null;
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
const type = def.triggerType ?? "cron";
|
|
1022
|
+
if (type === "once") {
|
|
1023
|
+
if (!def.runAt) return null;
|
|
1024
|
+
const at = Date.parse(def.runAt);
|
|
1025
|
+
return Number.isFinite(at) ? new Date(at).toISOString() : null;
|
|
1026
|
+
}
|
|
1027
|
+
if (type !== "cron") return null;
|
|
1028
|
+
|
|
1029
|
+
const schedule = (def.schedule || "").trim();
|
|
1030
|
+
if (!schedule) return null;
|
|
1031
|
+
|
|
1032
|
+
const timeZone = def.timezone?.trim() || undefined;
|
|
1033
|
+
const policy =
|
|
1034
|
+
def.windowPolicy === "skip" || def.windowPolicy === "run"
|
|
1035
|
+
? def.windowPolicy
|
|
1036
|
+
: "postpone";
|
|
1037
|
+
const windowOptions = {
|
|
1038
|
+
notBefore: def.notBefore,
|
|
1039
|
+
notAfter: def.notAfter,
|
|
1040
|
+
days: Array.isArray(def.activeDays) ? def.activeDays : undefined,
|
|
1041
|
+
timeZone,
|
|
1042
|
+
};
|
|
1043
|
+
|
|
1044
|
+
let tick: Date | null;
|
|
1045
|
+
try {
|
|
1046
|
+
tick = cronNextRun(schedule, now, timeZone);
|
|
1047
|
+
} catch {
|
|
1048
|
+
// Некорректное выражение не должно ломать ответ инструмента.
|
|
1049
|
+
return null;
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
// skip-политика может пропустить сколько угодно тиков вне окна;
|
|
1053
|
+
// ограничение защищает от бесконечного перебора (5-летнее окно cron).
|
|
1054
|
+
for (let guard = 0; tick && guard < 600; guard += 1) {
|
|
1055
|
+
if (policy === "run") return tick.toISOString();
|
|
1056
|
+
const state = activeWindowState(tick, windowOptions);
|
|
1057
|
+
if (state.active) return tick.toISOString();
|
|
1058
|
+
if (policy === "skip") {
|
|
1059
|
+
tick = cronNextRun(schedule, tick, timeZone);
|
|
1060
|
+
continue;
|
|
1061
|
+
}
|
|
1062
|
+
// postpone: gate ждёт открытия окна и запускает задачу тогда же.
|
|
1063
|
+
return state.nextOpenAt ? state.nextOpenAt.toISOString() : null;
|
|
1064
|
+
}
|
|
1065
|
+
return null;
|
|
1066
|
+
}
|
|
1067
|
+
|
|
953
1068
|
/** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
|
|
954
1069
|
const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
955
1070
|
const {
|
|
@@ -990,6 +1105,7 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
|
990
1105
|
gitPaths,
|
|
991
1106
|
gitIgnore,
|
|
992
1107
|
gitPollSeconds,
|
|
1108
|
+
runWhenLoggedOff,
|
|
993
1109
|
} = args;
|
|
994
1110
|
|
|
995
1111
|
let effectiveRunAt: string | undefined;
|
|
@@ -1053,7 +1169,9 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
|
1053
1169
|
gitPaths,
|
|
1054
1170
|
gitIgnore,
|
|
1055
1171
|
gitPollSeconds,
|
|
1056
|
-
}
|
|
1172
|
+
},
|
|
1173
|
+
// Спринт 27.5.4: Windows — работать без входа (/ru SYSTEM).
|
|
1174
|
+
runWhenLoggedOff === true
|
|
1057
1175
|
);
|
|
1058
1176
|
} catch (err: any) {
|
|
1059
1177
|
return {
|
|
@@ -1071,13 +1189,31 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
|
1071
1189
|
const workspace = workspaceId ? getWorkspace(workspaceId) : undefined;
|
|
1072
1190
|
const effectiveWorkdir =
|
|
1073
1191
|
workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
|
|
1192
|
+
// Спринт 27.5.2: отдаём ближайший запуск сразу, не дожидаясь обновления
|
|
1193
|
+
// списка задач планировщика ОС (schtasks иногда отдаёт nextRunTime с задержкой).
|
|
1194
|
+
const nextRun = computeTaskNextRun({
|
|
1195
|
+
schedule: schedule ?? "",
|
|
1196
|
+
triggerType: triggerType ?? "cron",
|
|
1197
|
+
runAt: effectiveRunAt,
|
|
1198
|
+
timezone,
|
|
1199
|
+
notBefore,
|
|
1200
|
+
notAfter,
|
|
1201
|
+
activeDays,
|
|
1202
|
+
windowPolicy,
|
|
1203
|
+
});
|
|
1074
1204
|
return {
|
|
1075
1205
|
content: JSON.stringify({
|
|
1076
1206
|
success: true,
|
|
1077
|
-
|
|
1207
|
+
paused: false,
|
|
1208
|
+
nextRun,
|
|
1209
|
+
runWhenLoggedOff: runWhenLoggedOff === true,
|
|
1210
|
+
message: t("tool.task.created", { name }),
|
|
1078
1211
|
task: {
|
|
1079
1212
|
name,
|
|
1080
1213
|
schedule,
|
|
1214
|
+
nextRun,
|
|
1215
|
+
paused: false,
|
|
1216
|
+
runWhenLoggedOff: runWhenLoggedOff === true,
|
|
1081
1217
|
timeoutSeconds: timeoutSeconds ?? 3600,
|
|
1082
1218
|
model: model?.trim() || null,
|
|
1083
1219
|
priority: priority ?? 5,
|
|
@@ -1109,14 +1245,18 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
|
1109
1245
|
|
|
1110
1246
|
/** list_tasks — список задач плагина (та же логика, что и у get_tasks). */
|
|
1111
1247
|
const listTasksExecute = wrapExecute<ListArgs>(async () => {
|
|
1112
|
-
const tasks = await collectTasksView();
|
|
1248
|
+
const { tasks, osAvailable, osError } = await collectTasksView();
|
|
1113
1249
|
|
|
1114
1250
|
if (tasks.length === 0) {
|
|
1115
1251
|
return {
|
|
1116
1252
|
content: JSON.stringify({
|
|
1117
1253
|
success: true,
|
|
1118
|
-
message:
|
|
1254
|
+
message: osAvailable
|
|
1255
|
+
? t("tool.task.listEmpty")
|
|
1256
|
+
: t("tool.task.listOsUnavailable"),
|
|
1119
1257
|
tasks: [],
|
|
1258
|
+
osAvailable,
|
|
1259
|
+
...(osError ? { osError } : {}),
|
|
1120
1260
|
}),
|
|
1121
1261
|
};
|
|
1122
1262
|
}
|
|
@@ -1124,8 +1264,12 @@ const listTasksExecute = wrapExecute<ListArgs>(async () => {
|
|
|
1124
1264
|
return {
|
|
1125
1265
|
content: JSON.stringify({
|
|
1126
1266
|
success: true,
|
|
1127
|
-
message:
|
|
1267
|
+
message: osAvailable
|
|
1268
|
+
? t("tool.task.found", { count: tasks.length })
|
|
1269
|
+
: t("tool.task.foundOsUnavailable", { count: tasks.length }),
|
|
1128
1270
|
tasks,
|
|
1271
|
+
osAvailable,
|
|
1272
|
+
...(osError ? { osError } : {}),
|
|
1129
1273
|
}),
|
|
1130
1274
|
};
|
|
1131
1275
|
});
|
|
@@ -1143,7 +1287,7 @@ async function cancelMatrixRun(
|
|
|
1143
1287
|
(def) => def.name.toLowerCase() === name.trim().toLowerCase()
|
|
1144
1288
|
);
|
|
1145
1289
|
if (!definition?.matrix) {
|
|
1146
|
-
throw new Error(
|
|
1290
|
+
throw new Error(t("tool.error.matrixNotMatrix", { name }));
|
|
1147
1291
|
}
|
|
1148
1292
|
|
|
1149
1293
|
const result = await cancelPendingMatrixClones(definition.name);
|
|
@@ -1160,9 +1304,10 @@ async function cancelMatrixRun(
|
|
|
1160
1304
|
await scheduler.deleteTask(clone.name);
|
|
1161
1305
|
} catch (err: any) {
|
|
1162
1306
|
warnings.push(
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1307
|
+
t("tool.matrix.stopFailed", {
|
|
1308
|
+
clone: clone.name,
|
|
1309
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1310
|
+
})
|
|
1166
1311
|
);
|
|
1167
1312
|
continue;
|
|
1168
1313
|
}
|
|
@@ -1197,30 +1342,40 @@ async function cancelMatrixRun(
|
|
|
1197
1342
|
clone.timezone,
|
|
1198
1343
|
clone.notBefore,
|
|
1199
1344
|
clone.notAfter,
|
|
1200
|
-
clone.pausedUntil
|
|
1345
|
+
clone.pausedUntil,
|
|
1346
|
+
clone.runAt,
|
|
1347
|
+
clone.session,
|
|
1348
|
+
clone.sessionId,
|
|
1349
|
+
clone.sessionMaxRuns,
|
|
1350
|
+
undefined,
|
|
1351
|
+
clone.runWhenLoggedOff,
|
|
1352
|
+
clone.paused
|
|
1201
1353
|
);
|
|
1202
1354
|
} catch (err: any) {
|
|
1203
1355
|
warnings.push(
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1356
|
+
t("tool.matrix.recreateFailed", {
|
|
1357
|
+
clone: clone.name,
|
|
1358
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1359
|
+
})
|
|
1207
1360
|
);
|
|
1208
1361
|
}
|
|
1209
1362
|
}
|
|
1210
1363
|
|
|
1211
1364
|
const parts = [
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1365
|
+
t("tool.matrix.cancelSummary", {
|
|
1366
|
+
matrix: definition.name,
|
|
1367
|
+
cancelled: result.cancelled.length,
|
|
1368
|
+
total: result.aggregate.totalCount,
|
|
1369
|
+
}),
|
|
1215
1370
|
];
|
|
1216
1371
|
if (result.running.length > 0) {
|
|
1217
|
-
parts.push(
|
|
1372
|
+
parts.push(t("tool.matrix.cancelRunning", { count: result.running.length }));
|
|
1218
1373
|
}
|
|
1219
1374
|
if (result.alreadyFinished.length > 0) {
|
|
1220
|
-
parts.push(
|
|
1375
|
+
parts.push(t("tool.matrix.cancelFinished", { count: result.alreadyFinished.length }));
|
|
1221
1376
|
}
|
|
1222
1377
|
if (warnings.length > 0) {
|
|
1223
|
-
parts.push(
|
|
1378
|
+
parts.push(t("tool.matrix.cancelWarnings", { warnings: warnings.join("; ") }));
|
|
1224
1379
|
}
|
|
1225
1380
|
|
|
1226
1381
|
return {
|
|
@@ -1265,6 +1420,83 @@ async function cleanupOrphanedMatrixTasks(): Promise<string[]> {
|
|
|
1265
1420
|
* - удаление родителя-матрицы каскадно удаляет клоны и агрегатор;
|
|
1266
1421
|
* - удаление клона поодиночке запрещено (защита от «сирот» и вечного running).
|
|
1267
1422
|
*/
|
|
1423
|
+
/**
|
|
1424
|
+
* Удаляет файлы-артефакты задачи (wrapper, prompt, log, lock, env).
|
|
1425
|
+
* Отсутствующие файлы игнорируются — операция идемпотентна.
|
|
1426
|
+
*/
|
|
1427
|
+
async function removeTaskArtifacts(name: string): Promise<void> {
|
|
1428
|
+
const sanitized = sanitizeName(name);
|
|
1429
|
+
const candidates = [
|
|
1430
|
+
path.join(WRAPPER_DIR, `run-${sanitized}.cmd`),
|
|
1431
|
+
path.join(WRAPPER_DIR, `run-${sanitized}.sh`),
|
|
1432
|
+
path.join(PLUGIN_DIR, "prompts", `${sanitized}.txt`),
|
|
1433
|
+
path.join(LOG_DIR, `${sanitized}.log`),
|
|
1434
|
+
path.join(PLUGIN_DIR, "env", `${sanitized}.env`),
|
|
1435
|
+
path.join(LOCK_DIR, `${sanitized}.lock`),
|
|
1436
|
+
path.join(LOCK_DIR, `${sanitized}.lock.defer`),
|
|
1437
|
+
path.join(LOCK_DIR, `${sanitized}.lock.force`),
|
|
1438
|
+
];
|
|
1439
|
+
await Promise.all(candidates.map((file) => fs.unlink(file).catch(() => undefined)));
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
/**
|
|
1443
|
+
* Сборщик мусора по wrapper-ам при старте: удаляет файлы задач, которых
|
|
1444
|
+
* больше нет ни в БД, ни в планировщике ОС. Активные (свежий lock) не трогает.
|
|
1445
|
+
*/
|
|
1446
|
+
async function garbageCollectTaskArtifacts(): Promise<void> {
|
|
1447
|
+
let entries: string[];
|
|
1448
|
+
try {
|
|
1449
|
+
entries = await fs.readdir(WRAPPER_DIR);
|
|
1450
|
+
} catch {
|
|
1451
|
+
return;
|
|
1452
|
+
}
|
|
1453
|
+
const wrappers = entries.filter((file) => /^run-.+\.(cmd|sh)$/.test(file));
|
|
1454
|
+
if (wrappers.length === 0) return;
|
|
1455
|
+
|
|
1456
|
+
const known = new Set<string>();
|
|
1457
|
+
try {
|
|
1458
|
+
for (const task of listTaskDefinitions()) known.add(sanitizeName(task.name));
|
|
1459
|
+
} catch {
|
|
1460
|
+
// БД может быть ещё не готова — тогда опираемся на ОС.
|
|
1461
|
+
}
|
|
1462
|
+
try {
|
|
1463
|
+
for (const task of await scheduler.listTasks()) {
|
|
1464
|
+
known.add(sanitizeName(task.taskName || ""));
|
|
1465
|
+
}
|
|
1466
|
+
} catch {
|
|
1467
|
+
// Планировщик недоступен — не удаляем ничего, чтобы не потерять данные.
|
|
1468
|
+
return;
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
let cleaned = 0;
|
|
1472
|
+
for (const file of wrappers) {
|
|
1473
|
+
const stem = file.replace(/^run-/, "").replace(/\.(cmd|sh)$/, "");
|
|
1474
|
+
const lockPath = path.join(LOCK_DIR, `${stem}.lock`);
|
|
1475
|
+
if (known.has(stem)) continue;
|
|
1476
|
+
try {
|
|
1477
|
+
const stat = await fs.stat(lockPath);
|
|
1478
|
+
if (Date.now() - stat.mtimeMs < STALE_LOCK_MAX_AGE_MS) continue;
|
|
1479
|
+
} catch {
|
|
1480
|
+
// lock-файла нет — можно удалять.
|
|
1481
|
+
}
|
|
1482
|
+
const candidates = [
|
|
1483
|
+
path.join(WRAPPER_DIR, `run-${stem}.cmd`),
|
|
1484
|
+
path.join(WRAPPER_DIR, `run-${stem}.sh`),
|
|
1485
|
+
path.join(PLUGIN_DIR, "prompts", `${stem}.txt`),
|
|
1486
|
+
path.join(LOG_DIR, `${stem}.log`),
|
|
1487
|
+
path.join(PLUGIN_DIR, "env", `${stem}.env`),
|
|
1488
|
+
path.join(LOCK_DIR, `${stem}.lock`),
|
|
1489
|
+
path.join(LOCK_DIR, `${stem}.lock.defer`),
|
|
1490
|
+
path.join(LOCK_DIR, `${stem}.lock.force`),
|
|
1491
|
+
];
|
|
1492
|
+
await Promise.all(candidates.map((pathToFile) => fs.unlink(pathToFile).catch(() => undefined)));
|
|
1493
|
+
cleaned += 1;
|
|
1494
|
+
}
|
|
1495
|
+
if (cleaned > 0) {
|
|
1496
|
+
console.log(`[gc] Вычищено мусорных файлов задач: ${cleaned}`);
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1268
1500
|
async function deleteTaskWithFamily(
|
|
1269
1501
|
name: string
|
|
1270
1502
|
): Promise<{ removed: string[]; existed: boolean }> {
|
|
@@ -1302,6 +1534,8 @@ async function deleteTaskWithFamily(
|
|
|
1302
1534
|
} catch {
|
|
1303
1535
|
// Не критично.
|
|
1304
1536
|
}
|
|
1537
|
+
removeTaskArtifacts(child);
|
|
1538
|
+
|
|
1305
1539
|
removed.push(child);
|
|
1306
1540
|
}
|
|
1307
1541
|
}
|
|
@@ -1312,6 +1546,7 @@ async function deleteTaskWithFamily(
|
|
|
1312
1546
|
} catch {
|
|
1313
1547
|
// Определения могло уже не быть — задача всё равно удалена из ОС.
|
|
1314
1548
|
}
|
|
1549
|
+
removeTaskArtifacts(trimmed);
|
|
1315
1550
|
|
|
1316
1551
|
return { removed, existed };
|
|
1317
1552
|
}
|
|
@@ -1327,8 +1562,8 @@ const deleteTaskExecute = wrapExecute<DeleteArgs>(async (args) => {
|
|
|
1327
1562
|
if (!existed && removed.length === 0) {
|
|
1328
1563
|
return {
|
|
1329
1564
|
content: JSON.stringify({
|
|
1330
|
-
success:
|
|
1331
|
-
|
|
1565
|
+
success: true,
|
|
1566
|
+
message: t("tool.task.alreadyAbsent", { name }),
|
|
1332
1567
|
}),
|
|
1333
1568
|
};
|
|
1334
1569
|
}
|
|
@@ -1337,8 +1572,8 @@ const deleteTaskExecute = wrapExecute<DeleteArgs>(async (args) => {
|
|
|
1337
1572
|
success: true,
|
|
1338
1573
|
message:
|
|
1339
1574
|
removed.length > 0
|
|
1340
|
-
?
|
|
1341
|
-
:
|
|
1575
|
+
? t("tool.task.matrixDeletedList", { name, list: removed.join(", ") })
|
|
1576
|
+
: t("tool.task.deleted", { name }),
|
|
1342
1577
|
}),
|
|
1343
1578
|
};
|
|
1344
1579
|
} catch (err: any) {
|
|
@@ -1372,8 +1607,8 @@ const runTaskNowExecute = wrapExecute<RunNowArgs>(async (args) => {
|
|
|
1372
1607
|
content: JSON.stringify({
|
|
1373
1608
|
success: true,
|
|
1374
1609
|
message: alreadyRunning
|
|
1375
|
-
?
|
|
1376
|
-
:
|
|
1610
|
+
? t("tool.task.alreadyRunning", { name })
|
|
1611
|
+
: t("tool.task.started", { name }),
|
|
1377
1612
|
}),
|
|
1378
1613
|
};
|
|
1379
1614
|
});
|
|
@@ -1425,15 +1660,26 @@ async function removeMatrixChildrenFromScheduler(name: string): Promise<string[]
|
|
|
1425
1660
|
*/
|
|
1426
1661
|
async function updateTaskFromInput(
|
|
1427
1662
|
input: UpdateArgs & { newSchedule?: string; newPrompt?: string }
|
|
1428
|
-
): Promise<{
|
|
1663
|
+
): Promise<{
|
|
1664
|
+
success: boolean;
|
|
1665
|
+
message: string;
|
|
1666
|
+
/** Спринт 27.5.2: состояние и ближайший запуск после обновления. */
|
|
1667
|
+
paused?: boolean;
|
|
1668
|
+
nextRun?: string | null;
|
|
1669
|
+
/**
|
|
1670
|
+
* Спринт 27.5.6: при ошибке обновления — удалось ли сохранить прежнюю
|
|
1671
|
+
* версию задачи в планировщике (true — старая версия на месте).
|
|
1672
|
+
*/
|
|
1673
|
+
restored?: boolean;
|
|
1674
|
+
}> {
|
|
1429
1675
|
const name = input.name?.trim();
|
|
1430
1676
|
if (!name) {
|
|
1431
|
-
return { success: false, message: "
|
|
1677
|
+
return { success: false, message: t("tool.error.taskNameMissing") };
|
|
1432
1678
|
}
|
|
1433
1679
|
|
|
1434
1680
|
const previous = getTask(name);
|
|
1435
1681
|
if (!previous) {
|
|
1436
|
-
return { success: false, message:
|
|
1682
|
+
return { success: false, message: t("tool.error.taskNotFound", { name }) };
|
|
1437
1683
|
}
|
|
1438
1684
|
|
|
1439
1685
|
const schedule = clearableString(input.schedule ?? input.newSchedule, previous.schedule);
|
|
@@ -1446,13 +1692,13 @@ async function updateTaskFromInput(
|
|
|
1446
1692
|
if (triggerType === "cron" && !schedule) {
|
|
1447
1693
|
return {
|
|
1448
1694
|
success: false,
|
|
1449
|
-
message:
|
|
1695
|
+
message: t("tool.error.updateCron", { name }),
|
|
1450
1696
|
};
|
|
1451
1697
|
}
|
|
1452
1698
|
if (!prompt) {
|
|
1453
1699
|
return {
|
|
1454
1700
|
success: false,
|
|
1455
|
-
message:
|
|
1701
|
+
message: t("tool.error.updatePrompt", { name }),
|
|
1456
1702
|
};
|
|
1457
1703
|
}
|
|
1458
1704
|
|
|
@@ -1473,7 +1719,7 @@ async function updateTaskFromInput(
|
|
|
1473
1719
|
if (!normalized.ok) {
|
|
1474
1720
|
return {
|
|
1475
1721
|
success: false,
|
|
1476
|
-
message:
|
|
1722
|
+
message: t("tool.error.taskReason", { name, error: normalized.error }),
|
|
1477
1723
|
};
|
|
1478
1724
|
}
|
|
1479
1725
|
runAt = normalized.runAt;
|
|
@@ -1487,7 +1733,7 @@ async function updateTaskFromInput(
|
|
|
1487
1733
|
if (!normalizedSession) {
|
|
1488
1734
|
return {
|
|
1489
1735
|
success: false,
|
|
1490
|
-
message:
|
|
1736
|
+
message: t("tool.error.sessionUnknown", { name, session: String(input.session) }),
|
|
1491
1737
|
};
|
|
1492
1738
|
}
|
|
1493
1739
|
session = normalizedSession;
|
|
@@ -1502,7 +1748,7 @@ async function updateTaskFromInput(
|
|
|
1502
1748
|
) {
|
|
1503
1749
|
return {
|
|
1504
1750
|
success: false,
|
|
1505
|
-
message:
|
|
1751
|
+
message: t("tool.error.sessionMaxRuns", { name }),
|
|
1506
1752
|
};
|
|
1507
1753
|
}
|
|
1508
1754
|
let sessionId = previous.sessionId;
|
|
@@ -1519,9 +1765,7 @@ async function updateTaskFromInput(
|
|
|
1519
1765
|
if (triggerType === "once" && matrixNext) {
|
|
1520
1766
|
return {
|
|
1521
1767
|
success: false,
|
|
1522
|
-
message:
|
|
1523
|
-
`Задача "${name}": one-shot нельзя комбинировать с matrix. ` +
|
|
1524
|
-
`Запустите матрицу вручную или используйте cron/file-триггер.`,
|
|
1768
|
+
message: t("tool.error.oneShotMatrix", { name }),
|
|
1525
1769
|
};
|
|
1526
1770
|
}
|
|
1527
1771
|
|
|
@@ -1553,9 +1797,18 @@ async function updateTaskFromInput(
|
|
|
1553
1797
|
gitPollSeconds: input.gitPollSeconds ?? previous.gitPollSeconds,
|
|
1554
1798
|
};
|
|
1555
1799
|
|
|
1800
|
+
// Спринт 27.5.8: update = пересоздание задачи, поэтому паузу нужно вернуть
|
|
1801
|
+
// после create — иначе задача молча начинает выполняться по расписанию.
|
|
1802
|
+
const wasPaused = Boolean(
|
|
1803
|
+
previous.paused === true ||
|
|
1804
|
+
(previous.pausedUntil && Date.parse(previous.pausedUntil) > Date.now())
|
|
1805
|
+
);
|
|
1806
|
+
|
|
1807
|
+
let previousDeleted = false;
|
|
1556
1808
|
try {
|
|
1557
1809
|
// Обновление = пересоздание в планировщике с сохранением старых значений.
|
|
1558
1810
|
await scheduler.deleteTask(name);
|
|
1811
|
+
previousDeleted = true;
|
|
1559
1812
|
await schedulerCreateTask(
|
|
1560
1813
|
name,
|
|
1561
1814
|
schedule ?? "",
|
|
@@ -1591,7 +1844,9 @@ async function updateTaskFromInput(
|
|
|
1591
1844
|
session,
|
|
1592
1845
|
sessionId,
|
|
1593
1846
|
sessionMaxRuns,
|
|
1594
|
-
triggerExtras
|
|
1847
|
+
triggerExtras,
|
|
1848
|
+
input.runWhenLoggedOff ?? previous.runWhenLoggedOff,
|
|
1849
|
+
wasPaused
|
|
1595
1850
|
);
|
|
1596
1851
|
|
|
1597
1852
|
// Матрица отключена при обновлении — убираем клонов и агрегатор.
|
|
@@ -1603,12 +1858,59 @@ async function updateTaskFromInput(
|
|
|
1603
1858
|
// пересобираем набор файловых watcher-ов.
|
|
1604
1859
|
await refreshTriggers();
|
|
1605
1860
|
|
|
1606
|
-
|
|
1607
|
-
|
|
1861
|
+
// Спринт 27.5.2: после пересоздания задачи сообщаем ближайший запуск,
|
|
1862
|
+
// рассчитанный из нового определения, не дожидаясь ОС.
|
|
1863
|
+
const updated = getTask(name);
|
|
1864
|
+
const paused = wasPaused;
|
|
1608
1865
|
return {
|
|
1609
|
-
success:
|
|
1610
|
-
|
|
1866
|
+
success: true,
|
|
1867
|
+
paused,
|
|
1868
|
+
nextRun: computeTaskNextRun(updated, { paused }),
|
|
1869
|
+
message: t("tool.task.updated", { name }),
|
|
1611
1870
|
};
|
|
1871
|
+
} catch (err: any) {
|
|
1872
|
+
const cause = err instanceof Error ? err.message : String(err);
|
|
1873
|
+
|
|
1874
|
+
// Спринт 27.5.6: задача удалена из ОС, но новую версию создать не удалось.
|
|
1875
|
+
if (!previousDeleted) {
|
|
1876
|
+
return {
|
|
1877
|
+
success: false,
|
|
1878
|
+
restored: true,
|
|
1879
|
+
message: t("tool.task.rollbackKept", { cause }),
|
|
1880
|
+
};
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
// Убираем возможный частичный результат новой попытки: обёртка могла
|
|
1884
|
+
// успеть зарегистрироваться, хотя create вернул ошибку.
|
|
1885
|
+
try {
|
|
1886
|
+
await scheduler.deleteTask(name);
|
|
1887
|
+
} catch {
|
|
1888
|
+
// Задачи могло не быть — это ожидаемо.
|
|
1889
|
+
}
|
|
1890
|
+
|
|
1891
|
+
// Определение в БД ещё не перезаписано, поэтому восстанавливаем ровно
|
|
1892
|
+
// прежнюю версию: расписание, промпт, обёртку и паузу.
|
|
1893
|
+
try {
|
|
1894
|
+
await recreateTaskFromDefinition(previous);
|
|
1895
|
+
await refreshTriggers().catch(() => undefined);
|
|
1896
|
+
return {
|
|
1897
|
+
success: false,
|
|
1898
|
+
restored: true,
|
|
1899
|
+
message: t("tool.task.rollbackRestored", { cause }),
|
|
1900
|
+
};
|
|
1901
|
+
} catch (restoreErr: any) {
|
|
1902
|
+
const restoreMessage =
|
|
1903
|
+
restoreErr instanceof Error ? restoreErr.message : String(restoreErr);
|
|
1904
|
+
return {
|
|
1905
|
+
success: false,
|
|
1906
|
+
restored: false,
|
|
1907
|
+
message: t("tool.task.rollbackFailed", {
|
|
1908
|
+
cause,
|
|
1909
|
+
restore: restoreMessage,
|
|
1910
|
+
name,
|
|
1911
|
+
}),
|
|
1912
|
+
};
|
|
1913
|
+
}
|
|
1612
1914
|
}
|
|
1613
1915
|
}
|
|
1614
1916
|
|
|
@@ -1626,15 +1928,27 @@ async function pauseOrResumeTask(
|
|
|
1626
1928
|
name: string,
|
|
1627
1929
|
paused: boolean,
|
|
1628
1930
|
until?: string
|
|
1629
|
-
): Promise<{
|
|
1931
|
+
): Promise<{
|
|
1932
|
+
success: boolean;
|
|
1933
|
+
message: string;
|
|
1934
|
+
affected: string[];
|
|
1935
|
+
warnings: string[];
|
|
1936
|
+
/** Спринт 27.5.2: состояние и ближайший запуск после мутации. */
|
|
1937
|
+
paused: boolean;
|
|
1938
|
+
nextRun: string | null;
|
|
1939
|
+
pausedUntil: string | null;
|
|
1940
|
+
}> {
|
|
1630
1941
|
const trimmed = name.trim();
|
|
1631
1942
|
const definition = getTask(trimmed);
|
|
1632
1943
|
if (!definition) {
|
|
1633
1944
|
return {
|
|
1634
1945
|
success: false,
|
|
1635
|
-
message:
|
|
1946
|
+
message: t("tool.error.taskNotFound", { name: trimmed }),
|
|
1636
1947
|
affected: [],
|
|
1637
1948
|
warnings: [],
|
|
1949
|
+
paused,
|
|
1950
|
+
nextRun: null,
|
|
1951
|
+
pausedUntil: null,
|
|
1638
1952
|
};
|
|
1639
1953
|
}
|
|
1640
1954
|
|
|
@@ -1645,17 +1959,23 @@ async function pauseOrResumeTask(
|
|
|
1645
1959
|
if (Number.isNaN(parsed)) {
|
|
1646
1960
|
return {
|
|
1647
1961
|
success: false,
|
|
1648
|
-
message:
|
|
1962
|
+
message: t("tool.error.pauseDateInvalid", { name: trimmed, until }),
|
|
1649
1963
|
affected: [],
|
|
1650
1964
|
warnings: [],
|
|
1965
|
+
paused,
|
|
1966
|
+
nextRun: null,
|
|
1967
|
+
pausedUntil: definition.pausedUntil ?? null,
|
|
1651
1968
|
};
|
|
1652
1969
|
}
|
|
1653
1970
|
if (parsed <= Date.now()) {
|
|
1654
1971
|
return {
|
|
1655
1972
|
success: false,
|
|
1656
|
-
message:
|
|
1973
|
+
message: t("tool.error.pauseDatePast", { name: trimmed }),
|
|
1657
1974
|
affected: [],
|
|
1658
1975
|
warnings: [],
|
|
1976
|
+
paused,
|
|
1977
|
+
nextRun: null,
|
|
1978
|
+
pausedUntil: definition.pausedUntil ?? null,
|
|
1659
1979
|
};
|
|
1660
1980
|
}
|
|
1661
1981
|
pausedUntil = new Date(parsed).toISOString();
|
|
@@ -1667,9 +1987,12 @@ async function pauseOrResumeTask(
|
|
|
1667
1987
|
if (targets.length === 0 && definition.matrix) {
|
|
1668
1988
|
return {
|
|
1669
1989
|
success: false,
|
|
1670
|
-
message:
|
|
1990
|
+
message: t("tool.error.matrixNoClones", { name: trimmed }),
|
|
1671
1991
|
affected: [],
|
|
1672
1992
|
warnings: [],
|
|
1993
|
+
paused,
|
|
1994
|
+
nextRun: null,
|
|
1995
|
+
pausedUntil: definition.pausedUntil ?? null,
|
|
1673
1996
|
};
|
|
1674
1997
|
}
|
|
1675
1998
|
|
|
@@ -1690,42 +2013,69 @@ async function pauseOrResumeTask(
|
|
|
1690
2013
|
}
|
|
1691
2014
|
}
|
|
1692
2015
|
|
|
1693
|
-
// Фиксируем (или снимаем)
|
|
2016
|
+
// Фиксируем (или снимаем) паузу в определении задачи. У матрицы
|
|
1694
2017
|
// родитель хранит pausedUntil за всех клонов — их включает авто-resume.
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
: definition.pausedUntil
|
|
1700
|
-
? { pausedUntil: undefined }
|
|
2018
|
+
// Спринт 27.5.8: бессрочная пауза тоже сохраняется в определении, иначе
|
|
2019
|
+
// update_task пересоздаёт задачу включённой и пауза теряется.
|
|
2020
|
+
const definitionUpdates: Partial<TaskDefinition> | undefined = paused
|
|
2021
|
+
? { paused: true, ...(pausedUntil ? { pausedUntil } : {}) }
|
|
2022
|
+
: definition.paused || definition.pausedUntil
|
|
2023
|
+
? { paused: false, pausedUntil: undefined }
|
|
1701
2024
|
: undefined;
|
|
1702
2025
|
if (definitionUpdates && affected.length > 0) {
|
|
1703
2026
|
try {
|
|
1704
2027
|
saveTask({ ...definition, ...definitionUpdates });
|
|
1705
2028
|
} catch (err: any) {
|
|
1706
2029
|
warnings.push(
|
|
1707
|
-
|
|
1708
|
-
err instanceof Error ? err.message : String(err)
|
|
1709
|
-
}
|
|
2030
|
+
t("tool.task.autosave", {
|
|
2031
|
+
error: err instanceof Error ? err.message : String(err),
|
|
2032
|
+
})
|
|
1710
2033
|
);
|
|
1711
2034
|
}
|
|
1712
2035
|
}
|
|
1713
2036
|
|
|
1714
2037
|
const untilText = pausedUntil
|
|
1715
|
-
?
|
|
2038
|
+
? t("tool.task.until", { date: new Date(pausedUntil).toLocaleString() })
|
|
1716
2039
|
: "";
|
|
1717
|
-
const verb = paused ? "
|
|
2040
|
+
const verb = paused ? t("tool.task.paused") : t("tool.task.resumed");
|
|
1718
2041
|
const message = definition.matrix
|
|
1719
|
-
?
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
2042
|
+
? t("tool.task.matrixPaused", {
|
|
2043
|
+
name: trimmed,
|
|
2044
|
+
verb,
|
|
2045
|
+
until: untilText,
|
|
2046
|
+
affected: affected.length,
|
|
2047
|
+
total: targets.length,
|
|
2048
|
+
}) +
|
|
2049
|
+
(warnings.length > 0
|
|
2050
|
+
? t("tool.task.matrixPauseErrors", { warnings: warnings.join("; ") })
|
|
2051
|
+
: "")
|
|
2052
|
+
: t("tool.task.pausedText", {
|
|
2053
|
+
name: trimmed,
|
|
2054
|
+
verb,
|
|
2055
|
+
until: untilText,
|
|
2056
|
+
}) +
|
|
2057
|
+
(warnings.length > 0
|
|
2058
|
+
? t("tool.task.pauseError", { warnings: warnings.join("; ") })
|
|
2059
|
+
: "");
|
|
2060
|
+
|
|
2061
|
+
// Спринт 27.5.2: состояние и ближайший запуск считаем из определения —
|
|
2062
|
+
// schtasks после /change (особенно /enable) отдаёт nextRunTime с задержкой.
|
|
2063
|
+
const effectivePausedUntil = paused
|
|
2064
|
+
? pausedUntil ?? definition.pausedUntil ?? null
|
|
2065
|
+
: null;
|
|
2066
|
+
const after = definitionUpdates
|
|
2067
|
+
? { ...definition, ...definitionUpdates }
|
|
2068
|
+
: { ...definition, paused: false, pausedUntil: undefined };
|
|
2069
|
+
const nextRun = paused ? null : computeTaskNextRun(after);
|
|
1723
2070
|
|
|
1724
2071
|
return {
|
|
1725
2072
|
success: warnings.length === 0,
|
|
1726
2073
|
message,
|
|
1727
2074
|
affected,
|
|
1728
2075
|
warnings,
|
|
2076
|
+
paused,
|
|
2077
|
+
nextRun,
|
|
2078
|
+
pausedUntil: effectivePausedUntil,
|
|
1729
2079
|
};
|
|
1730
2080
|
}
|
|
1731
2081
|
|
|
@@ -1765,7 +2115,11 @@ async function resumeExpiredPauses(): Promise<void> {
|
|
|
1765
2115
|
for (const target of targets) {
|
|
1766
2116
|
await scheduler.resumeTask(target);
|
|
1767
2117
|
}
|
|
1768
|
-
await saveTaskDefinition({
|
|
2118
|
+
await saveTaskDefinition({
|
|
2119
|
+
...definition,
|
|
2120
|
+
pausedUntil: undefined,
|
|
2121
|
+
paused: false,
|
|
2122
|
+
});
|
|
1769
2123
|
console.log(
|
|
1770
2124
|
`[windows-scheduler] Автопродолжение: задача "${definition.name}" включена (пауза истекла).`
|
|
1771
2125
|
);
|
|
@@ -1932,7 +2286,7 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
|
|
|
1932
2286
|
return {
|
|
1933
2287
|
content: JSON.stringify({
|
|
1934
2288
|
success: false,
|
|
1935
|
-
error: "
|
|
2289
|
+
error: t("tool.workspace.needPath"),
|
|
1936
2290
|
}),
|
|
1937
2291
|
};
|
|
1938
2292
|
}
|
|
@@ -1959,7 +2313,7 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
|
|
|
1959
2313
|
return {
|
|
1960
2314
|
content: JSON.stringify({
|
|
1961
2315
|
success: false,
|
|
1962
|
-
error: "
|
|
2316
|
+
error: t("tool.workspace.needUpdateId"),
|
|
1963
2317
|
}),
|
|
1964
2318
|
};
|
|
1965
2319
|
}
|
|
@@ -1974,7 +2328,7 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
|
|
|
1974
2328
|
return {
|
|
1975
2329
|
content: JSON.stringify({
|
|
1976
2330
|
success: false,
|
|
1977
|
-
error: "
|
|
2331
|
+
error: t("tool.workspace.notFound"),
|
|
1978
2332
|
}),
|
|
1979
2333
|
};
|
|
1980
2334
|
}
|
|
@@ -1998,7 +2352,7 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
|
|
|
1998
2352
|
return {
|
|
1999
2353
|
content: JSON.stringify({
|
|
2000
2354
|
success: false,
|
|
2001
|
-
error: "
|
|
2355
|
+
error: t("tool.workspace.needDeleteId"),
|
|
2002
2356
|
}),
|
|
2003
2357
|
};
|
|
2004
2358
|
}
|
|
@@ -2007,8 +2361,8 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
|
|
|
2007
2361
|
content: JSON.stringify({
|
|
2008
2362
|
success: deleted,
|
|
2009
2363
|
message: deleted
|
|
2010
|
-
? "
|
|
2011
|
-
: "
|
|
2364
|
+
? t("tool.workspace.deleted")
|
|
2365
|
+
: t("tool.workspace.notFound"),
|
|
2012
2366
|
}),
|
|
2013
2367
|
};
|
|
2014
2368
|
}
|
|
@@ -2056,8 +2410,8 @@ const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
|
|
|
2056
2410
|
success: true,
|
|
2057
2411
|
message:
|
|
2058
2412
|
removed.length > 0
|
|
2059
|
-
?
|
|
2060
|
-
: "
|
|
2413
|
+
? t("tool.matrix.orphansRemoved", { count: removed.length })
|
|
2414
|
+
: t("tool.matrix.orphansNone"),
|
|
2061
2415
|
removed,
|
|
2062
2416
|
}),
|
|
2063
2417
|
};
|
|
@@ -2068,7 +2422,7 @@ const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
|
|
|
2068
2422
|
return {
|
|
2069
2423
|
content: JSON.stringify({
|
|
2070
2424
|
success: false,
|
|
2071
|
-
error:
|
|
2425
|
+
error: t("tool.matrix.actionName", { action: args.action }),
|
|
2072
2426
|
}),
|
|
2073
2427
|
};
|
|
2074
2428
|
}
|
|
@@ -2137,6 +2491,7 @@ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
|
|
|
2137
2491
|
|
|
2138
2492
|
if (
|
|
2139
2493
|
args.maxConcurrent === undefined &&
|
|
2494
|
+
args.locale === undefined &&
|
|
2140
2495
|
args.winterMode === undefined &&
|
|
2141
2496
|
args.notifications === undefined &&
|
|
2142
2497
|
args.history === undefined &&
|
|
@@ -2146,8 +2501,7 @@ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
|
|
|
2146
2501
|
return {
|
|
2147
2502
|
content: JSON.stringify({
|
|
2148
2503
|
success: false,
|
|
2149
|
-
error:
|
|
2150
|
-
"Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications, history, integrations или audit.",
|
|
2504
|
+
error: t("tool.settings.updateFields"),
|
|
2151
2505
|
settings: current,
|
|
2152
2506
|
}),
|
|
2153
2507
|
};
|
|
@@ -2155,12 +2509,15 @@ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
|
|
|
2155
2509
|
|
|
2156
2510
|
const settings = await saveSettings({
|
|
2157
2511
|
maxConcurrent: args.maxConcurrent,
|
|
2512
|
+
locale: args.locale,
|
|
2158
2513
|
winterMode: args.winterMode,
|
|
2159
2514
|
notifications: args.notifications as NotificationSettings | undefined,
|
|
2160
2515
|
history: args.history as HistorySettings | undefined,
|
|
2161
2516
|
integrations: args.integrations as IntegrationSettings | undefined,
|
|
2162
2517
|
audit: args.audit as AuditSettings | undefined,
|
|
2163
2518
|
});
|
|
2519
|
+
// Локаль процесса меняется сразу — перезапуск плагина не нужен.
|
|
2520
|
+
setLocale(settings.locale);
|
|
2164
2521
|
return { content: JSON.stringify({ success: true, settings }) };
|
|
2165
2522
|
});
|
|
2166
2523
|
|
|
@@ -2173,7 +2530,7 @@ const manageTemplatesExecute = wrapExecute<TemplatesArgs>(async (args) => {
|
|
|
2173
2530
|
if (args.action === "delete") {
|
|
2174
2531
|
const id = args.id?.trim();
|
|
2175
2532
|
if (!id) {
|
|
2176
|
-
return { content: JSON.stringify({ success: false, error: "
|
|
2533
|
+
return { content: JSON.stringify({ success: false, error: t("tool.template.needDeleteId") }) };
|
|
2177
2534
|
}
|
|
2178
2535
|
const before = await loadTemplates();
|
|
2179
2536
|
const existed = before.some((template) => template.id === id);
|
|
@@ -2181,7 +2538,9 @@ const manageTemplatesExecute = wrapExecute<TemplatesArgs>(async (args) => {
|
|
|
2181
2538
|
return {
|
|
2182
2539
|
content: JSON.stringify({
|
|
2183
2540
|
success: existed,
|
|
2184
|
-
message: existed
|
|
2541
|
+
message: existed
|
|
2542
|
+
? t("tool.template.deleted", { id })
|
|
2543
|
+
: t("tool.template.notFound", { id }),
|
|
2185
2544
|
}),
|
|
2186
2545
|
};
|
|
2187
2546
|
}
|
|
@@ -2191,7 +2550,7 @@ const manageTemplatesExecute = wrapExecute<TemplatesArgs>(async (args) => {
|
|
|
2191
2550
|
return {
|
|
2192
2551
|
content: JSON.stringify({
|
|
2193
2552
|
success: false,
|
|
2194
|
-
error: "
|
|
2553
|
+
error: t("tool.template.saveRequired"),
|
|
2195
2554
|
}),
|
|
2196
2555
|
};
|
|
2197
2556
|
}
|
|
@@ -2217,7 +2576,7 @@ const manageProfilesExecute = wrapExecute<ProfilesArgs>(async (args) => {
|
|
|
2217
2576
|
return {
|
|
2218
2577
|
content: JSON.stringify({
|
|
2219
2578
|
success: false,
|
|
2220
|
-
error:
|
|
2579
|
+
error: t("tool.profile.nameRequired", { action: args.action }),
|
|
2221
2580
|
}),
|
|
2222
2581
|
};
|
|
2223
2582
|
}
|
|
@@ -2228,7 +2587,7 @@ const manageProfilesExecute = wrapExecute<ProfilesArgs>(async (args) => {
|
|
|
2228
2587
|
return {
|
|
2229
2588
|
content: JSON.stringify({
|
|
2230
2589
|
success: true,
|
|
2231
|
-
message:
|
|
2590
|
+
message: t("tool.profile.created", { name: meta.name, port: meta.port }),
|
|
2232
2591
|
profile: profile ?? {
|
|
2233
2592
|
name: meta.name,
|
|
2234
2593
|
dir: getProfileDir(meta.name),
|
|
@@ -2249,8 +2608,8 @@ const manageProfilesExecute = wrapExecute<ProfilesArgs>(async (args) => {
|
|
|
2249
2608
|
current,
|
|
2250
2609
|
restartRequired: true,
|
|
2251
2610
|
message: isProfilePinnedByEnv()
|
|
2252
|
-
?
|
|
2253
|
-
:
|
|
2611
|
+
? t("tool.profile.envVar", { name: current })
|
|
2612
|
+
: t("tool.profile.active", { name: sanitizeProfileName(name) }),
|
|
2254
2613
|
}),
|
|
2255
2614
|
};
|
|
2256
2615
|
}
|
|
@@ -2260,8 +2619,8 @@ const manageProfilesExecute = wrapExecute<ProfilesArgs>(async (args) => {
|
|
|
2260
2619
|
content: JSON.stringify({
|
|
2261
2620
|
success: removed,
|
|
2262
2621
|
message: removed
|
|
2263
|
-
?
|
|
2264
|
-
: "
|
|
2622
|
+
? t("tool.profile.deleted", { name: sanitizeProfileName(name) })
|
|
2623
|
+
: t("tool.profile.notFound"),
|
|
2265
2624
|
}),
|
|
2266
2625
|
};
|
|
2267
2626
|
});
|
|
@@ -2277,14 +2636,14 @@ const transferTasksExecute = wrapExecute<TransferArgs>(async (args) => {
|
|
|
2277
2636
|
}
|
|
2278
2637
|
|
|
2279
2638
|
if (!args.data) {
|
|
2280
|
-
return { content: JSON.stringify({ success: false, error: "
|
|
2639
|
+
return { content: JSON.stringify({ success: false, error: t("tool.transfer.importData") }) };
|
|
2281
2640
|
}
|
|
2282
2641
|
const parsed = parseImportJson(args.data);
|
|
2283
2642
|
if (parsed.tasks.length === 0) {
|
|
2284
2643
|
return {
|
|
2285
2644
|
content: JSON.stringify({
|
|
2286
2645
|
success: false,
|
|
2287
|
-
error: "
|
|
2646
|
+
error: t("tool.transfer.noTasks"),
|
|
2288
2647
|
errors: parsed.errors,
|
|
2289
2648
|
}),
|
|
2290
2649
|
};
|
|
@@ -2372,7 +2731,12 @@ const cleanupHistoryExecute = wrapExecute<CleanupHistoryArgs>(async (args) => {
|
|
|
2372
2731
|
success: true,
|
|
2373
2732
|
message: report.skipped
|
|
2374
2733
|
? report.skipped
|
|
2375
|
-
:
|
|
2734
|
+
: t("tool.history.cleaned", {
|
|
2735
|
+
deleted: report.deleted,
|
|
2736
|
+
byAge: report.deletedByAge,
|
|
2737
|
+
byCount: report.deletedByCount,
|
|
2738
|
+
kept: report.kept,
|
|
2739
|
+
}),
|
|
2376
2740
|
report,
|
|
2377
2741
|
}),
|
|
2378
2742
|
};
|
|
@@ -2382,7 +2746,7 @@ const cleanupHistoryExecute = wrapExecute<CleanupHistoryArgs>(async (args) => {
|
|
|
2382
2746
|
const emitEventExecute = wrapExecute<EmitEventArgs>(async (args) => {
|
|
2383
2747
|
const eventName = args.eventName?.trim();
|
|
2384
2748
|
if (!eventName) {
|
|
2385
|
-
return { content: JSON.stringify({ success: false, error: "
|
|
2749
|
+
return { content: JSON.stringify({ success: false, error: t("tool.event.nameRequired") }) };
|
|
2386
2750
|
}
|
|
2387
2751
|
const payload = args.payload ?? {};
|
|
2388
2752
|
const definitions = await loadTaskDefinitions();
|
|
@@ -2412,8 +2776,8 @@ const emitEventExecute = wrapExecute<EmitEventArgs>(async (args) => {
|
|
|
2412
2776
|
success: true,
|
|
2413
2777
|
message:
|
|
2414
2778
|
triggered.length > 0
|
|
2415
|
-
?
|
|
2416
|
-
:
|
|
2779
|
+
? t("tool.event.triggered", { count: triggered.length })
|
|
2780
|
+
: t("tool.event.none", { event: eventName }),
|
|
2417
2781
|
triggered,
|
|
2418
2782
|
}),
|
|
2419
2783
|
};
|
|
@@ -2430,7 +2794,7 @@ const manageSecretsExecute = wrapExecute<SecretsArgs>(async (args) => {
|
|
|
2430
2794
|
return {
|
|
2431
2795
|
content: JSON.stringify({
|
|
2432
2796
|
success: false,
|
|
2433
|
-
error: "
|
|
2797
|
+
error: t("tool.secret.nameRequired"),
|
|
2434
2798
|
}),
|
|
2435
2799
|
};
|
|
2436
2800
|
}
|
|
@@ -2442,8 +2806,8 @@ const manageSecretsExecute = wrapExecute<SecretsArgs>(async (args) => {
|
|
|
2442
2806
|
content: JSON.stringify({
|
|
2443
2807
|
success: existed,
|
|
2444
2808
|
message: existed
|
|
2445
|
-
?
|
|
2446
|
-
:
|
|
2809
|
+
? t("tool.secret.deleted", { name })
|
|
2810
|
+
: t("tool.secret.notFound", { name }),
|
|
2447
2811
|
}),
|
|
2448
2812
|
};
|
|
2449
2813
|
}
|
|
@@ -2453,7 +2817,7 @@ const manageSecretsExecute = wrapExecute<SecretsArgs>(async (args) => {
|
|
|
2453
2817
|
return {
|
|
2454
2818
|
content: JSON.stringify({
|
|
2455
2819
|
success: false,
|
|
2456
|
-
error: "
|
|
2820
|
+
error: t("tool.secret.valueRequired"),
|
|
2457
2821
|
}),
|
|
2458
2822
|
};
|
|
2459
2823
|
}
|
|
@@ -2462,7 +2826,7 @@ const manageSecretsExecute = wrapExecute<SecretsArgs>(async (args) => {
|
|
|
2462
2826
|
return {
|
|
2463
2827
|
content: JSON.stringify({
|
|
2464
2828
|
success: true,
|
|
2465
|
-
message:
|
|
2829
|
+
message: t("tool.secret.saved", { name: item.name }),
|
|
2466
2830
|
secret: item,
|
|
2467
2831
|
}),
|
|
2468
2832
|
};
|
|
@@ -2726,6 +3090,14 @@ export default Plugin.define({
|
|
|
2726
3090
|
// `opencode run` подхватывает opencode.json с MCP-серверами проекта.
|
|
2727
3091
|
projectDirectory = ctx.location?.directory || process.cwd();
|
|
2728
3092
|
|
|
3093
|
+
// Спринт 28: язык интерфейса берём из настроек. Ошибка чтения не должна
|
|
3094
|
+
// мешать старту — в этом случае остаётся локаль по умолчанию (ru).
|
|
3095
|
+
try {
|
|
3096
|
+
setLocale((await loadSettings()).locale);
|
|
3097
|
+
} catch {
|
|
3098
|
+
// Локаль по умолчанию уже активна.
|
|
3099
|
+
}
|
|
3100
|
+
|
|
2729
3101
|
// Спринт 12: SQLite — основное хранилище. Открываем БД, при первом запуске
|
|
2730
3102
|
// автоматически переносим данные из JSON, затем восстанавливаем прерванные
|
|
2731
3103
|
// запуски. Ошибки миграции не должны мешать плагину стартовать.
|
|
@@ -2749,6 +3121,9 @@ export default Plugin.define({
|
|
|
2749
3121
|
);
|
|
2750
3122
|
}
|
|
2751
3123
|
checkJsonBackups();
|
|
3124
|
+
void garbageCollectTaskArtifacts().catch((err) => {
|
|
3125
|
+
console.log(`[gc] Не удалось вычистить мусорные файлы: ${err instanceof Error ? err.message : String(err)}`);
|
|
3126
|
+
});
|
|
2752
3127
|
|
|
2753
3128
|
// Спринт 18: ежедневная очистка истории. Ошибка ретеншна не должна мешать
|
|
2754
3129
|
// плагину стартовать — пишем в лог и продолжаем.
|
|
@@ -3253,7 +3628,12 @@ export default Plugin.define({
|
|
|
3253
3628
|
// schedule_task и create_task использовали один и тот же путь.
|
|
3254
3629
|
const rpcHandlers = {
|
|
3255
3630
|
get_tasks: async () => {
|
|
3256
|
-
|
|
3631
|
+
const view = await collectTasksView();
|
|
3632
|
+
return {
|
|
3633
|
+
tasks: view.tasks,
|
|
3634
|
+
osAvailable: view.osAvailable,
|
|
3635
|
+
...(view.osError ? { osError: view.osError } : {}),
|
|
3636
|
+
};
|
|
3257
3637
|
},
|
|
3258
3638
|
create_task: async (input: unknown) => {
|
|
3259
3639
|
console.log("[windows-scheduler] create_task input:", input);
|
|
@@ -3286,6 +3666,7 @@ export default Plugin.define({
|
|
|
3286
3666
|
delaySeconds,
|
|
3287
3667
|
session,
|
|
3288
3668
|
sessionMaxRuns,
|
|
3669
|
+
runWhenLoggedOff,
|
|
3289
3670
|
} = input as {
|
|
3290
3671
|
name: string;
|
|
3291
3672
|
schedule?: string;
|
|
@@ -3315,12 +3696,13 @@ export default Plugin.define({
|
|
|
3315
3696
|
delaySeconds?: number;
|
|
3316
3697
|
session?: "new" | "reuse" | "last";
|
|
3317
3698
|
sessionMaxRuns?: number;
|
|
3699
|
+
runWhenLoggedOff?: boolean;
|
|
3318
3700
|
};
|
|
3319
3701
|
let effectiveRunAt: string | undefined;
|
|
3320
3702
|
if (triggerType === "once") {
|
|
3321
3703
|
const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
|
|
3322
3704
|
if (!normalized.ok) {
|
|
3323
|
-
return { success: false, message:
|
|
3705
|
+
return { success: false, message: t("tool.error.taskReason", { name, error: normalized.error }) };
|
|
3324
3706
|
}
|
|
3325
3707
|
effectiveRunAt = normalized.runAt;
|
|
3326
3708
|
}
|
|
@@ -3328,7 +3710,7 @@ export default Plugin.define({
|
|
|
3328
3710
|
if (session !== undefined) {
|
|
3329
3711
|
const normalizedSession = normalizeSessionMode(session);
|
|
3330
3712
|
if (!normalizedSession) {
|
|
3331
|
-
return { success: false, message:
|
|
3713
|
+
return { success: false, message: t("tool.error.sessionUnknown", { name, session: String(session) }) };
|
|
3332
3714
|
}
|
|
3333
3715
|
effectiveSession = normalizedSession;
|
|
3334
3716
|
}
|
|
@@ -3336,7 +3718,7 @@ export default Plugin.define({
|
|
|
3336
3718
|
sessionMaxRuns !== undefined &&
|
|
3337
3719
|
(!Number.isInteger(sessionMaxRuns) || sessionMaxRuns < 1)
|
|
3338
3720
|
) {
|
|
3339
|
-
return { success: false, message:
|
|
3721
|
+
return { success: false, message: t("tool.error.sessionMaxRuns", { name }) };
|
|
3340
3722
|
}
|
|
3341
3723
|
const effectiveSessionId =
|
|
3342
3724
|
effectiveSession === "reuse" ? generateSessionId() : undefined;
|
|
@@ -3373,9 +3755,24 @@ export default Plugin.define({
|
|
|
3373
3755
|
effectiveRunAt,
|
|
3374
3756
|
effectiveSession,
|
|
3375
3757
|
effectiveSessionId,
|
|
3376
|
-
sessionMaxRuns
|
|
3758
|
+
sessionMaxRuns,
|
|
3759
|
+
undefined,
|
|
3760
|
+
runWhenLoggedOff === true
|
|
3377
3761
|
);
|
|
3378
|
-
|
|
3762
|
+
const nextRun = computeTaskNextRun({
|
|
3763
|
+
schedule: schedule ?? "",
|
|
3764
|
+
triggerType: triggerType ?? "cron",
|
|
3765
|
+
runAt: effectiveRunAt,
|
|
3766
|
+
timezone,
|
|
3767
|
+
notBefore,
|
|
3768
|
+
notAfter,
|
|
3769
|
+
});
|
|
3770
|
+
return {
|
|
3771
|
+
success: true,
|
|
3772
|
+
paused: false,
|
|
3773
|
+
nextRun,
|
|
3774
|
+
message: t("tool.task.created", { name }),
|
|
3775
|
+
};
|
|
3379
3776
|
} catch (err: any) {
|
|
3380
3777
|
const message = err instanceof Error ? err.message : String(err);
|
|
3381
3778
|
return { success: false, message };
|
|
@@ -3389,8 +3786,11 @@ export default Plugin.define({
|
|
|
3389
3786
|
success: true,
|
|
3390
3787
|
message:
|
|
3391
3788
|
removed.length > 0
|
|
3392
|
-
?
|
|
3393
|
-
|
|
3789
|
+
? t("tool.task.matrixDeletedCount", {
|
|
3790
|
+
name,
|
|
3791
|
+
count: removed.length,
|
|
3792
|
+
})
|
|
3793
|
+
: t("tool.task.deleted", { name }),
|
|
3394
3794
|
};
|
|
3395
3795
|
} catch (err: any) {
|
|
3396
3796
|
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
@@ -3420,8 +3820,8 @@ export default Plugin.define({
|
|
|
3420
3820
|
success: true,
|
|
3421
3821
|
message:
|
|
3422
3822
|
removed.length > 0
|
|
3423
|
-
?
|
|
3424
|
-
: "
|
|
3823
|
+
? t("tool.matrix.orphansRemoved", { count: removed.length })
|
|
3824
|
+
: t("tool.matrix.orphansNone"),
|
|
3425
3825
|
removed,
|
|
3426
3826
|
};
|
|
3427
3827
|
} catch (err: any) {
|
|
@@ -3443,9 +3843,21 @@ export default Plugin.define({
|
|
|
3443
3843
|
const matrixResult = await runMatrix(definition);
|
|
3444
3844
|
const total = definition.matrix.workspaceIds.length;
|
|
3445
3845
|
const message =
|
|
3446
|
-
|
|
3447
|
-
|
|
3448
|
-
|
|
3846
|
+
t("tool.matrix.started", {
|
|
3847
|
+
name,
|
|
3848
|
+
started: matrixResult.started.length,
|
|
3849
|
+
total,
|
|
3850
|
+
}) +
|
|
3851
|
+
(matrixResult.skipped.length
|
|
3852
|
+
? t("tool.matrix.startedSkipped", {
|
|
3853
|
+
count: matrixResult.skipped.length,
|
|
3854
|
+
})
|
|
3855
|
+
: "") +
|
|
3856
|
+
(matrixResult.errors.length
|
|
3857
|
+
? t("tool.matrix.startedErrors", {
|
|
3858
|
+
errors: matrixResult.errors.join("; "),
|
|
3859
|
+
})
|
|
3860
|
+
: ".");
|
|
3449
3861
|
return { success: matrixResult.success, message };
|
|
3450
3862
|
}
|
|
3451
3863
|
// Контроль параллелизма: не позволяем запускать новую задачу,
|
|
@@ -3460,7 +3872,7 @@ export default Plugin.define({
|
|
|
3460
3872
|
return {
|
|
3461
3873
|
success: false,
|
|
3462
3874
|
message:
|
|
3463
|
-
"
|
|
3875
|
+
t("tool.matrix.limit"),
|
|
3464
3876
|
};
|
|
3465
3877
|
}
|
|
3466
3878
|
}
|
|
@@ -3470,9 +3882,9 @@ export default Plugin.define({
|
|
|
3470
3882
|
// в том числе инициированном из GUI, — дублировать запись здесь не нужно.
|
|
3471
3883
|
if (result.alreadyRunning) {
|
|
3472
3884
|
// Мягкое предупреждение: задача уже идёт, это не ошибка запуска.
|
|
3473
|
-
return { success: true, message:
|
|
3885
|
+
return { success: true, message: t("tool.task.alreadyRunning", { name }) };
|
|
3474
3886
|
}
|
|
3475
|
-
return { success: true, message:
|
|
3887
|
+
return { success: true, message: t("tool.task.started", { name }) };
|
|
3476
3888
|
} catch (err: any) {
|
|
3477
3889
|
return { success: false, message: `schtasks error: ${err instanceof Error ? err.message : String(err)}` };
|
|
3478
3890
|
}
|
|
@@ -3484,7 +3896,7 @@ export default Plugin.define({
|
|
|
3484
3896
|
};
|
|
3485
3897
|
const normalized = eventName?.trim();
|
|
3486
3898
|
if (!normalized) {
|
|
3487
|
-
return { success: false, message: "
|
|
3899
|
+
return { success: false, message: t("tool.event.nameRequiredShort"), triggered: [] };
|
|
3488
3900
|
}
|
|
3489
3901
|
|
|
3490
3902
|
// Ищем задачи с MCP-триггером, совпадающим по имени события и фильтру.
|
|
@@ -3521,18 +3933,18 @@ export default Plugin.define({
|
|
|
3521
3933
|
return {
|
|
3522
3934
|
success: true,
|
|
3523
3935
|
triggered,
|
|
3524
|
-
message:
|
|
3936
|
+
message: t("tool.event.processed", { event: normalized, count: triggered.length }),
|
|
3525
3937
|
};
|
|
3526
3938
|
},
|
|
3527
3939
|
pause_task: async (input: unknown) => {
|
|
3528
3940
|
const { name, until } = input as { name: string; until?: string };
|
|
3529
3941
|
const result = await pauseOrResumeTask(name, true, until);
|
|
3530
|
-
return
|
|
3942
|
+
return result;
|
|
3531
3943
|
},
|
|
3532
3944
|
resume_task: async (input: unknown) => {
|
|
3533
3945
|
const { name } = input as { name: string };
|
|
3534
3946
|
const result = await pauseOrResumeTask(name, false);
|
|
3535
|
-
return
|
|
3947
|
+
return result;
|
|
3536
3948
|
},
|
|
3537
3949
|
update_task: async (input: unknown) => {
|
|
3538
3950
|
return await updateTaskFromInput(input as UpdateArgs);
|
|
@@ -3575,8 +3987,12 @@ export default Plugin.define({
|
|
|
3575
3987
|
const report = await runHistoryRetention({ retentionDays, maxRecords });
|
|
3576
3988
|
const message = report.skipped
|
|
3577
3989
|
? report.skipped
|
|
3578
|
-
:
|
|
3579
|
-
|
|
3990
|
+
: t("tool.history.cleaned", {
|
|
3991
|
+
deleted: report.deleted,
|
|
3992
|
+
byAge: report.deletedByAge,
|
|
3993
|
+
byCount: report.deletedByCount,
|
|
3994
|
+
kept: report.kept,
|
|
3995
|
+
});
|
|
3580
3996
|
return {
|
|
3581
3997
|
success: true,
|
|
3582
3998
|
message,
|
|
@@ -3591,9 +4007,9 @@ export default Plugin.define({
|
|
|
3591
4007
|
} catch (err: any) {
|
|
3592
4008
|
return {
|
|
3593
4009
|
success: false,
|
|
3594
|
-
message:
|
|
3595
|
-
err instanceof Error ? err.message : String(err)
|
|
3596
|
-
}
|
|
4010
|
+
message: t("tool.history.cleanFailed", {
|
|
4011
|
+
error: err instanceof Error ? err.message : String(err),
|
|
4012
|
+
}),
|
|
3597
4013
|
deleted: 0,
|
|
3598
4014
|
deletedByAge: 0,
|
|
3599
4015
|
deletedByCount: 0,
|
|
@@ -3677,7 +4093,7 @@ export default Plugin.define({
|
|
|
3677
4093
|
const { parentId } = input as { parentId?: string; name?: string };
|
|
3678
4094
|
const target = (parentId ?? "").trim();
|
|
3679
4095
|
if (!target) {
|
|
3680
|
-
return { success: false, error: "
|
|
4096
|
+
return { success: false, error: t("tool.matrix.parentMissing") };
|
|
3681
4097
|
}
|
|
3682
4098
|
try {
|
|
3683
4099
|
const report = aggregateMatrixResults(target);
|
|
@@ -3770,7 +4186,7 @@ export default Plugin.define({
|
|
|
3770
4186
|
};
|
|
3771
4187
|
const workspace = updateWorkspace(id, { name, path: workspacePath, color, env, envFile });
|
|
3772
4188
|
if (!workspace) {
|
|
3773
|
-
return { success: false, error: "
|
|
4189
|
+
return { success: false, error: t("tool.workspace.notFound") };
|
|
3774
4190
|
}
|
|
3775
4191
|
// env-файлы существующих задач перегенерируются сразу (Спринт 21).
|
|
3776
4192
|
await refreshWorkspaceEnvFiles(workspace.id);
|
|
@@ -3793,8 +4209,8 @@ export default Plugin.define({
|
|
|
3793
4209
|
return {
|
|
3794
4210
|
success: deleted,
|
|
3795
4211
|
message: deleted
|
|
3796
|
-
? "
|
|
3797
|
-
: "
|
|
4212
|
+
? t("tool.workspace.deleted")
|
|
4213
|
+
: t("tool.workspace.notFound"),
|
|
3798
4214
|
};
|
|
3799
4215
|
} catch (err: any) {
|
|
3800
4216
|
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
@@ -3817,8 +4233,8 @@ export default Plugin.define({
|
|
|
3817
4233
|
current,
|
|
3818
4234
|
restartRequired: true,
|
|
3819
4235
|
message: isProfilePinnedByEnv()
|
|
3820
|
-
?
|
|
3821
|
-
:
|
|
4236
|
+
? t("tool.profile.envVarLong", { name: current })
|
|
4237
|
+
: t("tool.profile.active", { name: sanitizeProfileName(name) }),
|
|
3822
4238
|
};
|
|
3823
4239
|
} catch (err: any) {
|
|
3824
4240
|
return {
|
|
@@ -3836,7 +4252,7 @@ export default Plugin.define({
|
|
|
3836
4252
|
const profile = listProfiles().find((item) => item.name === meta.name);
|
|
3837
4253
|
return {
|
|
3838
4254
|
success: true,
|
|
3839
|
-
message:
|
|
4255
|
+
message: t("tool.profile.created", { name: meta.name, port: meta.port }),
|
|
3840
4256
|
profile: profile ?? {
|
|
3841
4257
|
name: meta.name,
|
|
3842
4258
|
dir: getProfileDir(meta.name),
|
|
@@ -3859,8 +4275,8 @@ export default Plugin.define({
|
|
|
3859
4275
|
return {
|
|
3860
4276
|
success: removed,
|
|
3861
4277
|
message: removed
|
|
3862
|
-
?
|
|
3863
|
-
: "
|
|
4278
|
+
? t("tool.profile.deleted", { name: sanitizeProfileName(name) })
|
|
4279
|
+
: t("tool.profile.notFound"),
|
|
3864
4280
|
};
|
|
3865
4281
|
} catch (err: any) {
|
|
3866
4282
|
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
@@ -3870,8 +4286,9 @@ export default Plugin.define({
|
|
|
3870
4286
|
return await loadSettings();
|
|
3871
4287
|
},
|
|
3872
4288
|
save_settings: async (input: unknown) => {
|
|
3873
|
-
const { maxConcurrent, winterMode, notifications, history, integrations, audit } = input as {
|
|
4289
|
+
const { maxConcurrent, locale, winterMode, notifications, history, integrations, audit } = input as {
|
|
3874
4290
|
maxConcurrent?: number;
|
|
4291
|
+
locale?: Locale;
|
|
3875
4292
|
winterMode?: boolean;
|
|
3876
4293
|
notifications?: NotificationSettings;
|
|
3877
4294
|
history?: HistorySettings;
|
|
@@ -3881,6 +4298,7 @@ export default Plugin.define({
|
|
|
3881
4298
|
const current = await loadSettings();
|
|
3882
4299
|
if (
|
|
3883
4300
|
maxConcurrent === undefined &&
|
|
4301
|
+
locale === undefined &&
|
|
3884
4302
|
winterMode === undefined &&
|
|
3885
4303
|
notifications === undefined &&
|
|
3886
4304
|
history === undefined &&
|
|
@@ -3890,6 +4308,7 @@ export default Plugin.define({
|
|
|
3890
4308
|
return {
|
|
3891
4309
|
success: false,
|
|
3892
4310
|
maxConcurrent: current.maxConcurrent,
|
|
4311
|
+
locale: current.locale,
|
|
3893
4312
|
winterMode: current.winterMode,
|
|
3894
4313
|
notifications: current.notifications,
|
|
3895
4314
|
history: current.history,
|
|
@@ -3899,15 +4318,19 @@ export default Plugin.define({
|
|
|
3899
4318
|
}
|
|
3900
4319
|
const settings = await saveSettings({
|
|
3901
4320
|
maxConcurrent,
|
|
4321
|
+
locale,
|
|
3902
4322
|
winterMode,
|
|
3903
4323
|
notifications,
|
|
3904
4324
|
history,
|
|
3905
4325
|
integrations,
|
|
3906
4326
|
audit,
|
|
3907
4327
|
});
|
|
4328
|
+
// Локаль процесса меняется сразу — перезапуск не нужен.
|
|
4329
|
+
setLocale(settings.locale);
|
|
3908
4330
|
return {
|
|
3909
4331
|
success: true,
|
|
3910
4332
|
maxConcurrent: settings.maxConcurrent,
|
|
4333
|
+
locale: settings.locale,
|
|
3911
4334
|
winterMode: settings.winterMode,
|
|
3912
4335
|
notifications: settings.notifications,
|
|
3913
4336
|
history: settings.history,
|
|
@@ -3932,15 +4355,15 @@ export default Plugin.define({
|
|
|
3932
4355
|
const source = (input ?? {}) as { name?: string; value?: string };
|
|
3933
4356
|
const name = (source.name ?? "").trim();
|
|
3934
4357
|
if (!name) {
|
|
3935
|
-
return { success: false, message: "
|
|
4358
|
+
return { success: false, message: t("tool.secret.needName") };
|
|
3936
4359
|
}
|
|
3937
4360
|
if (typeof source.value !== "string" || source.value.length === 0) {
|
|
3938
|
-
return { success: false, message: "
|
|
4361
|
+
return { success: false, message: t("tool.secret.needValue") };
|
|
3939
4362
|
}
|
|
3940
4363
|
const secret = setSecret(name, source.value);
|
|
3941
4364
|
return {
|
|
3942
4365
|
success: true,
|
|
3943
|
-
message:
|
|
4366
|
+
message: t("tool.secret.saved", { name: secret.name }),
|
|
3944
4367
|
secret,
|
|
3945
4368
|
};
|
|
3946
4369
|
} catch (err: any) {
|
|
@@ -3954,15 +4377,15 @@ export default Plugin.define({
|
|
|
3954
4377
|
try {
|
|
3955
4378
|
const name = (((input ?? {}) as { name?: string }).name ?? "").trim();
|
|
3956
4379
|
if (!name) {
|
|
3957
|
-
return { success: false, message: "
|
|
4380
|
+
return { success: false, message: t("tool.secret.needName") };
|
|
3958
4381
|
}
|
|
3959
4382
|
const existed = hasSecret(name);
|
|
3960
4383
|
deleteSecret(name);
|
|
3961
4384
|
return {
|
|
3962
4385
|
success: existed,
|
|
3963
4386
|
message: existed
|
|
3964
|
-
?
|
|
3965
|
-
:
|
|
4387
|
+
? t("tool.secret.deleted", { name })
|
|
4388
|
+
: t("tool.secret.notFound", { name }),
|
|
3966
4389
|
};
|
|
3967
4390
|
} catch (err: any) {
|
|
3968
4391
|
return {
|
|
@@ -4007,7 +4430,7 @@ export default Plugin.define({
|
|
|
4007
4430
|
if (!source?.name?.trim() || !source?.prompt?.trim()) {
|
|
4008
4431
|
return {
|
|
4009
4432
|
success: false,
|
|
4010
|
-
error: "
|
|
4433
|
+
error: t("tool.template.namePromptRequired"),
|
|
4011
4434
|
};
|
|
4012
4435
|
}
|
|
4013
4436
|
const template = await saveTemplate({
|
|
@@ -4034,7 +4457,7 @@ export default Plugin.define({
|
|
|
4034
4457
|
delete_template: async (input: unknown) => {
|
|
4035
4458
|
const { id } = input as { id?: string };
|
|
4036
4459
|
if (!id) {
|
|
4037
|
-
return { success: false, error: "
|
|
4460
|
+
return { success: false, error: t("tool.template.needId") };
|
|
4038
4461
|
}
|
|
4039
4462
|
try {
|
|
4040
4463
|
await deleteTemplate(id);
|
|
@@ -4062,14 +4485,14 @@ export default Plugin.define({
|
|
|
4062
4485
|
import_tasks: async (input: unknown) => {
|
|
4063
4486
|
const { data } = input as { data?: string };
|
|
4064
4487
|
if (!data) {
|
|
4065
|
-
return { success: false, error: "
|
|
4488
|
+
return { success: false, error: t("tool.transfer.noData") };
|
|
4066
4489
|
}
|
|
4067
4490
|
try {
|
|
4068
4491
|
const parsed = parseImportJson(data);
|
|
4069
4492
|
if (parsed.tasks.length === 0) {
|
|
4070
4493
|
return {
|
|
4071
4494
|
success: false,
|
|
4072
|
-
error: "
|
|
4495
|
+
error: t("tool.transfer.noTasksInFile"),
|
|
4073
4496
|
errors: parsed.errors,
|
|
4074
4497
|
};
|
|
4075
4498
|
}
|
|
@@ -4108,7 +4531,22 @@ export default Plugin.define({
|
|
|
4108
4531
|
def.notBefore,
|
|
4109
4532
|
def.notAfter,
|
|
4110
4533
|
def.pausedUntil,
|
|
4111
|
-
def.runAt
|
|
4534
|
+
def.runAt,
|
|
4535
|
+
def.session ?? "new",
|
|
4536
|
+
def.sessionId,
|
|
4537
|
+
def.sessionMaxRuns,
|
|
4538
|
+
{
|
|
4539
|
+
activeDays: def.activeDays,
|
|
4540
|
+
windowPolicy: def.windowPolicy,
|
|
4541
|
+
watchGlobs: def.watchGlobs,
|
|
4542
|
+
watchIgnore: def.watchIgnore,
|
|
4543
|
+
gitBranch: def.gitBranch,
|
|
4544
|
+
gitPaths: def.gitPaths,
|
|
4545
|
+
gitIgnore: def.gitIgnore,
|
|
4546
|
+
gitPollSeconds: def.gitPollSeconds,
|
|
4547
|
+
},
|
|
4548
|
+
def.runWhenLoggedOff === true,
|
|
4549
|
+
def.paused === true
|
|
4112
4550
|
);
|
|
4113
4551
|
await saveTaskDefinition(def);
|
|
4114
4552
|
imported.push(def.name);
|
|
@@ -4147,7 +4585,7 @@ export default Plugin.define({
|
|
|
4147
4585
|
// Повторный вызов не создаёт второй сервер — защита от двойного запуска
|
|
4148
4586
|
// реализована внутри startDashboardServer.
|
|
4149
4587
|
const dashboard = await startDashboardServer({
|
|
4150
|
-
getTasks: collectTasksView,
|
|
4588
|
+
getTasks: async () => (await collectTasksView()).tasks,
|
|
4151
4589
|
runTask: (name) => runTaskEntry(name),
|
|
4152
4590
|
deleteTask: async (name) => {
|
|
4153
4591
|
await deleteTaskWithFamily(name);
|
|
@@ -4196,7 +4634,7 @@ function resolveMatrixExtraConfig(
|
|
|
4196
4634
|
matrix.concurrency < 1
|
|
4197
4635
|
) {
|
|
4198
4636
|
throw new Error(
|
|
4199
|
-
|
|
4637
|
+
t("tool.error.matrixConcurrency", { task: name })
|
|
4200
4638
|
);
|
|
4201
4639
|
}
|
|
4202
4640
|
extra.concurrency = Math.floor(matrix.concurrency);
|
|
@@ -4209,8 +4647,10 @@ function resolveMatrixExtraConfig(
|
|
|
4209
4647
|
const workspaceKey = key.trim();
|
|
4210
4648
|
if (!allowed.has(workspaceKey)) {
|
|
4211
4649
|
throw new Error(
|
|
4212
|
-
|
|
4213
|
-
|
|
4650
|
+
t("tool.error.matrixOverride", {
|
|
4651
|
+
task: name,
|
|
4652
|
+
workspace: workspaceKey,
|
|
4653
|
+
})
|
|
4214
4654
|
);
|
|
4215
4655
|
}
|
|
4216
4656
|
if (!value || typeof value !== "object") continue;
|
|
@@ -4295,8 +4735,28 @@ async function schedulerCreateTask(
|
|
|
4295
4735
|
/** Сколько запусков переживает reuse-сессия до ротации (0/undefined — без ограничения). */
|
|
4296
4736
|
sessionMaxRuns?: number,
|
|
4297
4737
|
/** Спринт 27: дни недели, политика окна, glob- и git-фильтры. */
|
|
4298
|
-
triggerExtras?: TriggerExtras
|
|
4738
|
+
triggerExtras?: TriggerExtras,
|
|
4739
|
+
/** Спринт 27.5.4: Windows — запускать без входа пользователя (/ru SYSTEM). */
|
|
4740
|
+
runWhenLoggedOff?: boolean,
|
|
4741
|
+
/**
|
|
4742
|
+
* Спринт 27.5.8: пересоздать задачу сразу отключённой (пауза переживает
|
|
4743
|
+
* update). Для матрицы пауза применяется к клонам.
|
|
4744
|
+
*/
|
|
4745
|
+
paused?: boolean
|
|
4299
4746
|
): Promise<void> {
|
|
4747
|
+
// Спринт 27.5 (hotfix 1.5.1): проверяем имя до создания wrapper/prompt и записи
|
|
4748
|
+
// в БД. Недопустимые символы отклоняются с понятным сообщением, а не ошибкой
|
|
4749
|
+
// schtasks; имя нормализуется (trim) для всех путей: MCP, RPC и импорт.
|
|
4750
|
+
const normalizedName = name.trim();
|
|
4751
|
+
const nameError = validateTaskName(normalizedName);
|
|
4752
|
+
if (nameError) {
|
|
4753
|
+
throw new Error(nameError);
|
|
4754
|
+
}
|
|
4755
|
+
name = normalizedName;
|
|
4756
|
+
// Для отката файлов: при обновлении существующей задачи файлы переиспользуются,
|
|
4757
|
+
// удалять их при сбое нельзя — в БД остаётся прежнее определение.
|
|
4758
|
+
const definitionExisted = Boolean(getTask(normalizedName));
|
|
4759
|
+
|
|
4300
4760
|
const normalizedModel = model?.trim() || undefined;
|
|
4301
4761
|
const normalizedPriority = normalizePriority(priority);
|
|
4302
4762
|
const normalizedBefore = beforeScript?.trim() || undefined;
|
|
@@ -4305,6 +4765,10 @@ async function schedulerCreateTask(
|
|
|
4305
4765
|
const normalizedNotBefore = notBefore?.trim() || undefined;
|
|
4306
4766
|
const normalizedNotAfter = notAfter?.trim() || undefined;
|
|
4307
4767
|
const normalizedPausedUntil = pausedUntil?.trim() || undefined;
|
|
4768
|
+
// Спринт 27.5.4: true → задача работает без входа (Windows /ru SYSTEM).
|
|
4769
|
+
const normalizedRunWhenLoggedOff = runWhenLoggedOff === true ? true : undefined;
|
|
4770
|
+
// Спринт 27.5.8: пауза сохраняется при пересоздании задачи.
|
|
4771
|
+
const normalizedPaused = paused === true ? true : undefined;
|
|
4308
4772
|
// Спринт 27: дни недели, политика окна и glob/git-фильтры.
|
|
4309
4773
|
const normalizeGlobList = (raw?: string[]): string[] | undefined => {
|
|
4310
4774
|
if (!Array.isArray(raw)) return undefined;
|
|
@@ -4349,7 +4813,7 @@ async function schedulerCreateTask(
|
|
|
4349
4813
|
if (effectiveTriggerType === "once") {
|
|
4350
4814
|
const normalized = normalizeOneShotRunAt({ runAt });
|
|
4351
4815
|
if (!normalized.ok) {
|
|
4352
|
-
throw new Error(
|
|
4816
|
+
throw new Error(t("tool.error.taskReason", { name, error: normalized.error }));
|
|
4353
4817
|
}
|
|
4354
4818
|
effectiveRunAt = normalized.runAt;
|
|
4355
4819
|
}
|
|
@@ -4360,7 +4824,12 @@ async function schedulerCreateTask(
|
|
|
4360
4824
|
if (session !== undefined) {
|
|
4361
4825
|
const normalizedSession = normalizeSessionMode(session);
|
|
4362
4826
|
if (!normalizedSession) {
|
|
4363
|
-
throw new Error(
|
|
4827
|
+
throw new Error(
|
|
4828
|
+
t("tool.error.sessionUnknown", {
|
|
4829
|
+
name,
|
|
4830
|
+
session: String(session),
|
|
4831
|
+
})
|
|
4832
|
+
);
|
|
4364
4833
|
}
|
|
4365
4834
|
effectiveSession = normalizedSession;
|
|
4366
4835
|
}
|
|
@@ -4385,7 +4854,7 @@ async function schedulerCreateTask(
|
|
|
4385
4854
|
};
|
|
4386
4855
|
if (Array.isArray(allowedTools) && allowedTools.filter((t) => typeof t === "string" && t.trim()).length === 0) {
|
|
4387
4856
|
throw new Error(
|
|
4388
|
-
|
|
4857
|
+
t("tool.error.allowedToolsEmpty", { task: name })
|
|
4389
4858
|
);
|
|
4390
4859
|
}
|
|
4391
4860
|
const normalizedAllowedTools = normalizeToolList(allowedTools);
|
|
@@ -4397,7 +4866,7 @@ async function schedulerCreateTask(
|
|
|
4397
4866
|
if (matrix) {
|
|
4398
4867
|
if (workspaceId?.trim()) {
|
|
4399
4868
|
throw new Error(
|
|
4400
|
-
|
|
4869
|
+
t("tool.error.workspaceIdConflict", { task: name })
|
|
4401
4870
|
);
|
|
4402
4871
|
}
|
|
4403
4872
|
const ids = Array.from(
|
|
@@ -4409,18 +4878,26 @@ async function schedulerCreateTask(
|
|
|
4409
4878
|
)
|
|
4410
4879
|
);
|
|
4411
4880
|
if (ids.length === 0) {
|
|
4412
|
-
throw new Error(
|
|
4881
|
+
throw new Error(
|
|
4882
|
+
t("tool.error.workspaceIdsEmpty", { task: name })
|
|
4883
|
+
);
|
|
4413
4884
|
}
|
|
4414
4885
|
for (const id of ids) {
|
|
4415
4886
|
const ws = getWorkspace(id);
|
|
4416
4887
|
if (!ws) {
|
|
4417
|
-
throw new Error(
|
|
4888
|
+
throw new Error(
|
|
4889
|
+
t("tool.error.workspaceMissing", { task: name, id })
|
|
4890
|
+
);
|
|
4418
4891
|
}
|
|
4419
4892
|
try {
|
|
4420
4893
|
validateWorkspacePath(ws.path);
|
|
4421
4894
|
} catch {
|
|
4422
4895
|
throw new Error(
|
|
4423
|
-
|
|
4896
|
+
t("tool.error.workspaceUnavailable", {
|
|
4897
|
+
task: name,
|
|
4898
|
+
workspace: ws.name,
|
|
4899
|
+
path: ws.path,
|
|
4900
|
+
})
|
|
4424
4901
|
);
|
|
4425
4902
|
}
|
|
4426
4903
|
}
|
|
@@ -4442,7 +4919,7 @@ async function schedulerCreateTask(
|
|
|
4442
4919
|
|
|
4443
4920
|
// MCP-триггер без имени события бессмыслен — валидируем до создания файлов.
|
|
4444
4921
|
if (effectiveTriggerType === "mcp-event" && !normalizedMcpEvent) {
|
|
4445
|
-
throw new Error("
|
|
4922
|
+
throw new Error(t("tool.error.mcpEventRequired"));
|
|
4446
4923
|
}
|
|
4447
4924
|
// Спринт 27: git-триггеру нужен git-репозиторий в рабочей директории.
|
|
4448
4925
|
if (effectiveTriggerType === "git") {
|
|
@@ -4451,12 +4928,12 @@ async function schedulerCreateTask(
|
|
|
4451
4928
|
: workingDirectory?.trim() || projectDirectory || process.cwd();
|
|
4452
4929
|
if (!gitCwd) {
|
|
4453
4930
|
throw new Error(
|
|
4454
|
-
|
|
4931
|
+
t("tool.error.gitCwdRequired", { task: name })
|
|
4455
4932
|
);
|
|
4456
4933
|
}
|
|
4457
4934
|
if (!readGitBranch(gitCwd)) {
|
|
4458
4935
|
throw new Error(
|
|
4459
|
-
|
|
4936
|
+
t("tool.error.gitNoRepo", { task: name, path: gitCwd })
|
|
4460
4937
|
);
|
|
4461
4938
|
}
|
|
4462
4939
|
}
|
|
@@ -4472,8 +4949,10 @@ async function schedulerCreateTask(
|
|
|
4472
4949
|
}
|
|
4473
4950
|
if (normalizedTz && !isValidIanaTimeZone(normalizedTz)) {
|
|
4474
4951
|
throw new Error(
|
|
4475
|
-
|
|
4476
|
-
|
|
4952
|
+
t("tool.error.timezone", {
|
|
4953
|
+
task: name,
|
|
4954
|
+
timezone: normalizedTz,
|
|
4955
|
+
})
|
|
4477
4956
|
);
|
|
4478
4957
|
}
|
|
4479
4958
|
const windowError = validateLaunchWindow(
|
|
@@ -4481,7 +4960,7 @@ async function schedulerCreateTask(
|
|
|
4481
4960
|
normalizedNotAfter
|
|
4482
4961
|
);
|
|
4483
4962
|
if (windowError) {
|
|
4484
|
-
throw new Error(
|
|
4963
|
+
throw new Error(t("tool.error.window", { task: name, error: windowError }));
|
|
4485
4964
|
}
|
|
4486
4965
|
}
|
|
4487
4966
|
// Спринт 27: окно и дни недели применимы и к событийным триггерам
|
|
@@ -4489,7 +4968,7 @@ async function schedulerCreateTask(
|
|
|
4489
4968
|
if (effectiveTriggerType !== "cron") {
|
|
4490
4969
|
const windowError = validateLaunchWindow(normalizedNotBefore, normalizedNotAfter);
|
|
4491
4970
|
if (windowError) {
|
|
4492
|
-
throw new Error(
|
|
4971
|
+
throw new Error(t("tool.error.window", { task: name, error: windowError }));
|
|
4493
4972
|
}
|
|
4494
4973
|
}
|
|
4495
4974
|
|
|
@@ -4522,13 +5001,22 @@ async function schedulerCreateTask(
|
|
|
4522
5001
|
const normalizedWorkspaceId = workspaceId?.trim() || undefined;
|
|
4523
5002
|
const workspace = normalizedWorkspaceId ? getWorkspace(normalizedWorkspaceId) : undefined;
|
|
4524
5003
|
if (normalizedWorkspaceId && !workspace) {
|
|
4525
|
-
throw new Error(
|
|
5004
|
+
throw new Error(
|
|
5005
|
+
t("tool.error.workspaceIdMissing", {
|
|
5006
|
+
id: normalizedWorkspaceId,
|
|
5007
|
+
})
|
|
5008
|
+
);
|
|
4526
5009
|
}
|
|
4527
5010
|
if (workspace) {
|
|
4528
5011
|
try {
|
|
4529
5012
|
validateWorkspacePath(workspace.path);
|
|
4530
5013
|
} catch {
|
|
4531
|
-
throw new Error(
|
|
5014
|
+
throw new Error(
|
|
5015
|
+
t("tool.error.workspacePathMissing", {
|
|
5016
|
+
name: workspace.name,
|
|
5017
|
+
path: workspace.path,
|
|
5018
|
+
})
|
|
5019
|
+
);
|
|
4532
5020
|
}
|
|
4533
5021
|
if (workingDirectory?.trim() && workingDirectory.trim() !== workspace.path) {
|
|
4534
5022
|
console.warn(
|
|
@@ -4553,7 +5041,11 @@ async function schedulerCreateTask(
|
|
|
4553
5041
|
await fs.mkdir(LOG_DIR, { recursive: true });
|
|
4554
5042
|
await fs.writeFile(logFile, "", "utf8");
|
|
4555
5043
|
} catch (err: any) {
|
|
4556
|
-
throw new Error(
|
|
5044
|
+
throw new Error(
|
|
5045
|
+
t("tool.error.prepareFiles", {
|
|
5046
|
+
error: err.message || String(err),
|
|
5047
|
+
})
|
|
5048
|
+
);
|
|
4557
5049
|
}
|
|
4558
5050
|
|
|
4559
5051
|
// Обёртка зависит от платформы:
|
|
@@ -4611,9 +5103,24 @@ async function schedulerCreateTask(
|
|
|
4611
5103
|
});
|
|
4612
5104
|
}
|
|
4613
5105
|
} catch (err: any) {
|
|
4614
|
-
throw new Error(
|
|
5106
|
+
throw new Error(
|
|
5107
|
+
t("tool.error.wrapper", {
|
|
5108
|
+
error: err.message || String(err),
|
|
5109
|
+
})
|
|
5110
|
+
);
|
|
4615
5111
|
}
|
|
4616
5112
|
|
|
5113
|
+
// 27.5.5.3: при сбое создания новой задачи убираем подготовленные файлы.
|
|
5114
|
+
// При обновлении файлы переиспользуются существующей задачей — не удаляем.
|
|
5115
|
+
const rollbackArtifacts = async (): Promise<void> => {
|
|
5116
|
+
if (definitionExisted) return;
|
|
5117
|
+
await Promise.all(
|
|
5118
|
+
[wrapperPath, promptFile, logFile, taskEnvFile].map((file) =>
|
|
5119
|
+
file ? fs.unlink(file).catch(() => undefined) : Promise.resolve()
|
|
5120
|
+
)
|
|
5121
|
+
);
|
|
5122
|
+
};
|
|
5123
|
+
|
|
4617
5124
|
try {
|
|
4618
5125
|
// Бэкенд сам преобразует cron в родное расписание ОС.
|
|
4619
5126
|
await scheduler.createTask({
|
|
@@ -4630,11 +5137,55 @@ async function schedulerCreateTask(
|
|
|
4630
5137
|
timezone: normalizedTz,
|
|
4631
5138
|
notBefore: normalizedNotBefore,
|
|
4632
5139
|
notAfter: normalizedNotAfter,
|
|
5140
|
+
runWhenLoggedOff: normalizedRunWhenLoggedOff,
|
|
4633
5141
|
});
|
|
4634
5142
|
} catch (err: any) {
|
|
5143
|
+
await rollbackArtifacts();
|
|
4635
5144
|
throw new Error(err instanceof Error ? err.message : String(err));
|
|
4636
5145
|
}
|
|
4637
5146
|
|
|
5147
|
+
// Проверяем фактическое наличие задачи в планировщике: до 3 попыток с паузой
|
|
5148
|
+
// 200 мс. Это ловит случай, когда ОС/обёртка вернула код 0, но задачи нет.
|
|
5149
|
+
const isListed = (tasks: Awaited<ReturnType<typeof scheduler.listTasks>>): boolean =>
|
|
5150
|
+
tasks.some(
|
|
5151
|
+
(task) => (task.taskName || "").trim().toLowerCase() === name.toLowerCase()
|
|
5152
|
+
);
|
|
5153
|
+
let listedTasks: Awaited<ReturnType<typeof scheduler.listTasks>> | undefined;
|
|
5154
|
+
let verifyQueryError: unknown;
|
|
5155
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
5156
|
+
try {
|
|
5157
|
+
listedTasks = await scheduler.listTasks();
|
|
5158
|
+
if (isListed(listedTasks)) break;
|
|
5159
|
+
} catch (err) {
|
|
5160
|
+
verifyQueryError = err;
|
|
5161
|
+
}
|
|
5162
|
+
if (attempt < 2) {
|
|
5163
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
5164
|
+
}
|
|
5165
|
+
}
|
|
5166
|
+
if (listedTasks && !isListed(listedTasks)) {
|
|
5167
|
+
await rollbackArtifacts();
|
|
5168
|
+
throw new Error(
|
|
5169
|
+
t("tool.error.schedulerNotConfirmed", {
|
|
5170
|
+
task: name,
|
|
5171
|
+
scheduler: scheduler.title,
|
|
5172
|
+
}) +
|
|
5173
|
+
" " +
|
|
5174
|
+
(definitionExisted
|
|
5175
|
+
? t("tool.error.schedulerKeptFiles")
|
|
5176
|
+
: t("tool.error.schedulerRemovedFiles"))
|
|
5177
|
+
);
|
|
5178
|
+
}
|
|
5179
|
+
if (!listedTasks && verifyQueryError) {
|
|
5180
|
+
// Список получить не удалось — не удаляем возможно созданную задачу,
|
|
5181
|
+
// но явно предупреждаем: проверка наличия не выполнена.
|
|
5182
|
+
console.warn(
|
|
5183
|
+
`[windows-scheduler] Задача "${name}" создана, но проверить её в планировщике не удалось: ${
|
|
5184
|
+
verifyQueryError instanceof Error ? verifyQueryError.message : String(verifyQueryError)
|
|
5185
|
+
}`
|
|
5186
|
+
);
|
|
5187
|
+
}
|
|
5188
|
+
|
|
4638
5189
|
// Сохраняем определение задачи для последующего экспорта/импорта.
|
|
4639
5190
|
// Определение до перезаписи: нужно и для очереди матрицы, и для счётчика сессии.
|
|
4640
5191
|
const previousDefinition = getTask(name);
|
|
@@ -4675,6 +5226,10 @@ async function schedulerCreateTask(
|
|
|
4675
5226
|
timezone: normalizedTz,
|
|
4676
5227
|
notBefore: normalizedNotBefore,
|
|
4677
5228
|
notAfter: normalizedNotAfter,
|
|
5229
|
+
// Спринт 27.5.4: режим входа (Windows: /ru SYSTEM при true).
|
|
5230
|
+
runWhenLoggedOff: normalizedRunWhenLoggedOff,
|
|
5231
|
+
// Спринт 27.5.8: бессрочная пауза переживает пересоздание.
|
|
5232
|
+
paused: normalizedPaused,
|
|
4678
5233
|
// Спринт 27: дни недели, политика окна, glob- и git-фильтры.
|
|
4679
5234
|
activeDays: normalizedActiveDays,
|
|
4680
5235
|
windowPolicy: normalizedWindowPolicy,
|
|
@@ -4746,7 +5301,14 @@ async function schedulerCreateTask(
|
|
|
4746
5301
|
clone.timezone,
|
|
4747
5302
|
clone.notBefore,
|
|
4748
5303
|
clone.notAfter,
|
|
4749
|
-
clone.pausedUntil
|
|
5304
|
+
clone.pausedUntil,
|
|
5305
|
+
clone.runAt,
|
|
5306
|
+
clone.session,
|
|
5307
|
+
clone.sessionId,
|
|
5308
|
+
clone.sessionMaxRuns,
|
|
5309
|
+
undefined,
|
|
5310
|
+
clone.runWhenLoggedOff,
|
|
5311
|
+
clone.paused
|
|
4750
5312
|
);
|
|
4751
5313
|
};
|
|
4752
5314
|
|
|
@@ -4761,6 +5323,8 @@ async function schedulerCreateTask(
|
|
|
4761
5323
|
} catch {
|
|
4762
5324
|
// Не критично.
|
|
4763
5325
|
}
|
|
5326
|
+
// Спринт 27.5.7: при откате прогона не оставляем и файлы клона.
|
|
5327
|
+
await removeTaskArtifacts(child);
|
|
4764
5328
|
};
|
|
4765
5329
|
|
|
4766
5330
|
// Создаёт/обновляет/удаляет matrix-complete по текущему определению.
|
|
@@ -4775,8 +5339,10 @@ async function schedulerCreateTask(
|
|
|
4775
5339
|
await schedulerCreateTask(
|
|
4776
5340
|
aggregatorName,
|
|
4777
5341
|
schedule,
|
|
4778
|
-
|
|
4779
|
-
|
|
5342
|
+
t("tool.matrix.completed", {
|
|
5343
|
+
name,
|
|
5344
|
+
clones: cloneNames.join(", "),
|
|
5345
|
+
}),
|
|
4780
5346
|
timeoutSeconds,
|
|
4781
5347
|
undefined,
|
|
4782
5348
|
undefined,
|
|
@@ -4818,15 +5384,146 @@ async function schedulerCreateTask(
|
|
|
4818
5384
|
for (const child of removeMatrixChildren(name)) {
|
|
4819
5385
|
await removeChild(child);
|
|
4820
5386
|
}
|
|
4821
|
-
|
|
4822
|
-
|
|
4823
|
-
|
|
5387
|
+
// Спринт 27.5.7: если клон не создался, откатываем весь прогон. Иначе
|
|
5388
|
+
// остаётся родитель с половиной клонов — он выглядит рабочим, но часть
|
|
5389
|
+
// workspace никогда не запускается. Ошибку expandMatrixTask (неизвестный
|
|
5390
|
+
// workspace) обрабатываем там же: родитель уже записан в БД.
|
|
5391
|
+
const createdInRun: string[] = [];
|
|
5392
|
+
try {
|
|
5393
|
+
const clones = expandMatrixTask(taskDefinition);
|
|
5394
|
+
for (const clone of clones) {
|
|
5395
|
+
try {
|
|
5396
|
+
await createClone(clone);
|
|
5397
|
+
createdInRun.push(clone.name);
|
|
5398
|
+
} catch (err: any) {
|
|
5399
|
+
const workspaceLabel = clone.workspaceId
|
|
5400
|
+
? getWorkspace(clone.workspaceId)?.name ?? clone.workspaceId
|
|
5401
|
+
: "без workspace";
|
|
5402
|
+
throw new Error(
|
|
5403
|
+
t("tool.error.matrixCloneFailed", {
|
|
5404
|
+
clone: clone.name,
|
|
5405
|
+
workspace: workspaceLabel,
|
|
5406
|
+
error: err instanceof Error ? err.message : String(err),
|
|
5407
|
+
})
|
|
5408
|
+
);
|
|
5409
|
+
}
|
|
5410
|
+
}
|
|
5411
|
+
await syncAggregator();
|
|
5412
|
+
} catch (err: any) {
|
|
5413
|
+
for (const child of [...createdInRun].reverse()) {
|
|
5414
|
+
await removeChild(child);
|
|
5415
|
+
}
|
|
5416
|
+
const aggregatorName = matrixCompleteName(name);
|
|
5417
|
+
if (getTask(aggregatorName)) {
|
|
5418
|
+
await removeChild(aggregatorName);
|
|
5419
|
+
}
|
|
5420
|
+
// Новая матрица: без клонов родитель бесполезен — убираем и его,
|
|
5421
|
+
// вместе с подготовленными файлами обёртки.
|
|
5422
|
+
if (!definitionExisted) {
|
|
5423
|
+
try {
|
|
5424
|
+
await scheduler.deleteTask(name);
|
|
5425
|
+
} catch {
|
|
5426
|
+
// Задачи могло не быть: бэкенд уже вернул ошибку.
|
|
5427
|
+
}
|
|
5428
|
+
try {
|
|
5429
|
+
await removeTaskDefinition(name);
|
|
5430
|
+
} catch {
|
|
5431
|
+
// Не критично: запись могла не сохраниться.
|
|
5432
|
+
}
|
|
5433
|
+
await rollbackArtifacts();
|
|
5434
|
+
}
|
|
5435
|
+
throw new Error(
|
|
5436
|
+
t("tool.error.matrixExpandRuntime", {
|
|
5437
|
+
name,
|
|
5438
|
+
error: err instanceof Error ? err.message : String(err),
|
|
5439
|
+
})
|
|
5440
|
+
);
|
|
5441
|
+
}
|
|
5442
|
+
}
|
|
5443
|
+
}
|
|
5444
|
+
|
|
5445
|
+
// Спринт 27.5.8: пересозданная задача должна остаться на паузе. У матрицы
|
|
5446
|
+
// пауза применяется к клонам — родитель сам никогда не выполняется.
|
|
5447
|
+
if (normalizedPaused) {
|
|
5448
|
+
const pauseTargets = normalizedMatrix
|
|
5449
|
+
? listMatrixClones(name).map((clone) => clone.name)
|
|
5450
|
+
: [name];
|
|
5451
|
+
for (const target of pauseTargets) {
|
|
5452
|
+
try {
|
|
5453
|
+
await scheduler.pauseTask(target);
|
|
5454
|
+
} catch (err: any) {
|
|
5455
|
+
console.warn(
|
|
5456
|
+
`[windows-scheduler] Задача "${target}": пауза не восстановлена после пересоздания: ${
|
|
5457
|
+
err instanceof Error ? err.message : String(err)
|
|
5458
|
+
}`
|
|
5459
|
+
);
|
|
4824
5460
|
}
|
|
4825
|
-
await syncAggregator();
|
|
4826
5461
|
}
|
|
4827
5462
|
}
|
|
4828
5463
|
}
|
|
4829
5464
|
|
|
5465
|
+
/**
|
|
5466
|
+
* Спринт 27.5.6: восстановление задачи из определения в БД.
|
|
5467
|
+
*
|
|
5468
|
+
* update_task пересоздаёт задачу в планировщике (delete + create). Раньше при
|
|
5469
|
+
* сбое create после успешного delete старая версия терялась навсегда: в ОС её
|
|
5470
|
+
* уже нет, а в БД лежит новое (не применённое) определение. Здесь мы заново
|
|
5471
|
+
* создаём задачу из прежнего определения — обёртка, промпт, расписание и
|
|
5472
|
+
* пауза восстанавливаются тем же путём, что и при обычном create.
|
|
5473
|
+
*/
|
|
5474
|
+
async function recreateTaskFromDefinition(definition: TaskDefinition): Promise<void> {
|
|
5475
|
+
const paused = Boolean(
|
|
5476
|
+
definition.paused === true ||
|
|
5477
|
+
(definition.pausedUntil && Date.parse(definition.pausedUntil) > Date.now())
|
|
5478
|
+
);
|
|
5479
|
+
await schedulerCreateTask(
|
|
5480
|
+
definition.name,
|
|
5481
|
+
definition.schedule ?? "",
|
|
5482
|
+
definition.prompt,
|
|
5483
|
+
definition.timeoutSeconds,
|
|
5484
|
+
definition.workingDirectory,
|
|
5485
|
+
definition.retryCount,
|
|
5486
|
+
definition.retryDelay,
|
|
5487
|
+
definition.qualityGate,
|
|
5488
|
+
definition.nextTaskOnSuccess,
|
|
5489
|
+
definition.nextTaskOnError,
|
|
5490
|
+
definition.triggerType ?? "cron",
|
|
5491
|
+
definition.watchPath,
|
|
5492
|
+
Array.isArray(definition.dependsOn) ? definition.dependsOn : undefined,
|
|
5493
|
+
definition.model,
|
|
5494
|
+
definition.priority,
|
|
5495
|
+
definition.beforeScript,
|
|
5496
|
+
definition.afterScript,
|
|
5497
|
+
definition.mcpEvent,
|
|
5498
|
+
definition.workspaceId,
|
|
5499
|
+
definition.allowedTools,
|
|
5500
|
+
definition.deniedTools,
|
|
5501
|
+
definition.matrix,
|
|
5502
|
+
definition.matrixParentId,
|
|
5503
|
+
"create",
|
|
5504
|
+
definition.timezone,
|
|
5505
|
+
definition.notBefore,
|
|
5506
|
+
definition.notAfter,
|
|
5507
|
+
definition.pausedUntil,
|
|
5508
|
+
definition.runAt,
|
|
5509
|
+
definition.session ?? "new",
|
|
5510
|
+
definition.sessionId,
|
|
5511
|
+
definition.sessionMaxRuns,
|
|
5512
|
+
{
|
|
5513
|
+
activeDays: definition.activeDays,
|
|
5514
|
+
windowPolicy: definition.windowPolicy,
|
|
5515
|
+
watchGlobs: definition.watchGlobs,
|
|
5516
|
+
watchIgnore: definition.watchIgnore,
|
|
5517
|
+
gitBranch: definition.gitBranch,
|
|
5518
|
+
gitPaths: definition.gitPaths,
|
|
5519
|
+
gitIgnore: definition.gitIgnore,
|
|
5520
|
+
gitPollSeconds: definition.gitPollSeconds,
|
|
5521
|
+
},
|
|
5522
|
+
definition.runWhenLoggedOff,
|
|
5523
|
+
paused
|
|
5524
|
+
);
|
|
5525
|
+
}
|
|
5526
|
+
|
|
4830
5527
|
/**
|
|
4831
5528
|
* Запуск задачи «как есть», но с учётом матрицы: родитель раскладывается
|
|
4832
5529
|
* на клоны, а не выполняет свой промпт.
|
|
@@ -4857,20 +5554,60 @@ async function runTaskEntry(name: string): Promise<{ alreadyRunning: boolean }>
|
|
|
4857
5554
|
}
|
|
4858
5555
|
}
|
|
4859
5556
|
|
|
5557
|
+
/**
|
|
5558
|
+
* Спринт 27.5.3: чтение задач ОС с одним повтором.
|
|
5559
|
+
*
|
|
5560
|
+
* Сразу после мутации (create/delete/pause/resume) `schtasks /query` иногда
|
|
5561
|
+
* отдаёт пустой список, хотя в БД задачи уже есть, или падает. Один короткий
|
|
5562
|
+
* retry убирает ложный «задач нет»; если ОС так и не ответила осмысленно —
|
|
5563
|
+
* возвращаем `osAvailable: false`, и вызывающий код показывает состояние БД.
|
|
5564
|
+
*/
|
|
5565
|
+
async function readOsTasksWithRetry(
|
|
5566
|
+
expectNonEmpty: boolean,
|
|
5567
|
+
delayMs = 300
|
|
5568
|
+
): Promise<{
|
|
5569
|
+
tasks: Awaited<ReturnType<typeof scheduler.listTasks>>;
|
|
5570
|
+
osAvailable: boolean;
|
|
5571
|
+
osError?: string;
|
|
5572
|
+
}> {
|
|
5573
|
+
let lastError: string | undefined;
|
|
5574
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
5575
|
+
if (attempt > 0) {
|
|
5576
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
5577
|
+
}
|
|
5578
|
+
try {
|
|
5579
|
+
const tasks = await scheduler.listTasks();
|
|
5580
|
+
if (tasks.length > 0 || !expectNonEmpty) {
|
|
5581
|
+
return { tasks, osAvailable: true };
|
|
5582
|
+
}
|
|
5583
|
+
lastError = "планировщик ОС вернул пустой список, хотя в БД есть задачи";
|
|
5584
|
+
} catch (err) {
|
|
5585
|
+
lastError = err instanceof Error ? err.message : String(err);
|
|
5586
|
+
}
|
|
5587
|
+
}
|
|
5588
|
+
return { tasks: [], osAvailable: false, osError: lastError };
|
|
5589
|
+
}
|
|
5590
|
+
|
|
4860
5591
|
/**
|
|
4861
5592
|
* Собирает задачи плагина в формате, который отдают оба потребителя:
|
|
4862
5593
|
* RPC get_tasks (GUI) и инструмент list_tasks (агент).
|
|
5594
|
+
*
|
|
5595
|
+
* Спринт 27.5.3: возвращает также состояние чтения ОС. Если ОС недоступна,
|
|
5596
|
+
* `tasks` — состояние из БД (задачи помечены `orphaned: true`), а не пустой
|
|
5597
|
+
* массив: иначе GUI и агент решали бы, что задач нет.
|
|
4863
5598
|
*/
|
|
4864
5599
|
async function collectTasksView() {
|
|
4865
|
-
const
|
|
5600
|
+
const defs = await loadTaskDefinitions();
|
|
5601
|
+
const osRead = await readOsTasksWithRetry(defs.length > 0);
|
|
5602
|
+
const tasks = osRead.tasks;
|
|
4866
5603
|
|
|
4867
5604
|
// Читаем историю один раз, чтобы определить финальный статус по последней записи.
|
|
4868
5605
|
const history = await loadHistory();
|
|
4869
5606
|
// loadHistory() отдаёт записи от новых к старым; helper оставляет самую свежую.
|
|
4870
5607
|
const lastByTask = latestHistoryByTask(history);
|
|
4871
5608
|
|
|
4872
|
-
//
|
|
4873
|
-
|
|
5609
|
+
// Определения задач читаются один раз заранее (см. выше) — расписание,
|
|
5610
|
+
// повторы, цепочки, директория.
|
|
4874
5611
|
const workspaces = listWorkspaces();
|
|
4875
5612
|
const workspaceById = new Map(workspaces.map((workspace) => [workspace.id, workspace]));
|
|
4876
5613
|
|
|
@@ -4915,7 +5652,7 @@ async function collectTasksView() {
|
|
|
4915
5652
|
})),
|
|
4916
5653
|
];
|
|
4917
5654
|
|
|
4918
|
-
|
|
5655
|
+
const view = sources.map(({ task: t, orphaned }) => {
|
|
4919
5656
|
// Все бэкенды возвращают короткие имена (без папки планировщика).
|
|
4920
5657
|
const name = t.taskName || "";
|
|
4921
5658
|
|
|
@@ -4958,6 +5695,15 @@ async function collectTasksView() {
|
|
|
4958
5695
|
partial: 0,
|
|
4959
5696
|
};
|
|
4960
5697
|
|
|
5698
|
+
// Спринт 27.5.2: пауза учитывает и флаг ОС, и активный pausedUntil.
|
|
5699
|
+
// nextRun считаем из определения — schtasks после мутации отдаёт
|
|
5700
|
+
// nextRunTime с задержкой, из-за чего API показывал null после resume.
|
|
5701
|
+
const pausedUntil = def?.pausedUntil ?? null;
|
|
5702
|
+
const paused =
|
|
5703
|
+
Boolean(t.paused) ||
|
|
5704
|
+
def?.paused === true ||
|
|
5705
|
+
Boolean(pausedUntil && Date.parse(pausedUntil) > Date.now());
|
|
5706
|
+
|
|
4961
5707
|
return {
|
|
4962
5708
|
name,
|
|
4963
5709
|
schedule: def?.schedule ?? "",
|
|
@@ -4966,15 +5712,15 @@ async function collectTasksView() {
|
|
|
4966
5712
|
// Спринт 24 (фикс): явный признак паузы. Раньше GUI пытался вывести его
|
|
4967
5713
|
// из текстового статуса, но mapStatus() превращает "disabled" в "unknown",
|
|
4968
5714
|
// поэтому кнопка «возобновить» была недоступна.
|
|
4969
|
-
paused
|
|
5715
|
+
paused,
|
|
4970
5716
|
runsTotal: counts.total,
|
|
4971
5717
|
runsSuccess: counts.success,
|
|
4972
5718
|
runsError: counts.error,
|
|
4973
5719
|
runsPartial: counts.partial,
|
|
4974
|
-
|
|
4975
|
-
|
|
4976
|
-
|
|
4977
|
-
|
|
5720
|
+
nextRun: paused
|
|
5721
|
+
? null
|
|
5722
|
+
: computeTaskNextRun(def) ??
|
|
5723
|
+
(t.nextRunTime ? String(t.nextRunTime) : null),
|
|
4978
5724
|
runAt: def?.runAt ?? null,
|
|
4979
5725
|
session: def?.session ?? "new",
|
|
4980
5726
|
sessionId: def?.sessionId ?? null,
|
|
@@ -4997,6 +5743,10 @@ async function collectTasksView() {
|
|
|
4997
5743
|
notBefore: def?.notBefore ?? null,
|
|
4998
5744
|
notAfter: def?.notAfter ?? null,
|
|
4999
5745
|
pausedUntil: def?.pausedUntil ?? null,
|
|
5746
|
+
// Спринт 27.5.4: режим входа — из ОС (Interactive/Background) и из
|
|
5747
|
+
// определения (запуск без входа через /ru SYSTEM).
|
|
5748
|
+
logonMode: t.logonMode ?? null,
|
|
5749
|
+
runWhenLoggedOff: Boolean(def?.runWhenLoggedOff),
|
|
5000
5750
|
workingDirectory: workspace?.path ?? def?.workingDirectory ?? def?.workdir ?? null,
|
|
5001
5751
|
workspaceId: workspace?.id ?? def?.workspaceId ?? null,
|
|
5002
5752
|
workspaceName: workspace?.name ?? null,
|
|
@@ -5019,6 +5769,8 @@ async function collectTasksView() {
|
|
|
5019
5769
|
prompt: def?.prompt ?? "",
|
|
5020
5770
|
};
|
|
5021
5771
|
});
|
|
5772
|
+
|
|
5773
|
+
return { tasks: view, osAvailable: osRead.osAvailable, osError: osRead.osError };
|
|
5022
5774
|
}
|
|
5023
5775
|
|
|
5024
5776
|
/**
|