# Scheduled start point — Design

Date: 2026-10-01 · Status: approved in conversation, pending written review
Repos: tiledesk-server, design-studio, tiledesk-agent-runtime. tiledesk-chatbot (tybot) and chat21-ionic unchanged.
Branch: `feature/scheduled-start-point`, created from `feature/webhook-chatbot-hitl` in each repo (start points
are not on master yet). Builds on `2026-09-30-flow-start-points-design.md` (web + webhook start points).

## 1. Goal

A conversational chatbot (subtype `chatbot`) can start its flow on a schedule. A **Scheduled** start box, picked
from the Start points palette like Web and Webhook, opens a new conversation at the chosen times and runs the
flow from that box. The schedule runs on the scheduler already used for KB auto re-index (Apache
DolphinScheduler), and it is live only for the **published** version of the chatbot.

## 2. Decisions (user, 2026-10-01)

1. Scheduler: DolphinScheduler, the same mechanism as KB auto re-index (not the scheduled-jobs service, which is
   only on master-COLLAUDO).
2. Schedule expressiveness: presets plus time plus timezone — every N minutes/hours, daily at a time, weekly on
   chosen weekdays at a time, monthly on a day at a time, in an IANA timezone. No raw cron.
3. Overlap: every run starts a new conversation, even while the previous scheduled one is open.
4. Run data: a Source name and a static payload, stored as JSON but edited through a visual builder (rows of
   name / type / value), never a raw JSON editor.
5. Integration approach A: tiledesk-server talks to DolphinScheduler directly and synchronously; the workflow's
   HTTP task calls a token-protected server endpoint.
6. Lifecycle: a schedule becomes triggerable only when the chatbot is published. Every change to the Scheduled
   start point — timing, payload, Source name, the enabled switch, deleting the box — takes effect in production
   at the next publish. Deleting the chatbot removes its schedule immediately.
7. At most one Scheduled start point per chatbot (same rule as the other types).

## 3. Current state (verified 2026-10-01)

- KB auto re-index: tiledesk-training-jobworker (`tiledesk/ReindexScheduler.js`, `utils/shedulerUtils.js`) creates a
  DolphinScheduler process definition `auto-reindex-<content_id>` with one HTTP task
  `POST {API_ENDPOINT}/webhook/kb/reindex` (body `content_id`, header `x-auth-token` = `KB_WEBHOOK_TOKEN`, both as
  workflow global params), releases it, creates a schedule (Quartz cron from `daily|weekly|monthly` anchored on the
  start time, `startTime` now+20s, `endTime` 2099-12-31) and sets it online. tiledesk-server only deletes them
  (`services/aiReindexService.js`: schedule offline → definition offline → delete), from `/webhook/kb/reindex`.
  Env: `SCHEDULER_BASEURL`, `SCHEDULER_TOKEN`, `SCHEDULER_PROJECT` (all set on stage).
- Stage runs `apache/dolphinscheduler-standalone-server:3.2.2` (tiledesk-argo `helm/values.yaml`). In 3.2 a schedule
  carries `timezoneId`, and an online schedule must be taken offline to be updated.
- Publish (`PUT /:projectid/faq_kb/:id/publish`) forks a frozen copy (`root_id` = the chatbot, `trashed: true`),
  points the chatbot's `url` at it and emits `faqbot.publish`. The fork keeps every `intent_id`. Production
  conversations run the published copy; requests whose `sourcePage` contains `td_draft=true` run the draft.
- Start points: one webhook record per chatbot (`models/webhook.js`) with `start_points[]`; `startPointService`
  (upsert/remove/find, one per type), routes `PUT|DELETE /:projectid/webhooks/:chatbot_id/start_points/:type`,
  `startPointCleanupListener` on `faq.delete`, `webhookConversationService.start` (lead, department, request with
  `start_type`, `/start` with `attributes.action = '#<block_id>'`).
- Invite/Remove human accept a request whose `channel.name === 'webhook'`
  (`participantInviteService.js:45`, `participantRemoveService.js:27`).
- tybot already exposes `start_type` and the payload keys as flow variables and falls back to `start` when the
  action's box is missing.

## 4. Data model (tiledesk-server)

`start_points[]` gains the type `'scheduled'`:

