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/dist/index.js
CHANGED
|
@@ -5,8 +5,8 @@ import { existsSync } from "node:fs";
|
|
|
5
5
|
import fs from "node:fs/promises";
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
import { LockManager } from "./core/lock.js";
|
|
8
|
-
import { LOCK_DIR, LOG_DIR, PLUGIN_DIR, sanitizeName } from "./types.js";
|
|
9
|
-
import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun, normalizeActiveDays, activeWindowState, nextWindowOpenDelayMs } from "./core/schedule-v2.js";
|
|
8
|
+
import { LOCK_DIR, LOG_DIR, PLUGIN_DIR, STALE_LOCK_MAX_AGE_MS, WRAPPER_DIR, sanitizeName, validateTaskName, } from "./types.js";
|
|
9
|
+
import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun, nextRun as cronNextRun, normalizeActiveDays, activeWindowState, nextWindowOpenDelayMs } from "./core/schedule-v2.js";
|
|
10
10
|
import { buildLaunchdOneShotCleanup, normalizeOneShotRunAt, } from "./core/one-shot.js";
|
|
11
11
|
import { generateSessionId, normalizeSessionMode, preservedSessionRunCount, } from "./core/session.js";
|
|
12
12
|
import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun } from "./core/ps-wrapper.js";
|
|
@@ -19,6 +19,7 @@ import { aggregateMatrixResults, cancelPendingMatrixClones, expandMatrixTask, fi
|
|
|
19
19
|
import { SchedulerRpc } from "./rpc.js";
|
|
20
20
|
import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
|
|
21
21
|
import { loadSettings, saveSettings } from "./settings.js";
|
|
22
|
+
import { setLocale, t } from "./i18n.js";
|
|
22
23
|
import { runHistoryRetention, maybeRunHistoryRetention } from "./core/retention.js";
|
|
23
24
|
import { buildAnalytics } from "./core/analytics.js";
|
|
24
25
|
import { getHistory, listRunningRecords } from "./db/history-repo.js";
|
|
@@ -33,7 +34,7 @@ import { DEFAULT_PROFILE, createProfile, deleteProfile, getProfileDir, getProfil
|
|
|
33
34
|
import { closeDb, initDb } from "./db/index.js";
|
|
34
35
|
import { migrateJsonToDb } from "./db/migrate.js";
|
|
35
36
|
import { checkJsonBackups, recoverInterruptedRuns } from "./db/recovery.js";
|
|
36
|
-
import { getTask, listMatrixClones, saveTask } from "./db/tasks-repo.js";
|
|
37
|
+
import { getTask, listMatrixClones, listTasks as listTaskDefinitions, saveTask } from "./db/tasks-repo.js";
|
|
37
38
|
import { addWorkspace, deleteWorkspace, getWorkspace, listWorkspaces, updateWorkspace, validateWorkspacePath, readGitBranch, writeWorkspaceEnvFile, maskEnvForLog, } from "./workspaces.js";
|
|
38
39
|
import { deleteSecret, hasSecret, listSecrets, setSecret, } from "./core/secrets.js";
|
|
39
40
|
import { readAuditLog, recordAudit, } from "./core/audit.js";
|
|
@@ -116,7 +117,9 @@ export const matrixSchema = z.object({
|
|
|
116
117
|
});
|
|
117
118
|
/** Zod-схема аргументов schedule_task */
|
|
118
119
|
export const scheduleTaskSchema = z.object({
|
|
119
|
-
name: z
|
|
120
|
+
name: z
|
|
121
|
+
.string()
|
|
122
|
+
.describe("Unique task name (the plugin prefix is applied automatically). Allowed: letters (including Cyrillic), digits, space, dot, underscore and hyphen."),
|
|
120
123
|
schedule: z
|
|
121
124
|
.string()
|
|
122
125
|
.optional()
|
|
@@ -267,6 +270,10 @@ export const scheduleTaskSchema = z.object({
|
|
|
267
270
|
.array(z.string())
|
|
268
271
|
.optional()
|
|
269
272
|
.describe("Role-scoped tool deny-list (takes precedence over allowedTools). Metadata-only."),
|
|
273
|
+
runWhenLoggedOff: z
|
|
274
|
+
.boolean()
|
|
275
|
+
.optional()
|
|
276
|
+
.describe("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."),
|
|
270
277
|
matrix: matrixSchema
|
|
271
278
|
.optional()
|
|
272
279
|
.describe("Matrix fan-out: the task becomes a template that is expanded into clones, one per workspace. The parent never runs itself. Cannot be combined with workspaceId."),
|
|
@@ -276,7 +283,7 @@ export const scheduleTaskSchema = z.object({
|
|
|
276
283
|
ctx.addIssue({
|
|
277
284
|
code: z.ZodIssueCode.custom,
|
|
278
285
|
path: ["schedule"],
|
|
279
|
-
message: "
|
|
286
|
+
message: t("tool.error.cronSchedule"),
|
|
280
287
|
});
|
|
281
288
|
}
|
|
282
289
|
if (trigger === "once" &&
|
|
@@ -285,21 +292,21 @@ export const scheduleTaskSchema = z.object({
|
|
|
285
292
|
ctx.addIssue({
|
|
286
293
|
code: z.ZodIssueCode.custom,
|
|
287
294
|
path: ["runAt"],
|
|
288
|
-
message: "
|
|
295
|
+
message: t("tool.error.onceSchedule"),
|
|
289
296
|
});
|
|
290
297
|
}
|
|
291
298
|
if (trigger === "once" && value.matrix) {
|
|
292
299
|
ctx.addIssue({
|
|
293
300
|
code: z.ZodIssueCode.custom,
|
|
294
301
|
path: ["matrix"],
|
|
295
|
-
message: "
|
|
302
|
+
message: t("tool.error.onceMatrixSchema"),
|
|
296
303
|
});
|
|
297
304
|
}
|
|
298
305
|
if (trigger !== "once" && (value.runAt || value.delaySeconds !== undefined)) {
|
|
299
306
|
ctx.addIssue({
|
|
300
307
|
code: z.ZodIssueCode.custom,
|
|
301
308
|
path: ["runAt"],
|
|
302
|
-
message: "
|
|
309
|
+
message: t("tool.error.onceFields"),
|
|
303
310
|
});
|
|
304
311
|
}
|
|
305
312
|
});
|
|
@@ -357,6 +364,10 @@ export const updateTaskSchema = z.object({
|
|
|
357
364
|
.enum(["skip", "postpone", "run"])
|
|
358
365
|
.optional()
|
|
359
366
|
.describe("New behaviour outside the window: postpone (default), skip or run."),
|
|
367
|
+
runWhenLoggedOff: z
|
|
368
|
+
.boolean()
|
|
369
|
+
.optional()
|
|
370
|
+
.describe("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."),
|
|
360
371
|
watchGlobs: z
|
|
361
372
|
.array(z.string())
|
|
362
373
|
.optional()
|
|
@@ -462,14 +473,14 @@ export const updateTaskSchema = z.object({
|
|
|
462
473
|
ctx.addIssue({
|
|
463
474
|
code: z.ZodIssueCode.custom,
|
|
464
475
|
path: ["runAt"],
|
|
465
|
-
message: "
|
|
476
|
+
message: t("tool.error.onceFields"),
|
|
466
477
|
});
|
|
467
478
|
}
|
|
468
479
|
if (value.triggerType === "once" && value.matrix) {
|
|
469
480
|
ctx.addIssue({
|
|
470
481
|
code: z.ZodIssueCode.custom,
|
|
471
482
|
path: ["matrix"],
|
|
472
|
-
message: "
|
|
483
|
+
message: t("tool.error.onceMatrixUpdate"),
|
|
473
484
|
});
|
|
474
485
|
}
|
|
475
486
|
});
|
|
@@ -522,12 +533,12 @@ const manageWorkspacesSchema = z.object({
|
|
|
522
533
|
.record(z.string(), z.string())
|
|
523
534
|
.nullable()
|
|
524
535
|
.optional()
|
|
525
|
-
.describe("
|
|
536
|
+
.describe("Workspace environment variables (key → value). Override envFile values; secrets are masked in logs (add/update)."),
|
|
526
537
|
envFile: z
|
|
527
538
|
.string()
|
|
528
539
|
.nullable()
|
|
529
540
|
.optional()
|
|
530
|
-
.describe("
|
|
541
|
+
.describe("Path to the workspace .env file (add/update, null clears it)."),
|
|
531
542
|
});
|
|
532
543
|
export const matrixControlSchema = z.object({
|
|
533
544
|
action: z
|
|
@@ -585,6 +596,10 @@ export const manageSettingsSchema = z.object({
|
|
|
585
596
|
.max(16)
|
|
586
597
|
.optional()
|
|
587
598
|
.describe("How many task runs may execute at the same time."),
|
|
599
|
+
locale: z
|
|
600
|
+
.enum(["ru", "en"])
|
|
601
|
+
.optional()
|
|
602
|
+
.describe("Interface language: ru (default) or en. Applies without restart."),
|
|
588
603
|
winterMode: z
|
|
589
604
|
.boolean()
|
|
590
605
|
.optional()
|
|
@@ -725,9 +740,78 @@ function wrapExecute(fn) {
|
|
|
725
740
|
}
|
|
726
741
|
};
|
|
727
742
|
}
|
|
743
|
+
/**
|
|
744
|
+
* Спринт 27.5.2: ближайший запуск по определению задачи, без чтения ОС.
|
|
745
|
+
*
|
|
746
|
+
* - `once` → `runAt` (запланированный момент);
|
|
747
|
+
* - пауза (`paused` или будущий `pausedUntil`) → null;
|
|
748
|
+
* - `cron` → ближайшее совпадение cron с учётом окна и дней недели:
|
|
749
|
+
* * `run` — окно игнорируется;
|
|
750
|
+
* * `skip` — ищем следующее совпадение внутри окна;
|
|
751
|
+
* * `postpone` (по умолчанию) — перенос на открытие окна, как в schedule-gate;
|
|
752
|
+
* - `file`/`git`/`mcp-event` → null (расписания нет).
|
|
753
|
+
*/
|
|
754
|
+
function computeTaskNextRun(def, options = {}) {
|
|
755
|
+
if (!def)
|
|
756
|
+
return null;
|
|
757
|
+
if (options.paused)
|
|
758
|
+
return null;
|
|
759
|
+
const now = options.now ?? new Date();
|
|
760
|
+
if (def.pausedUntil) {
|
|
761
|
+
const until = Date.parse(def.pausedUntil);
|
|
762
|
+
if (Number.isFinite(until) && until > now.getTime())
|
|
763
|
+
return null;
|
|
764
|
+
}
|
|
765
|
+
const type = def.triggerType ?? "cron";
|
|
766
|
+
if (type === "once") {
|
|
767
|
+
if (!def.runAt)
|
|
768
|
+
return null;
|
|
769
|
+
const at = Date.parse(def.runAt);
|
|
770
|
+
return Number.isFinite(at) ? new Date(at).toISOString() : null;
|
|
771
|
+
}
|
|
772
|
+
if (type !== "cron")
|
|
773
|
+
return null;
|
|
774
|
+
const schedule = (def.schedule || "").trim();
|
|
775
|
+
if (!schedule)
|
|
776
|
+
return null;
|
|
777
|
+
const timeZone = def.timezone?.trim() || undefined;
|
|
778
|
+
const policy = def.windowPolicy === "skip" || def.windowPolicy === "run"
|
|
779
|
+
? def.windowPolicy
|
|
780
|
+
: "postpone";
|
|
781
|
+
const windowOptions = {
|
|
782
|
+
notBefore: def.notBefore,
|
|
783
|
+
notAfter: def.notAfter,
|
|
784
|
+
days: Array.isArray(def.activeDays) ? def.activeDays : undefined,
|
|
785
|
+
timeZone,
|
|
786
|
+
};
|
|
787
|
+
let tick;
|
|
788
|
+
try {
|
|
789
|
+
tick = cronNextRun(schedule, now, timeZone);
|
|
790
|
+
}
|
|
791
|
+
catch {
|
|
792
|
+
// Некорректное выражение не должно ломать ответ инструмента.
|
|
793
|
+
return null;
|
|
794
|
+
}
|
|
795
|
+
// skip-политика может пропустить сколько угодно тиков вне окна;
|
|
796
|
+
// ограничение защищает от бесконечного перебора (5-летнее окно cron).
|
|
797
|
+
for (let guard = 0; tick && guard < 600; guard += 1) {
|
|
798
|
+
if (policy === "run")
|
|
799
|
+
return tick.toISOString();
|
|
800
|
+
const state = activeWindowState(tick, windowOptions);
|
|
801
|
+
if (state.active)
|
|
802
|
+
return tick.toISOString();
|
|
803
|
+
if (policy === "skip") {
|
|
804
|
+
tick = cronNextRun(schedule, tick, timeZone);
|
|
805
|
+
continue;
|
|
806
|
+
}
|
|
807
|
+
// postpone: gate ждёт открытия окна и запускает задачу тогда же.
|
|
808
|
+
return state.nextOpenAt ? state.nextOpenAt.toISOString() : null;
|
|
809
|
+
}
|
|
810
|
+
return null;
|
|
811
|
+
}
|
|
728
812
|
/** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
|
|
729
813
|
const scheduleTaskExecute = wrapExecute(async (args) => {
|
|
730
|
-
const { name, schedule, runAt, delaySeconds, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, watchPath, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, session, sessionMaxRuns, activeDays, windowPolicy, watchGlobs, watchIgnore, gitBranch, gitPaths, gitIgnore, gitPollSeconds, } = args;
|
|
814
|
+
const { name, schedule, runAt, delaySeconds, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, watchPath, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, session, sessionMaxRuns, activeDays, windowPolicy, watchGlobs, watchIgnore, gitBranch, gitPaths, gitIgnore, gitPollSeconds, runWhenLoggedOff, } = args;
|
|
731
815
|
let effectiveRunAt;
|
|
732
816
|
if ((triggerType ?? "cron") === "once") {
|
|
733
817
|
const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
|
|
@@ -752,7 +836,9 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
|
|
|
752
836
|
gitPaths,
|
|
753
837
|
gitIgnore,
|
|
754
838
|
gitPollSeconds,
|
|
755
|
-
}
|
|
839
|
+
},
|
|
840
|
+
// Спринт 27.5.4: Windows — работать без входа (/ru SYSTEM).
|
|
841
|
+
runWhenLoggedOff === true);
|
|
756
842
|
}
|
|
757
843
|
catch (err) {
|
|
758
844
|
return {
|
|
@@ -767,13 +853,31 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
|
|
|
767
853
|
await refreshTriggers();
|
|
768
854
|
const workspace = workspaceId ? getWorkspace(workspaceId) : undefined;
|
|
769
855
|
const effectiveWorkdir = workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
|
|
856
|
+
// Спринт 27.5.2: отдаём ближайший запуск сразу, не дожидаясь обновления
|
|
857
|
+
// списка задач планировщика ОС (schtasks иногда отдаёт nextRunTime с задержкой).
|
|
858
|
+
const nextRun = computeTaskNextRun({
|
|
859
|
+
schedule: schedule ?? "",
|
|
860
|
+
triggerType: triggerType ?? "cron",
|
|
861
|
+
runAt: effectiveRunAt,
|
|
862
|
+
timezone,
|
|
863
|
+
notBefore,
|
|
864
|
+
notAfter,
|
|
865
|
+
activeDays,
|
|
866
|
+
windowPolicy,
|
|
867
|
+
});
|
|
770
868
|
return {
|
|
771
869
|
content: JSON.stringify({
|
|
772
870
|
success: true,
|
|
773
|
-
|
|
871
|
+
paused: false,
|
|
872
|
+
nextRun,
|
|
873
|
+
runWhenLoggedOff: runWhenLoggedOff === true,
|
|
874
|
+
message: t("tool.task.created", { name }),
|
|
774
875
|
task: {
|
|
775
876
|
name,
|
|
776
877
|
schedule,
|
|
878
|
+
nextRun,
|
|
879
|
+
paused: false,
|
|
880
|
+
runWhenLoggedOff: runWhenLoggedOff === true,
|
|
777
881
|
timeoutSeconds: timeoutSeconds ?? 3600,
|
|
778
882
|
model: model?.trim() || null,
|
|
779
883
|
priority: priority ?? 5,
|
|
@@ -804,21 +908,29 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
|
|
|
804
908
|
});
|
|
805
909
|
/** list_tasks — список задач плагина (та же логика, что и у get_tasks). */
|
|
806
910
|
const listTasksExecute = wrapExecute(async () => {
|
|
807
|
-
const tasks = await collectTasksView();
|
|
911
|
+
const { tasks, osAvailable, osError } = await collectTasksView();
|
|
808
912
|
if (tasks.length === 0) {
|
|
809
913
|
return {
|
|
810
914
|
content: JSON.stringify({
|
|
811
915
|
success: true,
|
|
812
|
-
message:
|
|
916
|
+
message: osAvailable
|
|
917
|
+
? t("tool.task.listEmpty")
|
|
918
|
+
: t("tool.task.listOsUnavailable"),
|
|
813
919
|
tasks: [],
|
|
920
|
+
osAvailable,
|
|
921
|
+
...(osError ? { osError } : {}),
|
|
814
922
|
}),
|
|
815
923
|
};
|
|
816
924
|
}
|
|
817
925
|
return {
|
|
818
926
|
content: JSON.stringify({
|
|
819
927
|
success: true,
|
|
820
|
-
message:
|
|
928
|
+
message: osAvailable
|
|
929
|
+
? t("tool.task.found", { count: tasks.length })
|
|
930
|
+
: t("tool.task.foundOsUnavailable", { count: tasks.length }),
|
|
821
931
|
tasks,
|
|
932
|
+
osAvailable,
|
|
933
|
+
...(osError ? { osError } : {}),
|
|
822
934
|
}),
|
|
823
935
|
};
|
|
824
936
|
});
|
|
@@ -831,7 +943,7 @@ const listTasksExecute = wrapExecute(async () => {
|
|
|
831
943
|
async function cancelMatrixRun(name) {
|
|
832
944
|
const definition = (await loadTaskDefinitions()).find((def) => def.name.toLowerCase() === name.trim().toLowerCase());
|
|
833
945
|
if (!definition?.matrix) {
|
|
834
|
-
throw new Error(
|
|
946
|
+
throw new Error(t("tool.error.matrixNotMatrix", { name }));
|
|
835
947
|
}
|
|
836
948
|
const result = await cancelPendingMatrixClones(definition.name);
|
|
837
949
|
const warnings = [];
|
|
@@ -844,28 +956,38 @@ async function cancelMatrixRun(name) {
|
|
|
844
956
|
await scheduler.deleteTask(clone.name);
|
|
845
957
|
}
|
|
846
958
|
catch (err) {
|
|
847
|
-
warnings.push(
|
|
959
|
+
warnings.push(t("tool.matrix.stopFailed", {
|
|
960
|
+
clone: clone.name,
|
|
961
|
+
error: err instanceof Error ? err.message : String(err),
|
|
962
|
+
}));
|
|
848
963
|
continue;
|
|
849
964
|
}
|
|
850
965
|
// Возвращаем placeholder-задачу, чтобы следующая fan-out-волна работала.
|
|
851
966
|
try {
|
|
852
|
-
await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, definition.name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil);
|
|
967
|
+
await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, definition.name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused);
|
|
853
968
|
}
|
|
854
969
|
catch (err) {
|
|
855
|
-
warnings.push(
|
|
970
|
+
warnings.push(t("tool.matrix.recreateFailed", {
|
|
971
|
+
clone: clone.name,
|
|
972
|
+
error: err instanceof Error ? err.message : String(err),
|
|
973
|
+
}));
|
|
856
974
|
}
|
|
857
975
|
}
|
|
858
976
|
const parts = [
|
|
859
|
-
|
|
977
|
+
t("tool.matrix.cancelSummary", {
|
|
978
|
+
matrix: definition.name,
|
|
979
|
+
cancelled: result.cancelled.length,
|
|
980
|
+
total: result.aggregate.totalCount,
|
|
981
|
+
}),
|
|
860
982
|
];
|
|
861
983
|
if (result.running.length > 0) {
|
|
862
|
-
parts.push(
|
|
984
|
+
parts.push(t("tool.matrix.cancelRunning", { count: result.running.length }));
|
|
863
985
|
}
|
|
864
986
|
if (result.alreadyFinished.length > 0) {
|
|
865
|
-
parts.push(
|
|
987
|
+
parts.push(t("tool.matrix.cancelFinished", { count: result.alreadyFinished.length }));
|
|
866
988
|
}
|
|
867
989
|
if (warnings.length > 0) {
|
|
868
|
-
parts.push(
|
|
990
|
+
parts.push(t("tool.matrix.cancelWarnings", { warnings: warnings.join("; ") }));
|
|
869
991
|
}
|
|
870
992
|
return {
|
|
871
993
|
cancelled: result.cancelled,
|
|
@@ -905,6 +1027,87 @@ async function cleanupOrphanedMatrixTasks() {
|
|
|
905
1027
|
* - удаление родителя-матрицы каскадно удаляет клоны и агрегатор;
|
|
906
1028
|
* - удаление клона поодиночке запрещено (защита от «сирот» и вечного running).
|
|
907
1029
|
*/
|
|
1030
|
+
/**
|
|
1031
|
+
* Удаляет файлы-артефакты задачи (wrapper, prompt, log, lock, env).
|
|
1032
|
+
* Отсутствующие файлы игнорируются — операция идемпотентна.
|
|
1033
|
+
*/
|
|
1034
|
+
async function removeTaskArtifacts(name) {
|
|
1035
|
+
const sanitized = sanitizeName(name);
|
|
1036
|
+
const candidates = [
|
|
1037
|
+
path.join(WRAPPER_DIR, `run-${sanitized}.cmd`),
|
|
1038
|
+
path.join(WRAPPER_DIR, `run-${sanitized}.sh`),
|
|
1039
|
+
path.join(PLUGIN_DIR, "prompts", `${sanitized}.txt`),
|
|
1040
|
+
path.join(LOG_DIR, `${sanitized}.log`),
|
|
1041
|
+
path.join(PLUGIN_DIR, "env", `${sanitized}.env`),
|
|
1042
|
+
path.join(LOCK_DIR, `${sanitized}.lock`),
|
|
1043
|
+
path.join(LOCK_DIR, `${sanitized}.lock.defer`),
|
|
1044
|
+
path.join(LOCK_DIR, `${sanitized}.lock.force`),
|
|
1045
|
+
];
|
|
1046
|
+
await Promise.all(candidates.map((file) => fs.unlink(file).catch(() => undefined)));
|
|
1047
|
+
}
|
|
1048
|
+
/**
|
|
1049
|
+
* Сборщик мусора по wrapper-ам при старте: удаляет файлы задач, которых
|
|
1050
|
+
* больше нет ни в БД, ни в планировщике ОС. Активные (свежий lock) не трогает.
|
|
1051
|
+
*/
|
|
1052
|
+
async function garbageCollectTaskArtifacts() {
|
|
1053
|
+
let entries;
|
|
1054
|
+
try {
|
|
1055
|
+
entries = await fs.readdir(WRAPPER_DIR);
|
|
1056
|
+
}
|
|
1057
|
+
catch {
|
|
1058
|
+
return;
|
|
1059
|
+
}
|
|
1060
|
+
const wrappers = entries.filter((file) => /^run-.+\.(cmd|sh)$/.test(file));
|
|
1061
|
+
if (wrappers.length === 0)
|
|
1062
|
+
return;
|
|
1063
|
+
const known = new Set();
|
|
1064
|
+
try {
|
|
1065
|
+
for (const task of listTaskDefinitions())
|
|
1066
|
+
known.add(sanitizeName(task.name));
|
|
1067
|
+
}
|
|
1068
|
+
catch {
|
|
1069
|
+
// БД может быть ещё не готова — тогда опираемся на ОС.
|
|
1070
|
+
}
|
|
1071
|
+
try {
|
|
1072
|
+
for (const task of await scheduler.listTasks()) {
|
|
1073
|
+
known.add(sanitizeName(task.taskName || ""));
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
catch {
|
|
1077
|
+
// Планировщик недоступен — не удаляем ничего, чтобы не потерять данные.
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
let cleaned = 0;
|
|
1081
|
+
for (const file of wrappers) {
|
|
1082
|
+
const stem = file.replace(/^run-/, "").replace(/\.(cmd|sh)$/, "");
|
|
1083
|
+
const lockPath = path.join(LOCK_DIR, `${stem}.lock`);
|
|
1084
|
+
if (known.has(stem))
|
|
1085
|
+
continue;
|
|
1086
|
+
try {
|
|
1087
|
+
const stat = await fs.stat(lockPath);
|
|
1088
|
+
if (Date.now() - stat.mtimeMs < STALE_LOCK_MAX_AGE_MS)
|
|
1089
|
+
continue;
|
|
1090
|
+
}
|
|
1091
|
+
catch {
|
|
1092
|
+
// lock-файла нет — можно удалять.
|
|
1093
|
+
}
|
|
1094
|
+
const candidates = [
|
|
1095
|
+
path.join(WRAPPER_DIR, `run-${stem}.cmd`),
|
|
1096
|
+
path.join(WRAPPER_DIR, `run-${stem}.sh`),
|
|
1097
|
+
path.join(PLUGIN_DIR, "prompts", `${stem}.txt`),
|
|
1098
|
+
path.join(LOG_DIR, `${stem}.log`),
|
|
1099
|
+
path.join(PLUGIN_DIR, "env", `${stem}.env`),
|
|
1100
|
+
path.join(LOCK_DIR, `${stem}.lock`),
|
|
1101
|
+
path.join(LOCK_DIR, `${stem}.lock.defer`),
|
|
1102
|
+
path.join(LOCK_DIR, `${stem}.lock.force`),
|
|
1103
|
+
];
|
|
1104
|
+
await Promise.all(candidates.map((pathToFile) => fs.unlink(pathToFile).catch(() => undefined)));
|
|
1105
|
+
cleaned += 1;
|
|
1106
|
+
}
|
|
1107
|
+
if (cleaned > 0) {
|
|
1108
|
+
console.log(`[gc] Вычищено мусорных файлов задач: ${cleaned}`);
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
908
1111
|
async function deleteTaskWithFamily(name) {
|
|
909
1112
|
const trimmed = name.trim();
|
|
910
1113
|
const guard = getMatrixDeletionGuard(trimmed);
|
|
@@ -940,6 +1143,7 @@ async function deleteTaskWithFamily(name) {
|
|
|
940
1143
|
catch {
|
|
941
1144
|
// Не критично.
|
|
942
1145
|
}
|
|
1146
|
+
removeTaskArtifacts(child);
|
|
943
1147
|
removed.push(child);
|
|
944
1148
|
}
|
|
945
1149
|
}
|
|
@@ -950,6 +1154,7 @@ async function deleteTaskWithFamily(name) {
|
|
|
950
1154
|
catch {
|
|
951
1155
|
// Определения могло уже не быть — задача всё равно удалена из ОС.
|
|
952
1156
|
}
|
|
1157
|
+
removeTaskArtifacts(trimmed);
|
|
953
1158
|
return { removed, existed };
|
|
954
1159
|
}
|
|
955
1160
|
/** delete_task — удаление задачи по имени (/f) */
|
|
@@ -962,8 +1167,8 @@ const deleteTaskExecute = wrapExecute(async (args) => {
|
|
|
962
1167
|
if (!existed && removed.length === 0) {
|
|
963
1168
|
return {
|
|
964
1169
|
content: JSON.stringify({
|
|
965
|
-
success:
|
|
966
|
-
|
|
1170
|
+
success: true,
|
|
1171
|
+
message: t("tool.task.alreadyAbsent", { name }),
|
|
967
1172
|
}),
|
|
968
1173
|
};
|
|
969
1174
|
}
|
|
@@ -971,8 +1176,8 @@ const deleteTaskExecute = wrapExecute(async (args) => {
|
|
|
971
1176
|
content: JSON.stringify({
|
|
972
1177
|
success: true,
|
|
973
1178
|
message: removed.length > 0
|
|
974
|
-
?
|
|
975
|
-
:
|
|
1179
|
+
? t("tool.task.matrixDeletedList", { name, list: removed.join(", ") })
|
|
1180
|
+
: t("tool.task.deleted", { name }),
|
|
976
1181
|
}),
|
|
977
1182
|
};
|
|
978
1183
|
}
|
|
@@ -1005,8 +1210,8 @@ const runTaskNowExecute = wrapExecute(async (args) => {
|
|
|
1005
1210
|
content: JSON.stringify({
|
|
1006
1211
|
success: true,
|
|
1007
1212
|
message: alreadyRunning
|
|
1008
|
-
?
|
|
1009
|
-
:
|
|
1213
|
+
? t("tool.task.alreadyRunning", { name })
|
|
1214
|
+
: t("tool.task.started", { name }),
|
|
1010
1215
|
}),
|
|
1011
1216
|
};
|
|
1012
1217
|
});
|
|
@@ -1053,11 +1258,11 @@ async function removeMatrixChildrenFromScheduler(name) {
|
|
|
1053
1258
|
async function updateTaskFromInput(input) {
|
|
1054
1259
|
const name = input.name?.trim();
|
|
1055
1260
|
if (!name) {
|
|
1056
|
-
return { success: false, message: "
|
|
1261
|
+
return { success: false, message: t("tool.error.taskNameMissing") };
|
|
1057
1262
|
}
|
|
1058
1263
|
const previous = getTask(name);
|
|
1059
1264
|
if (!previous) {
|
|
1060
|
-
return { success: false, message:
|
|
1265
|
+
return { success: false, message: t("tool.error.taskNotFound", { name }) };
|
|
1061
1266
|
}
|
|
1062
1267
|
const schedule = clearableString(input.schedule ?? input.newSchedule, previous.schedule);
|
|
1063
1268
|
const prompt = clearableString(input.prompt ?? input.newPrompt, previous.prompt);
|
|
@@ -1068,13 +1273,13 @@ async function updateTaskFromInput(input) {
|
|
|
1068
1273
|
if (triggerType === "cron" && !schedule) {
|
|
1069
1274
|
return {
|
|
1070
1275
|
success: false,
|
|
1071
|
-
message:
|
|
1276
|
+
message: t("tool.error.updateCron", { name }),
|
|
1072
1277
|
};
|
|
1073
1278
|
}
|
|
1074
1279
|
if (!prompt) {
|
|
1075
1280
|
return {
|
|
1076
1281
|
success: false,
|
|
1077
|
-
message:
|
|
1282
|
+
message: t("tool.error.updatePrompt", { name }),
|
|
1078
1283
|
};
|
|
1079
1284
|
}
|
|
1080
1285
|
// One-shot: без нового runAt/delaySeconds сохраняем прежнее время.
|
|
@@ -1093,7 +1298,7 @@ async function updateTaskFromInput(input) {
|
|
|
1093
1298
|
if (!normalized.ok) {
|
|
1094
1299
|
return {
|
|
1095
1300
|
success: false,
|
|
1096
|
-
message:
|
|
1301
|
+
message: t("tool.error.taskReason", { name, error: normalized.error }),
|
|
1097
1302
|
};
|
|
1098
1303
|
}
|
|
1099
1304
|
runAt = normalized.runAt;
|
|
@@ -1106,7 +1311,7 @@ async function updateTaskFromInput(input) {
|
|
|
1106
1311
|
if (!normalizedSession) {
|
|
1107
1312
|
return {
|
|
1108
1313
|
success: false,
|
|
1109
|
-
message:
|
|
1314
|
+
message: t("tool.error.sessionUnknown", { name, session: String(input.session) }),
|
|
1110
1315
|
};
|
|
1111
1316
|
}
|
|
1112
1317
|
session = normalizedSession;
|
|
@@ -1119,7 +1324,7 @@ async function updateTaskFromInput(input) {
|
|
|
1119
1324
|
(!Number.isInteger(sessionMaxRuns) || sessionMaxRuns < 1)) {
|
|
1120
1325
|
return {
|
|
1121
1326
|
success: false,
|
|
1122
|
-
message:
|
|
1327
|
+
message: t("tool.error.sessionMaxRuns", { name }),
|
|
1123
1328
|
};
|
|
1124
1329
|
}
|
|
1125
1330
|
let sessionId = previous.sessionId;
|
|
@@ -1134,8 +1339,7 @@ async function updateTaskFromInput(input) {
|
|
|
1134
1339
|
if (triggerType === "once" && matrixNext) {
|
|
1135
1340
|
return {
|
|
1136
1341
|
success: false,
|
|
1137
|
-
message:
|
|
1138
|
-
`Запустите матрицу вручную или используйте cron/file-триггер.`,
|
|
1342
|
+
message: t("tool.error.oneShotMatrix", { name }),
|
|
1139
1343
|
};
|
|
1140
1344
|
}
|
|
1141
1345
|
// Спринт 27: параметры триггеров сохраняются, если поле не передано.
|
|
@@ -1162,13 +1366,19 @@ async function updateTaskFromInput(input) {
|
|
|
1162
1366
|
gitIgnore: mergeStringList(input.gitIgnore, previous.gitIgnore),
|
|
1163
1367
|
gitPollSeconds: input.gitPollSeconds ?? previous.gitPollSeconds,
|
|
1164
1368
|
};
|
|
1369
|
+
// Спринт 27.5.8: update = пересоздание задачи, поэтому паузу нужно вернуть
|
|
1370
|
+
// после create — иначе задача молча начинает выполняться по расписанию.
|
|
1371
|
+
const wasPaused = Boolean(previous.paused === true ||
|
|
1372
|
+
(previous.pausedUntil && Date.parse(previous.pausedUntil) > Date.now()));
|
|
1373
|
+
let previousDeleted = false;
|
|
1165
1374
|
try {
|
|
1166
1375
|
// Обновление = пересоздание в планировщике с сохранением старых значений.
|
|
1167
1376
|
await scheduler.deleteTask(name);
|
|
1377
|
+
previousDeleted = true;
|
|
1168
1378
|
await schedulerCreateTask(name, schedule ?? "", prompt, input.timeoutSeconds ?? previous.timeoutSeconds, clearableString(input.workingDirectory, previous.workingDirectory), input.retryCount ?? previous.retryCount, input.retryDelay ?? previous.retryDelay, clearableString(input.qualityGate, previous.qualityGate), clearableString(input.nextTaskOnSuccess, previous.nextTaskOnSuccess), clearableString(input.nextTaskOnError, previous.nextTaskOnError), triggerType, clearableString(input.watchPath, previous.watchPath), clearableList(input.dependsOn, previous.dependsOn), clearableString(input.model, previous.model), input.priority ?? previous.priority, clearableString(input.beforeScript, previous.beforeScript), clearableString(input.afterScript, previous.afterScript), input.mcpEvent ?? previous.mcpEvent, clearableString(input.workspaceId, previous.workspaceId), clearableList(input.allowedTools, previous.allowedTools), clearableList(input.deniedTools, previous.deniedTools), matrixNext, undefined,
|
|
1169
1379
|
// Если задача была матрицей — синхронизируем клонов, а не
|
|
1170
1380
|
// пересоздаём их с нуля (Спринт 17).
|
|
1171
|
-
matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil, runAt, session, sessionId, sessionMaxRuns, triggerExtras);
|
|
1381
|
+
matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil, runAt, session, sessionId, sessionMaxRuns, triggerExtras, input.runWhenLoggedOff ?? previous.runWhenLoggedOff, wasPaused);
|
|
1172
1382
|
// Матрица отключена при обновлении — убираем клонов и агрегатор.
|
|
1173
1383
|
if (matrixWas && !matrixNext) {
|
|
1174
1384
|
await removeMatrixChildrenFromScheduler(name);
|
|
@@ -1176,14 +1386,59 @@ async function updateTaskFromInput(input) {
|
|
|
1176
1386
|
// Пересоздание могло изменить triggerType/watchPath — сразу
|
|
1177
1387
|
// пересобираем набор файловых watcher-ов.
|
|
1178
1388
|
await refreshTriggers();
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1389
|
+
// Спринт 27.5.2: после пересоздания задачи сообщаем ближайший запуск,
|
|
1390
|
+
// рассчитанный из нового определения, не дожидаясь ОС.
|
|
1391
|
+
const updated = getTask(name);
|
|
1392
|
+
const paused = wasPaused;
|
|
1182
1393
|
return {
|
|
1183
|
-
success:
|
|
1184
|
-
|
|
1394
|
+
success: true,
|
|
1395
|
+
paused,
|
|
1396
|
+
nextRun: computeTaskNextRun(updated, { paused }),
|
|
1397
|
+
message: t("tool.task.updated", { name }),
|
|
1185
1398
|
};
|
|
1186
1399
|
}
|
|
1400
|
+
catch (err) {
|
|
1401
|
+
const cause = err instanceof Error ? err.message : String(err);
|
|
1402
|
+
// Спринт 27.5.6: задача удалена из ОС, но новую версию создать не удалось.
|
|
1403
|
+
if (!previousDeleted) {
|
|
1404
|
+
return {
|
|
1405
|
+
success: false,
|
|
1406
|
+
restored: true,
|
|
1407
|
+
message: t("tool.task.rollbackKept", { cause }),
|
|
1408
|
+
};
|
|
1409
|
+
}
|
|
1410
|
+
// Убираем возможный частичный результат новой попытки: обёртка могла
|
|
1411
|
+
// успеть зарегистрироваться, хотя create вернул ошибку.
|
|
1412
|
+
try {
|
|
1413
|
+
await scheduler.deleteTask(name);
|
|
1414
|
+
}
|
|
1415
|
+
catch {
|
|
1416
|
+
// Задачи могло не быть — это ожидаемо.
|
|
1417
|
+
}
|
|
1418
|
+
// Определение в БД ещё не перезаписано, поэтому восстанавливаем ровно
|
|
1419
|
+
// прежнюю версию: расписание, промпт, обёртку и паузу.
|
|
1420
|
+
try {
|
|
1421
|
+
await recreateTaskFromDefinition(previous);
|
|
1422
|
+
await refreshTriggers().catch(() => undefined);
|
|
1423
|
+
return {
|
|
1424
|
+
success: false,
|
|
1425
|
+
restored: true,
|
|
1426
|
+
message: t("tool.task.rollbackRestored", { cause }),
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
catch (restoreErr) {
|
|
1430
|
+
const restoreMessage = restoreErr instanceof Error ? restoreErr.message : String(restoreErr);
|
|
1431
|
+
return {
|
|
1432
|
+
success: false,
|
|
1433
|
+
restored: false,
|
|
1434
|
+
message: t("tool.task.rollbackFailed", {
|
|
1435
|
+
cause,
|
|
1436
|
+
restore: restoreMessage,
|
|
1437
|
+
name,
|
|
1438
|
+
}),
|
|
1439
|
+
};
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1187
1442
|
}
|
|
1188
1443
|
/** update_task — частичное обновление существующей задачи. */
|
|
1189
1444
|
const updateTaskExecute = wrapExecute(async (args) => {
|
|
@@ -1200,9 +1455,12 @@ async function pauseOrResumeTask(name, paused, until) {
|
|
|
1200
1455
|
if (!definition) {
|
|
1201
1456
|
return {
|
|
1202
1457
|
success: false,
|
|
1203
|
-
message:
|
|
1458
|
+
message: t("tool.error.taskNotFound", { name: trimmed }),
|
|
1204
1459
|
affected: [],
|
|
1205
1460
|
warnings: [],
|
|
1461
|
+
paused,
|
|
1462
|
+
nextRun: null,
|
|
1463
|
+
pausedUntil: null,
|
|
1206
1464
|
};
|
|
1207
1465
|
}
|
|
1208
1466
|
// Пауза до даты (Спринт 19): проверяем ISO-момент до каких-либо изменений.
|
|
@@ -1212,17 +1470,23 @@ async function pauseOrResumeTask(name, paused, until) {
|
|
|
1212
1470
|
if (Number.isNaN(parsed)) {
|
|
1213
1471
|
return {
|
|
1214
1472
|
success: false,
|
|
1215
|
-
message:
|
|
1473
|
+
message: t("tool.error.pauseDateInvalid", { name: trimmed, until }),
|
|
1216
1474
|
affected: [],
|
|
1217
1475
|
warnings: [],
|
|
1476
|
+
paused,
|
|
1477
|
+
nextRun: null,
|
|
1478
|
+
pausedUntil: definition.pausedUntil ?? null,
|
|
1218
1479
|
};
|
|
1219
1480
|
}
|
|
1220
1481
|
if (parsed <= Date.now()) {
|
|
1221
1482
|
return {
|
|
1222
1483
|
success: false,
|
|
1223
|
-
message:
|
|
1484
|
+
message: t("tool.error.pauseDatePast", { name: trimmed }),
|
|
1224
1485
|
affected: [],
|
|
1225
1486
|
warnings: [],
|
|
1487
|
+
paused,
|
|
1488
|
+
nextRun: null,
|
|
1489
|
+
pausedUntil: definition.pausedUntil ?? null,
|
|
1226
1490
|
};
|
|
1227
1491
|
}
|
|
1228
1492
|
pausedUntil = new Date(parsed).toISOString();
|
|
@@ -1233,9 +1497,12 @@ async function pauseOrResumeTask(name, paused, until) {
|
|
|
1233
1497
|
if (targets.length === 0 && definition.matrix) {
|
|
1234
1498
|
return {
|
|
1235
1499
|
success: false,
|
|
1236
|
-
message:
|
|
1500
|
+
message: t("tool.error.matrixNoClones", { name: trimmed }),
|
|
1237
1501
|
affected: [],
|
|
1238
1502
|
warnings: [],
|
|
1503
|
+
paused,
|
|
1504
|
+
nextRun: null,
|
|
1505
|
+
pausedUntil: definition.pausedUntil ?? null,
|
|
1239
1506
|
};
|
|
1240
1507
|
}
|
|
1241
1508
|
const affected = [];
|
|
@@ -1254,37 +1521,65 @@ async function pauseOrResumeTask(name, paused, until) {
|
|
|
1254
1521
|
warnings.push(`${target}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1255
1522
|
}
|
|
1256
1523
|
}
|
|
1257
|
-
// Фиксируем (или снимаем)
|
|
1524
|
+
// Фиксируем (или снимаем) паузу в определении задачи. У матрицы
|
|
1258
1525
|
// родитель хранит pausedUntil за всех клонов — их включает авто-resume.
|
|
1526
|
+
// Спринт 27.5.8: бессрочная пауза тоже сохраняется в определении, иначе
|
|
1527
|
+
// update_task пересоздаёт задачу включённой и пауза теряется.
|
|
1259
1528
|
const definitionUpdates = paused
|
|
1260
|
-
? pausedUntil
|
|
1261
|
-
|
|
1262
|
-
: undefined
|
|
1263
|
-
: definition.pausedUntil
|
|
1264
|
-
? { pausedUntil: undefined }
|
|
1529
|
+
? { paused: true, ...(pausedUntil ? { pausedUntil } : {}) }
|
|
1530
|
+
: definition.paused || definition.pausedUntil
|
|
1531
|
+
? { paused: false, pausedUntil: undefined }
|
|
1265
1532
|
: undefined;
|
|
1266
1533
|
if (definitionUpdates && affected.length > 0) {
|
|
1267
1534
|
try {
|
|
1268
1535
|
saveTask({ ...definition, ...definitionUpdates });
|
|
1269
1536
|
}
|
|
1270
1537
|
catch (err) {
|
|
1271
|
-
warnings.push(
|
|
1538
|
+
warnings.push(t("tool.task.autosave", {
|
|
1539
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1540
|
+
}));
|
|
1272
1541
|
}
|
|
1273
1542
|
}
|
|
1274
1543
|
const untilText = pausedUntil
|
|
1275
|
-
?
|
|
1544
|
+
? t("tool.task.until", { date: new Date(pausedUntil).toLocaleString() })
|
|
1276
1545
|
: "";
|
|
1277
|
-
const verb = paused ? "
|
|
1546
|
+
const verb = paused ? t("tool.task.paused") : t("tool.task.resumed");
|
|
1278
1547
|
const message = definition.matrix
|
|
1279
|
-
?
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1548
|
+
? t("tool.task.matrixPaused", {
|
|
1549
|
+
name: trimmed,
|
|
1550
|
+
verb,
|
|
1551
|
+
until: untilText,
|
|
1552
|
+
affected: affected.length,
|
|
1553
|
+
total: targets.length,
|
|
1554
|
+
}) +
|
|
1555
|
+
(warnings.length > 0
|
|
1556
|
+
? t("tool.task.matrixPauseErrors", { warnings: warnings.join("; ") })
|
|
1557
|
+
: "")
|
|
1558
|
+
: t("tool.task.pausedText", {
|
|
1559
|
+
name: trimmed,
|
|
1560
|
+
verb,
|
|
1561
|
+
until: untilText,
|
|
1562
|
+
}) +
|
|
1563
|
+
(warnings.length > 0
|
|
1564
|
+
? t("tool.task.pauseError", { warnings: warnings.join("; ") })
|
|
1565
|
+
: "");
|
|
1566
|
+
// Спринт 27.5.2: состояние и ближайший запуск считаем из определения —
|
|
1567
|
+
// schtasks после /change (особенно /enable) отдаёт nextRunTime с задержкой.
|
|
1568
|
+
const effectivePausedUntil = paused
|
|
1569
|
+
? pausedUntil ?? definition.pausedUntil ?? null
|
|
1570
|
+
: null;
|
|
1571
|
+
const after = definitionUpdates
|
|
1572
|
+
? { ...definition, ...definitionUpdates }
|
|
1573
|
+
: { ...definition, paused: false, pausedUntil: undefined };
|
|
1574
|
+
const nextRun = paused ? null : computeTaskNextRun(after);
|
|
1283
1575
|
return {
|
|
1284
1576
|
success: warnings.length === 0,
|
|
1285
1577
|
message,
|
|
1286
1578
|
affected,
|
|
1287
1579
|
warnings,
|
|
1580
|
+
paused,
|
|
1581
|
+
nextRun,
|
|
1582
|
+
pausedUntil: effectivePausedUntil,
|
|
1288
1583
|
};
|
|
1289
1584
|
}
|
|
1290
1585
|
const pauseTaskExecute = wrapExecute(async (args) => {
|
|
@@ -1322,7 +1617,11 @@ async function resumeExpiredPauses() {
|
|
|
1322
1617
|
for (const target of targets) {
|
|
1323
1618
|
await scheduler.resumeTask(target);
|
|
1324
1619
|
}
|
|
1325
|
-
await saveTaskDefinition({
|
|
1620
|
+
await saveTaskDefinition({
|
|
1621
|
+
...definition,
|
|
1622
|
+
pausedUntil: undefined,
|
|
1623
|
+
paused: false,
|
|
1624
|
+
});
|
|
1326
1625
|
console.log(`[windows-scheduler] Автопродолжение: задача "${definition.name}" включена (пауза истекла).`);
|
|
1327
1626
|
}
|
|
1328
1627
|
catch (err) {
|
|
@@ -1476,7 +1775,7 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
|
|
|
1476
1775
|
return {
|
|
1477
1776
|
content: JSON.stringify({
|
|
1478
1777
|
success: false,
|
|
1479
|
-
error: "
|
|
1778
|
+
error: t("tool.workspace.needPath"),
|
|
1480
1779
|
}),
|
|
1481
1780
|
};
|
|
1482
1781
|
}
|
|
@@ -1503,7 +1802,7 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
|
|
|
1503
1802
|
return {
|
|
1504
1803
|
content: JSON.stringify({
|
|
1505
1804
|
success: false,
|
|
1506
|
-
error: "
|
|
1805
|
+
error: t("tool.workspace.needUpdateId"),
|
|
1507
1806
|
}),
|
|
1508
1807
|
};
|
|
1509
1808
|
}
|
|
@@ -1518,7 +1817,7 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
|
|
|
1518
1817
|
return {
|
|
1519
1818
|
content: JSON.stringify({
|
|
1520
1819
|
success: false,
|
|
1521
|
-
error: "
|
|
1820
|
+
error: t("tool.workspace.notFound"),
|
|
1522
1821
|
}),
|
|
1523
1822
|
};
|
|
1524
1823
|
}
|
|
@@ -1542,7 +1841,7 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
|
|
|
1542
1841
|
return {
|
|
1543
1842
|
content: JSON.stringify({
|
|
1544
1843
|
success: false,
|
|
1545
|
-
error: "
|
|
1844
|
+
error: t("tool.workspace.needDeleteId"),
|
|
1546
1845
|
}),
|
|
1547
1846
|
};
|
|
1548
1847
|
}
|
|
@@ -1551,8 +1850,8 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
|
|
|
1551
1850
|
content: JSON.stringify({
|
|
1552
1851
|
success: deleted,
|
|
1553
1852
|
message: deleted
|
|
1554
|
-
? "
|
|
1555
|
-
: "
|
|
1853
|
+
? t("tool.workspace.deleted")
|
|
1854
|
+
: t("tool.workspace.notFound"),
|
|
1556
1855
|
}),
|
|
1557
1856
|
};
|
|
1558
1857
|
}
|
|
@@ -1598,8 +1897,8 @@ const matrixControlExecute = wrapExecute(async (args) => {
|
|
|
1598
1897
|
content: JSON.stringify({
|
|
1599
1898
|
success: true,
|
|
1600
1899
|
message: removed.length > 0
|
|
1601
|
-
?
|
|
1602
|
-
: "
|
|
1900
|
+
? t("tool.matrix.orphansRemoved", { count: removed.length })
|
|
1901
|
+
: t("tool.matrix.orphansNone"),
|
|
1603
1902
|
removed,
|
|
1604
1903
|
}),
|
|
1605
1904
|
};
|
|
@@ -1609,7 +1908,7 @@ const matrixControlExecute = wrapExecute(async (args) => {
|
|
|
1609
1908
|
return {
|
|
1610
1909
|
content: JSON.stringify({
|
|
1611
1910
|
success: false,
|
|
1612
|
-
error:
|
|
1911
|
+
error: t("tool.matrix.actionName", { action: args.action }),
|
|
1613
1912
|
}),
|
|
1614
1913
|
};
|
|
1615
1914
|
}
|
|
@@ -1673,6 +1972,7 @@ const manageSettingsExecute = wrapExecute(async (args) => {
|
|
|
1673
1972
|
return { content: JSON.stringify({ success: true, settings: current }) };
|
|
1674
1973
|
}
|
|
1675
1974
|
if (args.maxConcurrent === undefined &&
|
|
1975
|
+
args.locale === undefined &&
|
|
1676
1976
|
args.winterMode === undefined &&
|
|
1677
1977
|
args.notifications === undefined &&
|
|
1678
1978
|
args.history === undefined &&
|
|
@@ -1681,19 +1981,22 @@ const manageSettingsExecute = wrapExecute(async (args) => {
|
|
|
1681
1981
|
return {
|
|
1682
1982
|
content: JSON.stringify({
|
|
1683
1983
|
success: false,
|
|
1684
|
-
error: "
|
|
1984
|
+
error: t("tool.settings.updateFields"),
|
|
1685
1985
|
settings: current,
|
|
1686
1986
|
}),
|
|
1687
1987
|
};
|
|
1688
1988
|
}
|
|
1689
1989
|
const settings = await saveSettings({
|
|
1690
1990
|
maxConcurrent: args.maxConcurrent,
|
|
1991
|
+
locale: args.locale,
|
|
1691
1992
|
winterMode: args.winterMode,
|
|
1692
1993
|
notifications: args.notifications,
|
|
1693
1994
|
history: args.history,
|
|
1694
1995
|
integrations: args.integrations,
|
|
1695
1996
|
audit: args.audit,
|
|
1696
1997
|
});
|
|
1998
|
+
// Локаль процесса меняется сразу — перезапуск плагина не нужен.
|
|
1999
|
+
setLocale(settings.locale);
|
|
1697
2000
|
return { content: JSON.stringify({ success: true, settings }) };
|
|
1698
2001
|
});
|
|
1699
2002
|
/** manage_templates — список, сохранение и удаление шаблонов задач. */
|
|
@@ -1704,7 +2007,7 @@ const manageTemplatesExecute = wrapExecute(async (args) => {
|
|
|
1704
2007
|
if (args.action === "delete") {
|
|
1705
2008
|
const id = args.id?.trim();
|
|
1706
2009
|
if (!id) {
|
|
1707
|
-
return { content: JSON.stringify({ success: false, error: "
|
|
2010
|
+
return { content: JSON.stringify({ success: false, error: t("tool.template.needDeleteId") }) };
|
|
1708
2011
|
}
|
|
1709
2012
|
const before = await loadTemplates();
|
|
1710
2013
|
const existed = before.some((template) => template.id === id);
|
|
@@ -1712,7 +2015,9 @@ const manageTemplatesExecute = wrapExecute(async (args) => {
|
|
|
1712
2015
|
return {
|
|
1713
2016
|
content: JSON.stringify({
|
|
1714
2017
|
success: existed,
|
|
1715
|
-
message: existed
|
|
2018
|
+
message: existed
|
|
2019
|
+
? t("tool.template.deleted", { id })
|
|
2020
|
+
: t("tool.template.notFound", { id }),
|
|
1716
2021
|
}),
|
|
1717
2022
|
};
|
|
1718
2023
|
}
|
|
@@ -1721,7 +2026,7 @@ const manageTemplatesExecute = wrapExecute(async (args) => {
|
|
|
1721
2026
|
return {
|
|
1722
2027
|
content: JSON.stringify({
|
|
1723
2028
|
success: false,
|
|
1724
|
-
error: "
|
|
2029
|
+
error: t("tool.template.saveRequired"),
|
|
1725
2030
|
}),
|
|
1726
2031
|
};
|
|
1727
2032
|
}
|
|
@@ -1745,7 +2050,7 @@ const manageProfilesExecute = wrapExecute(async (args) => {
|
|
|
1745
2050
|
return {
|
|
1746
2051
|
content: JSON.stringify({
|
|
1747
2052
|
success: false,
|
|
1748
|
-
error:
|
|
2053
|
+
error: t("tool.profile.nameRequired", { action: args.action }),
|
|
1749
2054
|
}),
|
|
1750
2055
|
};
|
|
1751
2056
|
}
|
|
@@ -1755,7 +2060,7 @@ const manageProfilesExecute = wrapExecute(async (args) => {
|
|
|
1755
2060
|
return {
|
|
1756
2061
|
content: JSON.stringify({
|
|
1757
2062
|
success: true,
|
|
1758
|
-
message:
|
|
2063
|
+
message: t("tool.profile.created", { name: meta.name, port: meta.port }),
|
|
1759
2064
|
profile: profile ?? {
|
|
1760
2065
|
name: meta.name,
|
|
1761
2066
|
dir: getProfileDir(meta.name),
|
|
@@ -1775,8 +2080,8 @@ const manageProfilesExecute = wrapExecute(async (args) => {
|
|
|
1775
2080
|
current,
|
|
1776
2081
|
restartRequired: true,
|
|
1777
2082
|
message: isProfilePinnedByEnv()
|
|
1778
|
-
?
|
|
1779
|
-
:
|
|
2083
|
+
? t("tool.profile.envVar", { name: current })
|
|
2084
|
+
: t("tool.profile.active", { name: sanitizeProfileName(name) }),
|
|
1780
2085
|
}),
|
|
1781
2086
|
};
|
|
1782
2087
|
}
|
|
@@ -1785,8 +2090,8 @@ const manageProfilesExecute = wrapExecute(async (args) => {
|
|
|
1785
2090
|
content: JSON.stringify({
|
|
1786
2091
|
success: removed,
|
|
1787
2092
|
message: removed
|
|
1788
|
-
?
|
|
1789
|
-
: "
|
|
2093
|
+
? t("tool.profile.deleted", { name: sanitizeProfileName(name) })
|
|
2094
|
+
: t("tool.profile.notFound"),
|
|
1790
2095
|
}),
|
|
1791
2096
|
};
|
|
1792
2097
|
});
|
|
@@ -1798,14 +2103,14 @@ const transferTasksExecute = wrapExecute(async (args) => {
|
|
|
1798
2103
|
return { content: JSON.stringify({ success: true, data, count }) };
|
|
1799
2104
|
}
|
|
1800
2105
|
if (!args.data) {
|
|
1801
|
-
return { content: JSON.stringify({ success: false, error: "
|
|
2106
|
+
return { content: JSON.stringify({ success: false, error: t("tool.transfer.importData") }) };
|
|
1802
2107
|
}
|
|
1803
2108
|
const parsed = parseImportJson(args.data);
|
|
1804
2109
|
if (parsed.tasks.length === 0) {
|
|
1805
2110
|
return {
|
|
1806
2111
|
content: JSON.stringify({
|
|
1807
2112
|
success: false,
|
|
1808
|
-
error: "
|
|
2113
|
+
error: t("tool.transfer.noTasks"),
|
|
1809
2114
|
errors: parsed.errors,
|
|
1810
2115
|
}),
|
|
1811
2116
|
};
|
|
@@ -1859,7 +2164,12 @@ const cleanupHistoryExecute = wrapExecute(async (args) => {
|
|
|
1859
2164
|
success: true,
|
|
1860
2165
|
message: report.skipped
|
|
1861
2166
|
? report.skipped
|
|
1862
|
-
:
|
|
2167
|
+
: t("tool.history.cleaned", {
|
|
2168
|
+
deleted: report.deleted,
|
|
2169
|
+
byAge: report.deletedByAge,
|
|
2170
|
+
byCount: report.deletedByCount,
|
|
2171
|
+
kept: report.kept,
|
|
2172
|
+
}),
|
|
1863
2173
|
report,
|
|
1864
2174
|
}),
|
|
1865
2175
|
};
|
|
@@ -1868,7 +2178,7 @@ const cleanupHistoryExecute = wrapExecute(async (args) => {
|
|
|
1868
2178
|
const emitEventExecute = wrapExecute(async (args) => {
|
|
1869
2179
|
const eventName = args.eventName?.trim();
|
|
1870
2180
|
if (!eventName) {
|
|
1871
|
-
return { content: JSON.stringify({ success: false, error: "
|
|
2181
|
+
return { content: JSON.stringify({ success: false, error: t("tool.event.nameRequired") }) };
|
|
1872
2182
|
}
|
|
1873
2183
|
const payload = args.payload ?? {};
|
|
1874
2184
|
const definitions = await loadTaskDefinitions();
|
|
@@ -1891,8 +2201,8 @@ const emitEventExecute = wrapExecute(async (args) => {
|
|
|
1891
2201
|
content: JSON.stringify({
|
|
1892
2202
|
success: true,
|
|
1893
2203
|
message: triggered.length > 0
|
|
1894
|
-
?
|
|
1895
|
-
:
|
|
2204
|
+
? t("tool.event.triggered", { count: triggered.length })
|
|
2205
|
+
: t("tool.event.none", { event: eventName }),
|
|
1896
2206
|
triggered,
|
|
1897
2207
|
}),
|
|
1898
2208
|
};
|
|
@@ -1907,7 +2217,7 @@ const manageSecretsExecute = wrapExecute(async (args) => {
|
|
|
1907
2217
|
return {
|
|
1908
2218
|
content: JSON.stringify({
|
|
1909
2219
|
success: false,
|
|
1910
|
-
error: "
|
|
2220
|
+
error: t("tool.secret.nameRequired"),
|
|
1911
2221
|
}),
|
|
1912
2222
|
};
|
|
1913
2223
|
}
|
|
@@ -1918,8 +2228,8 @@ const manageSecretsExecute = wrapExecute(async (args) => {
|
|
|
1918
2228
|
content: JSON.stringify({
|
|
1919
2229
|
success: existed,
|
|
1920
2230
|
message: existed
|
|
1921
|
-
?
|
|
1922
|
-
:
|
|
2231
|
+
? t("tool.secret.deleted", { name })
|
|
2232
|
+
: t("tool.secret.notFound", { name }),
|
|
1923
2233
|
}),
|
|
1924
2234
|
};
|
|
1925
2235
|
}
|
|
@@ -1928,7 +2238,7 @@ const manageSecretsExecute = wrapExecute(async (args) => {
|
|
|
1928
2238
|
return {
|
|
1929
2239
|
content: JSON.stringify({
|
|
1930
2240
|
success: false,
|
|
1931
|
-
error: "
|
|
2241
|
+
error: t("tool.secret.valueRequired"),
|
|
1932
2242
|
}),
|
|
1933
2243
|
};
|
|
1934
2244
|
}
|
|
@@ -1936,7 +2246,7 @@ const manageSecretsExecute = wrapExecute(async (args) => {
|
|
|
1936
2246
|
return {
|
|
1937
2247
|
content: JSON.stringify({
|
|
1938
2248
|
success: true,
|
|
1939
|
-
message:
|
|
2249
|
+
message: t("tool.secret.saved", { name: item.name }),
|
|
1940
2250
|
secret: item,
|
|
1941
2251
|
}),
|
|
1942
2252
|
};
|
|
@@ -2153,6 +2463,14 @@ export default Plugin.define({
|
|
|
2153
2463
|
// Папка проекта — рабочая директория задач по умолчанию. Благодаря ей
|
|
2154
2464
|
// `opencode run` подхватывает opencode.json с MCP-серверами проекта.
|
|
2155
2465
|
projectDirectory = ctx.location?.directory || process.cwd();
|
|
2466
|
+
// Спринт 28: язык интерфейса берём из настроек. Ошибка чтения не должна
|
|
2467
|
+
// мешать старту — в этом случае остаётся локаль по умолчанию (ru).
|
|
2468
|
+
try {
|
|
2469
|
+
setLocale((await loadSettings()).locale);
|
|
2470
|
+
}
|
|
2471
|
+
catch {
|
|
2472
|
+
// Локаль по умолчанию уже активна.
|
|
2473
|
+
}
|
|
2156
2474
|
// Спринт 12: SQLite — основное хранилище. Открываем БД, при первом запуске
|
|
2157
2475
|
// автоматически переносим данные из JSON, затем восстанавливаем прерванные
|
|
2158
2476
|
// запуски. Ошибки миграции не должны мешать плагину стартовать.
|
|
@@ -2170,6 +2488,9 @@ export default Plugin.define({
|
|
|
2170
2488
|
console.error(`[recovery] Не удалось восстановить незавершённые запуски: ${err instanceof Error ? err.message : String(err)}`);
|
|
2171
2489
|
}
|
|
2172
2490
|
checkJsonBackups();
|
|
2491
|
+
void garbageCollectTaskArtifacts().catch((err) => {
|
|
2492
|
+
console.log(`[gc] Не удалось вычистить мусорные файлы: ${err instanceof Error ? err.message : String(err)}`);
|
|
2493
|
+
});
|
|
2173
2494
|
// Спринт 18: ежедневная очистка истории. Ошибка ретеншна не должна мешать
|
|
2174
2495
|
// плагину стартовать — пишем в лог и продолжаем.
|
|
2175
2496
|
void maybeRunHistoryRetention()
|
|
@@ -2518,16 +2839,21 @@ export default Plugin.define({
|
|
|
2518
2839
|
// schedule_task и create_task использовали один и тот же путь.
|
|
2519
2840
|
const rpcHandlers = {
|
|
2520
2841
|
get_tasks: async () => {
|
|
2521
|
-
|
|
2842
|
+
const view = await collectTasksView();
|
|
2843
|
+
return {
|
|
2844
|
+
tasks: view.tasks,
|
|
2845
|
+
osAvailable: view.osAvailable,
|
|
2846
|
+
...(view.osError ? { osError: view.osError } : {}),
|
|
2847
|
+
};
|
|
2522
2848
|
},
|
|
2523
2849
|
create_task: async (input) => {
|
|
2524
2850
|
console.log("[windows-scheduler] create_task input:", input);
|
|
2525
|
-
const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, runAt, delaySeconds, session, sessionMaxRuns, } = input;
|
|
2851
|
+
const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, runAt, delaySeconds, session, sessionMaxRuns, runWhenLoggedOff, } = input;
|
|
2526
2852
|
let effectiveRunAt;
|
|
2527
2853
|
if (triggerType === "once") {
|
|
2528
2854
|
const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
|
|
2529
2855
|
if (!normalized.ok) {
|
|
2530
|
-
return { success: false, message:
|
|
2856
|
+
return { success: false, message: t("tool.error.taskReason", { name, error: normalized.error }) };
|
|
2531
2857
|
}
|
|
2532
2858
|
effectiveRunAt = normalized.runAt;
|
|
2533
2859
|
}
|
|
@@ -2535,18 +2861,31 @@ export default Plugin.define({
|
|
|
2535
2861
|
if (session !== undefined) {
|
|
2536
2862
|
const normalizedSession = normalizeSessionMode(session);
|
|
2537
2863
|
if (!normalizedSession) {
|
|
2538
|
-
return { success: false, message:
|
|
2864
|
+
return { success: false, message: t("tool.error.sessionUnknown", { name, session: String(session) }) };
|
|
2539
2865
|
}
|
|
2540
2866
|
effectiveSession = normalizedSession;
|
|
2541
2867
|
}
|
|
2542
2868
|
if (sessionMaxRuns !== undefined &&
|
|
2543
2869
|
(!Number.isInteger(sessionMaxRuns) || sessionMaxRuns < 1)) {
|
|
2544
|
-
return { success: false, message:
|
|
2870
|
+
return { success: false, message: t("tool.error.sessionMaxRuns", { name }) };
|
|
2545
2871
|
}
|
|
2546
2872
|
const effectiveSessionId = effectiveSession === "reuse" ? generateSessionId() : undefined;
|
|
2547
2873
|
try {
|
|
2548
|
-
await schedulerCreateTask(name, schedule ?? "", prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns);
|
|
2549
|
-
|
|
2874
|
+
await schedulerCreateTask(name, schedule ?? "", prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns, undefined, runWhenLoggedOff === true);
|
|
2875
|
+
const nextRun = computeTaskNextRun({
|
|
2876
|
+
schedule: schedule ?? "",
|
|
2877
|
+
triggerType: triggerType ?? "cron",
|
|
2878
|
+
runAt: effectiveRunAt,
|
|
2879
|
+
timezone,
|
|
2880
|
+
notBefore,
|
|
2881
|
+
notAfter,
|
|
2882
|
+
});
|
|
2883
|
+
return {
|
|
2884
|
+
success: true,
|
|
2885
|
+
paused: false,
|
|
2886
|
+
nextRun,
|
|
2887
|
+
message: t("tool.task.created", { name }),
|
|
2888
|
+
};
|
|
2550
2889
|
}
|
|
2551
2890
|
catch (err) {
|
|
2552
2891
|
const message = err instanceof Error ? err.message : String(err);
|
|
@@ -2560,8 +2899,11 @@ export default Plugin.define({
|
|
|
2560
2899
|
return {
|
|
2561
2900
|
success: true,
|
|
2562
2901
|
message: removed.length > 0
|
|
2563
|
-
?
|
|
2564
|
-
|
|
2902
|
+
? t("tool.task.matrixDeletedCount", {
|
|
2903
|
+
name,
|
|
2904
|
+
count: removed.length,
|
|
2905
|
+
})
|
|
2906
|
+
: t("tool.task.deleted", { name }),
|
|
2565
2907
|
};
|
|
2566
2908
|
}
|
|
2567
2909
|
catch (err) {
|
|
@@ -2592,8 +2934,8 @@ export default Plugin.define({
|
|
|
2592
2934
|
return {
|
|
2593
2935
|
success: true,
|
|
2594
2936
|
message: removed.length > 0
|
|
2595
|
-
?
|
|
2596
|
-
: "
|
|
2937
|
+
? t("tool.matrix.orphansRemoved", { count: removed.length })
|
|
2938
|
+
: t("tool.matrix.orphansNone"),
|
|
2597
2939
|
removed,
|
|
2598
2940
|
};
|
|
2599
2941
|
}
|
|
@@ -2613,9 +2955,21 @@ export default Plugin.define({
|
|
|
2613
2955
|
if (definition?.matrix) {
|
|
2614
2956
|
const matrixResult = await runMatrix(definition);
|
|
2615
2957
|
const total = definition.matrix.workspaceIds.length;
|
|
2616
|
-
const message =
|
|
2617
|
-
|
|
2618
|
-
|
|
2958
|
+
const message = t("tool.matrix.started", {
|
|
2959
|
+
name,
|
|
2960
|
+
started: matrixResult.started.length,
|
|
2961
|
+
total,
|
|
2962
|
+
}) +
|
|
2963
|
+
(matrixResult.skipped.length
|
|
2964
|
+
? t("tool.matrix.startedSkipped", {
|
|
2965
|
+
count: matrixResult.skipped.length,
|
|
2966
|
+
})
|
|
2967
|
+
: "") +
|
|
2968
|
+
(matrixResult.errors.length
|
|
2969
|
+
? t("tool.matrix.startedErrors", {
|
|
2970
|
+
errors: matrixResult.errors.join("; "),
|
|
2971
|
+
})
|
|
2972
|
+
: ".");
|
|
2619
2973
|
return { success: matrixResult.success, message };
|
|
2620
2974
|
}
|
|
2621
2975
|
// Контроль параллелизма: не позволяем запускать новую задачу,
|
|
@@ -2627,7 +2981,7 @@ export default Plugin.define({
|
|
|
2627
2981
|
if (runningCount >= settings.maxConcurrent) {
|
|
2628
2982
|
return {
|
|
2629
2983
|
success: false,
|
|
2630
|
-
message: "
|
|
2984
|
+
message: t("tool.matrix.limit"),
|
|
2631
2985
|
};
|
|
2632
2986
|
}
|
|
2633
2987
|
}
|
|
@@ -2636,9 +2990,9 @@ export default Plugin.define({
|
|
|
2636
2990
|
// в том числе инициированном из GUI, — дублировать запись здесь не нужно.
|
|
2637
2991
|
if (result.alreadyRunning) {
|
|
2638
2992
|
// Мягкое предупреждение: задача уже идёт, это не ошибка запуска.
|
|
2639
|
-
return { success: true, message:
|
|
2993
|
+
return { success: true, message: t("tool.task.alreadyRunning", { name }) };
|
|
2640
2994
|
}
|
|
2641
|
-
return { success: true, message:
|
|
2995
|
+
return { success: true, message: t("tool.task.started", { name }) };
|
|
2642
2996
|
}
|
|
2643
2997
|
catch (err) {
|
|
2644
2998
|
return { success: false, message: `schtasks error: ${err instanceof Error ? err.message : String(err)}` };
|
|
@@ -2648,7 +3002,7 @@ export default Plugin.define({
|
|
|
2648
3002
|
const { eventName, payload } = input;
|
|
2649
3003
|
const normalized = eventName?.trim();
|
|
2650
3004
|
if (!normalized) {
|
|
2651
|
-
return { success: false, message: "
|
|
3005
|
+
return { success: false, message: t("tool.event.nameRequiredShort"), triggered: [] };
|
|
2652
3006
|
}
|
|
2653
3007
|
// Ищем задачи с MCP-триггером, совпадающим по имени события и фильтру.
|
|
2654
3008
|
const definitions = await loadTaskDefinitions();
|
|
@@ -2671,18 +3025,18 @@ export default Plugin.define({
|
|
|
2671
3025
|
return {
|
|
2672
3026
|
success: true,
|
|
2673
3027
|
triggered,
|
|
2674
|
-
message:
|
|
3028
|
+
message: t("tool.event.processed", { event: normalized, count: triggered.length }),
|
|
2675
3029
|
};
|
|
2676
3030
|
},
|
|
2677
3031
|
pause_task: async (input) => {
|
|
2678
3032
|
const { name, until } = input;
|
|
2679
3033
|
const result = await pauseOrResumeTask(name, true, until);
|
|
2680
|
-
return
|
|
3034
|
+
return result;
|
|
2681
3035
|
},
|
|
2682
3036
|
resume_task: async (input) => {
|
|
2683
3037
|
const { name } = input;
|
|
2684
3038
|
const result = await pauseOrResumeTask(name, false);
|
|
2685
|
-
return
|
|
3039
|
+
return result;
|
|
2686
3040
|
},
|
|
2687
3041
|
update_task: async (input) => {
|
|
2688
3042
|
return await updateTaskFromInput(input);
|
|
@@ -2716,8 +3070,12 @@ export default Plugin.define({
|
|
|
2716
3070
|
const report = await runHistoryRetention({ retentionDays, maxRecords });
|
|
2717
3071
|
const message = report.skipped
|
|
2718
3072
|
? report.skipped
|
|
2719
|
-
:
|
|
2720
|
-
|
|
3073
|
+
: t("tool.history.cleaned", {
|
|
3074
|
+
deleted: report.deleted,
|
|
3075
|
+
byAge: report.deletedByAge,
|
|
3076
|
+
byCount: report.deletedByCount,
|
|
3077
|
+
kept: report.kept,
|
|
3078
|
+
});
|
|
2721
3079
|
return {
|
|
2722
3080
|
success: true,
|
|
2723
3081
|
message,
|
|
@@ -2733,7 +3091,9 @@ export default Plugin.define({
|
|
|
2733
3091
|
catch (err) {
|
|
2734
3092
|
return {
|
|
2735
3093
|
success: false,
|
|
2736
|
-
message:
|
|
3094
|
+
message: t("tool.history.cleanFailed", {
|
|
3095
|
+
error: err instanceof Error ? err.message : String(err),
|
|
3096
|
+
}),
|
|
2737
3097
|
deleted: 0,
|
|
2738
3098
|
deletedByAge: 0,
|
|
2739
3099
|
deletedByCount: 0,
|
|
@@ -2817,7 +3177,7 @@ export default Plugin.define({
|
|
|
2817
3177
|
const { parentId } = input;
|
|
2818
3178
|
const target = (parentId ?? "").trim();
|
|
2819
3179
|
if (!target) {
|
|
2820
|
-
return { success: false, error: "
|
|
3180
|
+
return { success: false, error: t("tool.matrix.parentMissing") };
|
|
2821
3181
|
}
|
|
2822
3182
|
try {
|
|
2823
3183
|
const report = aggregateMatrixResults(target);
|
|
@@ -2894,7 +3254,7 @@ export default Plugin.define({
|
|
|
2894
3254
|
const { id, name, path: workspacePath, color, env, envFile } = input;
|
|
2895
3255
|
const workspace = updateWorkspace(id, { name, path: workspacePath, color, env, envFile });
|
|
2896
3256
|
if (!workspace) {
|
|
2897
|
-
return { success: false, error: "
|
|
3257
|
+
return { success: false, error: t("tool.workspace.notFound") };
|
|
2898
3258
|
}
|
|
2899
3259
|
// env-файлы существующих задач перегенерируются сразу (Спринт 21).
|
|
2900
3260
|
await refreshWorkspaceEnvFiles(workspace.id);
|
|
@@ -2918,8 +3278,8 @@ export default Plugin.define({
|
|
|
2918
3278
|
return {
|
|
2919
3279
|
success: deleted,
|
|
2920
3280
|
message: deleted
|
|
2921
|
-
? "
|
|
2922
|
-
: "
|
|
3281
|
+
? t("tool.workspace.deleted")
|
|
3282
|
+
: t("tool.workspace.notFound"),
|
|
2923
3283
|
};
|
|
2924
3284
|
}
|
|
2925
3285
|
catch (err) {
|
|
@@ -2943,8 +3303,8 @@ export default Plugin.define({
|
|
|
2943
3303
|
current,
|
|
2944
3304
|
restartRequired: true,
|
|
2945
3305
|
message: isProfilePinnedByEnv()
|
|
2946
|
-
?
|
|
2947
|
-
:
|
|
3306
|
+
? t("tool.profile.envVarLong", { name: current })
|
|
3307
|
+
: t("tool.profile.active", { name: sanitizeProfileName(name) }),
|
|
2948
3308
|
};
|
|
2949
3309
|
}
|
|
2950
3310
|
catch (err) {
|
|
@@ -2963,7 +3323,7 @@ export default Plugin.define({
|
|
|
2963
3323
|
const profile = listProfiles().find((item) => item.name === meta.name);
|
|
2964
3324
|
return {
|
|
2965
3325
|
success: true,
|
|
2966
|
-
message:
|
|
3326
|
+
message: t("tool.profile.created", { name: meta.name, port: meta.port }),
|
|
2967
3327
|
profile: profile ?? {
|
|
2968
3328
|
name: meta.name,
|
|
2969
3329
|
dir: getProfileDir(meta.name),
|
|
@@ -2987,8 +3347,8 @@ export default Plugin.define({
|
|
|
2987
3347
|
return {
|
|
2988
3348
|
success: removed,
|
|
2989
3349
|
message: removed
|
|
2990
|
-
?
|
|
2991
|
-
: "
|
|
3350
|
+
? t("tool.profile.deleted", { name: sanitizeProfileName(name) })
|
|
3351
|
+
: t("tool.profile.notFound"),
|
|
2992
3352
|
};
|
|
2993
3353
|
}
|
|
2994
3354
|
catch (err) {
|
|
@@ -2999,9 +3359,10 @@ export default Plugin.define({
|
|
|
2999
3359
|
return await loadSettings();
|
|
3000
3360
|
},
|
|
3001
3361
|
save_settings: async (input) => {
|
|
3002
|
-
const { maxConcurrent, winterMode, notifications, history, integrations, audit } = input;
|
|
3362
|
+
const { maxConcurrent, locale, winterMode, notifications, history, integrations, audit } = input;
|
|
3003
3363
|
const current = await loadSettings();
|
|
3004
3364
|
if (maxConcurrent === undefined &&
|
|
3365
|
+
locale === undefined &&
|
|
3005
3366
|
winterMode === undefined &&
|
|
3006
3367
|
notifications === undefined &&
|
|
3007
3368
|
history === undefined &&
|
|
@@ -3010,6 +3371,7 @@ export default Plugin.define({
|
|
|
3010
3371
|
return {
|
|
3011
3372
|
success: false,
|
|
3012
3373
|
maxConcurrent: current.maxConcurrent,
|
|
3374
|
+
locale: current.locale,
|
|
3013
3375
|
winterMode: current.winterMode,
|
|
3014
3376
|
notifications: current.notifications,
|
|
3015
3377
|
history: current.history,
|
|
@@ -3019,15 +3381,19 @@ export default Plugin.define({
|
|
|
3019
3381
|
}
|
|
3020
3382
|
const settings = await saveSettings({
|
|
3021
3383
|
maxConcurrent,
|
|
3384
|
+
locale,
|
|
3022
3385
|
winterMode,
|
|
3023
3386
|
notifications,
|
|
3024
3387
|
history,
|
|
3025
3388
|
integrations,
|
|
3026
3389
|
audit,
|
|
3027
3390
|
});
|
|
3391
|
+
// Локаль процесса меняется сразу — перезапуск не нужен.
|
|
3392
|
+
setLocale(settings.locale);
|
|
3028
3393
|
return {
|
|
3029
3394
|
success: true,
|
|
3030
3395
|
maxConcurrent: settings.maxConcurrent,
|
|
3396
|
+
locale: settings.locale,
|
|
3031
3397
|
winterMode: settings.winterMode,
|
|
3032
3398
|
notifications: settings.notifications,
|
|
3033
3399
|
history: settings.history,
|
|
@@ -3051,15 +3417,15 @@ export default Plugin.define({
|
|
|
3051
3417
|
const source = (input ?? {});
|
|
3052
3418
|
const name = (source.name ?? "").trim();
|
|
3053
3419
|
if (!name) {
|
|
3054
|
-
return { success: false, message: "
|
|
3420
|
+
return { success: false, message: t("tool.secret.needName") };
|
|
3055
3421
|
}
|
|
3056
3422
|
if (typeof source.value !== "string" || source.value.length === 0) {
|
|
3057
|
-
return { success: false, message: "
|
|
3423
|
+
return { success: false, message: t("tool.secret.needValue") };
|
|
3058
3424
|
}
|
|
3059
3425
|
const secret = setSecret(name, source.value);
|
|
3060
3426
|
return {
|
|
3061
3427
|
success: true,
|
|
3062
|
-
message:
|
|
3428
|
+
message: t("tool.secret.saved", { name: secret.name }),
|
|
3063
3429
|
secret,
|
|
3064
3430
|
};
|
|
3065
3431
|
}
|
|
@@ -3074,15 +3440,15 @@ export default Plugin.define({
|
|
|
3074
3440
|
try {
|
|
3075
3441
|
const name = ((input ?? {}).name ?? "").trim();
|
|
3076
3442
|
if (!name) {
|
|
3077
|
-
return { success: false, message: "
|
|
3443
|
+
return { success: false, message: t("tool.secret.needName") };
|
|
3078
3444
|
}
|
|
3079
3445
|
const existed = hasSecret(name);
|
|
3080
3446
|
deleteSecret(name);
|
|
3081
3447
|
return {
|
|
3082
3448
|
success: existed,
|
|
3083
3449
|
message: existed
|
|
3084
|
-
?
|
|
3085
|
-
:
|
|
3450
|
+
? t("tool.secret.deleted", { name })
|
|
3451
|
+
: t("tool.secret.notFound", { name }),
|
|
3086
3452
|
};
|
|
3087
3453
|
}
|
|
3088
3454
|
catch (err) {
|
|
@@ -3119,7 +3485,7 @@ export default Plugin.define({
|
|
|
3119
3485
|
if (!source?.name?.trim() || !source?.prompt?.trim()) {
|
|
3120
3486
|
return {
|
|
3121
3487
|
success: false,
|
|
3122
|
-
error: "
|
|
3488
|
+
error: t("tool.template.namePromptRequired"),
|
|
3123
3489
|
};
|
|
3124
3490
|
}
|
|
3125
3491
|
const template = await saveTemplate({
|
|
@@ -3146,7 +3512,7 @@ export default Plugin.define({
|
|
|
3146
3512
|
delete_template: async (input) => {
|
|
3147
3513
|
const { id } = input;
|
|
3148
3514
|
if (!id) {
|
|
3149
|
-
return { success: false, error: "
|
|
3515
|
+
return { success: false, error: t("tool.template.needId") };
|
|
3150
3516
|
}
|
|
3151
3517
|
try {
|
|
3152
3518
|
await deleteTemplate(id);
|
|
@@ -3176,14 +3542,14 @@ export default Plugin.define({
|
|
|
3176
3542
|
import_tasks: async (input) => {
|
|
3177
3543
|
const { data } = input;
|
|
3178
3544
|
if (!data) {
|
|
3179
|
-
return { success: false, error: "
|
|
3545
|
+
return { success: false, error: t("tool.transfer.noData") };
|
|
3180
3546
|
}
|
|
3181
3547
|
try {
|
|
3182
3548
|
const parsed = parseImportJson(data);
|
|
3183
3549
|
if (parsed.tasks.length === 0) {
|
|
3184
3550
|
return {
|
|
3185
3551
|
success: false,
|
|
3186
|
-
error: "
|
|
3552
|
+
error: t("tool.transfer.noTasksInFile"),
|
|
3187
3553
|
errors: parsed.errors,
|
|
3188
3554
|
};
|
|
3189
3555
|
}
|
|
@@ -3191,7 +3557,16 @@ export default Plugin.define({
|
|
|
3191
3557
|
const errors = [...parsed.errors];
|
|
3192
3558
|
for (const def of parsed.tasks) {
|
|
3193
3559
|
try {
|
|
3194
|
-
await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId, "create", def.timezone, def.notBefore, def.notAfter, def.pausedUntil, def.runAt
|
|
3560
|
+
await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId, "create", def.timezone, def.notBefore, def.notAfter, def.pausedUntil, def.runAt, def.session ?? "new", def.sessionId, def.sessionMaxRuns, {
|
|
3561
|
+
activeDays: def.activeDays,
|
|
3562
|
+
windowPolicy: def.windowPolicy,
|
|
3563
|
+
watchGlobs: def.watchGlobs,
|
|
3564
|
+
watchIgnore: def.watchIgnore,
|
|
3565
|
+
gitBranch: def.gitBranch,
|
|
3566
|
+
gitPaths: def.gitPaths,
|
|
3567
|
+
gitIgnore: def.gitIgnore,
|
|
3568
|
+
gitPollSeconds: def.gitPollSeconds,
|
|
3569
|
+
}, def.runWhenLoggedOff === true, def.paused === true);
|
|
3195
3570
|
await saveTaskDefinition(def);
|
|
3196
3571
|
imported.push(def.name);
|
|
3197
3572
|
}
|
|
@@ -3220,7 +3595,7 @@ export default Plugin.define({
|
|
|
3220
3595
|
// Повторный вызов не создаёт второй сервер — защита от двойного запуска
|
|
3221
3596
|
// реализована внутри startDashboardServer.
|
|
3222
3597
|
const dashboard = await startDashboardServer({
|
|
3223
|
-
getTasks: collectTasksView,
|
|
3598
|
+
getTasks: async () => (await collectTasksView()).tasks,
|
|
3224
3599
|
runTask: (name) => runTaskEntry(name),
|
|
3225
3600
|
deleteTask: async (name) => {
|
|
3226
3601
|
await deleteTaskWithFamily(name);
|
|
@@ -3255,7 +3630,7 @@ function resolveMatrixExtraConfig(name, matrix, ids) {
|
|
|
3255
3630
|
if (typeof matrix.concurrency !== "number" ||
|
|
3256
3631
|
!Number.isFinite(matrix.concurrency) ||
|
|
3257
3632
|
matrix.concurrency < 1) {
|
|
3258
|
-
throw new Error(
|
|
3633
|
+
throw new Error(t("tool.error.matrixConcurrency", { task: name }));
|
|
3259
3634
|
}
|
|
3260
3635
|
extra.concurrency = Math.floor(matrix.concurrency);
|
|
3261
3636
|
}
|
|
@@ -3265,8 +3640,10 @@ function resolveMatrixExtraConfig(name, matrix, ids) {
|
|
|
3265
3640
|
for (const [key, value] of Object.entries(matrix.overrides)) {
|
|
3266
3641
|
const workspaceKey = key.trim();
|
|
3267
3642
|
if (!allowed.has(workspaceKey)) {
|
|
3268
|
-
throw new Error(
|
|
3269
|
-
|
|
3643
|
+
throw new Error(t("tool.error.matrixOverride", {
|
|
3644
|
+
task: name,
|
|
3645
|
+
workspace: workspaceKey,
|
|
3646
|
+
}));
|
|
3270
3647
|
}
|
|
3271
3648
|
if (!value || typeof value !== "object")
|
|
3272
3649
|
continue;
|
|
@@ -3310,7 +3687,26 @@ sessionId,
|
|
|
3310
3687
|
/** Сколько запусков переживает reuse-сессия до ротации (0/undefined — без ограничения). */
|
|
3311
3688
|
sessionMaxRuns,
|
|
3312
3689
|
/** Спринт 27: дни недели, политика окна, glob- и git-фильтры. */
|
|
3313
|
-
triggerExtras
|
|
3690
|
+
triggerExtras,
|
|
3691
|
+
/** Спринт 27.5.4: Windows — запускать без входа пользователя (/ru SYSTEM). */
|
|
3692
|
+
runWhenLoggedOff,
|
|
3693
|
+
/**
|
|
3694
|
+
* Спринт 27.5.8: пересоздать задачу сразу отключённой (пауза переживает
|
|
3695
|
+
* update). Для матрицы пауза применяется к клонам.
|
|
3696
|
+
*/
|
|
3697
|
+
paused) {
|
|
3698
|
+
// Спринт 27.5 (hotfix 1.5.1): проверяем имя до создания wrapper/prompt и записи
|
|
3699
|
+
// в БД. Недопустимые символы отклоняются с понятным сообщением, а не ошибкой
|
|
3700
|
+
// schtasks; имя нормализуется (trim) для всех путей: MCP, RPC и импорт.
|
|
3701
|
+
const normalizedName = name.trim();
|
|
3702
|
+
const nameError = validateTaskName(normalizedName);
|
|
3703
|
+
if (nameError) {
|
|
3704
|
+
throw new Error(nameError);
|
|
3705
|
+
}
|
|
3706
|
+
name = normalizedName;
|
|
3707
|
+
// Для отката файлов: при обновлении существующей задачи файлы переиспользуются,
|
|
3708
|
+
// удалять их при сбое нельзя — в БД остаётся прежнее определение.
|
|
3709
|
+
const definitionExisted = Boolean(getTask(normalizedName));
|
|
3314
3710
|
const normalizedModel = model?.trim() || undefined;
|
|
3315
3711
|
const normalizedPriority = normalizePriority(priority);
|
|
3316
3712
|
const normalizedBefore = beforeScript?.trim() || undefined;
|
|
@@ -3319,6 +3715,10 @@ triggerExtras) {
|
|
|
3319
3715
|
const normalizedNotBefore = notBefore?.trim() || undefined;
|
|
3320
3716
|
const normalizedNotAfter = notAfter?.trim() || undefined;
|
|
3321
3717
|
const normalizedPausedUntil = pausedUntil?.trim() || undefined;
|
|
3718
|
+
// Спринт 27.5.4: true → задача работает без входа (Windows /ru SYSTEM).
|
|
3719
|
+
const normalizedRunWhenLoggedOff = runWhenLoggedOff === true ? true : undefined;
|
|
3720
|
+
// Спринт 27.5.8: пауза сохраняется при пересоздании задачи.
|
|
3721
|
+
const normalizedPaused = paused === true ? true : undefined;
|
|
3322
3722
|
// Спринт 27: дни недели, политика окна и glob/git-фильтры.
|
|
3323
3723
|
const normalizeGlobList = (raw) => {
|
|
3324
3724
|
if (!Array.isArray(raw))
|
|
@@ -3357,7 +3757,7 @@ triggerExtras) {
|
|
|
3357
3757
|
if (effectiveTriggerType === "once") {
|
|
3358
3758
|
const normalized = normalizeOneShotRunAt({ runAt });
|
|
3359
3759
|
if (!normalized.ok) {
|
|
3360
|
-
throw new Error(
|
|
3760
|
+
throw new Error(t("tool.error.taskReason", { name, error: normalized.error }));
|
|
3361
3761
|
}
|
|
3362
3762
|
effectiveRunAt = normalized.runAt;
|
|
3363
3763
|
}
|
|
@@ -3368,7 +3768,10 @@ triggerExtras) {
|
|
|
3368
3768
|
if (session !== undefined) {
|
|
3369
3769
|
const normalizedSession = normalizeSessionMode(session);
|
|
3370
3770
|
if (!normalizedSession) {
|
|
3371
|
-
throw new Error(
|
|
3771
|
+
throw new Error(t("tool.error.sessionUnknown", {
|
|
3772
|
+
name,
|
|
3773
|
+
session: String(session),
|
|
3774
|
+
}));
|
|
3372
3775
|
}
|
|
3373
3776
|
effectiveSession = normalizedSession;
|
|
3374
3777
|
}
|
|
@@ -3389,7 +3792,7 @@ triggerExtras) {
|
|
|
3389
3792
|
return cleaned.length > 0 ? cleaned : undefined;
|
|
3390
3793
|
};
|
|
3391
3794
|
if (Array.isArray(allowedTools) && allowedTools.filter((t) => typeof t === "string" && t.trim()).length === 0) {
|
|
3392
|
-
throw new Error(
|
|
3795
|
+
throw new Error(t("tool.error.allowedToolsEmpty", { task: name }));
|
|
3393
3796
|
}
|
|
3394
3797
|
const normalizedAllowedTools = normalizeToolList(allowedTools);
|
|
3395
3798
|
const normalizedDeniedTools = normalizeToolList(deniedTools);
|
|
@@ -3398,25 +3801,29 @@ triggerExtras) {
|
|
|
3398
3801
|
let normalizedMatrix;
|
|
3399
3802
|
if (matrix) {
|
|
3400
3803
|
if (workspaceId?.trim()) {
|
|
3401
|
-
throw new Error(
|
|
3804
|
+
throw new Error(t("tool.error.workspaceIdConflict", { task: name }));
|
|
3402
3805
|
}
|
|
3403
3806
|
const ids = Array.from(new Set((Array.isArray(matrix.workspaceIds) ? matrix.workspaceIds : [])
|
|
3404
3807
|
.filter((id) => typeof id === "string")
|
|
3405
3808
|
.map((id) => id.trim())
|
|
3406
3809
|
.filter(Boolean)));
|
|
3407
3810
|
if (ids.length === 0) {
|
|
3408
|
-
throw new Error(
|
|
3811
|
+
throw new Error(t("tool.error.workspaceIdsEmpty", { task: name }));
|
|
3409
3812
|
}
|
|
3410
3813
|
for (const id of ids) {
|
|
3411
3814
|
const ws = getWorkspace(id);
|
|
3412
3815
|
if (!ws) {
|
|
3413
|
-
throw new Error(
|
|
3816
|
+
throw new Error(t("tool.error.workspaceMissing", { task: name, id }));
|
|
3414
3817
|
}
|
|
3415
3818
|
try {
|
|
3416
3819
|
validateWorkspacePath(ws.path);
|
|
3417
3820
|
}
|
|
3418
3821
|
catch {
|
|
3419
|
-
throw new Error(
|
|
3822
|
+
throw new Error(t("tool.error.workspaceUnavailable", {
|
|
3823
|
+
task: name,
|
|
3824
|
+
workspace: ws.name,
|
|
3825
|
+
path: ws.path,
|
|
3826
|
+
}));
|
|
3420
3827
|
}
|
|
3421
3828
|
}
|
|
3422
3829
|
normalizedMatrix = {
|
|
@@ -3435,7 +3842,7 @@ triggerExtras) {
|
|
|
3435
3842
|
}
|
|
3436
3843
|
// MCP-триггер без имени события бессмыслен — валидируем до создания файлов.
|
|
3437
3844
|
if (effectiveTriggerType === "mcp-event" && !normalizedMcpEvent) {
|
|
3438
|
-
throw new Error("
|
|
3845
|
+
throw new Error(t("tool.error.mcpEventRequired"));
|
|
3439
3846
|
}
|
|
3440
3847
|
// Спринт 27: git-триггеру нужен git-репозиторий в рабочей директории.
|
|
3441
3848
|
if (effectiveTriggerType === "git") {
|
|
@@ -3443,10 +3850,10 @@ triggerExtras) {
|
|
|
3443
3850
|
? getWorkspace(workspaceId.trim())?.path
|
|
3444
3851
|
: workingDirectory?.trim() || projectDirectory || process.cwd();
|
|
3445
3852
|
if (!gitCwd) {
|
|
3446
|
-
throw new Error(
|
|
3853
|
+
throw new Error(t("tool.error.gitCwdRequired", { task: name }));
|
|
3447
3854
|
}
|
|
3448
3855
|
if (!readGitBranch(gitCwd)) {
|
|
3449
|
-
throw new Error(
|
|
3856
|
+
throw new Error(t("tool.error.gitNoRepo", { task: name, path: gitCwd }));
|
|
3450
3857
|
}
|
|
3451
3858
|
}
|
|
3452
3859
|
// Валидируем cron-выражение до создания файлов. Для file/mcp-event
|
|
@@ -3461,12 +3868,14 @@ triggerExtras) {
|
|
|
3461
3868
|
throw new Error(err.message || String(err));
|
|
3462
3869
|
}
|
|
3463
3870
|
if (normalizedTz && !isValidIanaTimeZone(normalizedTz)) {
|
|
3464
|
-
throw new Error(
|
|
3465
|
-
|
|
3871
|
+
throw new Error(t("tool.error.timezone", {
|
|
3872
|
+
task: name,
|
|
3873
|
+
timezone: normalizedTz,
|
|
3874
|
+
}));
|
|
3466
3875
|
}
|
|
3467
3876
|
const windowError = validateLaunchWindow(normalizedNotBefore, normalizedNotAfter);
|
|
3468
3877
|
if (windowError) {
|
|
3469
|
-
throw new Error(
|
|
3878
|
+
throw new Error(t("tool.error.window", { task: name, error: windowError }));
|
|
3470
3879
|
}
|
|
3471
3880
|
}
|
|
3472
3881
|
// Спринт 27: окно и дни недели применимы и к событийным триггерам
|
|
@@ -3474,7 +3883,7 @@ triggerExtras) {
|
|
|
3474
3883
|
if (effectiveTriggerType !== "cron") {
|
|
3475
3884
|
const windowError = validateLaunchWindow(normalizedNotBefore, normalizedNotAfter);
|
|
3476
3885
|
if (windowError) {
|
|
3477
|
-
throw new Error(
|
|
3886
|
+
throw new Error(t("tool.error.window", { task: name, error: windowError }));
|
|
3478
3887
|
}
|
|
3479
3888
|
}
|
|
3480
3889
|
const sanitized = sanitizeName(name);
|
|
@@ -3498,14 +3907,19 @@ triggerExtras) {
|
|
|
3498
3907
|
const normalizedWorkspaceId = workspaceId?.trim() || undefined;
|
|
3499
3908
|
const workspace = normalizedWorkspaceId ? getWorkspace(normalizedWorkspaceId) : undefined;
|
|
3500
3909
|
if (normalizedWorkspaceId && !workspace) {
|
|
3501
|
-
throw new Error(
|
|
3910
|
+
throw new Error(t("tool.error.workspaceIdMissing", {
|
|
3911
|
+
id: normalizedWorkspaceId,
|
|
3912
|
+
}));
|
|
3502
3913
|
}
|
|
3503
3914
|
if (workspace) {
|
|
3504
3915
|
try {
|
|
3505
3916
|
validateWorkspacePath(workspace.path);
|
|
3506
3917
|
}
|
|
3507
3918
|
catch {
|
|
3508
|
-
throw new Error(
|
|
3919
|
+
throw new Error(t("tool.error.workspacePathMissing", {
|
|
3920
|
+
name: workspace.name,
|
|
3921
|
+
path: workspace.path,
|
|
3922
|
+
}));
|
|
3509
3923
|
}
|
|
3510
3924
|
if (workingDirectory?.trim() && workingDirectory.trim() !== workspace.path) {
|
|
3511
3925
|
console.warn(`[workspace] Задача "${name}": workingDirectory "${workingDirectory.trim()}" ` +
|
|
@@ -3526,7 +3940,9 @@ triggerExtras) {
|
|
|
3526
3940
|
await fs.writeFile(logFile, "", "utf8");
|
|
3527
3941
|
}
|
|
3528
3942
|
catch (err) {
|
|
3529
|
-
throw new Error(
|
|
3943
|
+
throw new Error(t("tool.error.prepareFiles", {
|
|
3944
|
+
error: err.message || String(err),
|
|
3945
|
+
}));
|
|
3530
3946
|
}
|
|
3531
3947
|
// Обёртка зависит от платформы:
|
|
3532
3948
|
// - Windows: .cmd → PowerShell-скрипт (lock, таймаут, метрики);
|
|
@@ -3565,8 +3981,17 @@ triggerExtras) {
|
|
|
3565
3981
|
}
|
|
3566
3982
|
}
|
|
3567
3983
|
catch (err) {
|
|
3568
|
-
throw new Error(
|
|
3984
|
+
throw new Error(t("tool.error.wrapper", {
|
|
3985
|
+
error: err.message || String(err),
|
|
3986
|
+
}));
|
|
3569
3987
|
}
|
|
3988
|
+
// 27.5.5.3: при сбое создания новой задачи убираем подготовленные файлы.
|
|
3989
|
+
// При обновлении файлы переиспользуются существующей задачей — не удаляем.
|
|
3990
|
+
const rollbackArtifacts = async () => {
|
|
3991
|
+
if (definitionExisted)
|
|
3992
|
+
return;
|
|
3993
|
+
await Promise.all([wrapperPath, promptFile, logFile, taskEnvFile].map((file) => file ? fs.unlink(file).catch(() => undefined) : Promise.resolve()));
|
|
3994
|
+
};
|
|
3570
3995
|
try {
|
|
3571
3996
|
// Бэкенд сам преобразует cron в родное расписание ОС.
|
|
3572
3997
|
await scheduler.createTask({
|
|
@@ -3583,11 +4008,47 @@ triggerExtras) {
|
|
|
3583
4008
|
timezone: normalizedTz,
|
|
3584
4009
|
notBefore: normalizedNotBefore,
|
|
3585
4010
|
notAfter: normalizedNotAfter,
|
|
4011
|
+
runWhenLoggedOff: normalizedRunWhenLoggedOff,
|
|
3586
4012
|
});
|
|
3587
4013
|
}
|
|
3588
4014
|
catch (err) {
|
|
4015
|
+
await rollbackArtifacts();
|
|
3589
4016
|
throw new Error(err instanceof Error ? err.message : String(err));
|
|
3590
4017
|
}
|
|
4018
|
+
// Проверяем фактическое наличие задачи в планировщике: до 3 попыток с паузой
|
|
4019
|
+
// 200 мс. Это ловит случай, когда ОС/обёртка вернула код 0, но задачи нет.
|
|
4020
|
+
const isListed = (tasks) => tasks.some((task) => (task.taskName || "").trim().toLowerCase() === name.toLowerCase());
|
|
4021
|
+
let listedTasks;
|
|
4022
|
+
let verifyQueryError;
|
|
4023
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
4024
|
+
try {
|
|
4025
|
+
listedTasks = await scheduler.listTasks();
|
|
4026
|
+
if (isListed(listedTasks))
|
|
4027
|
+
break;
|
|
4028
|
+
}
|
|
4029
|
+
catch (err) {
|
|
4030
|
+
verifyQueryError = err;
|
|
4031
|
+
}
|
|
4032
|
+
if (attempt < 2) {
|
|
4033
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
4034
|
+
}
|
|
4035
|
+
}
|
|
4036
|
+
if (listedTasks && !isListed(listedTasks)) {
|
|
4037
|
+
await rollbackArtifacts();
|
|
4038
|
+
throw new Error(t("tool.error.schedulerNotConfirmed", {
|
|
4039
|
+
task: name,
|
|
4040
|
+
scheduler: scheduler.title,
|
|
4041
|
+
}) +
|
|
4042
|
+
" " +
|
|
4043
|
+
(definitionExisted
|
|
4044
|
+
? t("tool.error.schedulerKeptFiles")
|
|
4045
|
+
: t("tool.error.schedulerRemovedFiles")));
|
|
4046
|
+
}
|
|
4047
|
+
if (!listedTasks && verifyQueryError) {
|
|
4048
|
+
// Список получить не удалось — не удаляем возможно созданную задачу,
|
|
4049
|
+
// но явно предупреждаем: проверка наличия не выполнена.
|
|
4050
|
+
console.warn(`[windows-scheduler] Задача "${name}" создана, но проверить её в планировщике не удалось: ${verifyQueryError instanceof Error ? verifyQueryError.message : String(verifyQueryError)}`);
|
|
4051
|
+
}
|
|
3591
4052
|
// Сохраняем определение задачи для последующего экспорта/импорта.
|
|
3592
4053
|
// Определение до перезаписи: нужно и для очереди матрицы, и для счётчика сессии.
|
|
3593
4054
|
const previousDefinition = getTask(name);
|
|
@@ -3623,6 +4084,10 @@ triggerExtras) {
|
|
|
3623
4084
|
timezone: normalizedTz,
|
|
3624
4085
|
notBefore: normalizedNotBefore,
|
|
3625
4086
|
notAfter: normalizedNotAfter,
|
|
4087
|
+
// Спринт 27.5.4: режим входа (Windows: /ru SYSTEM при true).
|
|
4088
|
+
runWhenLoggedOff: normalizedRunWhenLoggedOff,
|
|
4089
|
+
// Спринт 27.5.8: бессрочная пауза переживает пересоздание.
|
|
4090
|
+
paused: normalizedPaused,
|
|
3626
4091
|
// Спринт 27: дни недели, политика окна, glob- и git-фильтры.
|
|
3627
4092
|
activeDays: normalizedActiveDays,
|
|
3628
4093
|
windowPolicy: normalizedWindowPolicy,
|
|
@@ -3661,7 +4126,7 @@ triggerExtras) {
|
|
|
3661
4126
|
// с нуля, а синхронизируются с новым определением; выполняющиеся — не трогаем.
|
|
3662
4127
|
if (normalizedMatrix) {
|
|
3663
4128
|
const createClone = async (clone) => {
|
|
3664
|
-
await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil);
|
|
4129
|
+
await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused);
|
|
3665
4130
|
};
|
|
3666
4131
|
const removeChild = async (child) => {
|
|
3667
4132
|
try {
|
|
@@ -3676,6 +4141,8 @@ triggerExtras) {
|
|
|
3676
4141
|
catch {
|
|
3677
4142
|
// Не критично.
|
|
3678
4143
|
}
|
|
4144
|
+
// Спринт 27.5.7: при откате прогона не оставляем и файлы клона.
|
|
4145
|
+
await removeTaskArtifacts(child);
|
|
3679
4146
|
};
|
|
3680
4147
|
// Создаёт/обновляет/удаляет matrix-complete по текущему определению.
|
|
3681
4148
|
const syncAggregator = async () => {
|
|
@@ -3688,8 +4155,10 @@ triggerExtras) {
|
|
|
3688
4155
|
const cloneNames = listMatrixClones(name).map((clone) => clone.name);
|
|
3689
4156
|
if (cloneNames.length === 0)
|
|
3690
4157
|
return undefined;
|
|
3691
|
-
await schedulerCreateTask(aggregatorName, schedule,
|
|
3692
|
-
|
|
4158
|
+
await schedulerCreateTask(aggregatorName, schedule, t("tool.matrix.completed", {
|
|
4159
|
+
name,
|
|
4160
|
+
clones: cloneNames.join(", "),
|
|
4161
|
+
}), timeoutSeconds, undefined, undefined, undefined, undefined, undefined, undefined, "file", undefined, cloneNames, normalizedModel, normalizedPriority);
|
|
3693
4162
|
return aggregatorName;
|
|
3694
4163
|
};
|
|
3695
4164
|
if (matrixMode === "sync") {
|
|
@@ -3714,13 +4183,101 @@ triggerExtras) {
|
|
|
3714
4183
|
for (const child of removeMatrixChildren(name)) {
|
|
3715
4184
|
await removeChild(child);
|
|
3716
4185
|
}
|
|
3717
|
-
|
|
3718
|
-
|
|
3719
|
-
|
|
4186
|
+
// Спринт 27.5.7: если клон не создался, откатываем весь прогон. Иначе
|
|
4187
|
+
// остаётся родитель с половиной клонов — он выглядит рабочим, но часть
|
|
4188
|
+
// workspace никогда не запускается. Ошибку expandMatrixTask (неизвестный
|
|
4189
|
+
// workspace) обрабатываем там же: родитель уже записан в БД.
|
|
4190
|
+
const createdInRun = [];
|
|
4191
|
+
try {
|
|
4192
|
+
const clones = expandMatrixTask(taskDefinition);
|
|
4193
|
+
for (const clone of clones) {
|
|
4194
|
+
try {
|
|
4195
|
+
await createClone(clone);
|
|
4196
|
+
createdInRun.push(clone.name);
|
|
4197
|
+
}
|
|
4198
|
+
catch (err) {
|
|
4199
|
+
const workspaceLabel = clone.workspaceId
|
|
4200
|
+
? getWorkspace(clone.workspaceId)?.name ?? clone.workspaceId
|
|
4201
|
+
: "без workspace";
|
|
4202
|
+
throw new Error(t("tool.error.matrixCloneFailed", {
|
|
4203
|
+
clone: clone.name,
|
|
4204
|
+
workspace: workspaceLabel,
|
|
4205
|
+
error: err instanceof Error ? err.message : String(err),
|
|
4206
|
+
}));
|
|
4207
|
+
}
|
|
4208
|
+
}
|
|
4209
|
+
await syncAggregator();
|
|
4210
|
+
}
|
|
4211
|
+
catch (err) {
|
|
4212
|
+
for (const child of [...createdInRun].reverse()) {
|
|
4213
|
+
await removeChild(child);
|
|
4214
|
+
}
|
|
4215
|
+
const aggregatorName = matrixCompleteName(name);
|
|
4216
|
+
if (getTask(aggregatorName)) {
|
|
4217
|
+
await removeChild(aggregatorName);
|
|
4218
|
+
}
|
|
4219
|
+
// Новая матрица: без клонов родитель бесполезен — убираем и его,
|
|
4220
|
+
// вместе с подготовленными файлами обёртки.
|
|
4221
|
+
if (!definitionExisted) {
|
|
4222
|
+
try {
|
|
4223
|
+
await scheduler.deleteTask(name);
|
|
4224
|
+
}
|
|
4225
|
+
catch {
|
|
4226
|
+
// Задачи могло не быть: бэкенд уже вернул ошибку.
|
|
4227
|
+
}
|
|
4228
|
+
try {
|
|
4229
|
+
await removeTaskDefinition(name);
|
|
4230
|
+
}
|
|
4231
|
+
catch {
|
|
4232
|
+
// Не критично: запись могла не сохраниться.
|
|
4233
|
+
}
|
|
4234
|
+
await rollbackArtifacts();
|
|
4235
|
+
}
|
|
4236
|
+
throw new Error(t("tool.error.matrixExpandRuntime", {
|
|
4237
|
+
name,
|
|
4238
|
+
error: err instanceof Error ? err.message : String(err),
|
|
4239
|
+
}));
|
|
3720
4240
|
}
|
|
3721
|
-
await syncAggregator();
|
|
3722
4241
|
}
|
|
3723
4242
|
}
|
|
4243
|
+
// Спринт 27.5.8: пересозданная задача должна остаться на паузе. У матрицы
|
|
4244
|
+
// пауза применяется к клонам — родитель сам никогда не выполняется.
|
|
4245
|
+
if (normalizedPaused) {
|
|
4246
|
+
const pauseTargets = normalizedMatrix
|
|
4247
|
+
? listMatrixClones(name).map((clone) => clone.name)
|
|
4248
|
+
: [name];
|
|
4249
|
+
for (const target of pauseTargets) {
|
|
4250
|
+
try {
|
|
4251
|
+
await scheduler.pauseTask(target);
|
|
4252
|
+
}
|
|
4253
|
+
catch (err) {
|
|
4254
|
+
console.warn(`[windows-scheduler] Задача "${target}": пауза не восстановлена после пересоздания: ${err instanceof Error ? err.message : String(err)}`);
|
|
4255
|
+
}
|
|
4256
|
+
}
|
|
4257
|
+
}
|
|
4258
|
+
}
|
|
4259
|
+
/**
|
|
4260
|
+
* Спринт 27.5.6: восстановление задачи из определения в БД.
|
|
4261
|
+
*
|
|
4262
|
+
* update_task пересоздаёт задачу в планировщике (delete + create). Раньше при
|
|
4263
|
+
* сбое create после успешного delete старая версия терялась навсегда: в ОС её
|
|
4264
|
+
* уже нет, а в БД лежит новое (не применённое) определение. Здесь мы заново
|
|
4265
|
+
* создаём задачу из прежнего определения — обёртка, промпт, расписание и
|
|
4266
|
+
* пауза восстанавливаются тем же путём, что и при обычном create.
|
|
4267
|
+
*/
|
|
4268
|
+
async function recreateTaskFromDefinition(definition) {
|
|
4269
|
+
const paused = Boolean(definition.paused === true ||
|
|
4270
|
+
(definition.pausedUntil && Date.parse(definition.pausedUntil) > Date.now()));
|
|
4271
|
+
await schedulerCreateTask(definition.name, definition.schedule ?? "", definition.prompt, definition.timeoutSeconds, definition.workingDirectory, definition.retryCount, definition.retryDelay, definition.qualityGate, definition.nextTaskOnSuccess, definition.nextTaskOnError, definition.triggerType ?? "cron", definition.watchPath, Array.isArray(definition.dependsOn) ? definition.dependsOn : undefined, definition.model, definition.priority, definition.beforeScript, definition.afterScript, definition.mcpEvent, definition.workspaceId, definition.allowedTools, definition.deniedTools, definition.matrix, definition.matrixParentId, "create", definition.timezone, definition.notBefore, definition.notAfter, definition.pausedUntil, definition.runAt, definition.session ?? "new", definition.sessionId, definition.sessionMaxRuns, {
|
|
4272
|
+
activeDays: definition.activeDays,
|
|
4273
|
+
windowPolicy: definition.windowPolicy,
|
|
4274
|
+
watchGlobs: definition.watchGlobs,
|
|
4275
|
+
watchIgnore: definition.watchIgnore,
|
|
4276
|
+
gitBranch: definition.gitBranch,
|
|
4277
|
+
gitPaths: definition.gitPaths,
|
|
4278
|
+
gitIgnore: definition.gitIgnore,
|
|
4279
|
+
gitPollSeconds: definition.gitPollSeconds,
|
|
4280
|
+
}, definition.runWhenLoggedOff, paused);
|
|
3724
4281
|
}
|
|
3725
4282
|
/**
|
|
3726
4283
|
* Запуск задачи «как есть», но с учётом матрицы: родитель раскладывается
|
|
@@ -3749,18 +4306,51 @@ async function runTaskEntry(name) {
|
|
|
3749
4306
|
throw err;
|
|
3750
4307
|
}
|
|
3751
4308
|
}
|
|
4309
|
+
/**
|
|
4310
|
+
* Спринт 27.5.3: чтение задач ОС с одним повтором.
|
|
4311
|
+
*
|
|
4312
|
+
* Сразу после мутации (create/delete/pause/resume) `schtasks /query` иногда
|
|
4313
|
+
* отдаёт пустой список, хотя в БД задачи уже есть, или падает. Один короткий
|
|
4314
|
+
* retry убирает ложный «задач нет»; если ОС так и не ответила осмысленно —
|
|
4315
|
+
* возвращаем `osAvailable: false`, и вызывающий код показывает состояние БД.
|
|
4316
|
+
*/
|
|
4317
|
+
async function readOsTasksWithRetry(expectNonEmpty, delayMs = 300) {
|
|
4318
|
+
let lastError;
|
|
4319
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
4320
|
+
if (attempt > 0) {
|
|
4321
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
4322
|
+
}
|
|
4323
|
+
try {
|
|
4324
|
+
const tasks = await scheduler.listTasks();
|
|
4325
|
+
if (tasks.length > 0 || !expectNonEmpty) {
|
|
4326
|
+
return { tasks, osAvailable: true };
|
|
4327
|
+
}
|
|
4328
|
+
lastError = "планировщик ОС вернул пустой список, хотя в БД есть задачи";
|
|
4329
|
+
}
|
|
4330
|
+
catch (err) {
|
|
4331
|
+
lastError = err instanceof Error ? err.message : String(err);
|
|
4332
|
+
}
|
|
4333
|
+
}
|
|
4334
|
+
return { tasks: [], osAvailable: false, osError: lastError };
|
|
4335
|
+
}
|
|
3752
4336
|
/**
|
|
3753
4337
|
* Собирает задачи плагина в формате, который отдают оба потребителя:
|
|
3754
4338
|
* RPC get_tasks (GUI) и инструмент list_tasks (агент).
|
|
4339
|
+
*
|
|
4340
|
+
* Спринт 27.5.3: возвращает также состояние чтения ОС. Если ОС недоступна,
|
|
4341
|
+
* `tasks` — состояние из БД (задачи помечены `orphaned: true`), а не пустой
|
|
4342
|
+
* массив: иначе GUI и агент решали бы, что задач нет.
|
|
3755
4343
|
*/
|
|
3756
4344
|
async function collectTasksView() {
|
|
3757
|
-
const
|
|
4345
|
+
const defs = await loadTaskDefinitions();
|
|
4346
|
+
const osRead = await readOsTasksWithRetry(defs.length > 0);
|
|
4347
|
+
const tasks = osRead.tasks;
|
|
3758
4348
|
// Читаем историю один раз, чтобы определить финальный статус по последней записи.
|
|
3759
4349
|
const history = await loadHistory();
|
|
3760
4350
|
// loadHistory() отдаёт записи от новых к старым; helper оставляет самую свежую.
|
|
3761
4351
|
const lastByTask = latestHistoryByTask(history);
|
|
3762
|
-
//
|
|
3763
|
-
|
|
4352
|
+
// Определения задач читаются один раз заранее (см. выше) — расписание,
|
|
4353
|
+
// повторы, цепочки, директория.
|
|
3764
4354
|
const workspaces = listWorkspaces();
|
|
3765
4355
|
const workspaceById = new Map(workspaces.map((workspace) => [workspace.id, workspace]));
|
|
3766
4356
|
// Счётчики запусков по задачам. Основной источник — таблица metrics
|
|
@@ -3800,7 +4390,7 @@ async function collectTasksView() {
|
|
|
3800
4390
|
orphaned: true,
|
|
3801
4391
|
})),
|
|
3802
4392
|
];
|
|
3803
|
-
|
|
4393
|
+
const view = sources.map(({ task: t, orphaned }) => {
|
|
3804
4394
|
// Все бэкенды возвращают короткие имена (без папки планировщика).
|
|
3805
4395
|
const name = t.taskName || "";
|
|
3806
4396
|
// Приоритет 1: статус, который сообщает планировщик ОС.
|
|
@@ -3840,6 +4430,13 @@ async function collectTasksView() {
|
|
|
3840
4430
|
error: 0,
|
|
3841
4431
|
partial: 0,
|
|
3842
4432
|
};
|
|
4433
|
+
// Спринт 27.5.2: пауза учитывает и флаг ОС, и активный pausedUntil.
|
|
4434
|
+
// nextRun считаем из определения — schtasks после мутации отдаёт
|
|
4435
|
+
// nextRunTime с задержкой, из-за чего API показывал null после resume.
|
|
4436
|
+
const pausedUntil = def?.pausedUntil ?? null;
|
|
4437
|
+
const paused = Boolean(t.paused) ||
|
|
4438
|
+
def?.paused === true ||
|
|
4439
|
+
Boolean(pausedUntil && Date.parse(pausedUntil) > Date.now());
|
|
3843
4440
|
return {
|
|
3844
4441
|
name,
|
|
3845
4442
|
schedule: def?.schedule ?? "",
|
|
@@ -3848,15 +4445,15 @@ async function collectTasksView() {
|
|
|
3848
4445
|
// Спринт 24 (фикс): явный признак паузы. Раньше GUI пытался вывести его
|
|
3849
4446
|
// из текстового статуса, но mapStatus() превращает "disabled" в "unknown",
|
|
3850
4447
|
// поэтому кнопка «возобновить» была недоступна.
|
|
3851
|
-
paused
|
|
4448
|
+
paused,
|
|
3852
4449
|
runsTotal: counts.total,
|
|
3853
4450
|
runsSuccess: counts.success,
|
|
3854
4451
|
runsError: counts.error,
|
|
3855
4452
|
runsPartial: counts.partial,
|
|
3856
|
-
|
|
3857
|
-
|
|
3858
|
-
|
|
3859
|
-
|
|
4453
|
+
nextRun: paused
|
|
4454
|
+
? null
|
|
4455
|
+
: computeTaskNextRun(def) ??
|
|
4456
|
+
(t.nextRunTime ? String(t.nextRunTime) : null),
|
|
3860
4457
|
runAt: def?.runAt ?? null,
|
|
3861
4458
|
session: def?.session ?? "new",
|
|
3862
4459
|
sessionId: def?.sessionId ?? null,
|
|
@@ -3879,6 +4476,10 @@ async function collectTasksView() {
|
|
|
3879
4476
|
notBefore: def?.notBefore ?? null,
|
|
3880
4477
|
notAfter: def?.notAfter ?? null,
|
|
3881
4478
|
pausedUntil: def?.pausedUntil ?? null,
|
|
4479
|
+
// Спринт 27.5.4: режим входа — из ОС (Interactive/Background) и из
|
|
4480
|
+
// определения (запуск без входа через /ru SYSTEM).
|
|
4481
|
+
logonMode: t.logonMode ?? null,
|
|
4482
|
+
runWhenLoggedOff: Boolean(def?.runWhenLoggedOff),
|
|
3882
4483
|
workingDirectory: workspace?.path ?? def?.workingDirectory ?? def?.workdir ?? null,
|
|
3883
4484
|
workspaceId: workspace?.id ?? def?.workspaceId ?? null,
|
|
3884
4485
|
workspaceName: workspace?.name ?? null,
|
|
@@ -3901,6 +4502,7 @@ async function collectTasksView() {
|
|
|
3901
4502
|
prompt: def?.prompt ?? "",
|
|
3902
4503
|
};
|
|
3903
4504
|
});
|
|
4505
|
+
return { tasks: view, osAvailable: osRead.osAvailable, osError: osRead.osError };
|
|
3904
4506
|
}
|
|
3905
4507
|
/**
|
|
3906
4508
|
* Проверяет фильтр MCP-события.
|