# Scheduled start point — design-studio Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** A Scheduled item in the Start points palette that drops a Scheduled start box, and a panel to edit its schedule, Source name and run data (visual payload builder), see whether it is live, test-run the draft and delete it.

**Architecture:** Pure helpers in `utils-start-points.ts` (types, block factory, palette items, schedule summary/validation, payload rows ↔ JSON, live status) are unit-tested; `WebhookService` gains the test and sync calls; the canvas drop path and the intent panel reuse the webhook start box code with a `scheduled` branch.

**Tech Stack:** Angular 14, Node 16 (nvm), Jasmine/Karma via the workspace harness.

**Spec:** `tiledesk-server/docs/superpowers/specs/2026-10-01-scheduled-start-point-design.md` (§9).

## Global Constraints

- Repo `/Users/nicocardone/Desktop/DEV/TILEDESK/design-studio`, branch `feature/scheduled-start-point` (create it from `feature/webhook-chatbot-hitl` after `git pull`). Never push. Commit trailer: blank line + `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.
- Node 16 prefix for every npm/npx: `source ~/.nvm/nvm.sh >/dev/null && nvm use 16 >/dev/null && `. Never npm install/ci.
- Specs run with the untracked harness: `npx ng test --watch=false --browsers=ChromeHeadless --main=.superpowers/sdd/2026-09-29-hitl-participant-removal-design-studio/test-hitl.ts --ts-config=.superpowers/sdd/2026-09-29-hitl-participant-removal-design-studio/tsconfig.hitl-specs.json`; register new spec files in its regex (don't commit the harness). `npx ng build` exits 0 with no new warnings; delete `dist/`.
- Server contract (tiledesk-server plan): `PUT {API}/{projectId}/webhooks/{chatbot_id}/start_points/scheduled` body `{ block_id, enabled?, mapping?: { source_name?, payload? }, schedule, confirm? }` → webhook + `schedule_summary` (+ `live_summary`); `POST …/start_points/scheduled/test` → `{ request_id }`; `POST …/start_points/scheduled/sync` → `scheduled_live`; `GET {API}/{projectId}/webhooks/{chatbot_id}` → `start_points`, `scheduled_live`, `scheduled_available`, `next_runs`; 503 when not configured.
- `schedule` shape: `{ frequency: 'interval'|'daily'|'weekly'|'monthly', every?, unit?: 'minutes'|'hours', time?: 'HH:MM', weekdays?: ('mon'..'sun')[], day_of_month?: 1..28|'last', timezone }`. Same validation values as the server (interval minutes 5/10/15/20/30, hours 1..12, ≥1 weekday, day 1..28 or last, payload keys `^[A-Za-z_][A-Za-z0-9_]*$`, unique, ≤ 50).
- Marker `attributes.start_point = 'scheduled'`; default block name `"Scheduled start"`; drop defaults: `{ frequency: 'daily', time: '09:00', timezone: Intl.DateTimeFormat().resolvedOptions().timeZone }`, enabled, `source_name` = chatbot name, `payload` `{}`.
- Status values and copy (en.json): `live` "Live — {summary} · next run {next}", `not_live` "Not live — publish to activate", `changes` "Changes not live — publish to apply", `error` "Couldn't update the live schedule — Retry". Badge labels "Live", "Changes not live", "Not live". Switch hint "Takes effect when you publish". Delete help "A live schedule stops at the next publish." Payload hint "Each field is a variable in the flow, e.g. {{check}} — {{start_type}} is scheduled".
- Palette item hidden when `scheduled_available` is false; one per type ("Already in this flow"); subtype `chatbot` only.
- Pre branch (`master-pre`) read-only adaptation is done at merge time, not in this plan.

## Review Focus

1. Switching Repeat from Weekly to Daily and back → the weekday selection is not sent while Daily is selected, and an invalid intermediate state (Weekly with no weekday) is never PUT.
2. Payload builder: a number field typed "08" or a true/false field → stored as number 8 / boolean, and reloading the panel shows the same rows in the same order.
3. Draft equal to live except key order of payload → status `live`, not `changes`.
4. `scheduled_available` false (GET) → no Scheduled palette item, and an existing Scheduled box still opens its panel showing the 503 message instead of breaking.
5. Fast consecutive edits (time typed digit by digit) → debounced to one PUT after the last change.

---

### Task 1: scheduled start point helpers

**Files:**
- Modify: `src/app/chatbot-design-studio/utils-start-points.ts`
- Test: `src/app/chatbot-design-studio/utils-start-points.spec.ts`, new `src/app/chatbot-design-studio/utils-schedule.spec.ts`
- Create: `src/app/chatbot-design-studio/utils-schedule.ts`

**Interfaces:**
- `START_POINT_TYPES = ['web', 'webhook', 'scheduled']`; `startPointTypeOf(intent)` returns `'scheduled'` for the marker; `createStartPointBlock(type: 'webhook'|'scheduled', pos)` (name `"Webhook start"` / `"Scheduled start"`); `buildStartPointItems(present: string[], pending: boolean, scheduledAvailable: boolean)` adds the Scheduled item (`start_point: 'scheduled'`, name key `CDSActionList.NAME.StartPointScheduled`); `createStartPointBox(deps, type: 'webhook'|'scheduled', pos)`.
- `utils-schedule.ts`: `defaultSchedule(timezone: string)`, `describeSchedule(schedule): string` (same sentences as the server's `summarize`), `scheduleError(schedule): string|null`, `cleanSchedule(schedule)` (drops fields not used by the frequency), `payloadToRows(payload): { name, type: 'text'|'number'|'boolean', value }[]`, `rowsToPayload(rows): { payload, error: string|null }`, `scheduledStatus(startPoint, live): 'live'|'changes'|'not_live'|'error'` (deep compare of enabled, block_id, mapping, cleaned schedule; payload compared key-order-insensitively).

- [ ] **Step 1: Failing specs:** marker detection and block factory for `scheduled`; palette items (Scheduled hidden when `scheduledAvailable` false, disabled with tooltip when present); `describeSchedule` examples ("Every weekday at 08:30 (Europe/Rome)", "Every 15 minutes (UTC)", "Monthly on the last day at 07:00 (UTC)"); `scheduleError` for each invalid case; `cleanSchedule` drops `weekdays` from a daily schedule (Review Focus 1); rows ↔ payload round trip with number "08" → 8 and boolean (Review Focus 2), duplicate/invalid names → error; `scheduledStatus` for no live, equal (payload key order swapped → `live`, Review Focus 3), different, `live.error` set.
- [ ] **Step 2: Run** the harness → compile errors / failures.
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Run** the harness → pass; report TOTAL.
- [ ] **Step 5: Commit** — `feat(scheduled-start): schedule and payload helpers`.

### Task 2: palette, drop and service calls

**Files:**
- Modify: `src/app/chatbot-design-studio/services/webhook-service.service.ts` (`testScheduledStart(chatbot_id)`, `syncScheduledStart(chatbot_id)`; `upsertStartPoint` type widened to `'webhook'|'scheduled'`)
- Modify: `cds-dashboard/cds-canvas/cds-panel-elements/cds-panel-elements.component.ts` (pass `scheduled_available` from the webhook GET into `buildStartPointItems`)
- Modify: `cds-dashboard/cds-canvas/cds-canvas.component.ts` (drop of `scheduled` → `createStartPointBox(…, 'scheduled', pos)` with upsert body including the drop defaults of Global Constraints)
- Modify: `cds-dashboard/cds-canvas/cds-intent/cds-intent.component.{ts,html}` (box rendering for `scheduled`: clock icon, summary line, badge)
- Modify: `src/assets/i18n/en.json`, new icon `src/assets/images/actions_category/start_point_scheduled.svg`
- Test: `webhook-service.service.spec.ts`, `start-points-wiring.spec.ts`

- [ ] **Step 1: Failing specs:** HttpTestingController — test/sync URLs `POST https://api.test/p1/webhooks/bot1/start_points/scheduled/test` and `/sync`; PUT body on drop equals `{ block_id, enabled: true, mapping: { source_name: <chatbot name>, payload: {} }, schedule: { frequency: 'daily', time: '09:00', timezone: <tz> } }`; wiring: palette without `scheduled_available` has no Scheduled item (Review Focus 4).
- [ ] **Step 2: Run** → fail.
- [ ] **Step 3: Implement** (box badge from `scheduledStatus`, summary from `describeSchedule`; reuse the start box toolbar guards via `isStartBox`).
- [ ] **Step 4: Run** harness → pass.
- [ ] **Step 5: Commit** — `feat(scheduled-start): palette item, drop and box`.

