@nodestackapp/server 2.6.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +3 -1
  2. package/dist/NodeStack.d.ts +4 -0
  3. package/dist/NodeStack.d.ts.map +1 -1
  4. package/dist/NodeStack.js +44 -6
  5. package/dist/NodeStack.js.map +1 -1
  6. package/dist/admin/AdminUIBundler.d.ts.map +1 -1
  7. package/dist/admin/AdminUIBundler.js +1 -0
  8. package/dist/admin/AdminUIBundler.js.map +1 -1
  9. package/dist/admin/ui/css/main.css +6 -3
  10. package/dist/admin/ui/index.html +2345 -55
  11. package/dist/admin/ui/js/api.js +8 -0
  12. package/dist/admin/ui/js/app.js +38 -7
  13. package/dist/admin/ui/js/apps.js +18 -0
  14. package/dist/admin/ui/js/command-palette.js +10 -0
  15. package/dist/admin/ui/js/cron.js +1706 -0
  16. package/dist/admin/ui/js/database.js +10 -0
  17. package/dist/admin/ui/js/flows-designer.js +94 -0
  18. package/dist/admin/ui/js/flows.js +43 -4
  19. package/dist/admin/ui/js/functions-workbench.js +18 -0
  20. package/dist/admin/ui/js/functions.js +6 -3
  21. package/dist/admin/ui/js/snapshots.js +338 -0
  22. package/dist/admin/ui/js/views.js +1 -1
  23. package/dist/apps/AppManager.d.ts.map +1 -1
  24. package/dist/apps/AppManager.js +7 -3
  25. package/dist/apps/AppManager.js.map +1 -1
  26. package/dist/apps/AppScope.d.ts +2 -0
  27. package/dist/apps/AppScope.d.ts.map +1 -1
  28. package/dist/apps/AppScope.js +22 -2
  29. package/dist/apps/AppScope.js.map +1 -1
  30. package/dist/auth/ApiKeyService.d.ts +1 -0
  31. package/dist/auth/ApiKeyService.d.ts.map +1 -1
  32. package/dist/auth/ApiKeyService.js +16 -1
  33. package/dist/auth/ApiKeyService.js.map +1 -1
  34. package/dist/cli/cli.js +1 -1
  35. package/dist/core/container/Tokens.d.ts +2 -0
  36. package/dist/core/container/Tokens.d.ts.map +1 -1
  37. package/dist/core/container/Tokens.js +2 -0
  38. package/dist/core/container/Tokens.js.map +1 -1
  39. package/dist/cron/CronParser.d.ts +83 -0
  40. package/dist/cron/CronParser.d.ts.map +1 -0
  41. package/dist/cron/CronParser.js +538 -0
  42. package/dist/cron/CronParser.js.map +1 -0
  43. package/dist/cron/CronService.d.ts +74 -0
  44. package/dist/cron/CronService.d.ts.map +1 -0
  45. package/dist/cron/CronService.js +1254 -0
  46. package/dist/cron/CronService.js.map +1 -0
  47. package/dist/cron/types.d.ts +98 -0
  48. package/dist/cron/types.d.ts.map +1 -0
  49. package/dist/cron/types.js +3 -0
  50. package/dist/cron/types.js.map +1 -0
  51. package/dist/database/DatabaseService.d.ts +3 -1
  52. package/dist/database/DatabaseService.d.ts.map +1 -1
  53. package/dist/database/DatabaseService.js +10 -3
  54. package/dist/database/DatabaseService.js.map +1 -1
  55. package/dist/database/config/DatabaseConfigService.d.ts +1 -0
  56. package/dist/database/config/DatabaseConfigService.d.ts.map +1 -1
  57. package/dist/database/config/DatabaseConfigService.js +4 -2
  58. package/dist/database/config/DatabaseConfigService.js.map +1 -1
  59. package/dist/database/drivers/DriverPackageLoader.d.ts +11 -0
  60. package/dist/database/drivers/DriverPackageLoader.d.ts.map +1 -0
  61. package/dist/database/drivers/DriverPackageLoader.js +112 -0
  62. package/dist/database/drivers/DriverPackageLoader.js.map +1 -0
  63. package/dist/database/drivers/MssqlDriver.d.ts.map +1 -1
  64. package/dist/database/drivers/MssqlDriver.js +5 -6
  65. package/dist/database/drivers/MssqlDriver.js.map +1 -1
  66. package/dist/database/drivers/PostgresDriver.d.ts.map +1 -1
  67. package/dist/database/drivers/PostgresDriver.js +4 -5
  68. package/dist/database/drivers/PostgresDriver.js.map +1 -1
  69. package/dist/database/migration/DatabaseMigrationService.d.ts +1 -0
  70. package/dist/database/migration/DatabaseMigrationService.d.ts.map +1 -1
  71. package/dist/database/migration/DatabaseMigrationService.js +51 -0
  72. package/dist/database/migration/DatabaseMigrationService.js.map +1 -1
  73. package/dist/database/migrations/SystemMigrations.d.ts.map +1 -1
  74. package/dist/database/migrations/SystemMigrations.js +138 -0
  75. package/dist/database/migrations/SystemMigrations.js.map +1 -1
  76. package/dist/flows/FlowService.d.ts +3 -0
  77. package/dist/flows/FlowService.d.ts.map +1 -1
  78. package/dist/flows/FlowService.js +106 -7
  79. package/dist/flows/FlowService.js.map +1 -1
  80. package/dist/flows/FlowValidator.d.ts +1 -1
  81. package/dist/flows/FlowValidator.d.ts.map +1 -1
  82. package/dist/flows/FlowValidator.js +13 -3
  83. package/dist/flows/FlowValidator.js.map +1 -1
  84. package/dist/flows/types.d.ts +6 -1
  85. package/dist/flows/types.d.ts.map +1 -1
  86. package/dist/functions/FunctionService.d.ts +5 -1
  87. package/dist/functions/FunctionService.d.ts.map +1 -1
  88. package/dist/functions/FunctionService.js +190 -7
  89. package/dist/functions/FunctionService.js.map +1 -1
  90. package/dist/functions/runtime/QuickJsWasmRuntime.d.ts.map +1 -1
  91. package/dist/functions/runtime/QuickJsWasmRuntime.js +183 -180
  92. package/dist/functions/runtime/QuickJsWasmRuntime.js.map +1 -1
  93. package/dist/functions/types.d.ts +15 -0
  94. package/dist/functions/types.d.ts.map +1 -1
  95. package/dist/http/HttpServer.d.ts +4 -1
  96. package/dist/http/HttpServer.d.ts.map +1 -1
  97. package/dist/http/HttpServer.js +34 -2
  98. package/dist/http/HttpServer.js.map +1 -1
  99. package/dist/http/controllers/CronController.d.ts +63 -0
  100. package/dist/http/controllers/CronController.d.ts.map +1 -0
  101. package/dist/http/controllers/CronController.js +92 -0
  102. package/dist/http/controllers/CronController.js.map +1 -0
  103. package/dist/http/controllers/DatabaseController.d.ts.map +1 -1
  104. package/dist/http/controllers/DatabaseController.js +53 -0
  105. package/dist/http/controllers/DatabaseController.js.map +1 -1
  106. package/dist/http/controllers/HealthController.js +2 -2
  107. package/dist/schema/OpenApiGenerator.js +3 -3
  108. package/dist/snapshots/SnapshotService.d.ts.map +1 -1
  109. package/dist/snapshots/SnapshotService.js +21 -9
  110. package/dist/snapshots/SnapshotService.js.map +1 -1
  111. package/dist/snapshots/drivers/LogicalSnapshotDriver.d.ts.map +1 -1
  112. package/dist/snapshots/drivers/LogicalSnapshotDriver.js +2 -0
  113. package/dist/snapshots/drivers/LogicalSnapshotDriver.js.map +1 -1
  114. package/dist/webhooks/WebhookService.js +1 -1
  115. package/package.json +3 -2
