@hasna/testers 0.0.1 → 0.0.2

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.
@@ -80,6 +80,26 @@ function screenshotFromRow(row) {
80
80
  timestamp: row.timestamp
81
81
  };
82
82
  }
83
+ function scheduleFromRow(row) {
84
+ return {
85
+ id: row.id,
86
+ projectId: row.project_id,
87
+ name: row.name,
88
+ cronExpression: row.cron_expression,
89
+ url: row.url,
90
+ scenarioFilter: JSON.parse(row.scenario_filter),
91
+ model: row.model,
92
+ headed: row.headed === 1,
93
+ parallel: row.parallel,
94
+ timeoutMs: row.timeout_ms,
95
+ enabled: row.enabled === 1,
96
+ lastRunId: row.last_run_id,
97
+ lastRunAt: row.last_run_at,
98
+ nextRunAt: row.next_run_at,
99
+ createdAt: row.created_at,
100
+ updatedAt: row.updated_at
101
+ };
102
+ }
83
103
  class VersionConflictError extends Error {
84
104
  constructor(entity, id) {
85
105
  super(`Version conflict on ${entity}: ${id}`);
@@ -100,6 +120,12 @@ class AIClientError extends Error {
100
120
  this.name = "AIClientError";
101
121
  }
102
122
  }
123
+ class ScheduleNotFoundError extends Error {
124
+ constructor(id) {
125
+ super(`Schedule not found: ${id}`);
126
+ this.name = "ScheduleNotFoundError";
127
+ }
128
+ }
103
129
 
104
130
  // src/db/database.ts
105
131
  import { Database } from "bun:sqlite";
@@ -229,6 +255,30 @@ var MIGRATIONS = [
229
255
  `
230
256
  ALTER TABLE projects ADD COLUMN scenario_prefix TEXT DEFAULT 'TST';
231
257
  ALTER TABLE projects ADD COLUMN scenario_counter INTEGER DEFAULT 0;
258
+ `,
259
+ `
260
+ CREATE TABLE IF NOT EXISTS schedules (
261
+ id TEXT PRIMARY KEY,
262
+ project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
263
+ name TEXT NOT NULL,
264
+ cron_expression TEXT NOT NULL,
265
+ url TEXT NOT NULL,
266
+ scenario_filter TEXT NOT NULL DEFAULT '{}',
267
+ model TEXT,
268
+ headed INTEGER NOT NULL DEFAULT 0,
269
+ parallel INTEGER NOT NULL DEFAULT 1,
270
+ timeout_ms INTEGER,
271
+ enabled INTEGER NOT NULL DEFAULT 1,
272
+ last_run_id TEXT REFERENCES runs(id) ON DELETE SET NULL,
273
+ last_run_at TEXT,
274
+ next_run_at TEXT,
275
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
276
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
277
+ );
278
+
279
+ CREATE INDEX IF NOT EXISTS idx_schedules_project ON schedules(project_id);
280
+ CREATE INDEX IF NOT EXISTS idx_schedules_enabled ON schedules(enabled);
281
+ CREATE INDEX IF NOT EXISTS idx_schedules_next_run ON schedules(next_run_at);
232
282
  `
233
283
  ];
234
284
  function applyMigrations(database) {
@@ -950,6 +1000,127 @@ var BROWSER_TOOLS = [
950
1000
  required: ["text"]
951
1001
  }
952
1002
  },
1003
+ {
1004
+ name: "scroll",
1005
+ description: "Scroll the page up or down by a given amount of pixels.",
1006
+ input_schema: {
1007
+ type: "object",
1008
+ properties: {
1009
+ direction: {
1010
+ type: "string",
1011
+ enum: ["up", "down"],
1012
+ description: "Direction to scroll."
1013
+ },
1014
+ amount: {
1015
+ type: "number",
1016
+ description: "Number of pixels to scroll (default: 500)."
1017
+ }
1018
+ },
1019
+ required: ["direction"]
1020
+ }
1021
+ },
1022
+ {
1023
+ name: "get_page_html",
1024
+ description: "Get simplified HTML of the page body content, truncated to 8000 characters.",
1025
+ input_schema: {
1026
+ type: "object",
1027
+ properties: {},
1028
+ required: []
1029
+ }
1030
+ },
1031
+ {
1032
+ name: "get_elements",
1033
+ description: "List elements matching a CSS selector with their text, tag name, and key attributes (max 20 results).",
1034
+ input_schema: {
1035
+ type: "object",
1036
+ properties: {
1037
+ selector: {
1038
+ type: "string",
1039
+ description: "CSS selector to match elements."
1040
+ }
1041
+ },
1042
+ required: ["selector"]
1043
+ }
1044
+ },
1045
+ {
1046
+ name: "wait_for_navigation",
1047
+ description: "Wait for page navigation/load to complete (network idle).",
1048
+ input_schema: {
1049
+ type: "object",
1050
+ properties: {
1051
+ timeout: {
1052
+ type: "number",
1053
+ description: "Maximum time to wait in milliseconds (default: 10000)."
1054
+ }
1055
+ },
1056
+ required: []
1057
+ }
1058
+ },
1059
+ {
1060
+ name: "get_page_title",
1061
+ description: "Get the document title of the current page.",
1062
+ input_schema: {
1063
+ type: "object",
1064
+ properties: {},
1065
+ required: []
1066
+ }
1067
+ },
1068
+ {
1069
+ name: "count_elements",
1070
+ description: "Count the number of elements matching a CSS selector.",
1071
+ input_schema: {
1072
+ type: "object",
1073
+ properties: {
1074
+ selector: {
1075
+ type: "string",
1076
+ description: "CSS selector to count matching elements."
1077
+ }
1078
+ },
1079
+ required: ["selector"]
1080
+ }
1081
+ },
1082
+ {
1083
+ name: "hover",
1084
+ description: "Hover over an element matching the given CSS selector.",
1085
+ input_schema: {
1086
+ type: "object",
1087
+ properties: {
1088
+ selector: {
1089
+ type: "string",
1090
+ description: "CSS selector of the element to hover over."
1091
+ }
1092
+ },
1093
+ required: ["selector"]
1094
+ }
1095
+ },
1096
+ {
1097
+ name: "check",
1098
+ description: "Check a checkbox matching the given CSS selector.",
1099
+ input_schema: {
1100
+ type: "object",
1101
+ properties: {
1102
+ selector: {
1103
+ type: "string",
1104
+ description: "CSS selector of the checkbox to check."
1105
+ }
1106
+ },
1107
+ required: ["selector"]
1108
+ }
1109
+ },
1110
+ {
1111
+ name: "uncheck",
1112
+ description: "Uncheck a checkbox matching the given CSS selector.",
1113
+ input_schema: {
1114
+ type: "object",
1115
+ properties: {
1116
+ selector: {
1117
+ type: "string",
1118
+ description: "CSS selector of the checkbox to uncheck."
1119
+ }
1120
+ },
1121
+ required: ["selector"]
1122
+ }
1123
+ },
953
1124
  {
954
1125
  name: "report_result",
955
1126
  description: "Report the final test result. Call this when you have completed testing the scenario. This MUST be the last tool you call.",
@@ -1081,6 +1252,113 @@ async function executeTool(page, screenshotter, toolName, toolInput, context) {
1081
1252
  return { result: "false" };
1082
1253
  }
1083
1254
  }
1255
+ case "scroll": {
1256
+ const direction = toolInput.direction;
1257
+ const amount = typeof toolInput.amount === "number" ? toolInput.amount : 500;
1258
+ const scrollY = direction === "down" ? amount : -amount;
1259
+ await page.evaluate((y) => window.scrollBy(0, y), scrollY);
1260
+ const screenshot = await screenshotter.capture(page, {
1261
+ runId: context.runId,
1262
+ scenarioSlug: context.scenarioSlug,
1263
+ stepNumber: context.stepNumber,
1264
+ action: "scroll"
1265
+ });
1266
+ return {
1267
+ result: `Scrolled ${direction} by ${amount}px`,
1268
+ screenshot
1269
+ };
1270
+ }
1271
+ case "get_page_html": {
1272
+ const html = await page.evaluate(() => document.body.innerHTML);
1273
+ const truncated = html.length > 8000 ? html.slice(0, 8000) + "..." : html;
1274
+ return {
1275
+ result: truncated
1276
+ };
1277
+ }
1278
+ case "get_elements": {
1279
+ const selector = toolInput.selector;
1280
+ const allElements = await page.locator(selector).all();
1281
+ const elements = allElements.slice(0, 20);
1282
+ const results = [];
1283
+ for (let i = 0;i < elements.length; i++) {
1284
+ const el = elements[i];
1285
+ const tagName = await el.evaluate((e) => e.tagName.toLowerCase());
1286
+ const textContent = await el.textContent() ?? "";
1287
+ const trimmedText = textContent.trim().slice(0, 100);
1288
+ const id = await el.getAttribute("id");
1289
+ const className = await el.getAttribute("class");
1290
+ const href = await el.getAttribute("href");
1291
+ const type = await el.getAttribute("type");
1292
+ const placeholder = await el.getAttribute("placeholder");
1293
+ const ariaLabel = await el.getAttribute("aria-label");
1294
+ const attrs = [];
1295
+ if (id)
1296
+ attrs.push(`id="${id}"`);
1297
+ if (className)
1298
+ attrs.push(`class="${className}"`);
1299
+ if (href)
1300
+ attrs.push(`href="${href}"`);
1301
+ if (type)
1302
+ attrs.push(`type="${type}"`);
1303
+ if (placeholder)
1304
+ attrs.push(`placeholder="${placeholder}"`);
1305
+ if (ariaLabel)
1306
+ attrs.push(`aria-label="${ariaLabel}"`);
1307
+ results.push(`[${i}] <${tagName}${attrs.length ? " " + attrs.join(" ") : ""}> ${trimmedText}`);
1308
+ }
1309
+ return {
1310
+ result: results.length > 0 ? results.join(`
1311
+ `) : `No elements found matching "${selector}"`
1312
+ };
1313
+ }
1314
+ case "wait_for_navigation": {
1315
+ const timeout = typeof toolInput.timeout === "number" ? toolInput.timeout : 1e4;
1316
+ await page.waitForLoadState("networkidle", { timeout });
1317
+ return {
1318
+ result: "Navigation/load completed"
1319
+ };
1320
+ }
1321
+ case "get_page_title": {
1322
+ const title = await page.title();
1323
+ return {
1324
+ result: title || "(no title)"
1325
+ };
1326
+ }
1327
+ case "count_elements": {
1328
+ const selector = toolInput.selector;
1329
+ const count = await page.locator(selector).count();
1330
+ return {
1331
+ result: `${count} element(s) matching "${selector}"`
1332
+ };
1333
+ }
1334
+ case "hover": {
1335
+ const selector = toolInput.selector;
1336
+ await page.hover(selector);
1337
+ const screenshot = await screenshotter.capture(page, {
1338
+ runId: context.runId,
1339
+ scenarioSlug: context.scenarioSlug,
1340
+ stepNumber: context.stepNumber,
1341
+ action: "hover"
1342
+ });
1343
+ return {
1344
+ result: `Hovered over: ${selector}`,
1345
+ screenshot
1346
+ };
1347
+ }
1348
+ case "check": {
1349
+ const selector = toolInput.selector;
1350
+ await page.check(selector);
1351
+ return {
1352
+ result: `Checked checkbox: ${selector}`
1353
+ };
1354
+ }
1355
+ case "uncheck": {
1356
+ const selector = toolInput.selector;
1357
+ await page.uncheck(selector);
1358
+ return {
1359
+ result: `Unchecked checkbox: ${selector}`
1360
+ };
1361
+ }
1084
1362
  case "report_result": {
1085
1363
  const status = toolInput.status;
1086
1364
  const reasoning = toolInput.reasoning;
@@ -1107,13 +1385,26 @@ async function runAgentLoop(options) {
1107
1385
  maxTurns = 30
1108
1386
  } = options;
1109
1387
  const systemPrompt = [
1110
- "You are a QA testing agent. Test the following scenario by interacting with the browser.",
1111
- "Use the provided tools to navigate, click, fill forms, and verify results.",
1112
- "When done, call report_result with your findings.",
1113
- "Be methodical: navigate to the target page first, then follow the test steps.",
1114
- "If a step fails, try reasonable alternatives before reporting failure.",
1115
- "Always report a final result \u2014 never leave a test incomplete."
1116
- ].join(" ");
1388
+ "You are an expert QA testing agent. Your job is to thoroughly test web application scenarios.",
1389
+ "You have browser tools to navigate, interact with, and inspect web pages.",
1390
+ "",
1391
+ "Strategy:",
1392
+ "1. First navigate to the target page and take a screenshot to understand the layout",
1393
+ "2. If you can't find an element, use get_elements or get_page_html to discover selectors",
1394
+ "3. Use scroll to discover content below the fold",
1395
+ "4. Use wait_for or wait_for_navigation after actions that trigger page loads",
1396
+ "5. Take screenshots after every meaningful state change",
1397
+ "6. Use assert_text and assert_visible to verify expected outcomes",
1398
+ "7. When done testing, call report_result with detailed pass/fail reasoning",
1399
+ "",
1400
+ "Tips:",
1401
+ "- Try multiple selector strategies: by text, by role, by class, by id",
1402
+ "- If a click triggers navigation, use wait_for_navigation after",
1403
+ "- For forms, fill all fields before submitting",
1404
+ "- Check for error messages after form submissions",
1405
+ "- Verify both positive and negative states"
1406
+ ].join(`
1407
+ `);
1117
1408
  const userParts = [
1118
1409
  `**Scenario:** ${scenario.name}`,
1119
1410
  `**Description:** ${scenario.description}`
@@ -1424,6 +1715,345 @@ function estimateCost(model, tokens) {
1424
1715
  return tokens / 1e6 * costPer1M * 100;
1425
1716
  }
1426
1717
 
1718
+ // src/db/schedules.ts
1719
+ function createSchedule(input) {
1720
+ const db2 = getDatabase();
1721
+ const id = uuid();
1722
+ const timestamp = now();
1723
+ db2.query(`
1724
+ INSERT INTO schedules (id, project_id, name, cron_expression, url, scenario_filter, model, headed, parallel, timeout_ms, enabled, created_at, updated_at)
1725
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?)
1726
+ `).run(id, input.projectId ?? null, input.name, input.cronExpression, input.url, JSON.stringify(input.scenarioFilter ?? {}), input.model ?? null, input.headed ? 1 : 0, input.parallel ?? 1, input.timeoutMs ?? null, timestamp, timestamp);
1727
+ return getSchedule(id);
1728
+ }
1729
+ function getSchedule(id) {
1730
+ const db2 = getDatabase();
1731
+ let row = db2.query("SELECT * FROM schedules WHERE id = ?").get(id);
1732
+ if (row)
1733
+ return scheduleFromRow(row);
1734
+ const fullId = resolvePartialId("schedules", id);
1735
+ if (fullId) {
1736
+ row = db2.query("SELECT * FROM schedules WHERE id = ?").get(fullId);
1737
+ if (row)
1738
+ return scheduleFromRow(row);
1739
+ }
1740
+ return null;
1741
+ }
1742
+ function listSchedules(filter) {
1743
+ const db2 = getDatabase();
1744
+ const conditions = [];
1745
+ const params = [];
1746
+ if (filter?.projectId) {
1747
+ conditions.push("project_id = ?");
1748
+ params.push(filter.projectId);
1749
+ }
1750
+ if (filter?.enabled !== undefined) {
1751
+ conditions.push("enabled = ?");
1752
+ params.push(filter.enabled ? 1 : 0);
1753
+ }
1754
+ let sql = "SELECT * FROM schedules";
1755
+ if (conditions.length > 0) {
1756
+ sql += " WHERE " + conditions.join(" AND ");
1757
+ }
1758
+ sql += " ORDER BY created_at DESC";
1759
+ if (filter?.limit) {
1760
+ sql += " LIMIT ?";
1761
+ params.push(filter.limit);
1762
+ }
1763
+ if (filter?.offset) {
1764
+ sql += " OFFSET ?";
1765
+ params.push(filter.offset);
1766
+ }
1767
+ const rows = db2.query(sql).all(...params);
1768
+ return rows.map(scheduleFromRow);
1769
+ }
1770
+ function updateSchedule(id, input) {
1771
+ const db2 = getDatabase();
1772
+ const existing = getSchedule(id);
1773
+ if (!existing) {
1774
+ throw new ScheduleNotFoundError(id);
1775
+ }
1776
+ const sets = [];
1777
+ const params = [];
1778
+ if (input.name !== undefined) {
1779
+ sets.push("name = ?");
1780
+ params.push(input.name);
1781
+ }
1782
+ if (input.cronExpression !== undefined) {
1783
+ sets.push("cron_expression = ?");
1784
+ params.push(input.cronExpression);
1785
+ }
1786
+ if (input.url !== undefined) {
1787
+ sets.push("url = ?");
1788
+ params.push(input.url);
1789
+ }
1790
+ if (input.scenarioFilter !== undefined) {
1791
+ sets.push("scenario_filter = ?");
1792
+ params.push(JSON.stringify(input.scenarioFilter));
1793
+ }
1794
+ if (input.model !== undefined) {
1795
+ sets.push("model = ?");
1796
+ params.push(input.model);
1797
+ }
1798
+ if (input.headed !== undefined) {
1799
+ sets.push("headed = ?");
1800
+ params.push(input.headed ? 1 : 0);
1801
+ }
1802
+ if (input.parallel !== undefined) {
1803
+ sets.push("parallel = ?");
1804
+ params.push(input.parallel);
1805
+ }
1806
+ if (input.timeoutMs !== undefined) {
1807
+ sets.push("timeout_ms = ?");
1808
+ params.push(input.timeoutMs);
1809
+ }
1810
+ if (input.enabled !== undefined) {
1811
+ sets.push("enabled = ?");
1812
+ params.push(input.enabled ? 1 : 0);
1813
+ }
1814
+ if (sets.length === 0) {
1815
+ return existing;
1816
+ }
1817
+ sets.push("updated_at = ?");
1818
+ params.push(now());
1819
+ params.push(existing.id);
1820
+ db2.query(`UPDATE schedules SET ${sets.join(", ")} WHERE id = ?`).run(...params);
1821
+ return getSchedule(existing.id);
1822
+ }
1823
+ function deleteSchedule(id) {
1824
+ const db2 = getDatabase();
1825
+ const schedule = getSchedule(id);
1826
+ if (!schedule)
1827
+ return false;
1828
+ const result = db2.query("DELETE FROM schedules WHERE id = ?").run(schedule.id);
1829
+ return result.changes > 0;
1830
+ }
1831
+ function getEnabledSchedules() {
1832
+ const db2 = getDatabase();
1833
+ const rows = db2.query("SELECT * FROM schedules WHERE enabled = 1 ORDER BY created_at DESC").all();
1834
+ return rows.map(scheduleFromRow);
1835
+ }
1836
+ function updateLastRun(id, runId, nextRunAt) {
1837
+ const db2 = getDatabase();
1838
+ const timestamp = now();
1839
+ db2.query(`
1840
+ UPDATE schedules SET last_run_id = ?, last_run_at = ?, next_run_at = ?, updated_at = ? WHERE id = ?
1841
+ `).run(runId, timestamp, nextRunAt, timestamp, id);
1842
+ }
1843
+
1844
+ // src/lib/scheduler.ts
1845
+ function parseCronField(field, min, max) {
1846
+ const results = new Set;
1847
+ const parts = field.split(",");
1848
+ for (const part of parts) {
1849
+ const trimmed = part.trim();
1850
+ if (trimmed.includes("/")) {
1851
+ const slashParts = trimmed.split("/");
1852
+ const rangePart = slashParts[0] ?? "*";
1853
+ const stepStr = slashParts[1] ?? "1";
1854
+ const step = parseInt(stepStr, 10);
1855
+ if (isNaN(step) || step <= 0) {
1856
+ throw new Error(`Invalid step value in cron field: ${field}`);
1857
+ }
1858
+ let start;
1859
+ let end;
1860
+ if (rangePart === "*") {
1861
+ start = min;
1862
+ end = max;
1863
+ } else if (rangePart.includes("-")) {
1864
+ const dashParts = rangePart.split("-");
1865
+ start = parseInt(dashParts[0] ?? "0", 10);
1866
+ end = parseInt(dashParts[1] ?? "0", 10);
1867
+ } else {
1868
+ start = parseInt(rangePart, 10);
1869
+ end = max;
1870
+ }
1871
+ for (let i = start;i <= end; i += step) {
1872
+ if (i >= min && i <= max)
1873
+ results.add(i);
1874
+ }
1875
+ } else if (trimmed === "*") {
1876
+ for (let i = min;i <= max; i++) {
1877
+ results.add(i);
1878
+ }
1879
+ } else if (trimmed.includes("-")) {
1880
+ const dashParts = trimmed.split("-");
1881
+ const lo = parseInt(dashParts[0] ?? "0", 10);
1882
+ const hi = parseInt(dashParts[1] ?? "0", 10);
1883
+ if (isNaN(lo) || isNaN(hi)) {
1884
+ throw new Error(`Invalid range in cron field: ${field}`);
1885
+ }
1886
+ for (let i = lo;i <= hi; i++) {
1887
+ if (i >= min && i <= max)
1888
+ results.add(i);
1889
+ }
1890
+ } else {
1891
+ const val = parseInt(trimmed, 10);
1892
+ if (isNaN(val)) {
1893
+ throw new Error(`Invalid value in cron field: ${field}`);
1894
+ }
1895
+ if (val >= min && val <= max)
1896
+ results.add(val);
1897
+ }
1898
+ }
1899
+ return Array.from(results).sort((a, b) => a - b);
1900
+ }
1901
+ function parseCron(expression) {
1902
+ const fields = expression.trim().split(/\s+/);
1903
+ if (fields.length !== 5) {
1904
+ throw new Error(`Invalid cron expression "${expression}": expected 5 fields, got ${fields.length}`);
1905
+ }
1906
+ return {
1907
+ minutes: parseCronField(fields[0], 0, 59),
1908
+ hours: parseCronField(fields[1], 0, 23),
1909
+ daysOfMonth: parseCronField(fields[2], 1, 31),
1910
+ months: parseCronField(fields[3], 1, 12),
1911
+ daysOfWeek: parseCronField(fields[4], 0, 6)
1912
+ };
1913
+ }
1914
+ function shouldRunAt(cronExpression, date) {
1915
+ const cron = parseCron(cronExpression);
1916
+ const minute = date.getMinutes();
1917
+ const hour = date.getHours();
1918
+ const dayOfMonth = date.getDate();
1919
+ const month = date.getMonth() + 1;
1920
+ const dayOfWeek = date.getDay();
1921
+ return cron.minutes.includes(minute) && cron.hours.includes(hour) && cron.daysOfMonth.includes(dayOfMonth) && cron.months.includes(month) && cron.daysOfWeek.includes(dayOfWeek);
1922
+ }
1923
+ function getNextRunTime(cronExpression, after) {
1924
+ parseCron(cronExpression);
1925
+ const start = after ? new Date(after.getTime()) : new Date;
1926
+ start.setSeconds(0, 0);
1927
+ start.setMinutes(start.getMinutes() + 1);
1928
+ const maxDate = new Date(start.getTime() + 366 * 24 * 60 * 60 * 1000);
1929
+ const cursor = new Date(start.getTime());
1930
+ while (cursor.getTime() <= maxDate.getTime()) {
1931
+ if (shouldRunAt(cronExpression, cursor)) {
1932
+ return cursor;
1933
+ }
1934
+ cursor.setMinutes(cursor.getMinutes() + 1);
1935
+ }
1936
+ throw new Error(`No matching time found for cron expression "${cronExpression}" within 366 days`);
1937
+ }
1938
+
1939
+ class Scheduler {
1940
+ interval = null;
1941
+ running = new Set;
1942
+ checkIntervalMs;
1943
+ onEvent;
1944
+ constructor(options) {
1945
+ this.checkIntervalMs = options?.checkIntervalMs ?? 60000;
1946
+ this.onEvent = options?.onEvent;
1947
+ }
1948
+ start() {
1949
+ if (this.interval)
1950
+ return;
1951
+ this.tick().catch(() => {});
1952
+ this.interval = setInterval(() => {
1953
+ this.tick().catch(() => {});
1954
+ }, this.checkIntervalMs);
1955
+ }
1956
+ stop() {
1957
+ if (this.interval) {
1958
+ clearInterval(this.interval);
1959
+ this.interval = null;
1960
+ }
1961
+ }
1962
+ async tick() {
1963
+ const now2 = new Date;
1964
+ now2.setSeconds(0, 0);
1965
+ const schedules = getEnabledSchedules();
1966
+ for (const schedule of schedules) {
1967
+ if (this.running.has(schedule.id))
1968
+ continue;
1969
+ if (shouldRunAt(schedule.cronExpression, now2)) {
1970
+ this.running.add(schedule.id);
1971
+ this.emit({
1972
+ type: "schedule:triggered",
1973
+ scheduleId: schedule.id,
1974
+ scheduleName: schedule.name,
1975
+ timestamp: new Date().toISOString()
1976
+ });
1977
+ this.executeSchedule(schedule).then(({ runId }) => {
1978
+ const nextRun = getNextRunTime(schedule.cronExpression, new Date);
1979
+ updateLastRun(schedule.id, runId, nextRun.toISOString());
1980
+ this.emit({
1981
+ type: "schedule:completed",
1982
+ scheduleId: schedule.id,
1983
+ scheduleName: schedule.name,
1984
+ runId,
1985
+ timestamp: new Date().toISOString()
1986
+ });
1987
+ }).catch((err) => {
1988
+ this.emit({
1989
+ type: "schedule:failed",
1990
+ scheduleId: schedule.id,
1991
+ scheduleName: schedule.name,
1992
+ error: err instanceof Error ? err.message : String(err),
1993
+ timestamp: new Date().toISOString()
1994
+ });
1995
+ }).finally(() => {
1996
+ this.running.delete(schedule.id);
1997
+ });
1998
+ }
1999
+ }
2000
+ }
2001
+ async runScheduleNow(scheduleId) {
2002
+ const schedule = getSchedule(scheduleId);
2003
+ if (!schedule) {
2004
+ throw new ScheduleNotFoundError(scheduleId);
2005
+ }
2006
+ this.running.add(schedule.id);
2007
+ this.emit({
2008
+ type: "schedule:triggered",
2009
+ scheduleId: schedule.id,
2010
+ scheduleName: schedule.name,
2011
+ timestamp: new Date().toISOString()
2012
+ });
2013
+ try {
2014
+ const { runId } = await this.executeSchedule(schedule);
2015
+ const nextRun = getNextRunTime(schedule.cronExpression, new Date);
2016
+ updateLastRun(schedule.id, runId, nextRun.toISOString());
2017
+ this.emit({
2018
+ type: "schedule:completed",
2019
+ scheduleId: schedule.id,
2020
+ scheduleName: schedule.name,
2021
+ runId,
2022
+ timestamp: new Date().toISOString()
2023
+ });
2024
+ } catch (err) {
2025
+ this.emit({
2026
+ type: "schedule:failed",
2027
+ scheduleId: schedule.id,
2028
+ scheduleName: schedule.name,
2029
+ error: err instanceof Error ? err.message : String(err),
2030
+ timestamp: new Date().toISOString()
2031
+ });
2032
+ throw err;
2033
+ } finally {
2034
+ this.running.delete(schedule.id);
2035
+ }
2036
+ }
2037
+ async executeSchedule(schedule) {
2038
+ const { run } = await runByFilter({
2039
+ url: schedule.url,
2040
+ model: schedule.model ?? undefined,
2041
+ headed: schedule.headed,
2042
+ parallel: schedule.parallel,
2043
+ timeout: schedule.timeoutMs ?? undefined,
2044
+ tags: schedule.scenarioFilter.tags,
2045
+ priority: schedule.scenarioFilter.priority,
2046
+ scenarioIds: schedule.scenarioFilter.scenarioIds
2047
+ });
2048
+ return { runId: run.id };
2049
+ }
2050
+ emit(event) {
2051
+ if (this.onEvent) {
2052
+ this.onEvent(event);
2053
+ }
2054
+ }
2055
+ }
2056
+
1427
2057
  // src/server/index.ts
1428
2058
  function parseUrl(req) {
1429
2059
  const url = new URL(req.url);
@@ -1603,6 +2233,49 @@ async function handleRequest(req) {
1603
2233
  }
1604
2234
  });
1605
2235
  }