```
{
  type: 'scheduled',
  block_id: <intent_id of the Scheduled box>,
  enabled: Boolean (default true),
  mapping: {
    source_name: String,                      // requester; empty → chatbot name (as webhook)
    payload: { <key>: String|Number|Boolean } // static run data
  },
  schedule: {
    frequency: 'interval' | 'daily' | 'weekly' | 'monthly',
    every: Number, unit: 'minutes' | 'hours', // interval
    time: 'HH:MM',                            // daily, weekly, monthly
    weekdays: ['mon'..'sun'],                 // weekly, at least one
    day_of_month: 1..28 | 'last',             // monthly
    timezone: String                          // IANA zone
  },
  live: {                                     // server-owned: what is active in DolphinScheduler
    enabled, block_id, mapping, schedule,     // snapshot taken at publish
    published_bot_id, published_at,
    workflow_code, schedule_id,
    error                                     // last sync error message, absent when fine
  }
}
```

Everything except `live` is the **draft**, edited through the API. `live` is written only by the publish sync and
the sync/retry endpoint, never accepted from a client.

Validation (400, message naming the field):
- `interval`: `unit: 'minutes'` with `every` ∈ {5, 10, 15, 20, 30}; `unit: 'hours'` with `every` ∈ 1..12.
- `daily|weekly|monthly`: `time` matches `^([01]\d|2[0-3]):[0-5]\d$`; weekly needs ≥ 1 weekday; monthly
  `day_of_month` ∈ 1..28 or `'last'`.
- `timezone`: a valid IANA zone (`Intl.DateTimeFormat(undefined, { timeZone })` does not throw).
- `payload`: a plain object, flat; keys match `^[A-Za-z_][A-Za-z0-9_]*$`; values string, finite number or boolean;
  at most 50 keys and 8 KB serialized.

## 5. API (tiledesk-server)

Existing routes, new type value:
- `PUT /:projectid/webhooks/:chatbot_id/start_points/scheduled` body `{ block_id, enabled?, mapping?, schedule }`
  (`schedule` required on create) — saves the draft only, no scheduler call. Same rules as webhook start points:
  one per type, `block_id` of this chatbot (404), subtype `chatbot` (400), automation webhook → 409 unless
  `confirm`. Response: the webhook, plus `schedule_summary` (draft) and `live_summary` (live, when present),
  e.g. "Every weekday at 08:30 (Europe/Rome)".
- `DELETE …/start_points/scheduled` — removes the draft entry; `live` and the DolphinScheduler objects stay until
  the next publish, which removes them (§7).