@@ -1670,7 +1670,8 @@ html.light {
1670
1670
  /* Slide-Over Drawer Container */
1671
1671
  .record-drawer,
1672
1672
  .plugin-drawer,
1673
- .webhook-drawer {
1673
+ .webhook-drawer,
1674
+ .schedule-drawer {
1674
1675
  position: fixed;
1675
1676
  top: 0;
1676
1677
  right: 0;
@@ -1688,12 +1689,14 @@ html.light {
1688
1689
  }
1689
1690
  .record-drawer.open,
1690
1691
  .plugin-drawer.open,
1691
- .webhook-drawer.open {
1692
+ .webhook-drawer.open,
1693
+ .schedule-drawer.open {
1692
1694
  transform: translateX(0);
1693
1695
  }
1694
1696
  .record-drawer:focus,
1695
1697
  .plugin-drawer:focus,
1696
- .webhook-drawer:focus {
1698
+ .webhook-drawer:focus,
1699
+ .schedule-drawer:focus {
1697
1700
  outline: none;
1698
1701
  }
1699
1702
 
@@ -4140,7 +4143,7 @@ html.light .badge-status-failed {
4140
4143
  </div>
4141
4144
  <span>NodeStack</span>
4142
4145
  </div>
4143
- <span class="version-tag">v2.6.0</span>
4146
+ <span class="version-tag">v2.7.0</span>
4144
4147
  </div>
4145
4148
 
4146
4149
  <div style="padding: 0.75rem 1rem 0.25rem; display: flex; flex-direction: column; gap: 4px;">
@@ -4177,6 +4180,11 @@ html.light .badge-status-failed {
4177
4180
  <span>Queues</span>
4178
4181
  <span class="badge badge-primary" id="sidebar-queues-count" style="margin-left: auto; font-size: 10px; padding: 1px 6px; display: none;">0</span>
4179
4182
  </div>
4183
+ <div class="sidebar-nav-item" id="nav-schedules" onclick="selectNav('schedules')">
4184
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>
4185
+ <span>Schedules</span>
4186
+ <span class="badge badge-primary" id="sidebar-schedules-count" style="margin-left: auto; font-size: 10px; padding: 1px 6px; display: none;">0</span>
4187
+ </div>
4180
4188
  <div class="sidebar-nav-item" id="nav-api-keys" onclick="selectNav('api-keys')">
4181
4189
  <svg aria-hidden="true" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>
4182
4190
  <span>API Keys</span>
@@ -4443,6 +4451,9 @@ html.light .badge-status-failed {
4443
4451
  <!-- 3.8 Queues Page View -->
4444
4452
  <div id="page-view-queues" class="app-page-view" style="display: none;"></div>
4445
4453
 
4454
+ <!-- 3.85 Schedules Page View -->
4455
+ <div id="page-view-schedules" class="app-page-view" style="display: none;"></div>
4456
+
4446
4457
  <!-- 3.9 API Keys Page View -->
4447
4458
  <div id="page-view-api-keys" class="app-page-view" style="display: none;"></div>
4448
4459
 
@@ -4502,6 +4513,7 @@ html.light .badge-status-failed {
4502
4513
 
4503
4514
 
4504
4515
 
4516
+
4505
4517
 
4506
4518
 
4507
4519
  <script>
@@ -5042,6 +5054,9 @@ if (typeof document !== 'undefined') {
5042
5054
  if (typeof loadFlows === 'function') {
5043
5055
  loadFlows();
5044
5056
  }
5057
+ if (typeof loadCronStats === 'function') {
5058
+ loadCronStats();
5059
+ }
5045
5060
  loadCollections().then(() => {
5046
5061
  if (state.activeCollection) {
5047
5062
  if (state.collectionTab === 'records') loadRecords();
@@ -5134,6 +5149,9 @@ if (typeof document !== 'undefined') {
5134
5149
  if (typeof loadQueueStats === 'function') {
5135
5150
  loadQueueStats();
5136
5151
  }
5152
+ if (typeof loadCronStats === 'function') {
5153
+ loadCronStats();
5154
+ }
5137
5155
  try {
5138
5156
  const pRes = await fetch('/api/plugins');
5139
5157
  if (pRes.ok) {
@@ -5223,6 +5241,7 @@ if (typeof document !== 'undefined') {
5223
5241
  if (typeof loadFunctionStats === 'function') loadFunctionStats();
5224
5242
  if (typeof loadFlows === 'function') loadFlows();
5225
5243
  if (typeof loadQueueStats === 'function') loadQueueStats();
5244
+ if (typeof loadCronStats === 'function') loadCronStats();
5226
5245
  initRealtime();
5227
5246
  if (typeof parseUrlAndNavigate === 'function') {
5228
5247
  await parseUrlAndNavigate(false);
@@ -5297,6 +5316,7 @@ if (typeof document !== 'undefined') {
5297
5316
  if (typeof loadFunctionStats === 'function') loadFunctionStats();
5298
5317
  if (typeof loadFlows === 'function') loadFlows();
5299
5318
  if (typeof loadQueueStats === 'function') loadQueueStats();
5319
+ if (typeof loadCronStats === 'function') loadCronStats();
5300
5320
  initRealtime();
5301
5321
  if (typeof parseUrlAndNavigate === 'function') {
5302
5322
  await parseUrlAndNavigate(false);
@@ -5489,6 +5509,16 @@ async function selectApp(slugOrId) {
5489
5509
  apiKeysState.keys = [];
5490
5510
  if (typeof updateSidebarApiKeysBadge === 'function') updateSidebarApiKeysBadge([]);
5491
5511
  }
5512
+ if (typeof cronState !== 'undefined') {
5513
+ cronState.schedules = [];
5514
+ cronState.runs = [];
5515
+ cronState.functionsList = [];
5516
+ cronState.flowsList = [];
5517
+ cronState.stats = { totalSchedules: 0, activeSchedules: 0, successfulRuns: 0, failedRuns: 0, skippedRuns: 0, byTarget: { function: 0, flow: 0, snapshot: 0 } };
5518
+ }
5519
+ if (typeof closeScheduleDrawer === 'function') {
5520
+ closeScheduleDrawer();
5521
+ }
5492
5522
 
5493
5523
  try {
5494
5524
  if (typeof loadCollections === 'function') {
@@ -5527,6 +5557,12 @@ async function selectApp(slugOrId) {
5527
5557
  if (typeof loadApiKeys === 'function' && state.activeNav === 'api-keys') {
5528
5558
  await loadApiKeys();
5529
5559
  }
5560
+ if (typeof loadCronStats === 'function') {
5561
+ await loadCronStats();
5562
+ }
5563
+ if (typeof loadCronData === 'function' && state.activeNav === 'schedules') {
5564
+ await loadCronData();
5565
+ }
5530
5566
 
5531
5567
  // Refresh plugin catalog and nav items for the switched app
5532
5568
  try {
@@ -5542,6 +5578,8 @@ async function selectApp(slugOrId) {
5542
5578
 
5543
5579
  if (state.activeNav === 'home' && typeof renderHomeView === 'function') {
5544
5580
  renderHomeView();
5581
+ } else if (state.activeNav === 'schedules' && typeof renderSchedulesView === 'function') {
5582
+ renderSchedulesView();
5545
5583
  } else if (state.activeNav === 'snapshots' && typeof renderSnapshotsView === 'function') {
5546
5584
  renderSnapshotsView();
5547
5585
  } else if (state.activeNav === 'database' && typeof renderDatabaseView === 'function') {
@@ -10978,6 +11016,21 @@ async function fetchDemoStatus() {
10978
11016
  state.demo = { hasSnapshot: false, snapshots: [], total: 0, maxLimit: 10, snapshot: null, activeSnapshot: null };
10979
11017
  }
10980
11018
 
11019
+ // Also fetch scheduled snapshot backup if snapshot service is supported
11020
+ if (state.demo && state.demo.supported !== false) {
11021
+ try {
11022
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
11023
+ const cronUrl = slug && slug !== 'default' ? `/api/apps/${slug}/cron/schedules?targetType=snapshot` : '/api/cron/schedules?targetType=snapshot';
11024
+ const cronRes = await api(cronUrl);
11025
+ const schedules = Array.isArray(cronRes) ? cronRes : (cronRes && cronRes.schedules ? cronRes.schedules : []);
11026
+ state.snapshotSchedule = schedules.length > 0 ? schedules[0] : null;
11027
+ } catch (_) {
11028
+ state.snapshotSchedule = null;
11029
+ }
11030
+ } else {
11031
+ state.snapshotSchedule = null;
11032
+ }
11033
+
10981
11034
  updateDemoSidebarDot();
10982
11035
 
10983
11036
  if (state.activeNav === 'snapshots') {
@@ -11232,6 +11285,7 @@ function renderSnapshotsView() {
11232
11285
  <div style="max-width: 1040px; margin: 0 auto; display: flex; flex-direction: column; gap: 1.25rem; padding: 1rem 0;">
11233
11286
  ${headerHtml}
11234
11287
  ${activeCardHtml}
11288
+ ${renderScheduledBackupsCardHtml()}
11235
11289
  ${listHtml}
11236
11290
  ${guideHtml}
11237
11291
  </div>
@@ -11667,6 +11721,317 @@ async function openClearAllSnapshotsModal() {
11667
11721
  }
11668
11722
  }
11669
11723
 
11724
+ // ==========================================
11725
+ // Automated Scheduled Backups (SQLite)
11726
+ // ==========================================
11727
+
11728
+ function renderScheduledBackupsCardHtml() {
11729
+ const sched = state.snapshotSchedule;
11730
+ const isEnabled = sched && sched.enabled;
11731
+ const nextRun = sched?.nextRunAt ? new Date(sched.nextRunAt).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) : 'Not scheduled';
11732
+
11733
+ return `
11734
+ <div style="background: var(--bg-card); border: 1px solid var(--border-subtle); border-radius: 8px; padding: 1.1rem 1.25rem; display: flex; flex-direction: column; gap: 0.85rem;">
11735
+ <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 0.75rem;">
11736
+ <div style="display: flex; align-items: center; gap: 10px;">
11737
+ <div style="width: 32px; height: 32px; border-radius: 6px; background: rgba(16, 185, 129, 0.12); display: flex; align-items: center; justify-content: center; font-size: 16px;">
11738
+ ⏱️
11739
+ </div>
11740
+ <div>
11741
+ <div style="display: flex; align-items: center; gap: 8px;">
11742
+ <h3 style="font-size: 14px; font-weight: 700; color: var(--text-heading); margin: 0;">Automated Scheduled Backups</h3>
11743
+ ${isEnabled
11744
+ ? `<span class="badge badge-success" style="font-size: 10.5px; padding: 2px 7px;">● Active</span>`
11745
+ : `<span class="badge" style="font-size: 10.5px; padding: 2px 7px; background: var(--bg-input); color: var(--text-muted);">○ ${sched ? 'Paused' : 'Not Configured'}</span>`
11746
+ }
11747
+ </div>
11748
+ <div style="font-size: 12px; color: var(--text-muted); margin-top: 2px;">
11749
+ ${sched
11750
+ ? `Recurring schedule: <code style="font-family: var(--font-mono); font-size: 11px; background: var(--bg-input); padding: 1px 5px; border-radius: 3px;">${escapeHtml(sched.cronExpression)}</code> (${escapeHtml(sched.timezone || 'UTC')}) • Next run: <strong>${nextRun}</strong>`
11751
+ : 'Automatically capture point-in-time snapshots of database and storage files on a recurring schedule.'
11752
+ }
11753
+ </div>
11754
+ </div>
11755
+ </div>
11756
+
11757
+ <div style="display: flex; align-items: center; gap: 8px;">
11758
+ ${sched ? `
11759
+ <button class="btn btn-secondary btn-sm" onclick="triggerSnapshotScheduleNow('${sched.id}')" style="font-size: 11.5px; padding: 5px 10px;" title="Trigger immediate backup">
11760
+ ▶ Run Backup Now
11761
+ </button>
11762
+ <button class="btn btn-secondary btn-sm" onclick="toggleSnapshotSchedule('${sched.id}', ${!isEnabled})" style="font-size: 11.5px; padding: 5px 10px;">
11763
+ ${isEnabled ? 'Pause' : 'Resume'}
11764
+ </button>
11765
+ <button class="btn btn-secondary btn-sm" onclick="openSnapshotScheduleModal()" style="font-size: 11.5px; padding: 5px 10px; font-weight: 600;">
11766
+ ⚙️ Configure
11767
+ </button>
11768
+ ` : `
11769
+ <button class="btn btn-primary btn-sm" onclick="openSnapshotScheduleModal()" style="font-size: 12px; padding: 5px 12px; font-weight: 600;">
11770
+ + Set Up Automated Backups
11771
+ </button>
11772
+ `}
11773
+ </div>
11774
+ </div>
11775
+ </div>
11776
+ `;
11777
+ }
11778
+
11779
+ function openSnapshotScheduleModal() {
11780
+ const root = document.getElementById('modal-root');
11781
+ if (!root) return;
11782
+
11783
+ const existing = state.snapshotSchedule;
11784
+ const currentExpr = existing?.cronExpression || '0 2 * * *';
11785
+ const currentTz = existing?.timezone || 'UTC';
11786
+ const currentPolicy = existing?.missedRunPolicy || 'catch_up_once';
11787
+ const isEnabled = existing ? existing.enabled : true;
11788
+
11789
+ let presetVal = 'custom';
11790
+ if (currentExpr === '0 2 * * *') presetVal = 'daily_2am';
11791
+ else if (currentExpr === '0 0 * * *') presetVal = 'daily_midnight';
11792
+ else if (currentExpr === '0 3 * * 0') presetVal = 'weekly_sun';
11793
+ else if (currentExpr === '0 * * * *') presetVal = 'hourly';
11794
+
11795
+ root.innerHTML = `
11796
+ <div class="modal-backdrop" onclick="closeModal()">
11797
+ <div class="modal" onclick="event.stopPropagation()" style="max-width: 520px; width: 100%;">
11798
+ <div class="modal-header">
11799
+ <div>
11800
+ <h2 class="modal-title" style="font-size: 16px;">Automated Backup Schedule</h2>
11801
+ <span style="font-size: 11px; color: var(--text-muted);">Periodic SQLite database & storage snapshots</span>
11802
+ </div>
11803
+ <button class="btn btn-secondary btn-sm" onclick="closeModal()">✕</button>
11804
+ </div>
11805
+
11806
+ <form onsubmit="saveSnapshotScheduleModal(event)">
11807
+ <div class="modal-body" style="display: flex; flex-direction: column; gap: 1rem;">
11808
+ <div>
11809
+ <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Frequency Preset</label>
11810
+ <select id="snap-sched-preset" class="form-select" onchange="handleSnapshotSchedulePresetChange(this.value)">
11811
+ <option value="daily_2am" ${presetVal === 'daily_2am' ? 'selected' : ''}>Daily at 02:00 AM (Recommended)</option>
11812
+ <option value="daily_midnight" ${presetVal === 'daily_midnight' ? 'selected' : ''}>Daily at Midnight (00:00)</option>
11813
+ <option value="weekly_sun" ${presetVal === 'weekly_sun' ? 'selected' : ''}>Weekly on Sunday at 03:00 AM</option>
11814
+ <option value="hourly" ${presetVal === 'hourly' ? 'selected' : ''}>Hourly (At minute 0)</option>
11815
+ <option value="custom" ${presetVal === 'custom' ? 'selected' : ''}>Custom 5-Field Cron Expression</option>
11816
+ </select>
11817
+ </div>
11818
+
11819
+ <div id="snap-sched-custom-group" style="display: ${presetVal === 'custom' ? 'block' : 'none'};">
11820
+ <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Cron Expression</label>
11821
+ <input type="text" id="snap-sched-expr" class="input" style="width: 100%; font-family: var(--font-mono); font-size: 12px;" value="${escapeHtml(currentExpr)}" placeholder="0 2 * * *" oninput="updateSnapshotScheduleModalPreview()">
11822
+ </div>
11823
+
11824
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem;">
11825
+ <div>
11826
+ <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Timezone</label>
11827
+ <input type="text" id="snap-sched-tz" class="input" list="iana-timezones-list" style="width: 100%; font-size: 12px;" value="${escapeHtml(currentTz)}" placeholder="UTC" oninput="updateSnapshotScheduleModalPreview()">
11828
+ </div>
11829
+ <div>
11830
+ <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Missed Run Policy</label>
11831
+ <select id="snap-sched-policy" class="form-select">
11832
+ <option value="catch_up_once" ${currentPolicy === 'catch_up_once' ? 'selected' : ''}>Catch-up once on reboot</option>
11833
+ <option value="skip" ${currentPolicy === 'skip' ? 'selected' : ''}>Skip missed backups</option>
11834
+ <option value="catch_up_all" ${currentPolicy === 'catch_up_all' ? 'selected' : ''}>Replay all missed (up to 10)</option>
11835
+ </select>
11836
+ </div>
11837
+ </div>
11838
+
11839
+ <div style="background: var(--bg-input); border: 1px solid var(--border-subtle); border-radius: 6px; padding: 0.75rem 0.85rem;">
11840
+ <div style="font-size: 11px; font-weight: 700; color: var(--text-muted); text-transform: uppercase; margin-bottom: 4px;">Next Execution Preview</div>
11841
+ <div id="snap-sched-preview" style="font-size: 12px; color: var(--accent-success); font-family: var(--font-mono);">Calculating...</div>
11842
+ </div>
11843
+
11844
+ <div style="display: flex; align-items: center; gap: 8px;">
11845
+ <input type="checkbox" id="snap-sched-enabled" ${isEnabled ? 'checked' : ''} style="cursor: pointer;">
11846
+ <label for="snap-sched-enabled" style="font-size: 12px; font-weight: 600; cursor: pointer;">Enable Automated Schedule</label>
11847
+ </div>
11848
+
11849
+ <div style="font-size: 11.5px; color: var(--text-muted); line-height: 1.4; border-top: 1px solid var(--border-subtle); padding-top: 0.5rem;">
11850
+ ℹ️ Backups automatically capture the SQLite database & file assets. When the 10-snapshot storage limit is reached, automated backups evict the oldest unprotected snapshot.
11851
+ </div>
11852
+ </div>
11853
+
11854
+ <div class="modal-footer" style="display: flex; justify-content: space-between; align-items: center;">
11855
+ <div>
11856
+ ${existing ? `
11857
+ <button type="button" class="btn btn-secondary btn-sm" onclick="deleteSnapshotSchedule('${existing.id}')" style="color: var(--accent-danger);">
11858
+ Remove Schedule
11859
+ </button>
11860
+ ` : '<span></span>'}
11861
+ </div>
11862
+ <div style="display: flex; gap: 8px;">
11863
+ <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancel</button>
11864
+ <button type="submit" class="btn btn-primary" style="font-weight: 600;">Save Schedule</button>
11865
+ </div>
11866
+ </div>
11867
+ </form>
11868
+ </div>
11869
+ </div>
11870
+ `;
11871
+
11872
+ updateSnapshotScheduleModalPreview();
11873
+ }
11874
+
11875
+ function handleSnapshotSchedulePresetChange(preset) {
11876
+ const customGroup = document.getElementById('snap-sched-custom-group');
11877
+ const exprInput = document.getElementById('snap-sched-expr');
11878
+ if (!exprInput) return;
11879
+
11880
+ if (preset === 'daily_2am') {
11881
+ exprInput.value = '0 2 * * *';
11882
+ if (customGroup) customGroup.style.display = 'none';
11883
+ } else if (preset === 'daily_midnight') {
11884
+ exprInput.value = '0 0 * * *';
11885
+ if (customGroup) customGroup.style.display = 'none';
11886
+ } else if (preset === 'weekly_sun') {
11887
+ exprInput.value = '0 3 * * 0';
11888
+ if (customGroup) customGroup.style.display = 'none';
11889
+ } else if (preset === 'hourly') {
11890
+ exprInput.value = '0 * * * *';
11891
+ if (customGroup) customGroup.style.display = 'none';
11892
+ } else {
11893
+ if (customGroup) customGroup.style.display = 'block';
11894
+ }
11895
+ updateSnapshotScheduleModalPreview();
11896
+ }
11897
+
11898
+ let snapSchedPreviewTimer = null;
11899
+ function updateSnapshotScheduleModalPreview() {
11900
+ clearTimeout(snapSchedPreviewTimer);
11901
+ snapSchedPreviewTimer = setTimeout(async () => {
11902
+ const previewEl = document.getElementById('snap-sched-preview');
11903
+ const exprInput = document.getElementById('snap-sched-expr');
11904
+ const tzInput = document.getElementById('snap-sched-tz');
11905
+ if (!previewEl || !exprInput) return;
11906
+
11907
+ const expr = exprInput.value.trim();
11908
+ const tz = tzInput ? tzInput.value.trim() || 'UTC' : 'UTC';
11909
+
11910
+ if (!expr || expr.split(/\s+/).length < 5) {
11911
+ previewEl.textContent = 'Enter a valid 5-field cron expression';
11912
+ previewEl.style.color = 'var(--text-muted)';
11913
+ return;
11914
+ }
11915
+
11916
+ try {
11917
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
11918
+ const url = slug && slug !== 'default' ? `/api/apps/${slug}/cron/preview` : '/api/cron/preview';
11919
+ const res = await api(url, {
11920
+ method: 'POST',
11921
+ headers: { 'Content-Type': 'application/json' },
11922
+ body: JSON.stringify({ cronExpression: expr, timezone: tz, count: 3 }),
11923
+ });
11924
+
11925
+ if (res && res.valid && Array.isArray(res.nextRuns) && res.nextRuns.length > 0) {
11926
+ previewEl.innerHTML = res.nextRuns.map((r, i) => `<div>${i + 1}. ${escapeHtml(r.zonedFormatted || r.formattedTz || '')} (${escapeHtml(r.isoUtc || r.formattedUtc || '')})</div>`).join('');
11927
+ previewEl.style.color = 'var(--accent-success)';
11928
+ } else {
11929
+ previewEl.textContent = res?.error || 'Invalid cron expression';
11930
+ previewEl.style.color = 'var(--accent-danger)';
11931
+ }
11932
+ } catch (_) {
11933
+ previewEl.textContent = 'Invalid expression or timezone';
11934
+ previewEl.style.color = 'var(--accent-danger)';
11935
+ }
11936
+ }, 300);
11937
+ }
11938
+
11939
+ async function saveSnapshotScheduleModal(e) {
11940
+ e.preventDefault();
11941
+ const exprInput = document.getElementById('snap-sched-expr');
11942
+ const tzInput = document.getElementById('snap-sched-tz');
11943
+ const policyInput = document.getElementById('snap-sched-policy');
11944
+ const enabledInput = document.getElementById('snap-sched-enabled');
11945
+
11946
+ const cronExpression = exprInput ? exprInput.value.trim() : '0 2 * * *';
11947
+ const timezone = tzInput ? tzInput.value.trim() || 'UTC' : 'UTC';
11948
+ const missedRunPolicy = policyInput ? policyInput.value : 'catch_up_once';
11949
+ const enabled = enabledInput ? enabledInput.checked : true;
11950
+
11951
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
11952
+ const baseUrl = slug && slug !== 'default' ? `/api/apps/${slug}/cron/schedules` : '/api/cron/schedules';
11953
+
11954
+ try {
11955
+ if (state.snapshotSchedule && state.snapshotSchedule.id) {
11956
+ await api(`${baseUrl}/${state.snapshotSchedule.id}`, {
11957
+ method: 'PATCH',
11958
+ headers: { 'Content-Type': 'application/json' },
11959
+ body: JSON.stringify({
11960
+ cronExpression,
11961
+ timezone,
11962
+ missedRunPolicy,
11963
+ enabled,
11964
+ payload: { evictOldest: true, description: 'Automated scheduled backup' },
11965
+ }),
11966
+ });
11967
+ toast('Automated backup schedule updated', 'success');
11968
+ } else {
11969
+ await api(baseUrl, {
11970
+ method: 'POST',
11971
+ headers: { 'Content-Type': 'application/json' },
11972
+ body: JSON.stringify({
11973
+ name: 'Automated Snapshot Backup',
11974
+ targetType: 'snapshot',
11975
+ targetId: 'snapshot_auto',
11976
+ cronExpression,
11977
+ timezone,
11978
+ missedRunPolicy,
11979
+ enabled,
11980
+ payload: { evictOldest: true, description: 'Automated scheduled backup' },
11981
+ }),
11982
+ });
11983
+ toast('Automated backup schedule created', 'success');
11984
+ }
11985
+ closeModal();
11986
+ await fetchDemoStatus();
11987
+ } catch (err) {
11988
+ toast(`Failed to save schedule: ${err.message || String(err)}`, 'error');
11989
+ }
11990
+ }
11991
+
11992
+ async function toggleSnapshotSchedule(id, enable) {
11993
+ try {
11994
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
11995
+ const baseUrl = slug && slug !== 'default' ? `/api/apps/${slug}/cron/schedules` : '/api/cron/schedules';
11996
+ await api(`${baseUrl}/${id}`, {
11997
+ method: 'PATCH',
11998
+ headers: { 'Content-Type': 'application/json' },
11999
+ body: JSON.stringify({ enabled: enable }),
12000
+ });
12001
+ toast(enable ? 'Automated backup schedule resumed' : 'Automated backup schedule paused', 'info');
12002
+ await fetchDemoStatus();
12003
+ } catch (err) {
12004
+ toast(`Failed to toggle schedule: ${err.message || String(err)}`, 'error');
12005
+ }
12006
+ }
12007
+
12008
+ async function triggerSnapshotScheduleNow(id) {
12009
+ try {
12010
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
12011
+ const baseUrl = slug && slug !== 'default' ? `/api/apps/${slug}/cron/schedules` : '/api/cron/schedules';
12012
+ toast('Triggering snapshot backup...', 'info');
12013
+ await api(`${baseUrl}/${id}/trigger`, { method: 'POST' });
12014
+ toast('Snapshot backup completed successfully', 'success');
12015
+ await fetchDemoStatus();
12016
+ } catch (err) {
12017
+ toast(`Failed to run backup: ${err.message || String(err)}`, 'error');
12018
+ }
12019
+ }
12020
+
12021
+ async function deleteSnapshotSchedule(id) {
12022
+ if (!confirm('Are you sure you want to remove the automated snapshot schedule?')) return;
12023
+ try {
12024
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
12025
+ const baseUrl = slug && slug !== 'default' ? `/api/apps/${slug}/cron/schedules` : '/api/cron/schedules';
12026
+ await api(`${baseUrl}/${id}`, { method: 'DELETE' });
12027
+ toast('Automated backup schedule removed', 'info');
12028
+ closeModal();
12029
+ await fetchDemoStatus();
12030
+ } catch (err) {
12031
+ toast(`Failed to delete schedule: ${err.message || String(err)}`, 'error');
12032
+ }
12033
+ }
12034
+
11670
12035
  // Backwards compatibility aliases for existing buttons / triggers
11671
12036
  function openSnapshotDemoModal() {
11672
12037
  openCreateSnapshotModal();
@@ -11684,6 +12049,17 @@ function openResetDemoModal() {
11684
12049
  function openClearDemoModal() {
11685
12050
  openClearAllSnapshotsModal();
11686
12051
  }
12052
+
12053
+ if (typeof window !== 'undefined') {
12054
+ window.renderScheduledBackupsCardHtml = renderScheduledBackupsCardHtml;
12055
+ window.openSnapshotScheduleModal = openSnapshotScheduleModal;
12056
+ window.handleSnapshotSchedulePresetChange = handleSnapshotSchedulePresetChange;
12057
+ window.updateSnapshotScheduleModalPreview = updateSnapshotScheduleModalPreview;
12058
+ window.saveSnapshotScheduleModal = saveSnapshotScheduleModal;
12059
+ window.toggleSnapshotSchedule = toggleSnapshotSchedule;
12060
+ window.triggerSnapshotScheduleNow = triggerSnapshotScheduleNow;
12061
+ window.deleteSnapshotSchedule = deleteSnapshotSchedule;
12062
+ }
11687
12063
 
11688
12064
 
11689
12065
  // === analytics.js ===
@@ -12465,7 +12841,7 @@ if (typeof window !== 'undefined') {
12465
12841
  <div>
12466
12842
  <div style="display: flex; align-items: center; gap: 8px;">
12467
12843
  <span style="font-weight: 800; font-size: 15px; color: var(--text-heading); letter-spacing: -0.02em;">NodeStack Core</span>
12468
- <span class="version-tag version-tag-accent">v2.6.0</span>
12844
+ <span class="version-tag version-tag-accent">v2.7.0</span>
12469
12845
  <span class="badge badge-get" style="font-size: 10.5px; display: inline-flex; align-items: center; gap: 5px;">
12470
12846
  <span class="live-dot" style="width: 6px; height: 6px;"></span>
12471
12847
  <span>Server Online</span>
@@ -15311,6 +15687,16 @@ function getAllCommandPaletteItems() {
15311
15687
  keywords: ['queues', 'queue', 'jobs', 'messages', 'dlq', 'dead letter', 'worker', 'background', 'concurrency'],
15312
15688
  action: () => selectNav('queues')
15313
15689
  },
15690
+ {
15691
+ id: 'nav-schedules',
15692
+ title: 'Schedules Manager',
15693
+ description: 'Configure cron schedules, timezone wall-clock triggers, and automated background jobs',
15694
+ category: 'Navigation',
15695
+ badge: 'PAGE',
15696
+ icon: '⏱️',
15697
+ keywords: ['schedules', 'cron', 'timer', 'scheduled', 'triggers', 'backup', 'automation', 'misfire'],
15698
+ action: () => selectNav('schedules')
15699
+ },
15314
15700
  {
15315
15701
  id: 'nav-api-keys',
15316
15702
  title: 'API Keys',
@@ -17390,9 +17776,12 @@ function renderFunctionsTable(functions) {
17390
17776
  <div style="display: flex; align-items: center; gap: 8px;">
17391
17777
  <span class="status-indicator ${isEnabled ? 'status-active' : 'status-inactive'}" title="${isEnabled ? 'Active' : 'Disabled'}"></span>
17392
17778
  <div>
17393
- <a href="javascript:void(0)" onclick="openFunctionEditor('${fn.id}')" style="font-weight: 600; color: var(--accent-primary); text-decoration: none; font-size: 13.5px; font-family: monospace;">
17394
- ${escapeHtml(fn.name)}
17395
- </a>
17779
+ <div style="display: flex; align-items: center; gap: 6px;">
17780
+ <a href="javascript:void(0)" onclick="openFunctionEditor('${fn.id}')" style="font-weight: 600; color: var(--accent-primary); text-decoration: none; font-size: 13.5px; font-family: monospace;">
17781
+ ${escapeHtml(fn.name)}
17782
+ </a>
17783
+ <code style="font-size: 10px; color: var(--text-muted); background: var(--bg-card-hover); padding: 1px 5px; border-radius: 4px;" title="Unique Function ID">${escapeHtml(fn.id)}</code>
17784
+ </div>
17396
17785
  ${fn.description ? `<div style="font-size: 11.5px; color: var(--text-muted); margin-top: 2px;">${escapeHtml(fn.description)}</div>` : ''}
17397
17786
  </div>
17398
17787
  </div>
@@ -19070,6 +19459,7 @@ function renderWorkbenchHeader(fn, isNew, invokePath) {
19070
19459
  <h2 style="font-size: 1.35rem; font-weight: 700; color: var(--text-main); margin: 0; font-family: monospace; display: flex; align-items: center; gap: 8px;">
19071
19460
  ${escapeHtml(fn.name)}
19072
19461
  </h2>
19462
+ ${fn.id ? `<code style="font-size: 11px; color: var(--text-muted); background: var(--bg-card-hover); border: 1px solid var(--border-subtle); padding: 2px 6px; border-radius: 4px;" title="Unique Function ID">id: ${escapeHtml(fn.id)}</code>` : ''}
19073
19463
  <div id="editor-header-badges" style="display: inline-flex; align-items: center; gap: 6px;">
19074
19464
  <span class="badge" style="background: ${fn.enabled !== false ? 'rgba(16, 185, 129, 0.15)' : 'var(--bg-card-hover)'}; color: ${fn.enabled !== false ? '#10b981' : 'var(--text-muted)'};">
19075
19465
  ${fn.enabled !== false ? '● Active' : '○ Disabled'}
@@ -19084,6 +19474,7 @@ function renderWorkbenchHeader(fn, isNew, invokePath) {
19084
19474
  📋 Copy URL
19085
19475
  </button>
19086
19476
  ${fn.eventTrigger ? `<span style="color: var(--accent-primary);">⚡ Hook: <code>${escapeHtml(fn.eventTrigger)}</code></span>` : ''}
19477
+ ${fn.cronSchedule ? `<span style="color: var(--accent-success);">⏱️ Cron: <code>${escapeHtml(fn.cronSchedule)}</code> (${escapeHtml(fn.cronTimezone || 'UTC')})</span>` : ''}
19087
19478
  <span>Limits: ${fn.timeoutMs || 1000}ms / ${fn.memoryLimitMb || 32}MB</span>
19088
19479
  </div>
19089
19480
  `}
@@ -19274,6 +19665,16 @@ function renderWorkbenchConfigPane(fn, isNew, allowedDomainsString, envString) {
19274
19665
  Format: <code>&lt;collection&gt;:&lt;phase&gt;&lt;Action&gt;</code>. Available phases: <code>beforeCreate</code>, <code>afterCreate</code>, <code>beforeUpdate</code>, <code>afterUpdate</code>, <code>beforeDelete</code>, <code>afterDelete</code>.
19275
19666
  </span>
19276
19667
  </div>
19668
+ <div>
19669
+ <label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Scheduled Cron Trigger (Optional)</label>
19670
+ <div style="display: flex; gap: 8px;">
19671
+ <input type="text" id="fn-editor-cron" class="input" value="${escapeHtml(fn.cronSchedule || '')}" placeholder="e.g. 0 9 * * 1-5 or */15 * * * *" style="flex: 1; font-size: 12px; font-family: monospace;" autocomplete="off">
19672
+ <input type="text" id="fn-editor-timezone" class="input" value="${escapeHtml(fn.cronTimezone || 'UTC')}" placeholder="Timezone (UTC)" list="iana-timezones-list" style="width: 140px; font-size: 12px;">
19673
+ </div>
19674
+ <span style="font-size: 11px; color: var(--text-muted); margin-top: 3px; display: block;">
19675
+ Standard 5-field cron expression. Automatically scheduled with distributed atomic DB lease locking.
19676
+ </span>
19677
+ </div>
19277
19678
  </div>
19278
19679
  </div>
19279
19680
 
@@ -19438,6 +19839,8 @@ async function saveFunctionEditor() {
19438
19839
  const elevatedEl = document.getElementById('fn-editor-elevated');
19439
19840
  const enabledEl = document.getElementById('fn-editor-enabled');
19440
19841
  const envEl = document.getElementById('fn-editor-env');
19842
+ const cronEl = document.getElementById('fn-editor-cron');
19843
+ const tzEl = document.getElementById('fn-editor-timezone');
19441
19844
 
19442
19845
  const nameHeaderEl = document.getElementById('fn-editor-name-header');
19443
19846
  const nameConfigEl = document.getElementById('fn-editor-name');
@@ -19465,6 +19868,8 @@ async function saveFunctionEditor() {
19465
19868
  const allowedDomains = domainsRaw ? domainsRaw.split(',').map(s => s.trim()).filter(Boolean) : (fn.allowedDomains || []);
19466
19869
  const elevated = elevatedEl ? elevatedEl.checked : !!fn.elevated;
19467
19870
  const enabled = enabledEl ? enabledEl.checked : (fn.enabled !== false);
19871
+ const cronSchedule = cronEl ? (cronEl.value.trim() || null) : (fn.cronSchedule || null);
19872
+ const cronTimezone = tzEl ? (tzEl.value.trim() || 'UTC') : (fn.cronTimezone || 'UTC');
19468
19873
 
19469
19874
  let env = fn.env || {};
19470
19875
  if (envEl && envEl.value.trim()) {
@@ -19491,6 +19896,8 @@ async function saveFunctionEditor() {
19491
19896
  allowedDomains,
19492
19897
  elevated,
19493
19898
  enabled,
19899
+ cronSchedule,
19900
+ cronTimezone,
19494
19901
  code,
19495
19902
  env,
19496
19903
  };
@@ -19892,10 +20299,13 @@ function renderFlowsListHtml() {
19892
20299
  <div class="webhook-stat-card" style="cursor: default;">
19893
20300
  <div style="display: flex; align-items: flex-start; justify-content: space-between; gap: 0.5rem;">
19894
20301
  <div>
19895
- <h4 style="margin: 0 0 0.25rem 0; font-size: 1rem; color: var(--text-main); font-weight: 600;">
19896
- ${escapeHtml(flow.name)}
19897
- </h4>
19898
- <p style="margin: 0; font-size: 0.8rem; color: var(--text-muted); min-height: 1.2rem;">
20302
+ <div style="display: flex; align-items: center; gap: 6px; flex-wrap: wrap;">
20303
+ <h4 style="margin: 0; font-size: 1rem; color: var(--text-main); font-weight: 600;">
20304
+ ${escapeHtml(flow.name)}
20305
+ </h4>
20306
+ <code style="font-size: 10px; color: var(--text-muted); background: var(--bg-card-hover); padding: 1px 5px; border-radius: 4px;" title="Unique Flow ID">${escapeHtml(flow.id)}</code>
20307
+ </div>
20308
+ <p style="margin: 0.25rem 0 0 0; font-size: 0.8rem; color: var(--text-muted); min-height: 1.2rem;">
19899
20309
  ${escapeHtml(flow.description || 'No description provided')}
19900
20310
  </p>
19901
20311
  </div>
@@ -20181,6 +20591,7 @@ function openCreateFlowModal() {
20181
20591
  <select id="new-flow-trigger" class="form-select" onchange="toggleFlowTriggerInput(this.value)">
20182
20592
  <option value="http">HTTP Endpoint (POST /api/flows/:id/execute)</option>
20183
20593
  <option value="event">Database Event Hook (e.g. orders:create)</option>
20594
+ <option value="cron">Cron Schedule (Recurring Interval)</option>
20184
20595
  <option value="manual">Manual Execution Only</option>
20185
20596
  </select>
20186
20597
  </div>
@@ -20203,6 +20614,30 @@ function openCreateFlowModal() {
20203
20614
  placeholder="collection:action (e.g. orders:create, users:*)"
20204
20615
  />
20205
20616
  </div>
20617
+ <div class="form-group" id="flow-cron-field" style="display: none; flex-direction: column; gap: 8px;">
20618
+ <label class="form-label" for="new-flow-cron">Cron Expression & Timezone</label>
20619
+ <div style="display: flex; gap: 8px;">
20620
+ <input
20621
+ type="text"
20622
+ id="new-flow-cron"
20623
+ class="form-input"
20624
+ placeholder="e.g. 0 * * * * or */15 * * * *"
20625
+ style="flex: 1; font-family: monospace;"
20626
+ />
20627
+ <input
20628
+ type="text"
20629
+ id="new-flow-timezone"
20630
+ class="form-input"
20631
+ placeholder="UTC"
20632
+ list="iana-timezones-list"
20633
+ value="UTC"
20634
+ style="width: 140px;"
20635
+ />
20636
+ </div>
20637
+ <span style="font-size: 0.72rem; color: var(--text-muted);">
20638
+ Standard 5-field cron expression. Schedules will coordinate via atomic DB leases.
20639
+ </span>
20640
+ </div>
20206
20641
  <div class="form-group">
20207
20642
  <label class="form-label" for="new-flow-concurrency">Max Concurrent Executions (Optional)</label>
20208
20643
  <input
@@ -20235,6 +20670,8 @@ function toggleFlowTriggerInput(val) {
20235
20670
  if (field) field.style.display = val === 'event' ? 'flex' : 'none';
20236
20671
  const httpAuthField = document.getElementById('flow-http-auth-field');
20237
20672
  if (httpAuthField) httpAuthField.style.display = val === 'http' ? 'flex' : 'none';
20673
+ const cronField = document.getElementById('flow-cron-field');
20674
+ if (cronField) cronField.style.display = val === 'cron' ? 'flex' : 'none';
20238
20675
  }
20239
20676
 
20240
20677
  async function handleCreateFlowSubmit(e) {
@@ -20244,6 +20681,8 @@ async function handleCreateFlowSubmit(e) {
20244
20681
  const triggerInput = document.getElementById('new-flow-trigger');
20245
20682
  const authInput = document.getElementById('new-flow-auth-policy');
20246
20683
  const eventInput = document.getElementById('new-flow-event');
20684
+ const cronInput = document.getElementById('new-flow-cron');
20685
+ const tzInput = document.getElementById('new-flow-timezone');
20247
20686
  const concurrencyInput = document.getElementById('new-flow-concurrency');
20248
20687
 
20249
20688
  const name = nameInput ? nameInput.value.trim() : '';
@@ -20253,6 +20692,8 @@ async function handleCreateFlowSubmit(e) {
20253
20692
  const authPolicy = triggerType === 'http' && authInput ? authInput.value : 'admin';
20254
20693
  const invokeRule = triggerType === 'http' && authPolicy === 'custom' ? '@request.auth.id != ""' : null;
20255
20694
  const eventTrigger = triggerType === 'event' && eventInput ? eventInput.value.trim() : null;
20695
+ const cronSchedule = triggerType === 'cron' && cronInput ? cronInput.value.trim() || null : null;
20696
+ const cronTimezone = triggerType === 'cron' && tzInput ? tzInput.value.trim() || 'UTC' : 'UTC';
20256
20697
  const rawConcurrency = concurrencyInput ? concurrencyInput.value.trim() : '';
20257
20698
  const maxConcurrentExecutions = rawConcurrency !== '' ? parseInt(rawConcurrency, 10) : null;
20258
20699
 
@@ -20264,6 +20705,8 @@ async function handleCreateFlowSubmit(e) {
20264
20705
  authPolicy,
20265
20706
  invokeRule,
20266
20707
  eventTrigger,
20708
+ cronSchedule,
20709
+ cronTimezone,
20267
20710
  maxConcurrentExecutions,
20268
20711
  definition: {
20269
20712
  startAt: 'FirstStep',
@@ -20292,6 +20735,9 @@ async function handleCreateFlowSubmit(e) {
20292
20735
  }
20293
20736
 
20294
20737
  function formatFlowTriggerLabel(flow) {
20738
+ if (flow.triggerType === 'cron') {
20739
+ return `⏱️ Cron: ${flow.cronSchedule || ''} (${flow.cronTimezone || 'UTC'})`;
20740
+ }
20295
20741
  if (flow.triggerType === 'event') {
20296
20742
  return `DB Event${flow.eventTrigger ? `: ${escapeHtml(flow.eventTrigger)}` : ''}`;
20297
20743
  }
@@ -20655,6 +21101,37 @@ function renderTriggerConfigHtml(flow) {
20655
21101
  `;
20656
21102
  }
20657
21103
 
21104
+ if (triggerType === 'cron') {
21105
+ return `
21106
+ <div style="display: flex; align-items: center; gap: 6px;">
21107
+ <input
21108
+ type="text"
21109
+ id="flow-edit-cron-schedule"
21110
+ class="flow-field-input"
21111
+ placeholder="e.g. 0 * * * * or */15 * * * *"
21112
+ value="${escapeHtml(flow.cronSchedule || '')}"
21113
+ style="width: 140px; padding: 0.25rem 0.5rem; font-size: 0.8rem; font-family: var(--font-mono, monospace);"
21114
+ title="5-field cron expression"
21115
+ oninput="handleFlowCronScheduleChange(this.value)"
21116
+ />
21117
+ <input
21118
+ type="text"
21119
+ id="flow-edit-cron-timezone"
21120
+ class="flow-field-input"
21121
+ placeholder="Timezone"
21122
+ list="iana-timezones-list"
21123
+ value="${escapeHtml(flow.cronTimezone || 'UTC')}"
21124
+ style="width: 110px; padding: 0.25rem 0.5rem; font-size: 0.8rem;"
21125
+ title="IANA timezone (e.g. UTC, America/New_York)"
21126
+ oninput="handleFlowCronTimezoneChange(this.value)"
21127
+ />
21128
+ <span id="flow-cron-preview" style="font-size: 0.72rem; color: var(--text-muted); max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
21129
+ ${flow.cronSchedule ? '⏱️ Scheduled' : 'Enter expression'}
21130
+ </span>
21131
+ </div>
21132
+ `;
21133
+ }
21134
+
20658
21135
  if (triggerType === 'http') {
20659
21136
  const base = getDesignerFlowsApiBase();
20660
21137
  const endpointPath = `${base}/${flow.id}/execute`;
@@ -20706,6 +21183,16 @@ function handleFlowTriggerTypeChange(newType) {
20706
21183
  } else {
20707
21184
  designerState.activeFlow.eventTrigger = null;
20708
21185
  }
21186
+ if (newType === 'cron') {
21187
+ if (!designerState.activeFlow.cronSchedule) {
21188
+ designerState.activeFlow.cronSchedule = '0 * * * *';
21189
+ }
21190
+ if (!designerState.activeFlow.cronTimezone) {
21191
+ designerState.activeFlow.cronTimezone = 'UTC';
21192
+ }
21193
+ } else {
21194
+ designerState.activeFlow.cronSchedule = null;
21195
+ }
20709
21196
 
20710
21197
  const configArea = document.getElementById('flow-trigger-config-area');
20711
21198
  if (configArea) {
@@ -20718,6 +21205,53 @@ function handleFlowTriggerTypeChange(newType) {
20718
21205
  }
20719
21206
  }
20720
21207
 
21208
+ function handleFlowCronScheduleChange(val) {
21209
+ if (!designerState.activeFlow) return;
21210
+ designerState.activeFlow.cronSchedule = val.trim();
21211
+ updateFlowCronPreview();
21212
+ }
21213
+
21214
+ function handleFlowCronTimezoneChange(val) {
21215
+ if (!designerState.activeFlow) return;
21216
+ designerState.activeFlow.cronTimezone = val.trim() || 'UTC';
21217
+ updateFlowCronPreview();
21218
+ }
21219
+
21220
+ let flowPreviewTimer = null;
21221
+ function updateFlowCronPreview() {
21222
+ clearTimeout(flowPreviewTimer);
21223
+ flowPreviewTimer = setTimeout(async () => {
21224
+ const el = document.getElementById('flow-cron-preview');
21225
+ if (!el || !designerState.activeFlow) return;
21226
+ const expr = designerState.activeFlow.cronSchedule;
21227
+ const tz = designerState.activeFlow.cronTimezone || 'UTC';
21228
+ if (!expr || expr.split(/\s+/).length < 5) {
21229
+ el.textContent = 'Enter 5-field cron';
21230
+ el.style.color = 'var(--text-muted)';
21231
+ return;
21232
+ }
21233
+ try {
21234
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
21235
+ const url = slug && slug !== 'default' ? `/api/apps/${slug}/cron/preview` : '/api/cron/preview';
21236
+ const res = await api(url, {
21237
+ method: 'POST',
21238
+ headers: { 'Content-Type': 'application/json' },
21239
+ body: JSON.stringify({ cronExpression: expr, timezone: tz, count: 1 })
21240
+ });
21241
+ if (res && res.valid) {
21242
+ el.textContent = res.description || 'Valid cron';
21243
+ el.style.color = 'var(--accent-success)';
21244
+ } else {
21245
+ el.textContent = res?.error || 'Invalid cron';
21246
+ el.style.color = 'var(--accent-danger)';
21247
+ }
21248
+ } catch (_) {
21249
+ el.textContent = 'Invalid cron';
21250
+ el.style.color = 'var(--accent-danger)';
21251
+ }
21252
+ }, 400);
21253
+ }
21254
+
20721
21255
  function handleFlowAuthPolicyChange(policy) {
20722
21256
  if (!designerState.activeFlow) return;
20723
21257
  designerState.activeFlow.authPolicy = policy;
@@ -20758,6 +21292,7 @@ function renderFlowDesignerWorkbench(flow) {
20758
21292
  style="font-weight: 700; font-size: 1rem; width: 210px;"
20759
21293
  onchange="updateFlowMeta('name', this.value)"
20760
21294
  />
21295
+ ${flow.id ? `<code style="font-size: 11px; color: var(--text-muted); background: var(--bg-card); border: 1px solid var(--border-subtle); padding: 3px 6px; border-radius: 4px;" title="Unique Flow ID">id: ${escapeHtml(flow.id)}</code>` : ''}
20761
21296
  <div style="display: flex; align-items: center; gap: 0.4rem; background: var(--bg-card); padding: 3px 8px; border-radius: 6px; border: 1px solid var(--border-subtle);">
20762
21297
  <span style="font-size: 0.72rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.04em;">Trigger:</span>
20763
21298
  <select
@@ -20768,6 +21303,7 @@ function renderFlowDesignerWorkbench(flow) {
20768
21303
  >
20769
21304
  <option value="http" ${flow.triggerType === 'http' ? 'selected' : ''}>HTTP API</option>
20770
21305
  <option value="event" ${flow.triggerType === 'event' ? 'selected' : ''}>DB Event</option>
21306
+ <option value="cron" ${flow.triggerType === 'cron' ? 'selected' : ''}>Cron Schedule</option>
20771
21307
  <option value="manual" ${flow.triggerType === 'manual' ? 'selected' : ''}>Manual</option>
20772
21308
  </select>
20773
21309
  <div id="flow-trigger-config-area" style="display: flex; align-items: center; gap: 6px;">
@@ -21620,6 +22156,8 @@ async function saveFlowChanges(options = {}) {
21620
22156
  ? (typeof getStandaloneRuleValue === 'function' ? getStandaloneRuleValue('flow_invoke') : (flow.invokeRule || null))
21621
22157
  : null,
21622
22158
  eventTrigger: flow.triggerType === 'event' ? (flow.eventTrigger || null) : null,
22159
+ cronSchedule: flow.triggerType === 'cron' ? (flow.cronSchedule || null) : null,
22160
+ cronTimezone: flow.triggerType === 'cron' ? (flow.cronTimezone || 'UTC') : 'UTC',
21623
22161
  maxConcurrentExecutions: flow.maxConcurrentExecutions ?? null,
21624
22162
  definition: flow.definition,
21625
22163
  }),
@@ -21652,6 +22190,8 @@ if (typeof window !== 'undefined') {
21652
22190
  window.renderFlowDesignerWorkbench = renderFlowDesignerWorkbench;
21653
22191
  window.updateFlowMeta = updateFlowMeta;
21654
22192
  window.handleFlowTriggerTypeChange = handleFlowTriggerTypeChange;
22193
+ window.handleFlowCronScheduleChange = handleFlowCronScheduleChange;
22194
+ window.handleFlowCronTimezoneChange = handleFlowCronTimezoneChange;
21655
22195
  window.handleFlowAuthPolicyChange = handleFlowAuthPolicyChange;
21656
22196
  window.updateFlowStartAt = updateFlowStartAt;
21657
22197
  window.updateStepProp = updateStepProp;
@@ -24528,50 +25068,1759 @@ if (typeof window !== 'undefined') {
24528
25068
  }
24529
25069
 
24530
25070
 
24531
- // === api-keys.js ===
24532
- // ==========================================
24533
- // API Keys & Visual Scope Matrix Management
24534
- // ==========================================
25071
+ // === cron.js ===
25072
+ // Native Cron & Scheduled Triggers Module for NodeStack Admin UI
24535
25073
 
24536
- const apiKeysState = {
24537
- keys: [],
24538
- functions: [],
24539
- flows: [],
24540
- queues: [],
24541
- isLoading: false,
24542
- editingKeyId: null,
24543
- lastFocusedElement: null,
25074
+ const cronIcons = {
25075
+ clock: (w = 12, h = 12) => `<svg width="${w}" height="${h}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: -1px; display: inline-block;"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>`,
25076
+ calendar: (w = 13, h = 13) => `<svg width="${w}" height="${h}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: -1px; display: inline-block;"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect><line x1="16" y1="2" x2="16" y2="6"></line><line x1="8" y1="2" x2="8" y2="6"></line><line x1="3" y1="10" x2="21" y2="10"></line></svg>`,
25077
+ globe: (w = 11, h = 11) => `<svg width="${w}" height="${h}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: -1px; display: inline-block;"><circle cx="12" cy="12" r="10"></circle><line x1="2" y1="12" x2="22" y2="12"></line><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"></path></svg>`,
25078
+ alert: (w = 11, h = 11) => `<svg width="${w}" height="${h}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: -1px; display: inline-block;"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path><line x1="12" y1="9" x2="12" y2="13"></line><line x1="12" y1="17" x2="12.01" y2="17"></line></svg>`,
25079
+ refresh: (w = 10, h = 10) => `<svg width="${w}" height="${h}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: -1px; display: inline-block;"><polyline points="23 4 23 10 17 10"></polyline><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path></svg>`,
25080
+ zap: (w = 10, h = 10) => `<svg width="${w}" height="${h}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: -1px; display: inline-block;"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"></polygon></svg>`,
25081
+ hourglass: (w = 10, h = 10) => `<svg width="${w}" height="${h}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: -1px; display: inline-block;"><path d="M5 22h14M5 2h14M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22M7 2v4.172a2 2 0 0 0 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2"></path></svg>`,
25082
+ database: (w = 10, h = 10) => `<svg width="${w}" height="${h}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: -1px; display: inline-block;"><ellipse cx="12" cy="5" rx="9" ry="3"></ellipse><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"></path><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"></path></svg>`,
25083
+ play: (w = 9, h = 9) => `<svg width="${w}" height="${h}" viewBox="0 0 24 24" fill="currentColor" stroke="none" style="vertical-align: -1px; display: inline-block;"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg>`,
25084
+ externalLink: (w = 10, h = 10) => `<svg width="${w}" height="${h}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: -1px; display: inline-block;"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg>`,
25085
+ copy: (w = 12, h = 12) => `<svg width="${w}" height="${h}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: -1px; display: inline-block;"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>`,
25086
+ chart: (w = 18, h = 18) => `<svg width="${w}" height="${h}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display: inline-block;"><line x1="18" y1="20" x2="18" y2="10"></line><line x1="12" y1="20" x2="12" y2="4"></line><line x1="6" y1="20" x2="6" y2="14"></line></svg>`,
24544
25087
  };
24545
25088
 
24546
- function setAppShellInert(isInert) {
24547
- if (typeof document === 'undefined') return;
24548
- const appRoot = document.getElementById('app');
24549
- if (!appRoot) return;
24550
- try {
24551
- if (isInert) {
24552
- appRoot.setAttribute('inert', '');
24553
- } else {
24554
- appRoot.removeAttribute('inert');
24555
- }
24556
- } catch (_) {}
24557
- }
25089
+ let cronState = {
25090
+ subTab: 'schedules', // 'schedules' | 'history'
25091
+ schedules: [],
25092
+ functionsList: [],
25093
+ flowsList: [],
25094
+ searchQuery: '',
25095
+ statusFilter: 'all', // 'all' | 'enabled' | 'paused' | 'failed'
25096
+ sortBy: 'nextRun', // 'nextRun' | 'name' | 'lastRun' | 'created'
25097
+ stats: {
25098
+ totalSchedules: 0,
25099
+ activeSchedules: 0,
25100
+ totalRuns: 0,
25101
+ successfulRuns: 0,
25102
+ failedRuns: 0,
25103
+ skippedRuns: 0,
25104
+ byTarget: { function: 0, flow: 0, snapshot: 0 },
25105
+ },
25106
+ runs: [],
25107
+ runFilter: {
25108
+ scheduleId: '',
25109
+ targetType: '',
25110
+ status: 'all',
25111
+ page: 1,
25112
+ perPage: 25,
25113
+ total: 0,
25114
+ totalPages: 1,
25115
+ },
25116
+ targetFilter: 'all', // 'all' | 'function' | 'flow' | 'snapshot'
25117
+ activeScheduleForEdit: null,
25118
+ activeRunForDetail: null,
25119
+ };
24558
25120
 
24559
- function updateSidebarApiKeysBadge(keysList) {
24560
- if (typeof document === 'undefined') return;
24561
- const badge = document.getElementById('sidebar-api-keys-count');
24562
- if (!badge) return;
24563
- const list = Array.isArray(keysList) ? keysList : apiKeysState.keys;
24564
- const activeCount = list.filter(k => k.status === 'active').length;
24565
- badge.textContent = String(activeCount);
24566
- badge.style.display = activeCount > 0 ? 'inline-block' : 'none';
25121
+ if (typeof window !== 'undefined') {
25122
+ window.cronState = cronState;
24567
25123
  }
24568
25124
 
24569
- function getApiKeysApiPrefix() {
24570
- const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : (typeof state !== 'undefined' && state?.activeApp?.slug) || 'default';
24571
- return slug && slug !== 'default' ? `/api/apps/${encodeURIComponent(slug)}/api-keys` : '/api/api-keys';
25125
+ function getCronApiPrefix() {
25126
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
25127
+ return slug && slug !== 'default' ? `/api/apps/${encodeURIComponent(slug)}/cron` : '/api/cron';
24572
25128
  }
24573
25129
 
24574
- async function loadApiKeys() {
25130
+ function getFunctionsListApiPrefix() {
25131
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
25132
+ return slug && slug !== 'default' ? `/api/apps/${encodeURIComponent(slug)}/functions` : '/api/functions';
25133
+ }
25134
+
25135
+ function getFlowsListApiPrefix() {
25136
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
25137
+ return slug && slug !== 'default' ? `/api/apps/${encodeURIComponent(slug)}/flows` : '/api/flows';
25138
+ }
25139
+
25140
+ function getSupportedIanaTimezones() {
25141
+ if (typeof Intl !== 'undefined' && typeof Intl.supportedValuesOf === 'function') {
25142
+ try {
25143
+ return Intl.supportedValuesOf('timeZone');
25144
+ } catch {}
25145
+ }
25146
+ return ['UTC', 'America/New_York', 'America/Chicago', 'America/Denver', 'America/Los_Angeles', 'Europe/London', 'Europe/Paris', 'Asia/Tokyo', 'Asia/Kolkata', 'Australia/Sydney'];
25147
+ }
25148
+
25149
+ function isSqliteDatabase() {
25150
+ if (typeof state !== 'undefined' && state.demo && state.demo.supported === false) {
25151
+ return false;
25152
+ }
25153
+ if (typeof databaseState !== 'undefined' && databaseState.status?.provider) {
25154
+ return databaseState.status.provider.toLowerCase() === 'sqlite';
25155
+ }
25156
+ return true;
25157
+ }
25158
+
25159
+ function renderSchedulesView() {
25160
+ const container = document.getElementById('page-view-schedules') || document.getElementById('main-body');
25161
+ if (!container) return;
25162
+
25163
+ if (!isSqliteDatabase() && cronState.targetFilter === 'snapshot') {
25164
+ cronState.targetFilter = 'all';
25165
+ }
25166
+
25167
+ container.innerHTML = `
25168
+ <div class="webhooks-container" id="schedules-manager-root">
25169
+ <!-- Header -->
25170
+ <div class="webhooks-header">
25171
+ <div class="webhooks-title-area">
25172
+ <h2>
25173
+ <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
25174
+ <circle cx="12" cy="12" r="10"></circle>
25175
+ <polyline points="12 6 12 12 16 14"></polyline>
25176
+ </svg>
25177
+ Schedules Manager
25178
+ </h2>
25179
+ <p>Configure automated Cron triggers for Serverless Functions, Orchestrated Flows, and Backups with atomic distributed DB leases.</p>
25180
+ </div>
25181
+ <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
25182
+ <button class="btn btn-secondary btn-sm" id="btn-refresh-schedules" onclick="refreshSchedulesView()" title="Refresh Schedules & Stats">
25183
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M23 4v6h-6M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
25184
+ Refresh
25185
+ </button>
25186
+ <button class="btn btn-primary btn-sm" id="btn-new-schedule" onclick="openCreateScheduleDrawer()">
25187
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
25188
+ New Schedule
25189
+ </button>
25190
+ </div>
25191
+ </div>
25192
+
25193
+ <!-- Stats Grid -->
25194
+ <div class="webhooks-stats-grid" id="cron-stats-grid">
25195
+ <div class="webhook-stat-card">
25196
+ <span class="webhook-stat-label">Total Schedules</span>
25197
+ <div class="webhook-stat-value" id="cron-stat-total">0</div>
25198
+ </div>
25199
+ <div class="webhook-stat-card">
25200
+ <span class="webhook-stat-label">Active (Enabled)</span>
25201
+ <div class="webhook-stat-value" style="color: var(--accent-success);" id="cron-stat-active">0</div>
25202
+ </div>
25203
+ <div class="webhook-stat-card">
25204
+ <span class="webhook-stat-label">Succeeded Runs</span>
25205
+ <div class="webhook-stat-value" style="color: var(--accent-primary);" id="cron-stat-succeeded">0</div>
25206
+ </div>
25207
+ <div class="webhook-stat-card">
25208
+ <span class="webhook-stat-label">Failed Runs</span>
25209
+ <div class="webhook-stat-value" style="color: var(--accent-danger);" id="cron-stat-failed">0</div>
25210
+ </div>
25211
+ <div class="webhook-stat-card">
25212
+ <span class="webhook-stat-label">Skipped (Missed Window)</span>
25213
+ <div class="webhook-stat-value" style="color: var(--accent-warning);" id="cron-stat-skipped">0</div>
25214
+ </div>
25215
+ </div>
25216
+
25217
+ <!-- Subtabs Bar -->
25218
+ <div class="webhooks-tabs-bar" style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
25219
+ <div style="display: flex; align-items: center; gap: 6px;">
25220
+ <button class="webhook-tab-btn ${cronState.subTab === 'schedules' ? 'active' : ''}" id="tab-btn-cron-schedules" onclick="switchCronTab('schedules')">
25221
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>
25222
+ Active Schedules
25223
+ </button>
25224
+ <button class="webhook-tab-btn ${cronState.subTab === 'history' ? 'active' : ''}" id="tab-btn-cron-history" onclick="switchCronTab('history')">
25225
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="8" y1="6" x2="21" y2="6"></line><line x1="8" y1="12" x2="21" y2="12"></line><line x1="8" y1="18" x2="21" y2="18"></line><line x1="3" y1="6" x2="3.01" y2="6"></line><line x1="3" y1="12" x2="3.01" y2="12"></line><line x1="3" y1="18" x2="3.01" y2="18"></line></svg>
25226
+ Execution History
25227
+ </button>
25228
+ </div>
25229
+ <div id="cron-tab-actions" style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
25230
+ ${cronState.subTab === 'schedules' ? `
25231
+ <div style="display: flex; align-items: center; gap: 6px; flex-wrap: wrap;">
25232
+ <input type="text" class="input input-sm" id="cron-search-input" placeholder="Search schedules..." value="${escapeHtml(cronState.searchQuery || '')}" oninput="handleCronSearchInput(this.value)" style="font-size: 11px; width: 140px; padding: 3px 8px;">
25233
+ <select class="input input-sm" id="cron-target-filter" onchange="handleCronTargetFilter(this.value)" style="font-size: 11px; padding: 3px 6px;">
25234
+ <option value="all" ${cronState.targetFilter === 'all' ? 'selected' : ''}>All Targets</option>
25235
+ <option value="function" ${cronState.targetFilter === 'function' ? 'selected' : ''}>Functions</option>
25236
+ <option value="flow" ${cronState.targetFilter === 'flow' ? 'selected' : ''}>Flows</option>
25237
+ ${isSqliteDatabase() ? `<option value="snapshot" ${cronState.targetFilter === 'snapshot' ? 'selected' : ''}>Snapshots</option>` : ''}
25238
+ </select>
25239
+ <select class="input input-sm" id="cron-status-filter" onchange="handleCronStatusFilter(this.value)" style="font-size: 11px; padding: 3px 6px;">
25240
+ <option value="all" ${cronState.statusFilter === 'all' ? 'selected' : ''}>All States</option>
25241
+ <option value="enabled" ${cronState.statusFilter === 'enabled' ? 'selected' : ''}>Active Only</option>
25242
+ <option value="paused" ${cronState.statusFilter === 'paused' ? 'selected' : ''}>Paused Only</option>
25243
+ <option value="failed" ${cronState.statusFilter === 'failed' ? 'selected' : ''}>Failing Only</option>
25244
+ </select>
25245
+ <select class="input input-sm" id="cron-sort-filter" onchange="handleCronSortChange(this.value)" style="font-size: 11px; padding: 3px 6px;">
25246
+ <option value="nextRun" ${cronState.sortBy === 'nextRun' ? 'selected' : ''}>Sort: Next Run</option>
25247
+ <option value="name" ${cronState.sortBy === 'name' ? 'selected' : ''}>Sort: Name</option>
25248
+ <option value="lastRun" ${cronState.sortBy === 'lastRun' ? 'selected' : ''}>Sort: Last Run</option>
25249
+ <option value="created" ${cronState.sortBy === 'created' ? 'selected' : ''}>Sort: Created</option>
25250
+ </select>
25251
+ </div>
25252
+ ` : `
25253
+ <button class="btn btn-secondary btn-sm" id="btn-clear-cron-history" onclick="handleClearRunHistory()" style="font-size: 11px;">
25254
+ ${cronState.runFilter.scheduleId ? 'Clear Schedule History' : 'Clear All History'}
25255
+ </button>
25256
+ `}
25257
+ </div>
25258
+ </div>
25259
+
25260
+ <!-- Tab Content Area -->
25261
+ <div id="cron-tab-content" style="margin-top: 16px;">
25262
+ ${cronState.subTab === 'schedules' ? renderSchedulesListHtml() : renderHistoryTableHtml()}
25263
+ </div>
25264
+ </div>
25265
+
25266
+ <!-- Datalist for IANA Timezones -->
25267
+ <datalist id="iana-timezones-list">
25268
+ ${getSupportedIanaTimezones().map(tz => `<option value="${escapeHtml(tz)}"></option>`).join('')}
25269
+ </datalist>
25270
+
25271
+ <!-- Create / Edit Schedule Modal Container -->
25272
+ <div id="cron-schedule-modal-container"></div>
25273
+ `;
25274
+
25275
+ loadCronData();
25276
+ }
25277
+
25278
+ function switchCronTab(tab, updateUrl = true) {
25279
+ cronState.subTab = tab;
25280
+ if (updateUrl && typeof pushRoute === 'function') {
25281
+ pushRoute(`schedules/${tab}`);
25282
+ }
25283
+ renderSchedulesView();
25284
+ }
25285
+
25286
+ function handleCronTargetFilter(target) {
25287
+ if (!isSqliteDatabase() && target === 'snapshot') {
25288
+ target = 'all';
25289
+ }
25290
+ cronState.targetFilter = target;
25291
+ refreshSchedulesListDom();
25292
+ }
25293
+
25294
+ function handleCronSearchInput(query) {
25295
+ cronState.searchQuery = query || '';
25296
+ refreshSchedulesListDom();
25297
+ }
25298
+
25299
+ function handleCronStatusFilter(status) {
25300
+ cronState.statusFilter = status;
25301
+ refreshSchedulesListDom();
25302
+ }
25303
+
25304
+ function handleCronSortChange(sort) {
25305
+ cronState.sortBy = sort;
25306
+ refreshSchedulesListDom();
25307
+ }
25308
+
25309
+ function refreshSchedulesListDom() {
25310
+ const contentArea = document.getElementById('cron-tab-content');
25311
+ if (contentArea && cronState.subTab === 'schedules') {
25312
+ contentArea.innerHTML = renderSchedulesListHtml();
25313
+ }
25314
+ }
25315
+
25316
+ function viewScheduleHistory(scheduleId) {
25317
+ cronState.runFilter.scheduleId = scheduleId;
25318
+ cronState.runFilter.page = 1;
25319
+ switchCronTab('history');
25320
+ }
25321
+
25322
+ function navigateToCronTarget(targetType, targetId) {
25323
+ if (targetType === 'function') {
25324
+ if (typeof selectNav === 'function') {
25325
+ selectNav('functions');
25326
+ if (typeof openFunctionWorkbench === 'function' && targetId) {
25327
+ setTimeout(() => openFunctionWorkbench(targetId), 120);
25328
+ }
25329
+ }
25330
+ } else if (targetType === 'flow') {
25331
+ if (typeof selectNav === 'function') {
25332
+ selectNav('flows');
25333
+ if (typeof openFlowInDesigner === 'function' && targetId) {
25334
+ setTimeout(() => openFlowInDesigner(targetId), 120);
25335
+ }
25336
+ }
25337
+ } else if (targetType === 'snapshot') {
25338
+ if (typeof selectNav === 'function') {
25339
+ selectNav('snapshots');
25340
+ }
25341
+ }
25342
+ }
25343
+
25344
+ async function loadCronData() {
25345
+ try {
25346
+ const apiPrefix = getCronApiPrefix();
25347
+ const [stats, schedules] = await Promise.all([
25348
+ api(`${apiPrefix}/stats`).catch(() => null),
25349
+ api(`${apiPrefix}/schedules`).catch(() => []),
25350
+ loadFunctionsAndFlows(),
25351
+ (typeof fetchDatabaseStatus === 'function' && (typeof databaseState === 'undefined' || !databaseState.status)) ? fetchDatabaseStatus().catch(() => null) : Promise.resolve(null),
25352
+ ]);
25353
+
25354
+ if (stats) {
25355
+ cronState.stats = stats;
25356
+ updateStatsDom();
25357
+ }
25358
+ if (schedules) {
25359
+ cronState.schedules = Array.isArray(schedules) ? schedules : (schedules.schedules || []);
25360
+ const contentArea = document.getElementById('cron-tab-content');
25361
+ if (contentArea && cronState.subTab === 'schedules') {
25362
+ contentArea.innerHTML = renderSchedulesListHtml();
25363
+ }
25364
+ }
25365
+
25366
+ if (cronState.subTab === 'history') {
25367
+ await loadRunHistory();
25368
+ }
25369
+ } catch (err) {
25370
+ console.warn('[Cron] Failed to load schedule data:', err);
25371
+ }
25372
+ }
25373
+
25374
+ function getTargetDisplayName(targetType, targetId) {
25375
+ if (!targetId) return '';
25376
+ if (targetType === 'function') {
25377
+ const fn = (cronState.functionsList || []).find(f => f.id === targetId || f.name === targetId);
25378
+ return fn ? fn.name : targetId;
25379
+ }
25380
+ if (targetType === 'flow') {
25381
+ const fl = (cronState.flowsList || []).find(f => f.id === targetId || f.name === targetId);
25382
+ return fl ? fl.name : targetId;
25383
+ }
25384
+ if (targetType === 'snapshot') {
25385
+ return targetId === 'data.db' ? 'data.db (SQLite)' : targetId;
25386
+ }
25387
+ return targetId;
25388
+ }
25389
+
25390
+ async function loadCronStats() {
25391
+ try {
25392
+ const apiPrefix = getCronApiPrefix();
25393
+ const stats = await api(`${apiPrefix}/stats`).catch(() => null);
25394
+ if (stats) {
25395
+ cronState.stats = stats;
25396
+ updateStatsDom();
25397
+ }
25398
+ } catch (_) {}
25399
+ }
25400
+
25401
+ async function loadFunctionsAndFlows() {
25402
+ try {
25403
+ const fnPrefix = getFunctionsListApiPrefix();
25404
+ const flowPrefix = getFlowsListApiPrefix();
25405
+ const [fnData, flowData] = await Promise.all([
25406
+ api(fnPrefix).catch(() => []),
25407
+ api(flowPrefix).catch(() => []),
25408
+ ]);
25409
+ cronState.functionsList = Array.isArray(fnData) ? fnData : (fnData?.items || fnData?.functions || []);
25410
+ cronState.flowsList = Array.isArray(flowData) ? flowData : (flowData?.items || flowData?.flows || []);
25411
+
25412
+ // Re-render schedules list or target picker if open
25413
+ const contentArea = document.getElementById('cron-tab-content');
25414
+ if (contentArea && cronState.subTab === 'schedules' && cronState.schedules.length > 0) {
25415
+ contentArea.innerHTML = renderSchedulesListHtml();
25416
+ }
25417
+
25418
+ // If modal target picker is open, refresh its options
25419
+ const pickerArea = document.getElementById('sched-target-picker-area');
25420
+ const targetTypeEl = document.getElementById('sched-input-target-type');
25421
+ const targetIdEl = document.getElementById('sched-input-target-id');
25422
+ if (pickerArea && targetTypeEl) {
25423
+ pickerArea.innerHTML = renderModalTargetPickerHtml(targetTypeEl.value, targetIdEl?.value || '');
25424
+ }
25425
+ } catch (_) {}
25426
+ }
25427
+
25428
+ function updateStatsDom() {
25429
+ const s = cronState.stats;
25430
+ const totalEl = document.getElementById('cron-stat-total');
25431
+ const activeEl = document.getElementById('cron-stat-active');
25432
+ const succEl = document.getElementById('cron-stat-succeeded');
25433
+ const failEl = document.getElementById('cron-stat-failed');
25434
+ const skipEl = document.getElementById('cron-stat-skipped');
25435
+
25436
+ if (totalEl) totalEl.textContent = s.totalSchedules || 0;
25437
+ if (activeEl) activeEl.textContent = s.activeSchedules || 0;
25438
+ if (succEl) succEl.textContent = s.successfulRuns || 0;
25439
+ if (failEl) failEl.textContent = s.failedRuns || 0;
25440
+ if (skipEl) skipEl.textContent = s.skippedRuns || 0;
25441
+
25442
+ const sidebarCountEl = document.getElementById('sidebar-schedules-count');
25443
+ if (sidebarCountEl) {
25444
+ sidebarCountEl.textContent = s.totalSchedules || 0;
25445
+ sidebarCountEl.style.display = s.totalSchedules > 0 ? 'inline-block' : 'none';
25446
+ }
25447
+ }
25448
+
25449
+ function refreshSchedulesView() {
25450
+ loadCronData();
25451
+ }
25452
+
25453
+ function renderSchedulesListHtml() {
25454
+ let list = (cronState.schedules || []).slice();
25455
+
25456
+ // Target Filter
25457
+ if (cronState.targetFilter !== 'all') {
25458
+ list = list.filter(s => s.targetType === cronState.targetFilter);
25459
+ }
25460
+
25461
+ // Status Filter
25462
+ if (cronState.statusFilter === 'enabled') {
25463
+ list = list.filter(s => Boolean(s.enabled));
25464
+ } else if (cronState.statusFilter === 'paused') {
25465
+ list = list.filter(s => !s.enabled);
25466
+ } else if (cronState.statusFilter === 'failed') {
25467
+ list = list.filter(s => s.lastStatus === 'failed');
25468
+ }
25469
+
25470
+ // Search Filter
25471
+ if (cronState.searchQuery && cronState.searchQuery.trim()) {
25472
+ const q = cronState.searchQuery.trim().toLowerCase();
25473
+ list = list.filter(s =>
25474
+ (s.name && s.name.toLowerCase().includes(q)) ||
25475
+ (s.cronExpression && s.cronExpression.toLowerCase().includes(q)) ||
25476
+ (s.humanDescription && s.humanDescription.toLowerCase().includes(q)) ||
25477
+ (s.targetId && s.targetId.toLowerCase().includes(q)) ||
25478
+ (s.description && s.description.toLowerCase().includes(q))
25479
+ );
25480
+ }
25481
+
25482
+ // Sorting
25483
+ list.sort((a, b) => {
25484
+ if (cronState.sortBy === 'name') {
25485
+ return a.name.localeCompare(b.name);
25486
+ }
25487
+ if (cronState.sortBy === 'created') {
25488
+ return new Date(b.created).getTime() - new Date(a.created).getTime();
25489
+ }
25490
+ if (cronState.sortBy === 'lastRun') {
25491
+ const tA = a.lastRunAt ? new Date(a.lastRunAt).getTime() : 0;
25492
+ const tB = b.lastRunAt ? new Date(b.lastRunAt).getTime() : 0;
25493
+ return tB - tA;
25494
+ }
25495
+ // Default 'nextRun': soonest nextRunAt first; disabled/null at the end
25496
+ const tA = a.enabled && a.nextRunAt ? new Date(a.nextRunAt).getTime() : Infinity;
25497
+ const tB = b.enabled && b.nextRunAt ? new Date(b.nextRunAt).getTime() : Infinity;
25498
+ return tA - tB;
25499
+ });
25500
+
25501
+ if (list.length === 0) {
25502
+ if (cronState.schedules && cronState.schedules.length > 0) {
25503
+ return `
25504
+ <div style="padding: 40px 16px; text-align: center; background: var(--bg-card); border-radius: 8px; border: 1px dashed var(--border-subtle);">
25505
+ <h4 style="margin: 0 0 6px 0; font-size: 14px;">No Matching Schedules</h4>
25506
+ <p style="color: var(--text-muted); font-size: 12px; max-width: 420px; margin: 0 auto 14px auto;">
25507
+ No schedules matched your search query or active state filters.
25508
+ </p>
25509
+ <button class="btn btn-secondary btn-sm" onclick="handleResetScheduleFilters()">
25510
+ Reset Filters
25511
+ </button>
25512
+ </div>
25513
+ `;
25514
+ }
25515
+ return `
25516
+ <div style="padding: 48px 16px; text-align: center; background: var(--bg-card); border-radius: 8px; border: 1px dashed var(--border-subtle);">
25517
+ <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="margin-bottom: 12px; color: var(--text-muted); opacity: 0.7;">
25518
+ <circle cx="12" cy="12" r="10"></circle>
25519
+ <polyline points="12 6 12 12 16 14"></polyline>
25520
+ </svg>
25521
+ <h4 style="margin: 0 0 6px 0; font-size: 15px;">No Schedules Found</h4>
25522
+ <p style="color: var(--text-muted); font-size: 13px; max-width: 440px; margin: 0 auto 16px auto;">
25523
+ Automate periodic tasks like database health checks, daily metrics sync, scheduled flows, or automated backups.
25524
+ </p>
25525
+ <button class="btn btn-primary btn-sm" onclick="openCreateScheduleDrawer()">
25526
+ + Create First Schedule
25527
+ </button>
25528
+ </div>
25529
+ `;
25530
+ }
25531
+
25532
+ return `
25533
+ <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(360px, 1fr)); gap: 14px;">
25534
+ ${list.map(s => renderScheduleCardHtml(s)).join('')}
25535
+ </div>
25536
+ `;
25537
+ }
25538
+
25539
+ function handleResetScheduleFilters() {
25540
+ cronState.searchQuery = '';
25541
+ cronState.targetFilter = 'all';
25542
+ cronState.statusFilter = 'all';
25543
+ cronState.sortBy = 'nextRun';
25544
+ const searchInput = document.getElementById('cron-search-input');
25545
+ if (searchInput) searchInput.value = '';
25546
+ const targetFilterEl = document.getElementById('cron-target-filter');
25547
+ if (targetFilterEl) targetFilterEl.value = 'all';
25548
+ const statusFilterEl = document.getElementById('cron-status-filter');
25549
+ if (statusFilterEl) statusFilterEl.value = 'all';
25550
+ const sortFilterEl = document.getElementById('cron-sort-filter');
25551
+ if (sortFilterEl) sortFilterEl.value = 'nextRun';
25552
+ refreshSchedulesListDom();
25553
+ }
25554
+
25555
+ function renderScheduleCardHtml(s) {
25556
+ const isEnabled = Boolean(s.enabled);
25557
+ const isUnsupportedSnapshot = s.targetType === 'snapshot' && !isSqliteDatabase();
25558
+ const dbProviderName = (typeof databaseState !== 'undefined' && databaseState.status?.provider ? databaseState.status.provider : 'remote').toUpperCase();
25559
+ const targetBadgeColor = s.targetType === 'function' ? 'var(--accent-primary)' : (s.targetType === 'flow' ? '#8b5cf6' : '#10b981');
25560
+ const lastStatusColor = s.lastStatus === 'succeeded' ? 'var(--accent-success)' : (s.lastStatus === 'failed' ? 'var(--accent-danger)' : (s.lastStatus === 'skipped' ? 'var(--accent-warning)' : 'var(--text-muted)'));
25561
+
25562
+ // Target status checks (disabled or missing targets)
25563
+ let isTargetDisabled = false;
25564
+ let isTargetMissing = false;
25565
+ if (s.targetType === 'function' && (cronState.functionsList || []).length > 0) {
25566
+ const fn = cronState.functionsList.find(f => f.id === s.targetId || f.name === s.targetId);
25567
+ if (!fn) isTargetMissing = true;
25568
+ else if (fn.enabled === false) isTargetDisabled = true;
25569
+ } else if (s.targetType === 'flow' && (cronState.flowsList || []).length > 0) {
25570
+ const fl = cronState.flowsList.find(f => f.id === s.targetId || f.name === s.targetId);
25571
+ if (!fl) isTargetMissing = true;
25572
+ else if (fl.enabled === false) isTargetDisabled = true;
25573
+ }
25574
+
25575
+ const nextRunStr = s.nextRunAt ? formatDualTime(s.nextRunAt, s.timezone) : 'Disabled / Never';
25576
+ const lastRunStr = s.lastRunAt ? formatRelativeTime(s.lastRunAt) : 'Never executed';
25577
+
25578
+ return `
25579
+ <div style="background: var(--bg-card); border: 1px solid ${isUnsupportedSnapshot ? 'rgba(245,158,11,0.4)' : (isTargetMissing ? 'rgba(239,68,68,0.3)' : 'var(--border-subtle)')}; border-radius: 8px; padding: 16px; display: flex; flex-direction: column; justify-content: space-between; position: relative; transition: border-color 0.15s ease;">
25580
+ <div>
25581
+ <div style="display: flex; align-items: flex-start; justify-content: space-between; gap: 8px; margin-bottom: 6px;">
25582
+ <div>
25583
+ <div style="display: flex; align-items: center; gap: 6px; flex-wrap: wrap;">
25584
+ <span style="font-size: 14px; font-weight: 600; color: var(--text-heading);">${escapeHtml(s.name)}</span>
25585
+ ${s.isSystemBound ? `<span class="badge" style="font-size: 10px; background: rgba(59,130,246,0.12); color: var(--accent-primary);">1:1 Bound</span>` : ''}
25586
+ ${isUnsupportedSnapshot ? `<span class="badge" style="font-size: 10px; background: rgba(245,158,11,0.15); color: var(--accent-warning);">${cronIcons.alert(10, 10)} Unsupported on ${dbProviderName}</span>` : ''}
25587
+ ${isTargetDisabled ? `<span class="badge" style="font-size: 10px; background: rgba(245,158,11,0.15); color: var(--accent-warning);" title="Target is currently disabled">${cronIcons.alert(10, 10)} Target Disabled</span>` : ''}
25588
+ ${isTargetMissing ? `<span class="badge" style="font-size: 10px; background: rgba(239,68,68,0.15); color: var(--accent-danger);" title="Target ID not found in system">${cronIcons.alert(10, 10)} Target Missing</span>` : ''}
25589
+ </div>
25590
+ ${s.description ? `<p style="font-size: 12px; color: var(--text-muted); margin: 3px 0 0 0;">${escapeHtml(s.description)}</p>` : ''}
25591
+ </div>
25592
+ <label class="switch" style="transform: scale(0.8); transform-origin: right center;">
25593
+ <input type="checkbox" ${isEnabled ? 'checked' : ''} ${isUnsupportedSnapshot ? 'disabled title="Snapshots cannot be enabled on ' + dbProviderName + '"' : 'onchange="handleToggleScheduleEnabled(\'' + s.id + '\', this.checked)" title="Enable / Disable Schedule"'}>
25594
+ <span class="slider round"></span>
25595
+ </label>
25596
+ </div>
25597
+
25598
+ <!-- Human-Readable Cadence Display -->
25599
+ <div style="font-size: 12px; font-weight: 500; color: var(--text-heading); margin: 6px 0 8px 0; display: flex; align-items: center; gap: 6px;">
25600
+ ${cronIcons.calendar(13, 13)}
25601
+ <span>${escapeHtml(s.humanDescription || s.cronExpression)}</span>
25602
+ </div>
25603
+
25604
+ <div style="display: flex; align-items: center; gap: 8px; margin: 8px 0 10px 0; font-size: 11px; flex-wrap: wrap;">
25605
+ <span style="display: inline-flex; align-items: center; gap: 4px; padding: 2px 7px; border-radius: 4px; background: var(--bg-card-hover); border: 1px solid var(--border-subtle); cursor: pointer; transition: background 0.15s ease;"
25606
+ onclick="navigateToCronTarget('${escapeHtml(s.targetType)}', '${escapeHtml(s.targetId)}')"
25607
+ title="Click to view ${escapeHtml(s.targetType)}">
25608
+ <span style="width: 6px; height: 6px; border-radius: 50%; background: ${targetBadgeColor};"></span>
25609
+ <strong>${escapeHtml(s.targetType.toUpperCase())}:</strong> ${escapeHtml(getTargetDisplayName(s.targetType, s.targetId))} ${cronIcons.externalLink(10, 10)}
25610
+ </span>
25611
+ <span style="display: inline-flex; align-items: center; gap: 4px; padding: 2px 7px; border-radius: 4px; background: var(--bg-card-hover); border: 1px solid var(--border-subtle); font-family: monospace;" title="Cron expression: ${escapeHtml(s.cronExpression)}">
25612
+ ${cronIcons.clock(11, 11)} ${escapeHtml(s.cronExpression)}
25613
+ </span>
25614
+ <span style="display: inline-flex; align-items: center; gap: 4px; color: var(--text-muted);">
25615
+ ${cronIcons.globe(11, 11)} ${escapeHtml(s.timezone || 'UTC')}
25616
+ </span>
25617
+ </div>
25618
+
25619
+ ${(s.maxRetries > 0 || s.autoPauseAfterFailures > 0 || s.consecutiveFailures > 0 || s.expiresAt || (s.targetType === 'snapshot' && s.keepLast)) ? `
25620
+ <div style="display: flex; align-items: center; gap: 6px; margin: 0 0 10px 0; font-size: 10px; flex-wrap: wrap;">
25621
+ ${s.maxRetries > 0 ? `<span class="badge" style="background: rgba(99,102,241,0.12); color: #6366f1; display: inline-flex; align-items: center; gap: 3px;" title="Retries up to ${s.maxRetries} times with exponential backoff on failure">${cronIcons.refresh(10, 10)} ${s.maxRetries}x Retries</span>` : ''}
25622
+ ${s.autoPauseAfterFailures > 0 ? `<span class="badge" style="background: rgba(234,88,12,0.12); color: #ea580c; display: inline-flex; align-items: center; gap: 3px;" title="Circuit breaker: auto-pauses after ${s.autoPauseAfterFailures} consecutive failures">${cronIcons.zap(10, 10)} Auto-pause (${s.autoPauseAfterFailures}x)</span>` : ''}
25623
+ ${s.consecutiveFailures > 0 ? `<span class="badge" style="background: rgba(239,68,68,0.15); color: var(--accent-danger); display: inline-flex; align-items: center; gap: 3px;" title="${s.consecutiveFailures} consecutive failure(s)">${cronIcons.alert(10, 10)} ${s.consecutiveFailures} Failure${s.consecutiveFailures > 1 ? 's' : ''}</span>` : ''}
25624
+ ${s.expiresAt ? (() => {
25625
+ const isPast = new Date(s.expiresAt).getTime() <= Date.now();
25626
+ return `<span class="badge" style="background: ${isPast ? 'rgba(239,68,68,0.15)' : 'rgba(107,114,128,0.15)'}; color: ${isPast ? 'var(--accent-danger)' : 'var(--text-muted)'}; display: inline-flex; align-items: center; gap: 3px;" title="Auto-expires at ${escapeHtml(s.expiresAt)}">${cronIcons.hourglass(10, 10)} ${isPast ? `Expired (${formatRelativeTime(s.expiresAt)})` : `Expires: ${formatRelativeTime(s.expiresAt)}`}</span>`;
25627
+ })() : ''}
25628
+ ${s.targetType === 'snapshot' && s.keepLast ? `<span class="badge" style="background: rgba(16,185,129,0.12); color: #10b981; display: inline-flex; align-items: center; gap: 3px;" title="Retains last ${s.keepLast} snapshots created by this schedule">${cronIcons.database(10, 10)} Retain ${s.keepLast}</span>` : ''}
25629
+ </div>
25630
+ ` : ''}
25631
+
25632
+ ${isUnsupportedSnapshot ? `
25633
+ <div style="background: rgba(245,158,11,0.08); border: 1px solid rgba(245,158,11,0.25); border-radius: 6px; padding: 7px 10px; font-size: 11px; color: var(--accent-warning); margin-bottom: 10px; display: flex; align-items: center; gap: 6px;">
25634
+ ${cronIcons.alert(14, 14)}
25635
+ <span>In-app snapshots are exclusive to embedded SQLite applications and are paused on <strong>${dbProviderName}</strong>.</span>
25636
+ </div>
25637
+ ` : ''}
25638
+
25639
+ <div style="background: var(--bg-page); border-radius: 6px; padding: 8px 10px; font-size: 11px; margin-bottom: 12px; border: 1px solid var(--border-subtle);">
25640
+ <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
25641
+ <span style="color: var(--text-muted);">Next Run:</span>
25642
+ <span style="font-weight: 500; color: ${isEnabled && !isUnsupportedSnapshot ? 'var(--text-heading)' : 'var(--text-muted)'};">${isUnsupportedSnapshot ? 'Paused (Requires SQLite)' : nextRunStr}</span>
25643
+ </div>
25644
+ <div style="display: flex; justify-content: space-between;">
25645
+ <span style="color: var(--text-muted);">Last Run:</span>
25646
+ <span style="color: ${lastStatusColor}; font-weight: 500;">
25647
+ ${s.lastStatus ? `● ${escapeHtml(s.lastStatus)} (${lastRunStr})` : lastRunStr}
25648
+ </span>
25649
+ </div>
25650
+ ${s.lastError ? `
25651
+ <div style="color: var(--accent-danger); margin-top: 4px; font-size: 10px; word-break: break-all; display: flex; align-items: flex-start; gap: 4px;">
25652
+ ${cronIcons.alert(11, 11)} <span>${escapeHtml(s.lastError)}</span>
25653
+ </div>
25654
+ ` : ''}
25655
+ </div>
25656
+ </div>
25657
+
25658
+ <div style="display: flex; align-items: center; justify-content: space-between; gap: 6px; border-top: 1px solid var(--border-subtle); padding-top: 10px;">
25659
+ <span style="font-size: 11px; color: var(--text-muted);">
25660
+ Policy: <code style="font-size: 10px;">${escapeHtml(s.missedRunPolicy || 'skip')}</code>
25661
+ </span>
25662
+ <div style="display: flex; gap: 6px;">
25663
+ <button class="btn btn-secondary btn-sm" onclick="viewScheduleHistory('${s.id}')" title="View execution history logs for this schedule" style="font-size: 11px; padding: 2px 8px;">
25664
+ History
25665
+ </button>
25666
+ <button class="btn btn-secondary btn-sm" ${isUnsupportedSnapshot ? 'disabled' : ''} onclick="handleTriggerSchedule('${s.id}')" title="${isUnsupportedSnapshot ? 'Snapshots are unsupported on ' + dbProviderName : 'Trigger immediately on-demand'}" style="font-size: 11px; padding: 2px 8px; display: inline-flex; align-items: center; gap: 4px;">
25667
+ ${cronIcons.play(9, 9)} Run Now
25668
+ </button>
25669
+ </button>
25670
+ <button class="btn btn-secondary btn-sm" onclick="openEditScheduleDrawer('${s.id}')" title="Edit Schedule Configuration" style="font-size: 11px; padding: 2px 8px;">
25671
+ Edit
25672
+ </button>
25673
+ <button class="btn btn-danger btn-sm" onclick="handleDeleteSchedule('${s.id}')" title="Delete Schedule" style="font-size: 11px; padding: 2px 8px;">
25674
+ Delete
25675
+ </button>
25676
+ </div>
25677
+ </div>
25678
+ </div>
25679
+ `;
25680
+ }
25681
+
25682
+ async function handleToggleScheduleEnabled(id, enabled) {
25683
+ try {
25684
+ const apiPrefix = getCronApiPrefix();
25685
+ await api(`${apiPrefix}/schedules/${encodeURIComponent(id)}`, {
25686
+ method: 'PATCH',
25687
+ body: { enabled },
25688
+ });
25689
+ toast(enabled ? 'Schedule enabled' : 'Schedule disabled', 'success');
25690
+ await loadCronData();
25691
+ } catch (err) {
25692
+ toast(err.message || 'Failed to toggle schedule state', 'error');
25693
+ await loadCronData();
25694
+ }
25695
+ }
25696
+
25697
+ async function handleTriggerSchedule(id) {
25698
+ try {
25699
+ toast('Triggering scheduled run...', 'info');
25700
+ const apiPrefix = getCronApiPrefix();
25701
+ const runLog = await api(`${apiPrefix}/schedules/${encodeURIComponent(id)}/trigger`, {
25702
+ method: 'POST',
25703
+ });
25704
+ if (runLog && runLog.status === 'succeeded') {
25705
+ toast(`Schedule executed successfully in ${runLog.durationMs}ms`, 'success');
25706
+ } else {
25707
+ toast(`Schedule run ended with status '${runLog?.status || 'failed'}': ${runLog?.error || 'Unknown error'}`, 'error');
25708
+ }
25709
+ await loadCronData();
25710
+ } catch (err) {
25711
+ toast(err.message || 'Trigger failed', 'error');
25712
+ }
25713
+ }
25714
+
25715
+ async function handleDeleteSchedule(id) {
25716
+ const schedule = cronState.schedules.find(s => s.id === id);
25717
+ const name = schedule ? schedule.name : id;
25718
+ if (!confirm(`Are you sure you want to delete schedule "${name}"? This will cancel future runs and delete execution history for this schedule.`)) {
25719
+ return;
25720
+ }
25721
+
25722
+ try {
25723
+ const apiPrefix = getCronApiPrefix();
25724
+ await api(`${apiPrefix}/schedules/${encodeURIComponent(id)}`, {
25725
+ method: 'DELETE',
25726
+ });
25727
+ toast(`Schedule "${name}" deleted`, 'success');
25728
+ await loadCronData();
25729
+ } catch (err) {
25730
+ toast(err.message || 'Delete failed', 'error');
25731
+ }
25732
+ }
25733
+
25734
+ // ==========================================
25735
+ // Execution History Tab
25736
+ // ==========================================
25737
+
25738
+ async function loadRunHistory() {
25739
+ try {
25740
+ const apiPrefix = getCronApiPrefix();
25741
+ const filter = cronState.runFilter;
25742
+ const params = new URLSearchParams();
25743
+ if (filter.scheduleId) params.set('scheduleId', filter.scheduleId);
25744
+ if (filter.targetType) params.set('targetType', filter.targetType);
25745
+ if (filter.status && filter.status !== 'all') params.set('status', filter.status);
25746
+ params.set('page', String(filter.page));
25747
+ params.set('perPage', String(filter.perPage));
25748
+
25749
+ const data = await api(`${apiPrefix}/runs?${params.toString()}`);
25750
+ if (data) {
25751
+ cronState.runs = data.items || [];
25752
+ cronState.runFilter.total = data.total || 0;
25753
+ cronState.runFilter.totalPages = Math.ceil((data.total || 0) / filter.perPage) || 1;
25754
+ const contentArea = document.getElementById('cron-tab-content');
25755
+ if (contentArea && cronState.subTab === 'history') {
25756
+ contentArea.innerHTML = renderHistoryTableHtml();
25757
+ }
25758
+ }
25759
+ } catch (err) {
25760
+ console.warn('[Cron] Failed to load runs history:', err);
25761
+ }
25762
+ }
25763
+
25764
+ function renderHistoryTableHtml() {
25765
+ const runs = cronState.runs || [];
25766
+ const filter = cronState.runFilter;
25767
+
25768
+ return `
25769
+ <div style="background: var(--bg-card); border: 1px solid var(--border-subtle); border-radius: 8px; padding: 14px;">
25770
+ <!-- History Filters Bar -->
25771
+ <div style="display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 12px; flex-wrap: wrap;">
25772
+ <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
25773
+ <select class="input input-sm" onchange="handleHistoryStatusFilter(this.value)" style="font-size: 11px;">
25774
+ <option value="all" ${filter.status === 'all' ? 'selected' : ''}>All Statuses</option>
25775
+ <option value="succeeded" ${filter.status === 'succeeded' ? 'selected' : ''}>Succeeded</option>
25776
+ <option value="failed" ${filter.status === 'failed' ? 'selected' : ''}>Failed</option>
25777
+ <option value="skipped" ${filter.status === 'skipped' ? 'selected' : ''}>Skipped</option>
25778
+ <option value="running" ${filter.status === 'running' ? 'selected' : ''}>Running</option>
25779
+ </select>
25780
+ <select class="input input-sm" onchange="handleHistoryScheduleFilter(this.value)" style="font-size: 11px;">
25781
+ <option value="">All Schedules</option>
25782
+ ${cronState.schedules.map(s => `<option value="${s.id}" ${filter.scheduleId === s.id ? 'selected' : ''}>${escapeHtml(s.name)}</option>`).join('')}
25783
+ </select>
25784
+ </div>
25785
+ <div style="font-size: 11px; color: var(--text-muted);">
25786
+ Total: ${filter.total} runs
25787
+ </div>
25788
+ </div>
25789
+
25790
+ <!-- History Table -->
25791
+ ${runs.length === 0 ? `
25792
+ <div style="padding: 32px 16px; text-align: center; color: var(--text-muted); font-size: 13px;">
25793
+ No execution runs recorded yet.
25794
+ </div>
25795
+ ` : `
25796
+ <div style="overflow-x: auto;">
25797
+ <table class="table" style="width: 100%; font-size: 12px;">
25798
+ <thead>
25799
+ <tr>
25800
+ <th style="text-align: left;">Timestamp</th>
25801
+ <th style="text-align: left;">Schedule</th>
25802
+ <th style="text-align: left;">Target</th>
25803
+ <th style="text-align: left;">Status</th>
25804
+ <th style="text-align: right;">Duration</th>
25805
+ <th style="text-align: left;">Details</th>
25806
+ <th style="text-align: right;">Action</th>
25807
+ </tr>
25808
+ </thead>
25809
+ <tbody>
25810
+ ${runs.map(r => renderRunRowHtml(r)).join('')}
25811
+ </tbody>
25812
+ </table>
25813
+ </div>
25814
+
25815
+ <!-- Pagination -->
25816
+ <div style="display: flex; align-items: center; justify-content: space-between; margin-top: 12px; font-size: 11px; color: var(--text-muted);">
25817
+ <span>Page ${filter.page} of ${filter.totalPages}</span>
25818
+ <div style="display: flex; gap: 4px;">
25819
+ <button class="btn btn-secondary btn-sm" ${filter.page <= 1 ? 'disabled' : ''} onclick="handleHistoryPageChange(${filter.page - 1})">Prev</button>
25820
+ <button class="btn btn-secondary btn-sm" ${filter.page >= filter.totalPages ? 'disabled' : ''} onclick="handleHistoryPageChange(${filter.page + 1})">Next</button>
25821
+ </div>
25822
+ </div>
25823
+ `}
25824
+ </div>
25825
+ `;
25826
+ }
25827
+
25828
+ function renderRunRowHtml(r) {
25829
+ const statusBadge = r.status === 'succeeded'
25830
+ ? '<span class="badge" style="background: rgba(16,185,129,0.15); color: var(--accent-success);">Succeeded</span>'
25831
+ : (r.status === 'failed'
25832
+ ? '<span class="badge" style="background: rgba(239,68,68,0.15); color: var(--accent-danger);">Failed</span>'
25833
+ : (r.status === 'skipped'
25834
+ ? '<span class="badge" style="background: rgba(245,158,11,0.15); color: var(--accent-warning);">Skipped</span>'
25835
+ : '<span class="badge" style="background: rgba(59,130,246,0.15); color: var(--accent-primary);">Running</span>'));
25836
+
25837
+ return `
25838
+ <tr style="border-bottom: 1px solid var(--border-subtle); cursor: pointer;" onclick="openRunDetailDrawer('${r.id}')" title="Click to view run details">
25839
+ <td style="white-space: nowrap; font-family: monospace;">${formatDateTime(r.startedAt)}</td>
25840
+ <td>
25841
+ <strong>${escapeHtml(r.scheduleName)}</strong>
25842
+ ${r.isCatchUp ? '<span class="badge" style="font-size: 9px; margin-left: 4px; background: rgba(139,92,246,0.15); color: #8b5cf6;">Catch-Up</span>' : ''}
25843
+ ${r.attempt && r.attempt > 1 ? `<span class="badge" style="font-size: 9px; margin-left: 4px; background: rgba(99,102,241,0.15); color: #6366f1;" title="Execution completed on attempt #${r.attempt}">Retry #${r.attempt}</span>` : ''}
25844
+ </td>
25845
+ <td>
25846
+ <span style="font-size: 11px; padding: 1px 5px; border-radius: 3px; background: var(--bg-card-hover);" title="${r.targetId ? `Target ID: ${escapeHtml(r.targetId)}` : ''}">
25847
+ ${escapeHtml(r.targetType)}: <strong>${escapeHtml(getTargetDisplayName(r.targetType, r.targetId))}</strong>
25848
+ </span>
25849
+ </td>
25850
+ <td>${statusBadge}</td>
25851
+ <td style="text-align: right; font-family: monospace;">${r.durationMs || 0}ms</td>
25852
+ <td style="max-width: 240px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
25853
+ ${r.error ? `<span style="color: var(--accent-danger);" title="${escapeHtml(r.error)}">${cronIcons.alert(11, 11)} ${escapeHtml(r.error)}</span>` : (r.output ? `<code style="font-size: 10px;" title="${escapeHtml(r.output)}">${escapeHtml(r.output)}</code>` : '<span style="color: var(--text-muted);">-</span>')}
25854
+ </td>
25855
+ <td style="text-align: right; white-space: nowrap;">
25856
+ <button class="btn btn-secondary btn-sm" onclick="event.stopPropagation(); openRunDetailDrawer('${r.id}')" style="font-size: 10px; padding: 1px 7px;" title="Inspect output and error details">
25857
+ Inspect
25858
+ </button>
25859
+ </td>
25860
+ </tr>
25861
+ `;
25862
+ }
25863
+
25864
+ function handleHistoryStatusFilter(status) {
25865
+ cronState.runFilter.status = status;
25866
+ cronState.runFilter.page = 1;
25867
+ loadRunHistory();
25868
+ }
25869
+
25870
+ function handleHistoryScheduleFilter(scheduleId) {
25871
+ cronState.runFilter.scheduleId = scheduleId;
25872
+ cronState.runFilter.page = 1;
25873
+ const btn = document.getElementById('btn-clear-cron-history');
25874
+ if (btn) {
25875
+ btn.textContent = scheduleId ? 'Clear Schedule History' : 'Clear All History';
25876
+ }
25877
+ loadRunHistory();
25878
+ }
25879
+
25880
+ function handleHistoryPageChange(newPage) {
25881
+ cronState.runFilter.page = Math.max(1, newPage);
25882
+ loadRunHistory();
25883
+ }
25884
+
25885
+ async function handleClearRunHistory() {
25886
+ const scheduleId = cronState.runFilter.scheduleId;
25887
+ const targetSched = scheduleId ? (cronState.schedules || []).find(s => s.id === scheduleId) : null;
25888
+ const schedName = targetSched ? targetSched.name : scheduleId;
25889
+
25890
+ const confirmMsg = targetSched
25891
+ ? `Are you sure you want to clear execution history for schedule "${schedName}"?`
25892
+ : (scheduleId
25893
+ ? 'Are you sure you want to clear execution history for the selected schedule?'
25894
+ : 'Are you sure you want to clear all execution run history logs across ALL schedules?');
25895
+
25896
+ if (!confirm(confirmMsg)) {
25897
+ return;
25898
+ }
25899
+ try {
25900
+ const apiPrefix = getCronApiPrefix();
25901
+ const url = scheduleId
25902
+ ? `${apiPrefix}/runs?scheduleId=${encodeURIComponent(scheduleId)}`
25903
+ : `${apiPrefix}/runs`;
25904
+ await api(url, {
25905
+ method: 'DELETE',
25906
+ });
25907
+ toast(targetSched ? `Run history for "${schedName}" cleared` : 'Run history cleared', 'success');
25908
+ await loadCronData();
25909
+ } catch (err) {
25910
+ toast(err.message || 'Failed to clear run history', 'error');
25911
+ }
25912
+ }
25913
+
25914
+ // ==========================================
25915
+ // Slide-Over Drawer: Execution Run Detail Inspector
25916
+ // ==========================================
25917
+
25918
+ function openRunDetailDrawer(runId) {
25919
+ const run = (cronState.runs || []).find(r => r.id === runId);
25920
+ if (!run) return;
25921
+ cronState.activeRunForDetail = run;
25922
+ renderRunDetailDrawer();
25923
+ }
25924
+
25925
+ function renderRunDetailDrawer() {
25926
+ const r = cronState.activeRunForDetail;
25927
+ if (!r) return;
25928
+
25929
+ let root = document.getElementById('drawer-root');
25930
+ if (!root) {
25931
+ root = document.createElement('div');
25932
+ root.id = 'drawer-root';
25933
+ document.body.appendChild(root);
25934
+ }
25935
+
25936
+ let formattedOutput = '';
25937
+ if (r.output) {
25938
+ try {
25939
+ formattedOutput = JSON.stringify(JSON.parse(r.output), null, 2);
25940
+ } catch {
25941
+ formattedOutput = r.output;
25942
+ }
25943
+ }
25944
+
25945
+ // Calculate jitter/latency between scheduledAt and startedAt
25946
+ let latencyStr = '';
25947
+ if (r.scheduledAt && r.startedAt) {
25948
+ const diff = new Date(r.startedAt).getTime() - new Date(r.scheduledAt).getTime();
25949
+ if (r.isCatchUp) {
25950
+ latencyStr = `Catch-up execution (${Math.round(diff / 1000)}s delayed)`;
25951
+ } else if (Math.abs(diff) < 1000) {
25952
+ latencyStr = `${diff}ms jitter (on-time)`;
25953
+ } else {
25954
+ latencyStr = `${Math.round(diff / 1000)}s dispatch delay`;
25955
+ }
25956
+ }
25957
+
25958
+ const statusBadge = r.status === 'succeeded'
25959
+ ? '<span class="badge" style="background: rgba(16,185,129,0.15); color: var(--accent-success); font-size: 11px;">Succeeded</span>'
25960
+ : (r.status === 'failed'
25961
+ ? '<span class="badge" style="background: rgba(239,68,68,0.15); color: var(--accent-danger); font-size: 11px;">Failed</span>'
25962
+ : (r.status === 'skipped'
25963
+ ? '<span class="badge" style="background: rgba(245,158,11,0.15); color: var(--accent-warning); font-size: 11px;">Skipped</span>'
25964
+ : '<span class="badge" style="background: rgba(59,130,246,0.15); color: var(--accent-primary); font-size: 11px;">Running</span>'));
25965
+
25966
+ root.innerHTML = `
25967
+ <div id="run-detail-backdrop" class="drawer-backdrop" onclick="closeRunDetailDrawer()" aria-hidden="true"></div>
25968
+ <aside id="run-detail-panel" class="schedule-drawer" role="dialog" aria-modal="true" aria-labelledby="run-detail-title" tabindex="-1">
25969
+ <div class="drawer-header">
25970
+ <div class="drawer-title-area">
25971
+ <div style="width: 34px; height: 34px; border-radius: 8px; background: rgba(59,130,246,0.12); color: var(--accent-primary); display: flex; align-items: center; justify-content: center; font-size: 17px; flex-shrink: 0;">
25972
+ ${cronIcons.chart(18, 18)}
25973
+ </div>
25974
+ <div>
25975
+ <div style="display: flex; align-items: center; gap: 8px;">
25976
+ <h3 id="run-detail-title" class="drawer-title" style="margin: 0; font-size: 15px;">Run Details</h3>
25977
+ ${statusBadge}
25978
+ </div>
25979
+ <span style="font-size: 11px; color: var(--text-muted);">${escapeHtml(r.scheduleName)} &bull; ${formatDateTime(r.startedAt)}</span>
25980
+ </div>
25981
+ </div>
25982
+ <button type="button" class="btn btn-secondary btn-sm" onclick="closeRunDetailDrawer()" style="border: none; font-size: 18px; line-height: 1; cursor: pointer;" title="Close (Esc)">✕</button>
25983
+ </div>
25984
+
25985
+ <div class="drawer-body" style="flex: 1; overflow-y: auto; padding: 1.25rem 1.5rem; display: flex; flex-direction: column; gap: 1rem;">
25986
+ <!-- Metadata Summary Card -->
25987
+ <div class="drawer-card">
25988
+ <span class="drawer-section-title">Execution Summary</span>
25989
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; font-size: 12px;">
25990
+ <div>
25991
+ <span style="color: var(--text-muted); display: block; font-size: 11px;">Schedule</span>
25992
+ <strong style="color: var(--text-heading);">${escapeHtml(r.scheduleName)}</strong>
25993
+ </div>
25994
+ <div>
25995
+ <span style="color: var(--text-muted); display: block; font-size: 11px;">Target</span>
25996
+ <strong>${escapeHtml(r.targetType.toUpperCase())}:</strong> ${escapeHtml(getTargetDisplayName(r.targetType, r.targetId))}
25997
+ </div>
25998
+ <div>
25999
+ <span style="color: var(--text-muted); display: block; font-size: 11px;">Started At</span>
26000
+ <span style="font-family: monospace;">${formatDateTime(r.startedAt)}</span>
26001
+ </div>
26002
+ <div>
26003
+ <span style="color: var(--text-muted); display: block; font-size: 11px;">Duration</span>
26004
+ <span style="font-family: monospace; font-weight: 600;">${r.durationMs || 0}ms</span>
26005
+ </div>
26006
+ <div>
26007
+ <span style="color: var(--text-muted); display: block; font-size: 11px;">Attempt Count</span>
26008
+ <span style="font-family: monospace; font-weight: 600;">${r.attempt || 1}</span>
26009
+ </div>
26010
+ <div>
26011
+ <span style="color: var(--text-muted); display: block; font-size: 11px;">Scheduled At</span>
26012
+ <span style="font-family: monospace;">${formatDateTime(r.scheduledAt)}</span>
26013
+ </div>
26014
+ <div>
26015
+ <span style="color: var(--text-muted); display: block; font-size: 11px;">Dispatch Accuracy</span>
26016
+ <span style="color: ${r.isCatchUp ? 'var(--accent-warning)' : 'var(--accent-success)'}; font-size: 11px; font-weight: 500;">${escapeHtml(latencyStr || 'On-time')}</span>
26017
+ </div>
26018
+ ${r.executionRefId ? `
26019
+ <div style="grid-column: span 2;">
26020
+ <span style="color: var(--text-muted); display: block; font-size: 11px;">Execution Reference ID</span>
26021
+ <code style="font-size: 11px; word-break: break-all;">${escapeHtml(r.executionRefId)}</code>
26022
+ </div>
26023
+ ` : ''}
26024
+ </div>
26025
+ </div>
26026
+
26027
+ <!-- Error Card (if failed or error) -->
26028
+ ${r.error ? `
26029
+ <div class="drawer-card" style="border-left: 3px solid var(--accent-danger);">
26030
+ <span class="drawer-section-title" style="color: var(--accent-danger); margin-bottom: 6px;">Error Details</span>
26031
+ <div style="background: rgba(239,68,68,0.06); border: 1px solid rgba(239,68,68,0.2); border-radius: 6px; padding: 10px; font-family: monospace; font-size: 11px; color: var(--accent-danger); white-space: pre-wrap; word-break: break-word;">
26032
+ ${escapeHtml(r.error)}
26033
+ </div>
26034
+ </div>
26035
+ ` : ''}
26036
+
26037
+ <!-- Output Card (if output) -->
26038
+ ${formattedOutput ? `
26039
+ <div class="drawer-card" style="flex: 1; display: flex; flex-direction: column;">
26040
+ <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px;">
26041
+ <span class="drawer-section-title" style="margin-bottom: 0;">Output Data</span>
26042
+ <button class="btn btn-secondary btn-sm" onclick="copyRunOutputToClipboard()" style="font-size: 10px; padding: 2px 7px; display: inline-flex; align-items: center; gap: 4px;">
26043
+ ${cronIcons.copy(11, 11)} Copy Output
26044
+ </button>
26045
+ </div>
26046
+ <pre id="run-output-pre" style="background: var(--bg-page); border: 1px solid var(--border-subtle); border-radius: 6px; padding: 10px; font-size: 11px; font-family: monospace; overflow: auto; max-height: 280px; margin: 0; white-space: pre-wrap; word-break: break-word;">${escapeHtml(formattedOutput)}</pre>
26047
+ </div>
26048
+ ` : `
26049
+ <div class="drawer-card">
26050
+ <span class="drawer-section-title">Output Data</span>
26051
+ <span style="color: var(--text-muted); font-size: 12px;">No output payload recorded for this execution.</span>
26052
+ </div>
26053
+ `}
26054
+ </div>
26055
+
26056
+ <div class="drawer-footer" style="padding: 1rem 1.5rem; border-top: 1px solid var(--border-subtle); display: flex; justify-content: space-between; align-items: center; background: var(--bg-card); flex-shrink: 0;">
26057
+ <code style="font-size: 10px; color: var(--text-muted);">Run ID: ${escapeHtml(r.id)}</code>
26058
+ <button type="button" class="btn btn-secondary btn-sm" onclick="closeRunDetailDrawer()">Close</button>
26059
+ </div>
26060
+ </aside>
26061
+ `;
26062
+
26063
+ // Trigger animation
26064
+ const triggerDrawerOpen = () => {
26065
+ const backdrop = document.getElementById('run-detail-backdrop');
26066
+ const panel = document.getElementById('run-detail-panel');
26067
+ if (backdrop) backdrop.classList.add('open');
26068
+ if (panel) panel.classList.add('open');
26069
+ };
26070
+ if (typeof requestAnimationFrame === 'function') {
26071
+ requestAnimationFrame(triggerDrawerOpen);
26072
+ } else {
26073
+ triggerDrawerOpen();
26074
+ }
26075
+
26076
+ window.removeEventListener('keydown', handleRunDetailDrawerKeyDown);
26077
+ window.addEventListener('keydown', handleRunDetailDrawerKeyDown);
26078
+ }
26079
+
26080
+ function closeRunDetailDrawer() {
26081
+ const backdrop = document.getElementById('run-detail-backdrop');
26082
+ const panel = document.getElementById('run-detail-panel');
26083
+ if (backdrop) backdrop.classList.remove('open');
26084
+ if (panel) panel.classList.remove('open');
26085
+
26086
+ window.removeEventListener('keydown', handleRunDetailDrawerKeyDown);
26087
+ cronState.activeRunForDetail = null;
26088
+
26089
+ setTimeout(() => {
26090
+ const root = document.getElementById('drawer-root');
26091
+ if (root && root.querySelector('#run-detail-panel')) {
26092
+ root.innerHTML = '';
26093
+ }
26094
+ }, 280);
26095
+ }
26096
+
26097
+ function handleRunDetailDrawerKeyDown(e) {
26098
+ if (e.key === 'Escape' && document.getElementById('run-detail-backdrop')) {
26099
+ closeRunDetailDrawer();
26100
+ }
26101
+ }
26102
+
26103
+ function copyRunOutputToClipboard() {
26104
+ const pre = document.getElementById('run-output-pre');
26105
+ if (!pre) return;
26106
+ if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
26107
+ navigator.clipboard.writeText(pre.textContent || '').then(() => {
26108
+ toast('Output copied to clipboard', 'success');
26109
+ }).catch(() => {
26110
+ toast('Failed to copy', 'error');
26111
+ });
26112
+ }
26113
+ }
26114
+
26115
+ // ==========================================
26116
+ // Slide-Over Drawer: Create / Edit Schedule & Live Preview
26117
+ // ==========================================
26118
+
26119
+ function openCreateScheduleDrawer(targetType = 'function', targetId = '') {
26120
+ if (!isSqliteDatabase() && targetType === 'snapshot') {
26121
+ targetType = 'function';
26122
+ targetId = '';
26123
+ }
26124
+ cronState.activeScheduleForEdit = null;
26125
+ cronState.createTargetType = targetType;
26126
+ cronState.createTargetId = targetId;
26127
+ renderScheduleDrawer();
26128
+ }
26129
+
26130
+ function openEditScheduleDrawer(id) {
26131
+ const schedule = cronState.schedules.find(s => s.id === id);
26132
+ if (!schedule) return;
26133
+ cronState.activeScheduleForEdit = schedule;
26134
+ cronState.createTargetType = null;
26135
+ cronState.createTargetId = null;
26136
+ renderScheduleDrawer();
26137
+ }
26138
+
26139
+ function closeScheduleDrawer() {
26140
+ const backdrop = document.getElementById('schedule-drawer-backdrop');
26141
+ const panel = document.getElementById('schedule-drawer-panel');
26142
+ if (backdrop) backdrop.classList.remove('open');
26143
+ if (panel) panel.classList.remove('open');
26144
+
26145
+ window.removeEventListener('keydown', handleScheduleDrawerKeyDown);
26146
+ cronState.activeScheduleForEdit = null;
26147
+ cronState.createTargetType = null;
26148
+ cronState.createTargetId = null;
26149
+
26150
+ setTimeout(() => {
26151
+ const root = document.getElementById('drawer-root');
26152
+ if (root && root.querySelector('#schedule-drawer-panel')) {
26153
+ root.innerHTML = '';
26154
+ }
26155
+ const modalRoot = document.getElementById('modal-root');
26156
+ if (modalRoot && modalRoot.querySelector('#schedule-drawer-panel')) {
26157
+ modalRoot.innerHTML = '';
26158
+ }
26159
+ }, 280);
26160
+ }
26161
+
26162
+ function handleScheduleDrawerKeyDown(e) {
26163
+ if (e.key === 'Escape' && document.getElementById('schedule-drawer-backdrop')) {
26164
+ closeScheduleDrawer();
26165
+ }
26166
+ }
26167
+
26168
+ // Aliases for compatibility
26169
+ const openCreateScheduleModal = openCreateScheduleDrawer;
26170
+ const openEditScheduleModal = openEditScheduleDrawer;
26171
+ const closeScheduleModal = closeScheduleDrawer;
26172
+
26173
+ function renderScheduleDrawer() {
26174
+ let root = document.getElementById('drawer-root');
26175
+ if (!root) {
26176
+ root = document.createElement('div');
26177
+ root.id = 'drawer-root';
26178
+ document.body.appendChild(root);
26179
+ }
26180
+
26181
+ const isEdit = Boolean(cronState.activeScheduleForEdit);
26182
+ const isSqlite = isSqliteDatabase();
26183
+ const dbProviderName = (typeof databaseState !== 'undefined' && databaseState.status?.provider ? databaseState.status.provider : 'remote').toUpperCase();
26184
+ let defaultTargetType = cronState.createTargetType || 'function';
26185
+ if (!isSqlite && defaultTargetType === 'snapshot') {
26186
+ defaultTargetType = 'function';
26187
+ }
26188
+
26189
+ const s = cronState.activeScheduleForEdit || {
26190
+ name: '',
26191
+ targetType: defaultTargetType,
26192
+ targetId: cronState.createTargetId || '',
26193
+ cronExpression: '0 9 * * 1-5',
26194
+ timezone: 'UTC',
26195
+ missedRunPolicy: defaultTargetType === 'snapshot' ? 'catch_up_once' : 'skip',
26196
+ payload: null,
26197
+ enabled: true,
26198
+ };
26199
+ if (!isEdit && !isSqlite && s.targetType === 'snapshot') {
26200
+ s.targetType = 'function';
26201
+ }
26202
+
26203
+ const payloadStr = s.payload !== undefined && s.payload !== null
26204
+ ? (typeof s.payload === 'string' ? s.payload : JSON.stringify(s.payload, null, 2))
26205
+ : '';
26206
+
26207
+ root.innerHTML = `
26208
+ <div id="schedule-drawer-backdrop" class="drawer-backdrop" onclick="closeScheduleDrawer()" aria-hidden="true"></div>
26209
+ <aside id="schedule-drawer-panel" class="schedule-drawer" role="dialog" aria-modal="true" aria-labelledby="schedule-drawer-title" tabindex="-1">
26210
+ <!-- Drawer Header -->
26211
+ <div class="drawer-header">
26212
+ <div class="drawer-title-area">
26213
+ <div style="width: 34px; height: 34px; border-radius: 8px; background: rgba(59,130,246,0.12); color: var(--accent-primary); display: flex; align-items: center; justify-content: center; font-size: 17px; flex-shrink: 0;">
26214
+ ${cronIcons.clock(18, 18)}
26215
+ </div>
26216
+ <div>
26217
+ <h3 id="schedule-drawer-title" class="drawer-title" style="margin: 0; font-size: 15px;">${isEdit ? 'Edit Schedule' : 'Create New Schedule'}</h3>
26218
+ <span style="font-size: 11px; color: var(--text-muted);">${isEdit ? 'Modify scheduled trigger parameters and policies' : (isSqlite ? 'Configure an automated cron schedule for Functions, Flows, or Snapshots' : 'Configure an automated cron schedule for Functions or Flows')}</span>
26219
+ </div>
26220
+ </div>
26221
+ <button type="button" class="btn btn-secondary btn-sm" onclick="closeScheduleDrawer()" style="border: none; font-size: 18px; line-height: 1; cursor: pointer;" title="Close Drawer (Esc)">✕</button>
26222
+ </div>
26223
+
26224
+ <!-- Drawer Body (Form) -->
26225
+ <form id="cron-schedule-form" onsubmit="handleSaveSchedule(event)" style="display: flex; flex-direction: column; flex: 1; overflow: hidden; margin: 0;">
26226
+ <div class="drawer-body" style="flex: 1; overflow-y: auto; padding: 1.25rem 1.5rem; display: flex; flex-direction: column; gap: 1.25rem;">
26227
+ <!-- Schedule Name & Enabled -->
26228
+ <div class="drawer-card">
26229
+ <div style="display: flex; gap: 12px; align-items: flex-end;">
26230
+ <div style="flex: 1;">
26231
+ <label for="sched-input-name" style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Schedule Name *</label>
26232
+ <input type="text" id="sched-input-name" class="input" required value="${escapeHtml(s.name)}" placeholder="e.g. Daily Metrics Aggregation" style="width: 100%;">
26233
+ </div>
26234
+ <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 6px;">
26235
+ <label class="switch">
26236
+ <input type="checkbox" id="sched-input-enabled" ${s.enabled ? 'checked' : ''}>
26237
+ <span class="slider round"></span>
26238
+ </label>
26239
+ <span style="font-size: 12px; font-weight: 500;">Enabled</span>
26240
+ </div>
26241
+ </div>
26242
+ </div>
26243
+
26244
+ <!-- Target Selection -->
26245
+ <div class="drawer-card">
26246
+ <span class="drawer-section-title">Trigger Target</span>
26247
+ <div style="display: grid; grid-template-columns: 140px 1fr; gap: 10px;">
26248
+ <div>
26249
+ <label for="sched-input-target-type" style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Target Type</label>
26250
+ <select id="sched-input-target-type" class="input" onchange="handleModalTargetTypeChange(this.value)" style="width: 100%;">
26251
+ <option value="function" ${s.targetType === 'function' ? 'selected' : ''}>Function</option>
26252
+ <option value="flow" ${s.targetType === 'flow' ? 'selected' : ''}>Flow</option>
26253
+ ${isSqlite ? `<option value="snapshot" ${s.targetType === 'snapshot' ? 'selected' : ''}>Snapshot</option>` : (s.targetType === 'snapshot' ? `<option value="snapshot" selected>Snapshot (Unsupported on ${dbProviderName})</option>` : '')}
26254
+ </select>
26255
+ </div>
26256
+ <div>
26257
+ <label for="sched-input-target-id" style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Target Selection *</label>
26258
+ <div id="sched-target-picker-area">
26259
+ ${renderModalTargetPickerHtml(s.targetType, s.targetId)}
26260
+ </div>
26261
+ </div>
26262
+ </div>
26263
+ </div>
26264
+
26265
+ <!-- Schedule Cadence & Expression -->
26266
+ <div class="drawer-card">
26267
+ <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px;">
26268
+ <span class="drawer-section-title" style="margin-bottom: 0;">Cron Cadence</span>
26269
+ <select class="input input-sm" onchange="handleModalPresetChange(this.value)" style="font-size: 11px; padding: 2px 6px;">
26270
+ <option value="">Preset Templates...</option>
26271
+ <option value="* * * * *">Every minute (* * * * *)</option>
26272
+ <option value="*/15 * * * *">Every 15 minutes (*/15 * * * *)</option>
26273
+ <option value="@hourly">Hourly (@hourly)</option>
26274
+ <option value="@daily">Daily at midnight (@daily)</option>
26275
+ <option value="0 9 * * *">Daily at 9:00 AM (0 9 * * *)</option>
26276
+ <option value="0 9 * * 1-5">Weekdays at 9:00 AM (0 9 * * 1-5)</option>
26277
+ <option value="@weekly">Weekly on Sunday (@weekly)</option>
26278
+ <option value="@monthly">Monthly on 1st day (@monthly)</option>
26279
+ <option value="0 0 L * *">Monthly on last day (0 0 L * *)</option>
26280
+ <option value="@yearly">Yearly on Jan 1st (@yearly)</option>
26281
+ </select>
26282
+ </div>
26283
+
26284
+ <div style="display: flex; gap: 8px;">
26285
+ <input type="text" id="sched-input-expr" class="input" required value="${escapeHtml(s.cronExpression)}" placeholder="e.g. 0 9 * * 1-5" oninput="handleCronExpressionInput()" style="flex: 1; font-family: monospace; font-size: 13px;" autocomplete="off">
26286
+ <input type="text" id="sched-input-tz" class="input" required value="${escapeHtml(s.timezone || 'UTC')}" list="iana-timezones-list" placeholder="Timezone" oninput="handleCronExpressionInput()" style="width: 170px; font-size: 12px;">
26287
+ </div>
26288
+ <span style="font-size: 11px; color: var(--text-muted); margin-top: 3px; display: block;">
26289
+ Standard 5-field cron or macro (<code>@hourly</code>, <code>@daily</code>, <code>0 0 L * *</code>).
26290
+ </span>
26291
+
26292
+ <!-- Live Next Runs Preview Card -->
26293
+ <div id="sched-preview-card" style="background: var(--bg-page); border: 1px solid var(--border-subtle); border-radius: 6px; padding: 10px 12px; margin-top: 8px;">
26294
+ <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px;">
26295
+ <span style="font-size: 11px; font-weight: 600; color: var(--text-heading);">Upcoming Executions Preview</span>
26296
+ <span id="sched-preview-human" style="font-size: 11px; color: var(--accent-primary);">Loading...</span>
26297
+ </div>
26298
+ <ul id="sched-preview-list" style="margin: 0; padding-left: 18px; font-size: 11px; font-family: monospace; color: var(--text-muted);">
26299
+ <li>Calculating...</li>
26300
+ </ul>
26301
+ </div>
26302
+ </div>
26303
+
26304
+ <!-- Missed-Run Policy -->
26305
+ <div class="drawer-card">
26306
+ <span class="drawer-section-title">Missed-Run Policy (Misfire Grace >60s)</span>
26307
+ <div style="display: flex; flex-direction: column; gap: 8px; font-size: 12px;">
26308
+ <label style="display: flex; align-items: flex-start; gap: 8px; cursor: pointer;">
26309
+ <input type="radio" name="missedRunPolicy" value="skip" ${s.missedRunPolicy === 'skip' ? 'checked' : ''} style="margin-top: 2px;">
26310
+ <div>
26311
+ <strong>skip:</strong> Discard missed slots and jump next execution forward (default for Functions & Flows)
26312
+ </div>
26313
+ </label>
26314
+ <label style="display: flex; align-items: flex-start; gap: 8px; cursor: pointer;">
26315
+ <input type="radio" name="missedRunPolicy" value="catch_up_once" ${s.missedRunPolicy === 'catch_up_once' ? 'checked' : ''} style="margin-top: 2px;">
26316
+ <div>
26317
+ <strong>catch_up_once:</strong> Coalesce all missed slots into 1 immediate execution (default for Snapshots)
26318
+ </div>
26319
+ </label>
26320
+ <label style="display: flex; align-items: flex-start; gap: 8px; cursor: pointer;">
26321
+ <input type="radio" name="missedRunPolicy" value="catch_up_all" ${s.missedRunPolicy === 'catch_up_all' ? 'checked' : ''} style="margin-top: 2px;">
26322
+ <div>
26323
+ <strong>catch_up_all:</strong> Replay all missed slots sequentially (capped at safety limit of 10)
26324
+ </div>
26325
+ </label>
26326
+ </div>
26327
+ </div>
26328
+
26329
+ <!-- Reliability & Lifecycle Controls -->
26330
+ <div class="drawer-card">
26331
+ <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px;">
26332
+ <span class="drawer-section-title" style="margin-bottom: 0;">Reliability & Lifecycle Controls</span>
26333
+ <span style="font-size: 11px; color: var(--text-muted);">Retries, circuit breaker, expiration</span>
26334
+ </div>
26335
+
26336
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 10px;">
26337
+ <div>
26338
+ <label for="sched-input-retries" style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 3px;">Max Retries (Backoff)</label>
26339
+ <select id="sched-input-retries" class="input" style="width: 100%; font-size: 12px;">
26340
+ <option value="0" ${Number(s.maxRetries || 0) === 0 ? 'selected' : ''}>No retries (0)</option>
26341
+ <option value="1" ${Number(s.maxRetries) === 1 ? 'selected' : ''}>1 retry with backoff</option>
26342
+ <option value="2" ${Number(s.maxRetries) === 2 ? 'selected' : ''}>2 retries with backoff</option>
26343
+ <option value="3" ${Number(s.maxRetries) === 3 ? 'selected' : ''}>3 retries with backoff</option>
26344
+ <option value="5" ${Number(s.maxRetries) === 5 ? 'selected' : ''}>5 retries with backoff</option>
26345
+ </select>
26346
+ </div>
26347
+
26348
+ <div>
26349
+ <label for="sched-input-autopause" style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 3px;">Circuit Breaker (Auto-Pause)</label>
26350
+ <select id="sched-input-autopause" class="input" style="width: 100%; font-size: 12px;">
26351
+ <option value="0" ${Number(s.autoPauseAfterFailures || 0) === 0 ? 'selected' : ''}>Never auto-pause (Disabled)</option>
26352
+ <option value="3" ${Number(s.autoPauseAfterFailures) === 3 ? 'selected' : ''}>Pause after 3 failures</option>
26353
+ <option value="5" ${Number(s.autoPauseAfterFailures) === 5 ? 'selected' : ''}>Pause after 5 failures</option>
26354
+ <option value="10" ${Number(s.autoPauseAfterFailures) === 10 ? 'selected' : ''}>Pause after 10 failures</option>
26355
+ </select>
26356
+ </div>
26357
+ </div>
26358
+
26359
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
26360
+ <div>
26361
+ <label for="sched-input-expires" style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 3px;">Auto-Expire Date (Optional)</label>
26362
+ <input type="datetime-local" id="sched-input-expires" class="input" value="${s.expiresAt ? formatForDateTimeLocal(s.expiresAt) : ''}" style="width: 100%; font-size: 12px;">
26363
+ <span style="font-size: 10px; color: var(--text-muted); display: block; margin-top: 2px;">Schedule pauses after this timestamp</span>
26364
+ </div>
26365
+
26366
+ <div id="sched-retention-container" style="${s.targetType === 'snapshot' ? '' : 'display: none;'}">
26367
+ <label for="sched-input-keeplast" style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 3px;">Snapshot Retention (keepLast)</label>
26368
+ <input type="number" id="sched-input-keeplast" class="input" min="1" max="1000" placeholder="e.g. 7" value="${s.keepLast ? s.keepLast : ''}" style="width: 100%; font-size: 12px;">
26369
+ <span style="font-size: 10px; color: var(--text-muted); display: block; margin-top: 2px;">Retain last N snapshots created by this schedule</span>
26370
+ </div>
26371
+ </div>
26372
+ </div>
26373
+
26374
+ <!-- Input Payload (JSON) -->
26375
+ <div id="sched-payload-container" class="drawer-card" style="${s.targetType === 'snapshot' ? 'display: none;' : ''}">
26376
+ <label for="sched-input-payload" style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Payload / Context Data (JSON)</label>
26377
+ <textarea id="sched-input-payload" class="input" rows="3" placeholder='{"dryRun": false}' style="width: 100%; font-family: monospace; font-size: 12px;">${escapeHtml(payloadStr)}</textarea>
26378
+ <span style="font-size: 11px; color: var(--text-muted); margin-top: 3px; display: block;">
26379
+ Passed to function as <code>context.request.body</code> or flow as initial input payload.
26380
+ </span>
26381
+ </div>
26382
+ </div>
26383
+
26384
+ <!-- Drawer Footer -->
26385
+ <div class="drawer-footer" style="padding: 1rem 1.5rem; border-top: 1px solid var(--border-subtle); display: flex; justify-content: flex-end; align-items: center; gap: 8px; background: var(--bg-card); flex-shrink: 0;">
26386
+ <button type="button" class="btn btn-secondary btn-sm" onclick="closeScheduleDrawer()">Cancel</button>
26387
+ <button type="submit" class="btn btn-primary btn-sm" id="btn-save-schedule">${isEdit ? 'Save Changes' : 'Create Schedule'}</button>
26388
+ </div>
26389
+ </form>
26390
+ </aside>
26391
+ `;
26392
+
26393
+ // Trigger smooth slide-in animation
26394
+ const triggerDrawerOpen = () => {
26395
+ const backdrop = document.getElementById('schedule-drawer-backdrop');
26396
+ const panel = document.getElementById('schedule-drawer-panel');
26397
+ if (backdrop) backdrop.classList.add('open');
26398
+ if (panel) {
26399
+ panel.classList.add('open');
26400
+ const firstInput = panel.querySelector('input:not([type="hidden"]), select, textarea');
26401
+ if (firstInput && typeof firstInput.focus === 'function') {
26402
+ try { firstInput.focus(); } catch (_) {}
26403
+ }
26404
+ }
26405
+ };
26406
+ if (typeof requestAnimationFrame === 'function') {
26407
+ requestAnimationFrame(triggerDrawerOpen);
26408
+ } else {
26409
+ triggerDrawerOpen();
26410
+ }
26411
+
26412
+ window.removeEventListener('keydown', handleScheduleDrawerKeyDown);
26413
+ window.addEventListener('keydown', handleScheduleDrawerKeyDown);
26414
+
26415
+ // Fetch initial preview
26416
+ handleCronExpressionInput();
26417
+ }
26418
+
26419
+ const renderScheduleModal = renderScheduleDrawer;
26420
+
26421
+ function renderModalTargetPickerHtml(targetType, selectedId) {
26422
+ if (targetType === 'function') {
26423
+ const list = cronState.functionsList || [];
26424
+ if (list.length === 0) {
26425
+ return `<input type="text" id="sched-input-target-id" class="input" required value="${escapeHtml(selectedId || '')}" placeholder="Function ID or name" style="width: 100%;">`;
26426
+ }
26427
+ const nameCounts = {};
26428
+ for (const f of list) {
26429
+ nameCounts[f.name] = (nameCounts[f.name] || 0) + 1;
26430
+ }
26431
+ return `
26432
+ <select id="sched-input-target-id" class="input" required style="width: 100%;">
26433
+ <option value="">Select Function Target...</option>
26434
+ ${list.map(fn => {
26435
+ const isDup = (nameCounts[fn.name] || 0) > 1;
26436
+ const label = fn.name + (isDup ? ` (${fn.id.slice(0, 8)})` : '') + (fn.enabled === false ? ' [Disabled]' : '');
26437
+ return `<option value="${escapeHtml(fn.id)}" ${selectedId === fn.id || selectedId === fn.name ? 'selected' : ''}>${escapeHtml(label)}</option>`;
26438
+ }).join('')}
26439
+ </select>
26440
+ `;
26441
+ }
26442
+
26443
+ if (targetType === 'flow') {
26444
+ const list = cronState.flowsList || [];
26445
+ if (list.length === 0) {
26446
+ return `<input type="text" id="sched-input-target-id" class="input" required value="${escapeHtml(selectedId || '')}" placeholder="Flow ID or name" style="width: 100%;">`;
26447
+ }
26448
+ const nameCounts = {};
26449
+ for (const fl of list) {
26450
+ nameCounts[fl.name] = (nameCounts[fl.name] || 0) + 1;
26451
+ }
26452
+ return `
26453
+ <select id="sched-input-target-id" class="input" required style="width: 100%;">
26454
+ <option value="">Select Flow Target...</option>
26455
+ ${list.map(fl => {
26456
+ const isDup = (nameCounts[fl.name] || 0) > 1;
26457
+ const label = fl.name + (isDup ? ` (${fl.id.slice(0, 8)})` : '') + (fl.enabled === false ? ' [Disabled]' : '');
26458
+ return `<option value="${escapeHtml(fl.id)}" ${selectedId === fl.id || selectedId === fl.name ? 'selected' : ''}>${escapeHtml(label)}</option>`;
26459
+ }).join('')}
26460
+ </select>
26461
+ `;
26462
+ }
26463
+
26464
+ if (targetType === 'snapshot') {
26465
+ if (!isSqliteDatabase()) {
26466
+ return `
26467
+ <input type="hidden" id="sched-input-target-id" value="${escapeHtml(selectedId || 'data.db')}">
26468
+ <div class="alert alert-warning" style="font-size: 11px; padding: 8px 10px; margin: 0; border-radius: 4px; background: rgba(245,158,11,0.12); color: var(--accent-warning); border: 1px solid rgba(245,158,11,0.25);">
26469
+ Automated snapshots are exclusive to embedded SQLite databases and are paused.
26470
+ </div>
26471
+ `;
26472
+ }
26473
+ return `
26474
+ <input type="text" id="sched-input-target-id" class="input" value="${escapeHtml(selectedId || 'data.db')}" readonly style="width: 100%; background: var(--bg-card-hover);" title="Automated snapshot targets local SQLite database">
26475
+ <span style="font-size: 10px; color: var(--text-muted); margin-top: 2px; display: block;">
26476
+ Creates rolling baseline snapshots with oldest-unprotected eviction.
26477
+ </span>
26478
+ `;
26479
+ }
26480
+
26481
+ return `<input type="text" id="sched-input-target-id" class="input" required value="${escapeHtml(selectedId || '')}" style="width: 100%;">`;
26482
+ }
26483
+
26484
+ function handleModalTargetTypeChange(type) {
26485
+ if (!isSqliteDatabase() && type === 'snapshot') {
26486
+ type = 'function';
26487
+ const typeEl = document.getElementById('sched-input-target-type');
26488
+ if (typeEl) typeEl.value = 'function';
26489
+ }
26490
+ const pickerArea = document.getElementById('sched-target-picker-area');
26491
+ const payloadContainer = document.getElementById('sched-payload-container');
26492
+ const retentionContainer = document.getElementById('sched-retention-container');
26493
+ if (pickerArea) {
26494
+ pickerArea.innerHTML = renderModalTargetPickerHtml(type, '');
26495
+ }
26496
+ if (payloadContainer) {
26497
+ payloadContainer.style.display = type === 'snapshot' ? 'none' : 'block';
26498
+ }
26499
+ if (retentionContainer) {
26500
+ retentionContainer.style.display = type === 'snapshot' ? 'block' : 'none';
26501
+ }
26502
+
26503
+ // When creating a new schedule, update the selected default policy for the target type
26504
+ if (!cronState.activeScheduleForEdit) {
26505
+ const defaultPolicy = type === 'snapshot' ? 'catch_up_once' : 'skip';
26506
+ const radio = document.querySelector(`input[name="missedRunPolicy"][value="${defaultPolicy}"]`);
26507
+ if (radio) {
26508
+ radio.checked = true;
26509
+ }
26510
+ }
26511
+ }
26512
+
26513
+ function handleModalPresetChange(preset) {
26514
+ if (!preset) return;
26515
+ const exprInput = document.getElementById('sched-input-expr');
26516
+ if (exprInput) {
26517
+ exprInput.value = preset;
26518
+ handleCronExpressionInput();
26519
+ }
26520
+ }
26521
+
26522
+ let cronPreviewDebounceTimer = null;
26523
+ function handleCronExpressionInput() {
26524
+ if (cronPreviewDebounceTimer) {
26525
+ clearTimeout(cronPreviewDebounceTimer);
26526
+ }
26527
+ cronPreviewDebounceTimer = setTimeout(async () => {
26528
+ const exprInput = document.getElementById('sched-input-expr');
26529
+ const tzInput = document.getElementById('sched-input-tz');
26530
+ const humanEl = document.getElementById('sched-preview-human');
26531
+ const listEl = document.getElementById('sched-preview-list');
26532
+
26533
+ if (!exprInput || !humanEl || !listEl) return;
26534
+
26535
+ const cronExpression = exprInput.value.trim();
26536
+ const timezone = tzInput ? tzInput.value.trim() : 'UTC';
26537
+
26538
+ if (!cronExpression) {
26539
+ humanEl.textContent = 'Enter expression';
26540
+ listEl.innerHTML = '<li>Awaiting 5-field expression...</li>';
26541
+ return;
26542
+ }
26543
+
26544
+ try {
26545
+ const apiPrefix = getCronApiPrefix();
26546
+ const data = await api(`${apiPrefix}/preview`, {
26547
+ method: 'POST',
26548
+ body: { cronExpression, timezone, count: 5 },
26549
+ });
26550
+ if (data && data.valid) {
26551
+ humanEl.textContent = data.description || 'Valid Expression';
26552
+ humanEl.style.color = 'var(--accent-primary)';
26553
+ listEl.innerHTML = (data.nextRuns || []).map(r => `
26554
+ <li>${escapeHtml(r.zonedFormatted)} <span style="color: var(--text-muted); font-size: 10px;">(${escapeHtml(r.isoUtc)})</span></li>
26555
+ `).join('');
26556
+ } else {
26557
+ humanEl.textContent = data?.error || 'Invalid Expression';
26558
+ humanEl.style.color = 'var(--accent-danger)';
26559
+ listEl.innerHTML = `<li style="color: var(--accent-danger);">${escapeHtml(data?.error || 'Syntax error')}</li>`;
26560
+ }
26561
+ } catch {
26562
+ humanEl.textContent = 'Preview unavailable';
26563
+ }
26564
+ }, 250);
26565
+ }
26566
+
26567
+ async function handleSaveSchedule(e) {
26568
+ e.preventDefault();
26569
+ const nameEl = document.getElementById('sched-input-name');
26570
+ const enabledEl = document.getElementById('sched-input-enabled');
26571
+ const targetTypeEl = document.getElementById('sched-input-target-type');
26572
+ const targetIdEl = document.getElementById('sched-input-target-id');
26573
+ const exprEl = document.getElementById('sched-input-expr');
26574
+ const tzEl = document.getElementById('sched-input-tz');
26575
+ const payloadEl = document.getElementById('sched-input-payload');
26576
+ const policyEl = document.querySelector('input[name="missedRunPolicy"]:checked');
26577
+
26578
+ if (!nameEl || !targetTypeEl || !targetIdEl || !exprEl) return;
26579
+
26580
+ const retriesEl = document.getElementById('sched-input-retries');
26581
+ const autoPauseEl = document.getElementById('sched-input-autopause');
26582
+ const expiresEl = document.getElementById('sched-input-expires');
26583
+ const keepLastEl = document.getElementById('sched-input-keeplast');
26584
+
26585
+ const maxRetries = retriesEl ? parseInt(retriesEl.value, 10) : 0;
26586
+ const autoPauseAfterFailures = autoPauseEl ? parseInt(autoPauseEl.value, 10) : 0;
26587
+ const expiresAt = expiresEl && expiresEl.value ? new Date(expiresEl.value).toISOString() : null;
26588
+ const keepLast = (targetTypeEl.value === 'snapshot' && keepLastEl && keepLastEl.value) ? parseInt(keepLastEl.value, 10) : null;
26589
+
26590
+ let parsedPayload = undefined;
26591
+ if (payloadEl && payloadEl.value.trim()) {
26592
+ try {
26593
+ parsedPayload = JSON.parse(payloadEl.value.trim());
26594
+ } catch (err) {
26595
+ toast('Invalid JSON payload: ' + err.message, 'error');
26596
+ return;
26597
+ }
26598
+ }
26599
+
26600
+ if (targetTypeEl.value === 'snapshot' && !isSqliteDatabase() && enabledEl && enabledEl.checked) {
26601
+ toast('Snapshots cannot be enabled on non-SQLite databases and will remain paused.', 'warning');
26602
+ enabledEl.checked = false;
26603
+ }
26604
+
26605
+ const dto = {
26606
+ name: nameEl.value.trim(),
26607
+ targetType: targetTypeEl.value,
26608
+ targetId: targetIdEl.value.trim(),
26609
+ cronExpression: exprEl.value.trim(),
26610
+ timezone: tzEl ? tzEl.value.trim() : 'UTC',
26611
+ missedRunPolicy: policyEl ? policyEl.value : 'skip',
26612
+ payload: parsedPayload,
26613
+ enabled: (!isSqliteDatabase() && targetTypeEl.value === 'snapshot') ? false : (enabledEl ? enabledEl.checked : true),
26614
+ maxRetries,
26615
+ autoPauseAfterFailures,
26616
+ expiresAt,
26617
+ keepLast,
26618
+ };
26619
+
26620
+ try {
26621
+ const isEdit = Boolean(cronState.activeScheduleForEdit);
26622
+ const apiPrefix = getCronApiPrefix();
26623
+ const url = isEdit
26624
+ ? `${apiPrefix}/schedules/${encodeURIComponent(cronState.activeScheduleForEdit.id)}`
26625
+ : `${apiPrefix}/schedules`;
26626
+ const method = isEdit ? 'PATCH' : 'POST';
26627
+
26628
+ await api(url, {
26629
+ method,
26630
+ body: dto,
26631
+ });
26632
+
26633
+ closeScheduleModal();
26634
+ toast(isEdit ? 'Schedule updated' : 'Schedule created', 'success');
26635
+ await loadCronData();
26636
+ } catch (err) {
26637
+ toast('Error: ' + err.message, 'error');
26638
+ }
26639
+ }
26640
+
26641
+ // ==========================================
26642
+ // Helpers
26643
+ // ==========================================
26644
+
26645
+ function formatDualTime(isoString, timezone) {
26646
+ try {
26647
+ const d = new Date(isoString);
26648
+ if (isNaN(d.getTime())) return isoString;
26649
+ return d.toLocaleString('en-US', {
26650
+ timeZone: timezone || 'UTC',
26651
+ month: 'short',
26652
+ day: 'numeric',
26653
+ hour: '2-digit',
26654
+ minute: '2-digit',
26655
+ hour12: false,
26656
+ });
26657
+ } catch {
26658
+ return isoString;
26659
+ }
26660
+ }
26661
+
26662
+ function formatDateTime(isoString) {
26663
+ try {
26664
+ const d = new Date(isoString);
26665
+ if (isNaN(d.getTime())) return isoString;
26666
+ return d.toLocaleString('en-US', {
26667
+ month: 'short',
26668
+ day: 'numeric',
26669
+ hour: '2-digit',
26670
+ minute: '2-digit',
26671
+ second: '2-digit',
26672
+ hour12: false,
26673
+ });
26674
+ } catch {
26675
+ return isoString;
26676
+ }
26677
+ }
26678
+
26679
+ function formatRelativeTime(isoString) {
26680
+ try {
26681
+ const targetMs = new Date(isoString).getTime();
26682
+ if (isNaN(targetMs)) return isoString;
26683
+ const now = Date.now();
26684
+ const isFuture = targetMs > now;
26685
+ const diffSec = Math.floor(Math.abs(now - targetMs) / 1000);
26686
+
26687
+ if (diffSec < 60) {
26688
+ if (diffSec < 5 && !isFuture) return 'just now';
26689
+ return isFuture ? `in ${diffSec}s` : `${diffSec}s ago`;
26690
+ }
26691
+ const min = Math.floor(diffSec / 60);
26692
+ if (min < 60) {
26693
+ return isFuture ? `in ${min}m` : `${min}m ago`;
26694
+ }
26695
+ const hr = Math.floor(min / 60);
26696
+ if (hr < 24) {
26697
+ return isFuture ? `in ${hr}h` : `${hr}h ago`;
26698
+ }
26699
+ const days = Math.floor(hr / 24);
26700
+ if (days < 30) {
26701
+ return isFuture ? `in ${days}d` : `${days}d ago`;
26702
+ }
26703
+ const months = Math.floor(days / 30);
26704
+ if (months < 12) {
26705
+ return isFuture ? `in ${months}mo` : `${months}mo ago`;
26706
+ }
26707
+ const years = Math.floor(days / 365);
26708
+ return isFuture ? `in ${years}y` : `${years}y ago`;
26709
+ } catch {
26710
+ return isoString;
26711
+ }
26712
+ }
26713
+
26714
+ function formatForDateTimeLocal(isoString) {
26715
+ if (!isoString) return '';
26716
+ try {
26717
+ const d = new Date(isoString);
26718
+ if (isNaN(d.getTime())) return '';
26719
+ const pad = n => String(n).padStart(2, '0');
26720
+ const YYYY = d.getFullYear();
26721
+ const MM = pad(d.getMonth() + 1);
26722
+ const DD = pad(d.getDate());
26723
+ const hh = pad(d.getHours());
26724
+ const mm = pad(d.getMinutes());
26725
+ return `${YYYY}-${MM}-${DD}T${hh}:${mm}`;
26726
+ } catch {
26727
+ return '';
26728
+ }
26729
+ }
26730
+
26731
+ function showToast(msg, type = 'info') {
26732
+ if (typeof toast === 'function') {
26733
+ toast(msg, type);
26734
+ }
26735
+ }
26736
+
26737
+ if (typeof window !== 'undefined') {
26738
+ window.cronState = cronState;
26739
+ window.renderSchedulesView = renderSchedulesView;
26740
+ window.refreshSchedulesView = refreshSchedulesView;
26741
+ window.switchCronTab = switchCronTab;
26742
+ window.handleCronTargetFilter = handleCronTargetFilter;
26743
+ window.handleCronSearchInput = handleCronSearchInput;
26744
+ window.handleCronStatusFilter = handleCronStatusFilter;
26745
+ window.handleCronSortChange = handleCronSortChange;
26746
+ window.handleResetScheduleFilters = handleResetScheduleFilters;
26747
+ window.viewScheduleHistory = viewScheduleHistory;
26748
+ window.navigateToCronTarget = navigateToCronTarget;
26749
+ window.openRunDetailDrawer = openRunDetailDrawer;
26750
+ window.renderRunDetailDrawer = renderRunDetailDrawer;
26751
+ window.closeRunDetailDrawer = closeRunDetailDrawer;
26752
+ window.copyRunOutputToClipboard = copyRunOutputToClipboard;
26753
+ window.openCreateScheduleDrawer = openCreateScheduleDrawer;
26754
+ window.openEditScheduleDrawer = openEditScheduleDrawer;
26755
+ window.closeScheduleDrawer = closeScheduleDrawer;
26756
+ window.renderScheduleDrawer = renderScheduleDrawer;
26757
+ window.openCreateScheduleModal = openCreateScheduleDrawer;
26758
+ window.openEditScheduleModal = openEditScheduleDrawer;
26759
+ window.closeScheduleModal = closeScheduleDrawer;
26760
+ window.renderScheduleModal = renderScheduleDrawer;
26761
+ window.handleModalTargetTypeChange = handleModalTargetTypeChange;
26762
+ window.handleModalPresetChange = handleModalPresetChange;
26763
+ window.handleToggleScheduleEnabled = handleToggleScheduleEnabled;
26764
+ window.handleTriggerSchedule = handleTriggerSchedule;
26765
+ window.handleDeleteSchedule = handleDeleteSchedule;
26766
+ window.handleClearRunHistory = handleClearRunHistory;
26767
+ window.handleCronExpressionInput = handleCronExpressionInput;
26768
+ window.handleSaveSchedule = handleSaveSchedule;
26769
+ window.formatForDateTimeLocal = formatForDateTimeLocal;
26770
+ window.loadCronData = loadCronData;
26771
+ window.loadCronStats = loadCronStats;
26772
+ window.showToast = showToast;
26773
+ }
26774
+
26775
+ if (typeof state !== 'undefined' && state.token && typeof loadCronStats === 'function') {
26776
+ loadCronStats();
26777
+ }
26778
+
26779
+
26780
+ // === api-keys.js ===
26781
+ // ==========================================
26782
+ // API Keys & Visual Scope Matrix Management
26783
+ // ==========================================
26784
+
26785
+ const apiKeysState = {
26786
+ keys: [],
26787
+ functions: [],
26788
+ flows: [],
26789
+ queues: [],
26790
+ isLoading: false,
26791
+ editingKeyId: null,
26792
+ lastFocusedElement: null,
26793
+ };
26794
+
26795
+ function setAppShellInert(isInert) {
26796
+ if (typeof document === 'undefined') return;
26797
+ const appRoot = document.getElementById('app');
26798
+ if (!appRoot) return;
26799
+ try {
26800
+ if (isInert) {
26801
+ appRoot.setAttribute('inert', '');
26802
+ } else {
26803
+ appRoot.removeAttribute('inert');
26804
+ }
26805
+ } catch (_) {}
26806
+ }
26807
+
26808
+ function updateSidebarApiKeysBadge(keysList) {
26809
+ if (typeof document === 'undefined') return;
26810
+ const badge = document.getElementById('sidebar-api-keys-count');
26811
+ if (!badge) return;
26812
+ const list = Array.isArray(keysList) ? keysList : apiKeysState.keys;
26813
+ const activeCount = list.filter(k => k.status === 'active').length;
26814
+ badge.textContent = String(activeCount);
26815
+ badge.style.display = activeCount > 0 ? 'inline-block' : 'none';
26816
+ }
26817
+
26818
+ function getApiKeysApiPrefix() {
26819
+ const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : (typeof state !== 'undefined' && state?.activeApp?.slug) || 'default';
26820
+ return slug && slug !== 'default' ? `/api/apps/${encodeURIComponent(slug)}/api-keys` : '/api/api-keys';
26821
+ }
26822
+
26823
+ async function loadApiKeys() {
24575
26824
  apiKeysState.isLoading = true;
24576
26825
  if (state.activeNav === 'api-keys') {
24577
26826
  renderApiKeysView();
@@ -26133,6 +28382,16 @@ function renderDatabaseView() {
26133
28382
  </div>
26134
28383
  </div>
26135
28384
 
28385
+ ${status.error ? `
28386
+ <div style="background: rgba(239, 68, 68, 0.08); border: 1px solid rgba(239, 68, 68, 0.3); border-radius: 8px; padding: 12px 16px; margin: 0.5rem 0 1rem 0; font-size: 12.5px; color: #ef4444; display: flex; align-items: flex-start; gap: 10px; line-height: 1.5;">
28387
+ <span style="font-size: 16px; line-height: 1;">⚠️</span>
28388
+ <div>
28389
+ <strong style="color: #dc2626; display: block; margin-bottom: 2px;">Database Connection Alert (Fail-Closed)</strong>
28390
+ <span>${status.error}</span>
28391
+ </div>
28392
+ </div>
28393
+ ` : ''}
28394
+
26136
28395
  <!-- Engine Selector Cards -->
26137
28396
  <div style="display: flex; flex-direction: column; gap: 8px;">
26138
28397
  <div style="display: flex; align-items: center; justify-content: space-between;">
@@ -27091,6 +29350,9 @@ async function parseUrlAndNavigate(initial = false) {
27091
29350
  try {
27092
29351
  await loadCollections();
27093
29352
  } catch (_) {}
29353
+ if (typeof loadCronStats === 'function') {
29354
+ try { await loadCronStats(); } catch (_) {}
29355
+ }
27094
29356
  }
27095
29357
  } else if (!initial && state.activeApp && state.activeApp.slug !== 'default') {
27096
29358
  // Navigating back/forward (popstate) to a route without ?app= query parameter; restore default app
@@ -27105,6 +29367,9 @@ async function parseUrlAndNavigate(initial = false) {
27105
29367
  try {
27106
29368
  await loadCollections();
27107
29369
  } catch (_) {}
29370
+ if (typeof loadCronStats === 'function') {
29371
+ try { await loadCronStats(); } catch (_) {}
29372
+ }
27108
29373
  }
27109
29374
  }
27110
29375
 
@@ -27212,6 +29477,17 @@ async function parseUrlAndNavigate(initial = false) {
27212
29477
  } else {
27213
29478
  if (typeof switchQueuesTab === 'function') switchQueuesTab('queues', false);
27214
29479
  }
29480
+ } else if (root === 'schedules') {
29481
+ const isHistory = parts[1] === 'history' || parts[1] === 'runs';
29482
+ if (typeof cronState !== 'undefined') {
29483
+ cronState.subTab = isHistory ? 'history' : 'schedules';
29484
+ }
29485
+ await selectNav('schedules', false);
29486
+ if (isHistory) {
29487
+ if (typeof switchCronTab === 'function') switchCronTab('history', false);
29488
+ } else {
29489
+ if (typeof switchCronTab === 'function') switchCronTab('schedules', false);
29490
+ }
27215
29491
  } else if (root === 'webhooks') {
27216
29492
  if (typeof webhooksState !== 'undefined') {
27217
29493
  webhooksState.subTab = (parts[1] === 'deliveries') ? 'deliveries' : 'webhooks';
@@ -27273,6 +29549,7 @@ function initRouter() {
27273
29549
  if (typeof closeApiKeyDrawer === 'function') closeApiKeyDrawer();
27274
29550
  if (typeof closeApiKeySecretModal === 'function') closeApiKeySecretModal();
27275
29551
  if (typeof closeCommandPalette === 'function') closeCommandPalette();
29552
+ if (typeof closeScheduleDrawer === 'function') closeScheduleDrawer();
27276
29553
 
27277
29554
  await parseUrlAndNavigate(false);
27278
29555
  });
@@ -27280,7 +29557,7 @@ function initRouter() {
27280
29557
 
27281
29558
 
27282
29559
  function showPageView(viewName) {
27283
- const views = ['home', 'collections', 'plugins', 'webhooks', 'functions', 'flows', 'queues', 'api-keys', 'analytics', 'snapshots', 'database', 'logs'];
29560
+ const views = ['home', 'collections', 'plugins', 'webhooks', 'functions', 'flows', 'queues', 'schedules', 'api-keys', 'analytics', 'snapshots', 'database', 'logs'];
27284
29561
  for (const v of views) {
27285
29562
  const el = document.getElementById('page-view-' + v);
27286
29563
  if (el) {
@@ -27294,7 +29571,7 @@ function showPageView(viewName) {
27294
29571
  }
27295
29572
 
27296
29573
  function clearSidebarNavActive() {
27297
- const navIds = ['nav-home', 'nav-collections', 'nav-plugins', 'nav-webhooks', 'nav-functions', 'nav-flows', 'nav-queues', 'nav-api-keys', 'nav-analytics', 'nav-snapshots', 'nav-database', 'nav-logs'];
29574
+ const navIds = ['nav-home', 'nav-collections', 'nav-plugins', 'nav-webhooks', 'nav-functions', 'nav-flows', 'nav-queues', 'nav-schedules', 'nav-api-keys', 'nav-analytics', 'nav-snapshots', 'nav-database', 'nav-logs'];
27298
29575
  for (const id of navIds) {
27299
29576
  document.getElementById(id)?.classList.remove('active');
27300
29577
  }
@@ -27333,6 +29610,7 @@ async function selectNav(nav, pushState = true) {
27333
29610
  if (typeof closeApiKeyDrawer === 'function') closeApiKeyDrawer();
27334
29611
  if (typeof closeApiKeySecretModal === 'function') closeApiKeySecretModal();
27335
29612
  if (typeof closeCommandPalette === 'function') closeCommandPalette();
29613
+ if (typeof closeScheduleDrawer === 'function') closeScheduleDrawer();
27336
29614
  }
27337
29615
 
27338
29616
  if (nav === 'home') {
@@ -27451,6 +29729,20 @@ async function selectNav(nav, pushState = true) {
27451
29729
  document.getElementById('view-title').style.display = 'none';
27452
29730
  document.getElementById('view-actions').innerHTML = '';
27453
29731
  if (typeof renderQueuesView === 'function') renderQueuesView();
29732
+ } else if (nav === 'schedules') {
29733
+ state.activeCollection = null;
29734
+ if (pushState && typeof cronState !== 'undefined') {
29735
+ cronState.subTab = 'schedules';
29736
+ }
29737
+ if (typeof renderCollectionsList === 'function') renderCollectionsList();
29738
+ showPageView('schedules');
29739
+ document.getElementById('collection-tabs').style.display = 'none';
29740
+ document.getElementById('view-badge').style.display = 'none';
29741
+ document.getElementById('nav-schedules')?.classList.add('active');
29742
+ document.getElementById('view-title').textContent = 'Schedules Manager';
29743
+ document.getElementById('view-title').style.display = 'none';
29744
+ document.getElementById('view-actions').innerHTML = '';
29745
+ if (typeof renderSchedulesView === 'function') renderSchedulesView();
27454
29746
  } else if (nav === 'api-keys') {
27455
29747
  state.activeCollection = null;
27456
29748
  if (typeof renderCollectionsList === 'function') renderCollectionsList();
@@ -27485,11 +29777,7 @@ async function selectNav(nav, pushState = true) {
27485
29777
  document.getElementById('view-badge').style.display = 'none';
27486
29778
  document.getElementById('nav-snapshots')?.classList.add('active');
27487
29779
  document.getElementById('view-title').textContent = 'Snapshots';
27488
- document.getElementById('view-actions').innerHTML = `
27489
- <button class="btn btn-primary btn-sm" onclick="openCreateSnapshotModal()" style="font-weight:600;">
27490
- + Create Snapshot
27491
- </button>
27492
- `;
29780
+ document.getElementById('view-actions').innerHTML = '';
27493
29781
  if (typeof renderSnapshotsView === 'function') renderSnapshotsView();
27494
29782
  } else if (nav === 'database') {
27495
29783
  state.activeCollection = null;
@@ -27558,6 +29846,8 @@ async function selectNav(nav, pushState = true) {
27558
29846
  updateUrl('/_/flows');
27559
29847
  } else if (nav === 'queues') {
27560
29848
  updateUrl('/_/queues');
29849
+ } else if (nav === 'schedules') {
29850
+ updateUrl('/_/schedules');
27561
29851
  } else if (nav === 'api-keys') {
27562
29852
  updateUrl('/_/api-keys');
27563
29853
  } else if (nav === 'analytics') {