2236
+ if (pathname === "/api/schedules" && method === "GET") {
2237
+ const projectId = searchParams.get("projectId") ?? undefined;
2238
+ const enabled = searchParams.get("enabled");
2239
+ const limit = searchParams.get("limit");
2240
+ const schedules = listSchedules({
2241
+ projectId,
2242
+ enabled: enabled !== null ? enabled === "true" : undefined,
2243
+ limit: limit ? parseInt(limit, 10) : undefined
2244
+ });
2245
+ return jsonResponse(schedules);
2246
+ }
2247
+ if (pathname === "/api/schedules" && method === "POST") {
2248
+ try {
2249
+ const body = await req.json();
2250
+ const schedule = createSchedule(body);
2251
+ const nextRun = getNextRunTime(schedule.cronExpression);
2252
+ return jsonResponse({ ...schedule, nextRunAt: nextRun.toISOString() }, 201);
2253
+ } catch (e) {
2254
+ return errorResponse(e instanceof Error ? e.message : String(e), 400);
2255
+ }
2256
+ }
2257
+ const scheduleMatch = pathname.match(/^\/api\/schedules\/([^/]+)$/);
2258
+ if (scheduleMatch && method === "GET") {
2259
+ const schedule = getSchedule(scheduleMatch[1]);
2260
+ if (!schedule)
2261
+ return errorResponse("Schedule not found", 404);
2262
+ return jsonResponse(schedule);
2263
+ }
2264
+ if (scheduleMatch && method === "PUT") {
2265
+ try {
2266
+ const body = await req.json();
2267
+ const schedule = updateSchedule(scheduleMatch[1], body);
2268
+ return jsonResponse(schedule);
2269
+ } catch (e) {
2270
+ return errorResponse(e instanceof Error ? e.message : String(e), 400);
2271
+ }
2272
+ }
2273
+ if (scheduleMatch && method === "DELETE") {
2274
+ const deleted = deleteSchedule(scheduleMatch[1]);
2275
+ if (!deleted)
2276
+ return errorResponse("Schedule not found", 404);
2277
+ return jsonResponse({ deleted: true });
2278
+ }
1606
2279
  if (!pathname.startsWith("/api")) {
1607
2280
  const dashboardDir = join4(import.meta.dir, "..", "..", "dashboard", "dist");
1608
2281
  if (!existsSync4(dashboardDir)) {