- `GET /:projectid/webhooks/:chatbot_id` — adds `scheduled_available: Boolean` and, for a live scheduled start point,
  `next_runs` (next 3 fire times from DolphinScheduler's schedule preview; omitted on error).

New routes:
- `POST /:projectid/webhooks/:chatbot_id/start_points/scheduled/test` (admin) — runs the **draft** once now: starts a
  conversation as in §8 but with the draft mapping and `sourcePage … dev=true&td_draft=true`, so the draft bot
  runs. Answers 202 `{ request_id }`. Works whether or not the chatbot is published.
- `POST /:projectid/webhooks/:chatbot_id/start_points/scheduled/sync` (admin) — re-runs the publish sync of §7
  against the latest published copy (the retry behind "Couldn't update the live schedule").
- `POST /webhook/scheduled-start` (public, called by DolphinScheduler) — §8.

Errors: `{ success: false, error }`. Scheduler not configured (`SCHEDULER_BASEURL`, `SCHEDULER_TOKEN`,
`SCHEDULER_PROJECT` or `SCHEDULED_START_TOKEN` missing): the `scheduled` routes answer 503
"Scheduled starts are not available on this installation" and `scheduled_available` is false.

## 6. Scheduler integration (tiledesk-server)

`services/dolphinSchedulerClient.js` — thin REST client (axios, header `token`), same endpoints as KB re-index:
create/release/delete process definition, create/update/online/offline schedule, find definition by name,
schedule preview. `AiReindexService` is not changed.

`services/scheduledStartService.js` — owns the DolphinScheduler objects of scheduled starts:
- Workflow per chatbot, name `auto-start-<chatbot_id>`: one HTTP task `POST {API_URL}/webhook/scheduled-start`,
  body params `id_project`, `chatbot_id`, header `x-auth-token: ${token}`, values as workflow global params
  (`SCHEDULED_START_TOKEN`), `connectTimeout`/`socketTimeout` 60000, no retries.
- Schedule: `crontab = toQuartzCron(schedule)`, `timezoneId = schedule.timezone`, `startTime` = now,
  `endTime` = 2099-12-31 23:59:59, `failureStrategy: CONTINUE`, `warningType: NONE`.
- `toQuartzCron(schedule)` (pure):
  - interval minutes N → `0 0/N * * * ? *`; hours N → `0 0 0/N * * ? *`
  - daily HH:MM → `0 MM HH * * ? *`
  - weekly → `0 MM HH ? * MON,WED,FRI *`
  - monthly day D → `0 MM HH D * ? *`; `last` → `0 MM HH L * ? *`
- Operations: `activate(live)` (create definition → release online → create schedule → schedule online; on a
  failing step, undo the steps done), `update(live)` (schedule offline → update → online), `deactivate(live)`
  (schedule offline), `destroy(live)` (schedule offline → definition offline → delete). A stored
  `workflow_code`/`schedule_id` that DolphinScheduler no longer knows is recreated instead of failing.

Running is cluster-safe: DolphinScheduler fires once per due time; whichever server pod receives the HTTP call
handles it. No in-process timer.

## 7. Publish lifecycle

A listener on `faqbot.publish` (registered in `app.js` next to the start point cleanup listener) syncs the live
schedule with the draft, using the published copy:

| Draft scheduled start point | Published copy has `block_id` | Result |
|---|---|---|
| present, enabled | yes | `activate` (no live yet) or `update` (live exists); `live` = snapshot of the draft + published ids |
| present, disabled | — | `deactivate`; `live.enabled = false` |
| present | no | `destroy`; `live` cleared |
| absent (box deleted) | — | `destroy`; `live` cleared |

- Publishing never fails because of the scheduler: a sync error is stored in `live.error`, logged, and shown by the
  panel with a Retry (`…/scheduled/sync`).
- Deleting the chatbot (the existing faq_kb delete path) calls `destroy` immediately and deletes the webhook as
  today.
- Restoring a release (`publish` with `restore_from`) goes through the same listener.

## 8. A scheduled run

`POST /webhook/scheduled-start`, body `{ id_project, chatbot_id }`, header `x-auth-token`:
1. Missing/wrong token → 401. Token not configured → 503.
2. Chatbot, webhook record, scheduled start point or `live` missing, or `live.enabled` false → 410 and the
   workflow is taken offline (a dangling workflow removes itself, as `/webhook/kb/reindex` does for deleted
   content). Rate limit as webhook calls (429).
3. Start the conversation through `webhookConversationService.start` with the scheduled start point:
   - lead `scheduled_<chatbot_id>`, fullname `live.mapping.source_name` || chatbot name;
   - department: same rule as webhook starts (`resolveChatbotDepartment`);
   - channel `webhook` (chat21-ionic shows it as a webhook conversation; Invite/Remove human accept it);
   - request attributes `{ start_type: 'scheduled', payload: live.mapping.payload, scheduled_at: <ISO time> }`;
   - system `/start` with `attributes.action = '#' + live.block_id`;
   - not a draft request, so the published copy runs.
4. 202 `{ success: true, request_id }`.

Every run is a new conversation (decision 3). A run missed while DolphinScheduler is down is not recovered.

tybot needs no change: `{{start_type}}` is `scheduled`, each payload key is a variable, `{{payload}}` the object,
and the missing-box fallback to `start` still applies.

The 422 messages of Invite/Remove human become "… requires a conversation started by a webhook or a schedule".

## 9. design-studio

- Palette Start points: item **Scheduled** (clock icon) next to Web and Webhook; one per type ("Already in this
  flow"); subtype `chatbot` only; hidden when `scheduled_available` is false.
- Dropping it creates the protected block (`attributes.start_point: 'scheduled'`, name "Scheduled start"), then
  `PUT …/start_points/scheduled` with defaults: daily 09:00, browser timezone, enabled, Source name = chatbot
  name, empty payload. Same failure handling as the webhook box (the block is removed on error).
- The box behaves like the other start boxes (toolbar "⋮" only, one outgoing connector, delete from its panel,
  no copy/paste) and shows the draft summary and a badge: **Live**, **Changes not live**, **Not live**.
- Panel:
  1. Status: "Live — every weekday at 08:30 (Europe/Rome) · next run Tue 08:30" / "Not live — publish to activate"
     / "Changes not live — publish to apply" / "Couldn't update the live schedule — Retry".
  2. Enabled switch, hint "Takes effect when you publish".
  3. Schedule: Repeat (Every N minutes/hours, Daily, Weekly, Monthly) with the matching fields (interval
     selector, time picker, weekday chips, day of month 1–28 or Last day), Timezone (searchable, browser default),
     live summary sentence.
  4. Source name (placeholder: chatbot name).
  5. Data for each run — the visual payload builder: rows Name · Type (Text / Number / True-false) · Value ·
     remove, "+ Add field"; names validated as typed (pattern, no duplicates); converted to and from the stored
     JSON; hint "Each field is a variable in the flow, e.g. {{check}} — {{start_type}} is scheduled".
  6. Test scheduled start (draft, now; opens the conversation and the logs, like Test webhook start).
  7. Delete (confirmation; help text: a live schedule stops at the next publish).
- Saving: each change saves the draft with `PUT` (debounced), error toast on failure; invalid input is flagged and
  not sent.
- Help text: stopping a live schedule takes a publish (switch off, then publish).
- master-pre: read-only mode disables the palette item and the panel (pre-only adaptation, as for the webhook box).

## 10. Vibe coder (tiledesk-agent-runtime)

- Prompt §1c: the **Scheduled start box** (`attributes.start_point: "scheduled"`) — an entry point wired like
  `start`, never deleted or renamed; the agent cannot create it nor set its timing or data (the user does, from the
  palette and the panel); a run reads `{{start_type}}` = `scheduled` and the payload fields; it is live only after
  publish; nobody is on the other side until the flow invites someone; Invite/Remove human work.
- Back-office pattern: a scheduled example (a periodic check that invites a person only when something is wrong).
- Catalogue overlay of `invite_human`/`remove_human`: "started by a webhook or a schedule".

## 11. Backward compatibility

| Existing case | Guarantee |
|---|---|
| Web and webhook start points | Unchanged; their code paths do not read `schedule`/`live` |
| KB auto re-index | Untouched: `AiReindexService`, `/webhook/kb/reindex`, jobworker unchanged |
| Installations without DolphinScheduler / token | Feature off: palette item hidden, routes 503, publish unaffected |
| Publish | Never fails because of the scheduler (§7) |
| Chatbots without scheduled start | No listener work beyond a lookup; no scheduler calls |

## 12. Testing

- Server (mocha): `toQuartzCron` for every frequency and edge (5-minute floor, `last`, weekday lists); validation
  400s; DolphinScheduler client against a stub HTTP server, including rollback on a failing step and recreate on
  unknown ids; publish listener (activate, update, deactivate, destroy when box missing or deleted, `live.error` on
  failure, restore_from); `/webhook/scheduled-start` (401, 503, 410 + offline, 429, conversation with published
  copy, payload, `start_type`, `scheduled_at`); test-run on the draft; sync endpoint; chatbot delete destroys;
  regression on webhook start points and `/webhook/kb/reindex`.
- design-studio (specs): schedule summary and validation; payload builder rows ↔ JSON; palette rules and
  `scheduled_available`; panel states.
- runtime: prompt/catalogue assertions in `tests/test_examples.py`.
- End-to-end: local stack plus `apache/dolphinscheduler-standalone-server:3.2.2` in docker — add the box, test-run
  the draft, publish, see a run fire, change the time without publishing (old schedule keeps firing), switch off +
  publish (runs stop), delete the chatbot (workflow gone). Then the same on stage with test agents, checking the
  workflow in the DolphinScheduler UI.

## 13. Delivery

Branch `feature/scheduled-start-point` from `feature/webhook-chatbot-hitl` in tiledesk-server, design-studio and
tiledesk-agent-runtime; then the usual path (tests, push, merge into the pre branches, tags, argo stage). Stage
needs `SCHEDULED_START_TOKEN` on the server and worker deployments (argo values or secret), checked before deploy.

## 14. Out of scope / later

- Several scheduled start points per chatbot.
- One-off runs at a date ("once"), as another frequency.
- Catching up runs missed while DolphinScheduler is down.
- Nested payload objects in the builder.
- Moving KB auto re-index onto `dolphinSchedulerClient`.

## 15. Running on tiledesk-scheduler-service (added 2026-10-13)

Scheduled starts can run on tiledesk-scheduler-service ≥ 1.1.0 instead of DolphinScheduler. `SCHEDULED_START_BACKEND` selects the backend per call:

| `SCHEDULED_START_BACKEND` | Required env on server + worker | Code |
|---|---|---|
| `dolphin` (default, also used for unknown values) | `SCHEDULER_BASEURL`, `SCHEDULER_TOKEN`, `SCHEDULER_PROJECT`, `SCHEDULED_START_TOKEN` | `services/scheduledStart/dolphinBackend.js` |
| `scheduler` | `SCHEDULER_SERVICE_URL`, `SCHEDULER_API_TOKEN`, `SCHEDULED_START_TOKEN` | `services/scheduledStart/schedulerBackend.js` |

`services/scheduledStartService.js` is a façade with the same API as before (`activate`, `update`, `deactivate`, `destroy`, `nextRuns`, `offlineFor`, `destroyFor`) plus `hasLive` and `liveIds`.

**How the scheduler backend works**
- One cron slot per chatbot: `projectId = id_project`, `flowId = auto-start-<chatbotId>`, `target = scheduledStart`, payload `{ id_project, chatbot_id }`.
- The cron is a standard 5-field expression from `toCron5`, with the schedule's IANA `timezone`.
- The scheduler adds `x-auth-token: $SCHEDULED_START_TOKEN` when the job runs and calls `$TILEDESK_API_URL/webhook/scheduled-start`. The token is never sent to the scheduler, and rotating it needs no re-sync. **Rotate it on the server and on the scheduler worker at the same time**: a mismatch gets a 401 on every run, the target never retries, and the bots silently stop.
- The `scheduledStart` target never retries, so there's at most one conversation per tick. A 410 from the run endpoint pauses the slot.
- `scheduled_live` stores `{ backend: 'scheduler', job_id, id_project, chatbot_id }` instead of `{ workflow_code, schedule_id }`.
- `next_runs` comes from `POST /schedules/preview`, formatted as `YYYY-MM-DD HH:mm:ss` wall-clock in the schedule's timezone, as with DolphinScheduler.

**Handover between backends**
- When `scheduled_live` holds ids of the backend that is *not* selected, the next `update` / `deactivate` / `destroy` / `offlineFor` / `destroyFor` works on the selected backend first, then removes the other backend's schedule.
- If that removal fails, the other backend's ids **stay** in `scheduled_live` next to the new ones, and every later call retries. Dropping them would leave that schedule firing with nothing left to remove it, and the bot would start twice per tick.
- The ids are dropped only when the removal succeeds, or when the other backend's env is no longer set.
- With no ids stored (e.g. a trashed chatbot whose webhook is already gone), `offlineFor` / `destroyFor` look the schedule up on both backends.
- All of this works in both directions, so a rollback to `dolphin` also removes the scheduler slot.
- The new schedule is created before the old one is removed: a tick that falls in that window of a few hundred milliseconds fires on both. Migrate away from tick times.

**Cutover (stage, then prod)**
1. Deploy tiledesk-scheduler-service ≥ 1.1.0 (API + worker).
   - Scheduler env: `SCHEDULER_API_TOKEN`, `TILEDESK_API_URL` (server base URL reachable from the worker), `SCHEDULED_START_TOKEN` (same value as the server).
   - Check `GET /health/ready` and `GET /targets` (lists `scheduledStart`).
2. Server + server-worker env (argo values / `config-scheduler`):
   - `SCHEDULED_START_BACKEND=scheduler`
   - `SCHEDULER_SERVICE_URL=http://<release>-scheduler-api`
   - `SCHEDULER_API_TOKEN` (same as the scheduler).
   - Keep the DolphinScheduler variables until step 4, so the handover can remove the old workflows.
3. Migrate every live bot with `POST /:projectid/webhooks/:chatbot_id/start_points/scheduled/migrate`, for each webhook with a `scheduled_live`.
   - Migrate recreates the schedule from the **stored live snapshot**, so unpublished draft edits are not published. Do **not** use `/sync` here: it reads the draft, so it would publish draft edits, and it destroys the live schedule if the draft was deleted.
   - It creates the slot (or pauses it when `enabled` is false) and removes the `auto-start-<id>` DolphinScheduler workflow.
   - Check: the scheduler's `GET /jobs?projectId=` shows the slot; `scheduled_live` has no `workflow_code` left (if it still does, the DolphinScheduler cleanup failed: run migrate again); DolphinScheduler has no `auto-start-*` left; the first run creates a conversation with `start_type=scheduled`.
   - Bots that are not migrated keep firing from DolphinScheduler until their next publish, which moves them.
4. Once no `auto-start-*` workflow is left, the DolphinScheduler variables can be removed from the server. DolphinScheduler itself stays while KB re-index still uses it.