### Task 3: the Scheduled box panel

**Files:**
- Modify: `cds-dashboard/cds-canvas/cds-panel-intent-detail/cds-panel-intent-detail.component.{ts,html,scss}` (scheduled section; reuse `upsertStartPoint`, delete flow and test-run log opening of the webhook box)
- Modify: `src/assets/i18n/en.json`
- Test: extend `start-points-wiring.spec.ts` with the panel logic extracted as pure functions where possible

- [ ] **Step 1: Failing specs:** status line text per `scheduledStatus` value, with `next_runs[0]` formatted in the schedule's timezone; Retry calls `syncScheduledStart` then reloads; editing calls PUT once after a 600 ms debounce for several quick changes (fakeAsync, Review Focus 5); invalid schedule or payload → no PUT and the field error key shown; 503 on GET → panel shows "Scheduled starts are not available on this installation" (Review Focus 4).
- [ ] **Step 2: Run** → fail.
- [ ] **Step 3: Implement** the panel per spec §9 (status, Enabled switch + hint, Repeat with conditional fields, Timezone searchable select from `Intl.supportedValuesOf('timeZone')`, summary, Source name with chatbot-name placeholder, payload rows Name · Type · Value · remove + "Add field", Test scheduled start, Delete with confirmation and help text).
- [ ] **Step 4: Run** harness → pass; `npx ng build` → exit 0, no new warnings; delete `dist/`.
- [ ] **Step 5: Manual check** on the local stack (record as pending if DolphinScheduler is not running): drop the box, edit schedule and payload, Test scheduled start opens a conversation with `{{start_type}}` = scheduled and the payload variables; publish → status Live with next run.
- [ ] **Step 6: Commit** — `feat(scheduled-start): Scheduled box panel`.
