diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a198f3b..96ce9f0 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -180,3 +180,23 @@ Never commit credentials; use `.env.example` as reference. | [LOCAL_INFERENCE.md](LOCAL_INFERENCE.md) | llama.cpp, models, tegrastats | | [ASAP.md](ASAP.md) | Manifest, marketplace, compliance harness | | [SECURITY.md](SECURITY.md) | Threat model, sandbox audit | + +## Read scheduled jobs + +Send an authenticated `GET /api/cron/page` request for the first 16 jobs, in ID order. +Each entry includes a schedule preview and a message preview. ShellClaw keeps the full text for delivery. +If `next_after` contains a cursor, send it in `GET /api/cron/page?after=CURSOR`. +Use the job `key` in `POST /api/cron/job/KEY/toggle` and `DELETE /api/cron/job/KEY`. +A null cursor means that the list is complete. + +`GET /api/cron` returns the original array with full messages when it fits in one response. +If the list exceeds 64 jobs or the response buffer, this endpoint returns HTTP 413. + +Send a schedule to `POST /api/cron/preview` to see the next run before you save it. +The gateway evaluates the expression in its local time zone. Both the day of the month and the weekday must match. +For example, `0 9 1 * 1` runs at 09:00 when the first day of a month is a Monday. + +Each entry in a page includes `delivery_status`. A paused job stays paused after a restart. +A job with `waiting_for_channel` stays in the queue until its delivery channel becomes available. +A job with `invalid_destination` keeps this status when the scheduler disables it. A request to resume it returns HTTP 409. +Create a job with a supported destination before you delete the old job. diff --git a/src/core/memory.c b/src/core/memory.c index 91c3567..7fd3725 100644 --- a/src/core/memory.c +++ b/src/core/memory.c @@ -383,6 +383,22 @@ static char *dup_sqlite_text(sqlite3_stmt *stmt, int col) return strdup(p ? (const char *)p : ""); } +/* Copy complete UTF-8 characters. Keep the flag so the scheduler can reject a shortened address. */ +static int copy_cron_destination(sqlite3_stmt *stmt, int column, char *dst, size_t capacity) +{ + const unsigned char *text = sqlite3_column_text(stmt, column); + size_t length = (size_t)sqlite3_column_bytes(stmt, column); + size_t end = length; + if (length >= capacity) { + end = capacity - 1; + while (end > 0 && (text[end] & 0xc0) == 0x80) + end--; + } + if (text && end) memcpy(dst, text, end); + dst[end] = '\0'; + return length >= capacity; +} + void cron_job_row_free(cron_job_row_t *row) { if (!row) return; @@ -398,10 +414,8 @@ static int fill_cron_job_row(sqlite3_stmt *stmt, cron_job_row_t *out) copy_str_bounded(out->id, sizeof(out->id), (const char *)sqlite3_column_text(stmt, 0)); out->schedule = dup_sqlite_text(stmt, 1); out->message = dup_sqlite_text(stmt, 2); - out->channel_truncated = (size_t)sqlite3_column_bytes(stmt, 3) >= sizeof(out->channel); - out->recipient_truncated = (size_t)sqlite3_column_bytes(stmt, 4) >= sizeof(out->recipient); - copy_str_bounded(out->channel, sizeof(out->channel), (const char *)sqlite3_column_text(stmt, 3)); - copy_str_bounded(out->recipient, sizeof(out->recipient), (const char *)sqlite3_column_text(stmt, 4)); + out->channel_truncated = copy_cron_destination(stmt, 3, out->channel, sizeof(out->channel)); + out->recipient_truncated = copy_cron_destination(stmt, 4, out->recipient, sizeof(out->recipient)); out->next_run = sqlite3_column_int64(stmt, 5); out->enabled = sqlite3_column_int(stmt, 6); if (!out->schedule || !out->message) { @@ -490,26 +504,38 @@ int cron_job_update_next_run(const char *id, long long next_run) return ret; } -int cron_job_list(cron_job_row_t *out, int max_count) +static int read_cron_rows(const char *sql, const char *after, cron_job_row_t *out, int max_count) { + sqlite3_stmt *stmt = NULL; + int count = 0, rc; if (!g_db || !out || max_count <= 0) return -1; memory_sqlite_entry_probe(); - const char *sql = "SELECT id, schedule, message, channel, recipient, next_run, enabled " - "FROM cron_jobs ORDER BY next_run ASC, id ASC"; - sqlite3_stmt *stmt = NULL; if (sqlite3_prepare_v2(g_db, sql, -1, &stmt, NULL) != SQLITE_OK) return -1; - int count = 0; - while (count < max_count && sqlite3_step(stmt) == SQLITE_ROW) { - if (fill_cron_job_row(stmt, &out[count]) != 0) { - for (int i = 0; i < count; i++) - cron_job_row_free(&out[i]); - sqlite3_finalize(stmt); - return -1; - } + sqlite3_bind_int(stmt, 1, max_count); + if (after) sqlite3_bind_text(stmt, 2, after, -1, SQLITE_TRANSIENT); + while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) { + if (fill_cron_job_row(stmt, &out[count]) != 0) break; count++; } sqlite3_finalize(stmt); - return count; + if (rc == SQLITE_DONE) return count; + for (int i = 0; i < count; i++) cron_job_row_free(&out[i]); + return -1; +} + +int cron_job_list(cron_job_row_t *out, int max_count) +{ + return read_cron_rows("SELECT id, schedule, message, channel, recipient, next_run, enabled " + "FROM cron_jobs ORDER BY next_run, id LIMIT ?1", NULL, out, max_count); +} + +int cron_job_list_previews(const char *after, cron_job_row_t *out, int max_count) +{ + /* SQLite substr counts Unicode characters and preserves complete UTF-8 sequences. */ + const char *sql = "SELECT id, substr(schedule,1,128) || CASE WHEN length(schedule)>128 THEN '...' ELSE '' END, " + "substr(message,1,160) || CASE WHEN length(message)>160 THEN '...' ELSE '' END, " + "channel, recipient, next_run, enabled FROM cron_jobs WHERE id > ?2 ORDER BY id LIMIT ?1"; + return read_cron_rows(sql, after ? after : "", out, max_count); } int cron_job_list_due(long long now, const cron_due_key_t *after, @@ -535,14 +561,10 @@ int cron_job_list_due(long long now, const cron_due_key_t *after, copy_str_bounded(out[count].id, sizeof(out[count].id), (const char *)sqlite3_column_text(stmt, 0)); out[count].next_run = sqlite3_column_int64(stmt, 1); - out[count].channel_truncated = - (size_t)sqlite3_column_bytes(stmt, 2) >= sizeof(out[count].channel); - out[count].recipient_truncated = - (size_t)sqlite3_column_bytes(stmt, 3) >= sizeof(out[count].recipient); - copy_str_bounded(out[count].channel, sizeof(out[count].channel), - (const char *)sqlite3_column_text(stmt, 2)); - copy_str_bounded(out[count].recipient, sizeof(out[count].recipient), - (const char *)sqlite3_column_text(stmt, 3)); + out[count].channel_truncated = copy_cron_destination(stmt, 2, out[count].channel, + sizeof(out[count].channel)); + out[count].recipient_truncated = copy_cron_destination(stmt, 3, out[count].recipient, + sizeof(out[count].recipient)); count++; } sqlite3_finalize(stmt); diff --git a/src/core/memory.h b/src/core/memory.h index e2dd963..0483d5c 100644 --- a/src/core/memory.h +++ b/src/core/memory.h @@ -230,6 +230,9 @@ int cron_job_list_due(long long now, const cron_due_key_t *after, */ int cron_job_list(cron_job_row_t *out, int max_count); +/** List job previews after an exclusive ID, in ID order. Free each returned row. */ +int cron_job_list_previews(const char *after, cron_job_row_t *out, int max_count); + /** * Get the next due job (next_run <= now, enabled). * diff --git a/src/gateway/http_lws.c b/src/gateway/http_lws.c index 478215f..0cbc7ae 100644 --- a/src/gateway/http_lws.c +++ b/src/gateway/http_lws.c @@ -77,6 +77,8 @@ static int http_body_content_length(struct lws *wsi, long *cl_out) return 0; } +enum { HTTP_REQUEST_URI_SIZE = 512 }; + static int http_copy_request_uri(struct lws *wsi, char *uri, int uri_size) { int n; @@ -94,7 +96,7 @@ static int http_copy_request_uri(struct lws *wsi, char *uri, int uri_size) static void http_dispatch_body(http_server_ctx_t *ctx, struct lws *wsi, http_conn_t *conn) { - char uri[256]; + char uri[HTTP_REQUEST_URI_SIZE]; int uri_len; int method; if (!conn || !conn->has_body || conn->body_dispatched) @@ -189,7 +191,7 @@ int http_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, if (!ctx) return 0; switch (reason) { case LWS_CALLBACK_HTTP: { - char uri[256]; + char uri[HTTP_REQUEST_URI_SIZE]; int uri_len = http_copy_request_uri(wsi, uri, sizeof(uri)); if (uri_len <= 0 || uri_len >= (int)sizeof(uri)) { lws_return_http_status(wsi, 400, "Bad request"); @@ -245,7 +247,7 @@ int http_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, const unsigned char *data = NULL; size_t data_len = 0; const char *ct = NULL; - char path_buf[256]; + char path_buf[sizeof(uri)]; if (uri_len >= (int)sizeof(path_buf)) uri_len = (int)sizeof(path_buf) - 1; memcpy(path_buf, uri, (size_t)uri_len); path_buf[uri_len] = '\0'; diff --git a/src/gateway/routes.c b/src/gateway/routes.c index e53b975..87ca0fe 100644 --- a/src/gateway/routes.c +++ b/src/gateway/routes.c @@ -467,8 +467,8 @@ static void handle_skill_create(const config_t *cfg, const char *body, size_t bo json_error(buf, size, status, 500, "Failed to create skill"); return; } - *status = 201; json_response(buf, size, status, "{\"ok\":true}"); + *status = 201; } static void handle_skill_update(const config_t *cfg, const char *name, const char *body, size_t body_len, @@ -564,57 +564,134 @@ static void handle_session_delete(const char *id, char *buf, size_t size, int *s json_response(buf, size, status, "{\"ok\":true}"); } -static void free_cron_job_rows(cron_job_row_t *rows, int n) +enum { CRON_LEGACY_LIMIT = 64, CRON_PAGE_SIZE = 16 }; + +/* The opaque key also identifies jobs that older gateways stored with an incomplete UTF-8 ID. */ +static void cron_encode_key(const char *id, char out[256]) { - int i; - if (!rows || n <= 0) return; - for (i = 0; i < n; i++) - cron_job_row_free(&rows[i]); + static const char hex[] = "0123456789abcdef"; + *out++ = '~'; + for (const unsigned char *p = (const unsigned char *)id; *p; p++) { + *out++ = hex[*p >> 4]; + *out++ = hex[*p & 15]; + } + *out = 0; } -static void handle_cron_list(char *buf, size_t size, int *status) +static int cron_decode_key(const char *key, char id[128]) { - cron_job_row_t *rows = calloc(64, sizeof(cron_job_row_t)); - int n; - int i; - if (!rows) { json_error(buf, size, status, 500, "Out of memory"); return; } + static const char hex[] = "0123456789abcdef"; + size_t n = strlen(key); + if (key[0] != '~' || n < 3 || n > 255 || n % 2 == 0) return -1; + for (size_t i = 1; i < n; i += 2) { + const char *hi = strchr(hex, key[i]), *lo = strchr(hex, key[i + 1]); + if (!hi || !lo) return -1; + *id = (char)((hi - hex) * 16 + (lo - hex)); + if (!*id++) return -1; + } + *id = 0; + return 0; +} + +static int cron_id_is_utf8(const char *id) +{ + const unsigned char *p = (const unsigned char *)id; + while (*p) { + unsigned char lead = *p++; + if (lead < 0x80) continue; + if (lead < 0xc2 || lead > 0xf4) return 0; + unsigned count = lead < 0xe0 ? 1 : (lead < 0xf0 ? 2 : 3); + if ((lead == 0xe0 && *p < 0xa0) || (lead == 0xed && *p >= 0xa0) || + (lead == 0xf0 && *p < 0x90) || (lead == 0xf4 && *p >= 0x90)) return 0; + while (count--) { + if ((*p & 0xc0) != 0x80) return 0; + p++; + } + } + return 1; +} + +static cJSON *cron_list_item(const cron_job_row_t *row, const char *delivery_state) +{ + cJSON *obj = cJSON_CreateObject(); + char key[256]; + cron_encode_key(row->id, key); + if (obj && cJSON_AddStringToObject(obj, "id", cron_id_is_utf8(row->id) ? row->id : key) && + (!delivery_state || cJSON_AddStringToObject(obj, "key", key)) && + cJSON_AddStringToObject(obj, delivery_state ? "schedule_preview" : "schedule", row->schedule) && + cJSON_AddStringToObject(obj, delivery_state ? "message_preview" : "message", row->message) && + cJSON_AddStringToObject(obj, "channel", row->channel) && + cJSON_AddStringToObject(obj, "recipient", row->recipient) && + cJSON_AddNumberToObject(obj, "next_run", (double)row->next_run) && + cJSON_AddBoolToObject(obj, "enabled", row->enabled) && + (!delivery_state || cJSON_AddStringToObject(obj, "delivery_status", delivery_state))) + return obj; + cJSON_Delete(obj); + return NULL; +} + +static void handle_cron_list(const char *after, char *buf, size_t size, int *status) +{ + int limit = after ? CRON_PAGE_SIZE : CRON_LEGACY_LIMIT; + cron_job_row_t *rows = calloc((size_t)limit + 1, sizeof(*rows)); + cJSON *root = NULL, *jobs; + char *serialized = NULL; + int n = 0; + const char *states[CRON_PAGE_SIZE]; + if (!rows) goto fail; agent_lock(); - n = cron_job_list(rows, 64); + n = after ? cron_job_list_previews(after, rows, limit + 1) : cron_job_list(rows, limit + 1); + if (after) + for (int i = 0; i < n && i < limit; i++) + states[i] = cron_job_delivery_state(&rows[i]); agent_unlock(); - if (n < 0) { - free(rows); - json_error(buf, size, status, 500, "Internal error"); - return; - } - cJSON *arr = cJSON_CreateArray(); - if (!arr) { - free_cron_job_rows(rows, n); - free(rows); - json_error(buf, size, status, 500, "Internal error"); - return; - } - for (i = 0; i < n; i++) { - cJSON *obj = cJSON_CreateObject(); - if (!obj) { - free_cron_job_rows(rows, n); - free(rows); - cJSON_Delete(arr); - json_error(buf, size, status, 500, "Internal error"); - return; - } - cJSON_AddItemToObject(obj, "id", cJSON_CreateString(rows[i].id)); - cJSON_AddItemToObject(obj, "schedule", cJSON_CreateString(rows[i].schedule ? rows[i].schedule : "")); - cJSON_AddItemToObject(obj, "message", cJSON_CreateString(rows[i].message ? rows[i].message : "")); - cJSON_AddItemToObject(obj, "channel", cJSON_CreateString(rows[i].channel)); - cJSON_AddItemToObject(obj, "recipient", cJSON_CreateString(rows[i].recipient)); - cJSON_AddItemToObject(obj, "next_run", cJSON_CreateNumber((double)rows[i].next_run)); - cJSON_AddItemToObject(obj, "enabled", cJSON_CreateBool(rows[i].enabled)); - cJSON_AddItemToArray(arr, obj); - } - free_cron_job_rows(rows, n); + if (n < 0) goto fail; + if (!after && n > limit) goto too_large; + if (after) { + char next[256]; + if (n > limit) cron_encode_key(rows[limit - 1].id, next); + root = cJSON_CreateObject(); + jobs = root ? cJSON_AddArrayToObject(root, "jobs") : NULL; + if (!jobs || !(n > limit ? cJSON_AddStringToObject(root, "next_after", next) + : cJSON_AddNullToObject(root, "next_after"))) goto fail; + } else { + root = jobs = cJSON_CreateArray(); + if (!jobs) goto fail; + } + for (int i = 0; i < n && i < limit; i++) { + cJSON *item = cron_list_item(&rows[i], after ? states[i] : NULL); + if (!item) goto fail; + cJSON_AddItemToArray(jobs, item); + } + serialized = cJSON_PrintUnformatted(root); + if (!serialized) goto fail; + if (strlen(serialized) >= size) goto too_large; + json_response(buf, size, status, serialized); + goto done; +too_large: + json_error(buf, size, status, 413, "Use /api/cron/page to read the jobs in pages."); + goto done; +fail: + json_error(buf, size, status, 500, "Cannot read the jobs."); +done: + free(serialized); + cJSON_Delete(root); + for (int i = 0; i < n; i++) cron_job_row_free(&rows[i]); free(rows); - json_print_to_buf(arr, buf, size, status); - cJSON_Delete(arr); +} + +static void handle_cron_preview(const char *body, size_t body_len, char *buf, size_t size, int *status) +{ + cJSON *root = body ? cJSON_ParseWithLength(body, body_len) : NULL; + const char *schedule = cJSON_GetStringValue(cJSON_GetObjectItem(root, "schedule")); + long long next; + if (!schedule || cron_parse_next_run(schedule, (long long)time(NULL), &next) != 0) { + json_error(buf, size, status, 400, "Invalid schedule or no match in the search period."); + } else { + snprintf(buf, size, "{\"next_run\":%lld}", next); + *status = 200; + } + cJSON_Delete(root); } static void handle_cron_create(const char *body, size_t body_len, char *buf, size_t size, int *status) @@ -632,9 +709,14 @@ static void handle_cron_create(const char *body, size_t body_len, char *buf, siz cJSON *channel = cJSON_GetObjectItem(root, "channel"); cJSON *recipient = cJSON_GetObjectItem(root, "recipient"); char id[128]; - if (cJSON_IsString(id_node) && id_node->valuestring[0]) - snprintf(id, sizeof(id), "%.127s", id_node->valuestring); - else + if (cJSON_IsString(id_node) && id_node->valuestring[0]) { + if (strlen(id_node->valuestring) >= sizeof(id) || !cron_id_is_utf8(id_node->valuestring)) { + cJSON_Delete(root); + json_error(buf, size, status, 400, "Job IDs must use UTF-8 and fit in 127 bytes."); + return; + } + memcpy(id, id_node->valuestring, strlen(id_node->valuestring) + 1); + } else id[0] = '\0'; const char *ch = (channel && cJSON_IsString(channel)) ? channel->valuestring : NULL; const char *rec = (recipient && cJSON_IsString(recipient)) ? recipient->valuestring : NULL; @@ -678,8 +760,12 @@ static void handle_cron_toggle(const char *id, char *buf, size_t size, int *stat { int rc; agent_lock(); - rc = cron_job_toggle(id); + rc = cron_toggle_job(id); agent_unlock(); + if (rc == CRON_INVALID_DESTINATION) { + json_error(buf, size, status, 409, "Cannot resume a job with an invalid destination"); + return; + } if (rc != 0) { json_error(buf, size, status, 404, "Job not found"); return; @@ -1058,11 +1144,47 @@ int dispatch_route(http_server_ctx_t *ctx, struct lws *wsi, int method, return 0; } if (uri_exact_eq(uri, uri_len, "/api/cron")) { - if (method == HTTP_GET) handle_cron_list(buf, size, status); + if (method == HTTP_GET) handle_cron_list(NULL, buf, size, status); else if (method == HTTP_POST) handle_cron_create(body, body_len, buf, size, status); else json_error(buf, size, status, 405, "Method not allowed"); return 0; } + if (method == HTTP_POST && uri_exact_eq(uri, uri_len, "/api/cron/preview")) { + handle_cron_preview(body, body_len, buf, size, status); + return 0; + } + if (method == HTTP_GET && uri_exact_eq(uri, uri_len, "/api/cron/page")) { + char after[512] = ""; + int n = -1; + if (wsi && lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_URI_ARGS) >= (int)sizeof(after) - 1) { + json_error(buf, size, status, 400, "The page cursor is too long."); + return 0; + } + if (wsi) n = lws_get_urlarg_by_name_safe(wsi, "after=", after, sizeof(after)); + char id[128]; + int encoded = n > 0 && after[0] == '~'; + if ((n >= 0 && strlen(after) != (size_t)n) || (encoded ? cron_decode_key(after, id) != 0 : n >= 128)) + json_error(buf, size, status, 400, "Invalid page cursor."); + else + handle_cron_list(n < 0 ? "" : (encoded ? id : after), buf, size, status); + return 0; + } + if (uri_has_prefix(uri, uri_len, "/api/cron/job/~")) { + char key[256], id[128]; + const char *prefix = "/api/cron/job/"; + if (extract_path_param(uri, uri_len, prefix, key, sizeof(key)) != 0 || cron_decode_key(key, id) != 0) { + json_error(buf, size, status, 400, "Invalid job key."); + return 0; + } + size_t end = strlen(prefix) + strlen(key); + if (method == HTTP_DELETE && end == (size_t)uri_len) + handle_cron_delete(id, buf, size, status); + else if (method == HTTP_POST && (size_t)uri_len == end + 7 && memcmp(uri + end, "/toggle", 7) == 0) + handle_cron_toggle(id, buf, size, status); + else + json_error(buf, size, status, 405, "Method not allowed"); + return 0; + } if (uri_has_prefix(uri, uri_len, "/api/cron/")) { char id[128]; if (extract_path_param(uri, uri_len, "/api/cron/", id, sizeof(id)) != 0) { diff --git a/src/tools/cron.c b/src/tools/cron.c index 806276c..05e1b1f 100644 --- a/src/tools/cron.c +++ b/src/tools/cron.c @@ -80,7 +80,12 @@ static int cron_expr_matches(const int fields[10], int min, int hour, int mday, field_matches(wday, fields[8], fields[9]); } -static int parse_cron_expr(const char *s, int fields[10]) +typedef enum { + CRON_SCHEDULE_INPUT, + CRON_SCHEDULE_STORED +} cron_schedule_source_t; + +static int parse_cron_expr(const char *s, int fields[10], cron_schedule_source_t source) { char buf[256]; if (!s || strlen(s) >= sizeof(buf)) return -1; @@ -89,9 +94,11 @@ static int parse_cron_expr(const char *s, int fields[10]) char *ctx = NULL; const char *tokens[5]; int n = 0; - for (char *p = strtok_r(buf, " \t", &ctx); p && n < 5; p = strtok_r(NULL, " \t", &ctx)) + char *p = strtok_r(buf, " \t", &ctx); + for (; p && n < 5; p = strtok_r(NULL, " \t", &ctx)) tokens[n++] = p; - if (n != 5) return -1; + /* Older versions accepted text after the fifth field of a stored schedule. */ + if (n != 5 || (p && source == CRON_SCHEDULE_INPUT)) return -1; int lo, hi; if (parse_range(tokens[0], &lo, &hi, 0, 59) != 0) return -1; fields[0] = lo; fields[1] = hi; @@ -108,10 +115,10 @@ static int parse_cron_expr(const char *s, int fields[10]) return 0; } -static long long cron_next_from_expr(const char *cron_part, long long now) +static long long cron_next_from_expr(const char *cron_part, long long now, cron_schedule_source_t source) { int fields[10]; - if (parse_cron_expr(cron_part, fields) != 0) return -1; + if (parse_cron_expr(cron_part, fields, source) != 0) return -1; /* * Start at the beginning of the *next* minute. Returning the current * minute would leave next_run <= now after a fire, so the job would @@ -151,7 +158,8 @@ static int interval_next_run(const char *num, long long now, long long *next_out return 0; } -int cron_parse_next_run(const char *schedule, long long now, long long *next_out) +static int cron_next_run(const char *schedule, long long now, long long *next_out, + cron_schedule_source_t source) { if (!schedule || !next_out) return -1; if (strncmp(schedule, CRON_PREFIX_INTERVAL, strlen(CRON_PREFIX_INTERVAL)) == 0) @@ -162,20 +170,26 @@ int cron_parse_next_run(const char *schedule, long long now, long long *next_out long long ts; /* A partial convert (at:2026-10-08 -> 2026) is already due, so the * one-shot fires on the next poll and ack deletes the future reminder. */ + errno = 0; ts = strtoll(num, &end, 10); - if (!end || end == num || *end != '\0') return -1; + if (end == num || *end != '\0' || errno == ERANGE) return -1; *next_out = ts; return 0; } const char *cron_part = schedule; if (strncmp(schedule, CRON_PREFIX_CRON, strlen(CRON_PREFIX_CRON)) == 0) cron_part = schedule + strlen(CRON_PREFIX_CRON); - long long next = cron_next_from_expr(cron_part, now); + long long next = cron_next_from_expr(cron_part, now, source); if (next < 0) return -1; *next_out = next; return 0; } +int cron_parse_next_run(const char *schedule, long long now, long long *next_out) +{ + return cron_next_run(schedule, now, next_out, CRON_SCHEDULE_INPUT); +} + int cron_is_one_shot(const char *schedule) { if (!schedule) return 0; @@ -291,6 +305,28 @@ static cron_target_status_t cron_stored_target(const char *channel, const char * return cron_resolve_target(channel, recipient, CRON_TARGET_STORED, NULL); } +static cron_target_status_t cron_row_target(const cron_job_row_t *row) +{ + return cron_stored_target(row->channel, row->recipient, row->channel_truncated, row->recipient_truncated); +} + +const char *cron_job_delivery_state(const struct cron_job_row *row) +{ + cron_target_status_t target = cron_row_target(row); + if (target == CRON_TARGET_INVALID) return "invalid_destination"; + if (!row->enabled) return "paused"; + return target == CRON_TARGET_READY ? "scheduled" : "waiting_for_channel"; +} + +int cron_toggle_job(const char *id) +{ + cron_job_row_t row; + if (cron_job_get_by_id(id, &row) != 1) return -1; + int cannot_resume = !row.enabled && cron_row_target(&row) == CRON_TARGET_INVALID; + cron_job_row_free(&row); + return cannot_resume ? CRON_INVALID_DESTINATION : cron_job_toggle(id); +} + int cron_create_job(const char *schedule, const char *message, const char *channel, const char *recipient, char *id_out, size_t id_size) @@ -515,8 +551,7 @@ static int cron_pick_due_row(long long now, int timeout_ms, cron_job_row_t *row) cron_sleep_ms((long)timeout_ms); agent_lock(); found = cron_job_get_by_id(first, row) == 1 && row->enabled && row->next_run <= now && - cron_stored_target(row->channel, row->recipient, row->channel_truncated, - row->recipient_truncated) == CRON_TARGET_READY; + cron_row_target(row) == CRON_TARGET_READY; agent_unlock(); if (found) return 1; @@ -570,7 +605,7 @@ int cron_ack_delivery(const char *job_id) return rc; } now = (long long)time(NULL); - rc = cron_parse_next_run(row.schedule, now, &next); + rc = cron_next_run(row.schedule, now, &next, CRON_SCHEDULE_STORED); if (rc != 0) { /* A stored schedule the parser now rejects (e.g. a legacy comma * list) would otherwise snooze the job for a year with no trace; @@ -729,9 +764,11 @@ static int cron_tool_execute(const char *args_json, char *result_buf, size_t max snprintf(result_buf, max_len, "{\"error\":\"id required\"}"); return -1; } - if (cron_job_toggle(id_node->valuestring) != 0) { + int rc = cron_toggle_job(id_node->valuestring); + if (rc != 0) { cJSON_Delete(root); - snprintf(result_buf, max_len, "{\"error\":\"job not found\"}"); + snprintf(result_buf, max_len, "{\"error\":\"%s\"}", rc == CRON_INVALID_DESTINATION + ? "Cannot resume a job with an invalid destination" : "job not found"); return -1; } snprintf(result_buf, max_len, "{\"ok\":true}"); diff --git a/src/tools/cron.h b/src/tools/cron.h index a45caa1..290cfba 100644 --- a/src/tools/cron.h +++ b/src/tools/cron.h @@ -17,6 +17,7 @@ extern "C" { * Parse schedule and compute next_run strictly after `now`. * Formats: "cron:min hour dom month dow", "interval:N", "at:unix_ts". * Cron: 5 fields, * or N or N-M. dow 0-6 (Sun-Sat). + * The day of the month and day of the week must both match. * Cron expressions start searching at the next minute boundary so a just-fired * job cannot remain due in the same minute. * @@ -35,6 +36,10 @@ int cron_parse_next_run(const char *schedule, long long now, long long *next_out */ int cron_is_one_shot(const char *schedule); +struct cron_job_row; +/** Return the delivery state for a stored job while the caller holds the agent lock. */ +const char *cron_job_delivery_state(const struct cron_job_row *row); + /** * Commit cron delivery after the agent successfully handles a fired job. * One-shot jobs are deleted; recurring jobs advance next_run. @@ -54,6 +59,9 @@ const tool_t *tool_cron_get(void); #define CRON_INVALID_DESTINATION (-2) +/** Toggle a stored job under the agent lock. Return CRON_INVALID_DESTINATION if it cannot resume. */ +int cron_toggle_job(const char *id); + /** * Create a cron job (shared by tool and HTTP handler). * If id_out[0] == '\0', a random ID is generated. diff --git a/tests/test_cron.c b/tests/test_cron.c index 34c1817..7882d0f 100644 --- a/tests/test_cron.c +++ b/tests/test_cron.c @@ -194,6 +194,9 @@ static int test_schedule_rejects_partial_numbers(void) ASSERT(next == 99); ASSERT(cron_parse_next_run("at:tomorrow", now, &next) == -1); ASSERT(cron_parse_next_run("at:", now, &next) == -1); + ASSERT(cron_parse_next_run("at:9223372036854775808", now, &next) == -1); + ASSERT(cron_parse_next_run("at:-9223372036854775809", now, &next) == -1); + ASSERT(cron_parse_next_run("cron:0 9 * * * extra", now, &next) == -1); ASSERT(cron_parse_next_run("interval:60abc", now, &next) == -1); ASSERT(cron_parse_next_run("cron:0 9 * * 1,3,5", now, &next) == -1); ASSERT(cron_parse_next_run("cron:0 9 1,15 * *", now, &next) == -1); @@ -510,6 +513,25 @@ static int test_cron_ack_advances_recurring_past_due_minute(void) return 0; } +static int test_ack_keeps_a_legacy_five_field_schedule(void) +{ + const char *schedule = "cron:* * * * * daily"; + char id[] = "new-report"; + long long now = (long long)time(NULL); + cron_job_row_t row; + + ASSERT(memory_init(":memory:") == 0); + ASSERT(cron_create_job(schedule, "Report", "cli", "default", id, sizeof(id)) == -1); + ASSERT(cron_job_create("existing-report", schedule, "Report", "cli", "default", now - 1, 1) == 0); + ASSERT(cron_ack_delivery("existing-report") == 0); + ASSERT(cron_job_get_by_id("existing-report", &row) == 1); + ASSERT(row.enabled && strcmp(row.schedule, schedule) == 0); + ASSERT(row.next_run > now && row.next_run <= (long long)time(NULL) + 60); + cron_job_row_free(&row); + memory_cleanup(); + return 0; +} + static int test_cron_ack_fail_closed_on_parse_error(void) { const char *path = "/tmp/shellclaw_test_cron_ack_fail_closed.db"; @@ -804,6 +826,7 @@ static int test_cron_unavailable_targets_do_not_block_ready_jobs(void) ASSERT(cron_ack_delivery(msg.user_id) == 0); channel_incoming_msg_clear(&msg); ASSERT(cron_job_get_by_id("old-chat", &row) == 1 && row.enabled == 0); + ASSERT(strcmp(cron_job_delivery_state(&row), "invalid_destination") == 0); ASSERT(strcmp(row.channel, "webchat") == 0 && strcmp(row.recipient, "webchat:42") == 0); ASSERT(strcmp(row.message, "old") == 0 && strcmp(row.schedule, "at:1") == 0 && row.next_run == due - 2); cron_job_row_free(&row); @@ -814,6 +837,11 @@ static int test_cron_unavailable_targets_do_not_block_ready_jobs(void) ASSERT(cron_job_get_by_id("waiting00", &row) == 1 && row.enabled == 1); ASSERT(row.next_run == due - 1); cron_job_row_free(&row); + char result[128]; + ASSERT(tool_cron_get()->execute("{\"operation\":\"toggle\",\"id\":\"old-chat\"}", result, sizeof(result)) != 0); + ASSERT(strstr(result, "destination") != NULL); + ASSERT(cron_job_get_by_id("old-chat", &row) == 1 && row.enabled == 0); + cron_job_row_free(&row); ASSERT(clock_gettime(CLOCK_MONOTONIC, &start) == 0); ASSERT(cron->poll(&msg, 80) == 0); ASSERT(clock_gettime(CLOCK_MONOTONIC, &end) == 0); @@ -944,6 +972,7 @@ int main(void) RUN(test_cron_poll_holds_agent_lock()); RUN(test_cron_poll_keeps_job_until_ack()); RUN(test_cron_ack_advances_recurring_past_due_minute()); + RUN(test_ack_keeps_a_legacy_five_field_schedule()); RUN(test_cron_ack_fail_closed_on_parse_error()); RUN(test_cron_poll_waits_before_reoffer()); RUN(test_cron_job_rejects_oversized_text()); diff --git a/tests/test_gateway_db_lock.c b/tests/test_gateway_db_lock.c index df5889e..1bfcf7c 100644 --- a/tests/test_gateway_db_lock.c +++ b/tests/test_gateway_db_lock.c @@ -85,6 +85,12 @@ static int test_dashboard_sqlite_holds_agent_lock(void) ASSERT(status == 200); ASSERT(call_route(&ctx, HTTP_DELETE, "/api/cron/job_lock", NULL, &status) == 0); ASSERT(status == 200); + agent_lock(); + int seeded = cron_job_create("legacy", "at:1", "Report", "webchat", "42", 1, 0); + agent_unlock(); + ASSERT(seeded == 0); + ASSERT(call_route(&ctx, HTTP_POST, "/api/cron/legacy/toggle", NULL, &status) == 0); + ASSERT(status == 409); memory_sqlite_entry_set_hook_for_test(NULL); ASSERT(agent_mutex_is_locked_for_test() == 0); diff --git a/tests/test_gateway_http.c b/tests/test_gateway_http.c index a1e61bc..b4d04c1 100644 --- a/tests/test_gateway_http.c +++ b/tests/test_gateway_http.c @@ -1261,7 +1261,7 @@ static int test_api_skill_create_delete(const char *token) "{\"name\":\"test_integration_skill\",\"content\":\"# Test skill for integration\"}", &code, &body); ASSERT(r == 0); - ASSERT(code == 200 || code == 201); + ASSERT(code == 201); free(body); body = NULL; r = http_get_auth(gw_url("/api/skills/test_integration_skill"), token, &code, &body); @@ -1362,6 +1362,124 @@ static int test_api_cron_list(const char *token) return 0; } +static int test_api_cron_pages(const char *token) +{ + char message[6001], json[6500], path[512], cursor[256] = ""; + char *body = NULL; + long status; + int seen = 0; + memset(message, 'a', sizeof(message) - 1); + message[sizeof(message) - 1] = '\0'; + for (int i = 0; i < 67; i++) { + snprintf(json, sizeof(json), + "{\"id\":\"qa-%03d\",\"schedule\":\"interval:86400\",\"message\":\"%s\"}", + i, i < 12 ? message : "note"); + ASSERT(http_post_auth(gw_url("/api/cron"), token, json, &status, &body) == 0); + ASSERT(status == 201); + free(body); + if (i == 11 || i == 66) { + ASSERT(http_get_auth(gw_url("/api/cron"), token, &status, &body) == 0); + cJSON *error = cJSON_Parse(body); + ASSERT(status == 413 && cJSON_IsString(cJSON_GetObjectItem(error, "error"))); + cJSON_Delete(error); + free(body); + } + } + do { + snprintf(path, sizeof(path), "/api/cron/page?after=%s", cursor); + ASSERT(http_get_auth(gw_url(path), token, &status, &body) == 0); + cJSON *page = cJSON_Parse(body); + cJSON *jobs = cJSON_GetObjectItem(page, "jobs"); + ASSERT(status == 200 && cJSON_IsArray(jobs)); + ASSERT(cJSON_GetArraySize(jobs) > 0 && cJSON_GetArraySize(jobs) <= 16); + cJSON *job; + cJSON_ArrayForEach(job, jobs) { + char expected[32]; + snprintf(expected, sizeof(expected), "qa-%03d", seen++); + ASSERT(strcmp(cJSON_GetStringValue(cJSON_GetObjectItem(job, "id")), expected) == 0); + ASSERT(cJSON_IsString(cJSON_GetObjectItem(job, "message_preview"))); + } + cJSON *next = cJSON_GetObjectItem(page, "next_after"); + ASSERT(cJSON_IsNull(next) || cJSON_IsString(next)); + snprintf(cursor, sizeof(cursor), "%s", cJSON_IsString(next) ? next->valuestring : ""); + cJSON_Delete(page); + free(body); + } while (cursor[0] && seen < 68); + ASSERT(seen == 67 && !cursor[0]); + for (int i = 0; i < seen; i++) { + snprintf(path, sizeof(path), "/api/cron/qa-%03d", i); + ASSERT(http_delete_auth(gw_url(path), token, &status, &body) == 0 && status == 200); + free(body); + } + return 0; +} + +static int test_cron_job_id_bytes(const char *token) +{ + char id[132], json[320], path[320], *body = NULL; + long status; + memset(id, 'x', 125); + memcpy(id + 125, "é", sizeof("é")); + id[0] = '/'; + snprintf(json, sizeof(json), "{\"id\":\"%s\",\"schedule\":\"interval:86400\",\"message\":\"note\"}", id); + ASSERT(http_post_auth(gw_url("/api/cron"), token, json, &status, &body) == 0 && status == 201); + free(body); + ASSERT(http_get_auth(gw_url("/api/cron/page"), token, &status, &body) == 0 && status == 200); + cJSON *page = cJSON_Parse(body); + cJSON *job = cJSON_GetArrayItem(cJSON_GetObjectItem(page, "jobs"), 0); + const char *key = cJSON_GetStringValue(cJSON_GetObjectItem(job, "key")); + const char *name = cJSON_GetStringValue(cJSON_GetObjectItem(job, "id")); + ASSERT(name && !strcmp(name, id) && key && strlen(key) == 255); + snprintf(path, sizeof(path), "/api/cron/job/%s", key); + cJSON_Delete(page); + free(body); + ASSERT(http_delete_auth(gw_url(path), token, &status, &body) == 0 && status == 200); + free(body); + memcpy(id + 125, "xé", sizeof("xé")); + snprintf(json, sizeof(json), "{\"id\":\"%s\",\"schedule\":\"interval:86400\",\"message\":\"note\"}", id); + ASSERT(http_post_auth(gw_url("/api/cron"), token, json, &status, &body) == 0 && status == 400); + free(body); + return 0; +} + +static int test_cron_preview_and_delivery(const char *token) +{ + char *body = NULL; + long status; + const char *schedule = "{\"schedule\":\"at:4070908800\"}"; + ASSERT(http_post_auth(gw_url("/api/cron/preview"), token, schedule, &status, &body) == 0); + cJSON *result = cJSON_Parse(body); + ASSERT(status == 200 && cJSON_GetNumberValue(cJSON_GetObjectItem(result, "next_run")) == 4070908800.0); + cJSON_Delete(result); + free(body); + ASSERT(http_post_auth(gw_url("/api/cron/preview"), token, "{\"schedule\":\"invalid\"}", &status, &body) == 0); + ASSERT(status == 400); + free(body); + ASSERT(http_post_auth(gw_url("/api/cron"), token, + "{\"id\":\"qa-offline\",\"schedule\":\"at:4070908800\",\"channel\":\"telegram\"," + "\"recipient\":\"-10012\",\"message\":\"reminder\"}", &status, &body) == 0 && status == 201); + free(body); + const char *states[] = { "waiting_for_channel", "paused" }; + for (int i = 0; i < 2; i++) { + ASSERT(http_get_auth(gw_url("/api/cron/page"), token, &status, &body) == 0 && status == 200); + result = cJSON_Parse(body); + cJSON *jobs = cJSON_GetObjectItem(result, "jobs"); + ASSERT(cJSON_GetArraySize(jobs) == 1); + cJSON *job = cJSON_GetArrayItem(jobs, 0); + cJSON *state = cJSON_GetObjectItem(job, "delivery_status"); + ASSERT(cJSON_IsString(state) && strcmp(state->valuestring, states[i]) == 0); + cJSON_Delete(result); + free(body); + if (i == 0) { + ASSERT(http_post_auth(gw_url("/api/cron/qa-offline/toggle"), token, "{}", &status, &body) == 0 && status == 200); + free(body); + } + } + ASSERT(http_delete_auth(gw_url("/api/cron/qa-offline"), token, &status, &body) == 0 && status == 200); + free(body); + return 0; +} + static int test_api_cron_create_delete(const char *token) { long code; @@ -1889,6 +2007,9 @@ int main(int argc, char **argv) } if (test_api_memory(token) != 0) { fprintf(stderr, "test_api_memory failed\n"); failed++; } if (test_api_cron_list(token) != 0) { fprintf(stderr, "test_api_cron_list failed\n"); failed++; } + if (test_cron_job_id_bytes(token) != 0) failed++; + if (test_cron_preview_and_delivery(token) != 0) failed++; + if (test_api_cron_pages(token) != 0) failed++; if (test_api_cron_create_delete(token) != 0) { fprintf(stderr, "test_api_cron_create_delete failed\n"); failed++; } if (test_api_cron_toggle_post(token) != 0) { fprintf(stderr, "test_api_cron_toggle_post failed\n"); failed++; } if (test_api_sessions(token) != 0) { fprintf(stderr, "test_api_sessions failed\n"); failed++; } diff --git a/tests/test_memory.c b/tests/test_memory.c index 8b0c7b5..892bd04 100644 --- a/tests/test_memory.c +++ b/tests/test_memory.c @@ -31,6 +31,26 @@ static int test_schema_and_fts5(void) return 0; } +static int test_cron_destination_preview_keeps_complete_characters(void) +{ + char channel[72], recipient[72]; + cron_job_row_t row; + + memset(channel, 'c', 61); + strcpy(channel + 61, "\xf0\xa0\x80\x80"); + memset(recipient, 'r', 62); + strcpy(recipient + 62, "é"); + ASSERT(memory_init(":memory:") == 0); + ASSERT(cron_job_create("old", "interval:60", "Report", channel, recipient, 1, 1) == 0); + ASSERT(cron_job_list_previews("", &row, 1) == 1); + ASSERT(row.channel_truncated && row.recipient_truncated); + ASSERT(strlen(row.channel) == 61 && memcmp(row.channel, channel, 61) == 0); + ASSERT(strlen(row.recipient) == 62 && memcmp(row.recipient, recipient, 62) == 0); + cron_job_row_free(&row); + memory_cleanup(); + return 0; +} + static int test_save_overwrite(void) { const char *path = "/tmp/shellclaw_test_memory2.db"; @@ -215,6 +235,7 @@ static int test_existing_db_preserved_on_open_failure(void) int main(void) { RUN(test_schema_and_fts5()); + RUN(test_cron_destination_preview_keeps_complete_characters()); RUN(test_save_overwrite()); RUN(test_corrupted_db_recreated()); RUN(test_existing_db_preserved_on_open_failure()); diff --git a/tests/test_web_dashboard.js b/tests/test_web_dashboard.js index 4723668..9ae6ffe 100644 --- a/tests/test_web_dashboard.js +++ b/tests/test_web_dashboard.js @@ -202,3 +202,50 @@ testHardwareFetchMocks().then(function () { console.error('FAIL:', err && err.message ? err.message : err); process.exit(1); }); + +async function testDashboardResponseAfterNavigation() { + const location = { protocol: 'http:', host: 'localhost', hash: '#/' }; + const elements = { app: {}, 'mem-q': {}, 'mem-results': {} }; + let navigate; + let release; + let timers = 0; + const response = { ok: true, status: 200, json: async () => ({}) }; + const delayed = new Promise(resolve => { release = resolve; }); + const script = fs.readFileSync(path.join(__dirname, '../web/js/app.js'), 'utf8'); + vm.runInNewContext(script, { + location, ShellClawDashboard: dash, + window: { location, addEventListener: (name, cb) => { if (name === 'hashchange') navigate = cb; }, + setInterval: () => ++timers, clearInterval() {} }, + localStorage: { getItem: () => 'paired-device' }, + document: { getElementById: id => elements[id], querySelectorAll: () => [] }, + WebSocket: function () {}, + fetch: url => url === '/api/status' ? delayed : Promise.resolve(response), + }); + location.hash = '#/memory'; + navigate(); + release(response); + await new Promise(resolve => setImmediate(resolve)); + assert(elements.app.innerHTML.includes('

Memory

'), 'late dashboard response replaced current view'); + assert(timers === 0, 'inactive dashboard started status timers'); +} +testDashboardResponseAfterNavigation().catch(error => { console.error(error); process.exitCode = 1; }); + +async function testSignedManifestCards() { + const location = { hash: '#/asap' }; + const elements = { app: {}, 'asap-content': {} }; + const signed = { manifest: { id: 'urn:asap:agent:test', name: 'Gateway', + capabilities: { asap_version: '2.1.0' } }, signature: { algorithm: 'ed25519' } }; + const script = fs.readFileSync(path.join(__dirname, '../web/js/app.js'), 'utf8'); + vm.runInNewContext(script, { + location, window: { location, addEventListener() {} }, ShellClawDashboard: dash, + document: { getElementById: id => elements[id], querySelectorAll: () => [] }, + localStorage: { getItem: () => 'paired-device' }, + fetch: async url => ({ ok: true, json: async () => url.includes('manifest') ? signed : { entries: [] } }), + }); + await new Promise(resolve => setImmediate(resolve)); + const content = elements['asap-content'].innerHTML; + for (const value of ['urn:asap:agent:test', 'Gateway', '2.1.0']) + assert(content.includes('>' + value + ''), 'missing manifest card ' + value); + assert(content.includes('ed25519'), 'missing original signature'); +} +testSignedManifestCards().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/web/css/style.css b/web/css/style.css index 34fdf85..6e9d355 100644 --- a/web/css/style.css +++ b/web/css/style.css @@ -255,3 +255,10 @@ button.danger { background: #f85149; border-color: #f85149; } } .hw-roadmap-link { color: var(--accent); } .hw-roadmap-link:hover { text-decoration: underline; } + +#cron-create { max-width: 36rem; } +#cron-create label { display: block; margin-top: 0.6rem; } +#cron-create input, #cron-create textarea, #cron-create select { display: block; width: 100%; } +#cron-create button, #cron-jobs button { margin: 0.4rem 0.4rem 0 0; } +#cron-jobs { overflow-x: auto; } +#cron-jobs td { overflow-wrap: anywhere; } diff --git a/web/js/app.js b/web/js/app.js index 34b16f1..52e53e5 100644 --- a/web/js/app.js +++ b/web/js/app.js @@ -90,44 +90,49 @@ if (!token) { window.location.hash = '#/pair'; return; } stopDashboardLive(); render(app, '

Dashboard

Loading live status…

'); + let active = true; + let timer, ctxTimer, ws; + dashboardLiveStop = function () { + active = false; + window.clearInterval(timer); + window.clearInterval(ctxTimer); + if (ws) ws.close(); + }; let lastHealth = {}; let lastStatus = {}; let lastCtx = {}; function paint() { - render(app, dashboardMarkup(lastHealth, lastStatus, lastCtx)); + if (active) render(app, dashboardMarkup(lastHealth, lastStatus, lastCtx)); } Promise.all([ api('GET', '/health'), api('GET', '/api/status'), api('GET', '/api/context/snapshot') ]).then(function (results) { + if (!active) return; lastHealth = results[0] || {}; lastStatus = results[1] || {}; lastCtx = results[2] || {}; paint(); - const timer = window.setInterval(function () { + timer = window.setInterval(function () { api('GET', '/api/status').then(function (st) { lastStatus = st || lastStatus; paint(); }).catch(function () {}); }, 12000); - const ctxTimer = window.setInterval(function () { + ctxTimer = window.setInterval(function () { api('GET', '/api/context/snapshot').then(function (snap) { lastCtx = snap || lastCtx; paint(); }).catch(function () {}); }, 45000); - const ws = wsConnect(function (msg) { + ws = wsConnect(function (msg) { if (!msg || msg.type !== 'provider_status') return; lastStatus = mergeStatusWithWs(lastStatus, msg); paint(); }); - dashboardLiveStop = function () { - window.clearInterval(timer); - window.clearInterval(ctxTimer); - if (ws && ws.readyState === WebSocket.OPEN) ws.close(); - }; }).catch(function (err) { + if (!active) return; render(app, '

Dashboard

' + escapeHtml(err || 'Load failed') + '

'); }); } @@ -184,26 +189,32 @@ function renderSkills() { const token = getToken(); if (!token) { window.location.hash = '#/pair'; return; } + const page = pageVersion; + const list = ++listVersion; + const current = () => page === pageVersion && list === listVersion; + const refresh = () => { if (page === pageVersion) renderSkills(); }; + const reportError = err => { if (page === pageVersion) alert('Error: ' + err); }; api('GET', '/api/skills').then(arr => { + if (!current()) return; let html = '

Skills

' + '

Create skill

'; render(app, html); const ul = document.getElementById('skill-list'); (arr || []).forEach(n => { const li = document.createElement('li'); - li.innerHTML = '' + escapeHtml(n) + 'View '; + li.innerHTML = '' + escapeHtml(n) + 'View '; li.querySelector('[data-delete]').onclick = () => { if (!confirm('Delete ' + n + '?')) return; - api('DELETE', '/api/skills/' + encodeURIComponent(n)).then(() => { window.location.hash = '#/skills'; }); + api('DELETE', '/api/skills/' + encodeURIComponent(n)).then(refresh).catch(reportError); }; ul.appendChild(li); }); document.getElementById('skill-create').onsubmit = function (e) { e.preventDefault(); const f = e.target; - api('POST', '/api/skills', { name: f.name.value, content: f.content.value }).then(() => { window.location.hash = '#/skills'; }); + api('POST', '/api/skills', { name: f.name.value, content: f.content.value }).then(refresh).catch(reportError); }; - }).catch(e => { render(app, '

Skills

' + escapeHtml(e || 'Load failed') + '

'); }); + }).catch(e => { if (current()) render(app, '

Skills

' + escapeHtml(e || 'Load failed') + '

'); }); } function renderSkillView(name) { @@ -236,26 +247,192 @@ function renderSessions() { const token = getToken(); if (!token) { window.location.hash = '#/pair'; return; } + const page = pageVersion; + const list = ++listVersion; + const current = () => page === pageVersion && list === listVersion; + const refresh = () => { if (page === pageVersion) renderSessions(); }; + const reportError = err => { + if (page !== pageVersion) return; + let message = String(err); + try { message = JSON.parse(message).error || message; } catch (_) {} + window.alert(message); + }; api('GET', '/api/sessions').then(arr => { + if (!current()) return; let html = '

Sessions

'; render(app, html); const ul = document.getElementById('session-list'); (arr || []).forEach(id => { const li = document.createElement('li'); - li.innerHTML = '' + escapeHtml(id) + ''; + li.innerHTML = '' + escapeHtml(id) + ''; li.querySelector('[data-delete]').onclick = () => { - api('DELETE', '/api/sessions/' + encodeURIComponent(id)).then(() => { window.location.hash = '#/sessions'; }); + const prompt = id.startsWith('webchat:device:') + ? 'Delete this conversation and its transcript?' : 'Delete session ' + id + '?'; + if (!window.confirm(prompt)) return; + api('DELETE', '/api/sessions/' + encodeURIComponent(id)).then(refresh).catch(reportError); }; ul.appendChild(li); }); - }).catch(e => { render(app, '

Sessions

' + escapeHtml(e || 'Load failed') + '

'); }); + }).catch(e => { if (current()) render(app, '

Sessions

' + escapeHtml(e || 'Load failed') + '

'); }); } function renderCron() { - const token = getToken(); - if (!token) { window.location.hash = '#/pair'; return; } - api('GET', '/api/cron').then(() => {}).catch(() => {}); - render(app, '

Cron

GET /api/cron returns 501 Not Implemented. Placeholder for create/delete/toggle.

'); + if (!getToken()) { window.location.hash = '#/pair'; return; } + render(app, '

Cron

' + + '' + + '

Use interval:seconds, at:unix_time, or five cron fields. The gateway uses its local time. ' + + 'The day of the month and the weekday must both match.

' + + '' + + '' + + '' + + ' ' + + '

' + + '

Scheduled jobs

' + + ' ' + + ''); + const form = document.getElementById('cron-create'); + const fields = form.elements; + const create = form.querySelector('button[type=submit]'); + const preview = document.getElementById('cron-preview'); + const result = document.getElementById('cron-result'); + const jobs = document.getElementById('cron-jobs'); + const prev = document.getElementById('cron-prev'); + const next = document.getElementById('cron-next'); + const cursors = ['']; + let nextAfter = null; + let request = 0; + let previewRequest = 0; + let checkedSchedule = ''; + let saving = false; + + function timeText(seconds) { + const date = new Date(seconds * 1000); + return Number.isFinite(date.getTime()) ? date.toLocaleString(undefined, {timeZoneName:'short'}) : String(seconds); + } + + function showError(error) { + let text = String(error); + try { text = JSON.parse(text).error || text; } catch (_) {} + result.textContent = text; + } + + function cell(row, value) { + row.insertCell().textContent = value; + } + + function action(cell, label, method, path, id) { + const button = document.createElement('button'); + button.type = 'button'; + button.textContent = label; + cell.appendChild(button); + button.onclick = async function () { + if (method === 'DELETE' && !window.confirm('Delete job ' + id + '?')) return; + for (const control of cell.querySelectorAll('button')) control.disabled = true; + try { + await api(method, path, method === 'POST' ? {} : undefined); + result.textContent = ''; + await load(); + } catch (error) { + showError(error); + for (const control of cell.querySelectorAll('button')) control.disabled = false; + } + }; + } + + async function load() { + const revision = ++request; + const after = cursors[cursors.length - 1]; + prev.disabled = next.disabled = true; + try { + const page = await api('GET', '/api/cron/page?after=' + encodeURIComponent(after)); + if (revision !== request) return; + nextAfter = page.next_after; + if (page.jobs.length === 0 && cursors.length > 1) { + cursors.pop(); + return load(); + } + jobs.textContent = ''; + if (page.jobs.length === 0) jobs.textContent = 'No scheduled jobs.'; + else { + const table = document.createElement('table'); + table.className = 'dash-table'; + table.innerHTML = 'JobScheduleMessageDestination' + + 'Next runStatusActions'; + const body = table.createTBody(); + const states = {scheduled:'Scheduled', paused:'Paused', waiting_for_channel:'Waiting for channel', + invalid_destination:'Invalid destination. Create a job with a supported destination.'}; + for (const job of page.jobs) { + const row = body.insertRow(); + cell(row, job.id); + cell(row, job.schedule_preview); + cell(row, job.message_preview); + cell(row, job.channel + ' / ' + job.recipient); + cell(row, timeText(job.next_run)); + cell(row, states[job.delivery_status] || job.delivery_status); + const controls = row.insertCell(); + const path = '/api/cron/job/' + encodeURIComponent(job.key); + if (job.enabled || job.delivery_status !== 'invalid_destination') + action(controls, job.enabled ? 'Pause' : 'Resume', 'POST', path + '/toggle', job.id); + action(controls, 'Delete', 'DELETE', path, job.id); + } + jobs.appendChild(table); + } + } catch (error) { + if (revision !== request) return; + nextAfter = null; + showError(error); + jobs.textContent = 'Could not load the current jobs. '; + const retry = document.createElement('button'); + retry.type = 'button'; + retry.textContent = 'Retry list'; + retry.onclick = () => { result.textContent = ''; load(); }; + jobs.appendChild(retry); + } + prev.disabled = cursors.length === 1; + next.disabled = !nextAfter; + } + prev.onclick = () => { cursors.pop(); load(); }; + next.onclick = () => { cursors.push(nextAfter); load(); }; + + function clearPreview() { + previewRequest++; + checkedSchedule = ''; + create.disabled = true; + preview.textContent = ''; + } + fields.schedule.oninput = clearPreview; + document.getElementById('cron-check').onclick = async function () { + clearPreview(); + const revision = previewRequest; + const schedule = fields.schedule.value.trim(); + result.textContent = ''; + try { + const data = await api('POST', '/api/cron/preview', {schedule}); + if (revision !== previewRequest) return; + checkedSchedule = schedule; + preview.textContent = 'Next run: ' + timeText(data.next_run); + create.disabled = saving; + } catch (error) { if (revision === previewRequest) showError(error); } + }; + form.onsubmit = async function (event) { + event.preventDefault(); + const schedule = fields.schedule.value.trim(); + if (saving || !checkedSchedule || schedule !== checkedSchedule) return; + saving = true; + create.disabled = true; + try { + const data = await api('POST', '/api/cron', {schedule, message:fields.message.value, + channel:fields.channel.value, recipient:fields.recipient.value.trim()}); + result.textContent = 'Created job ' + data.id + '.'; + form.reset(); + clearPreview(); + cursors.length = 1; + await load(); + } catch (error) { showError(error); } + finally { saving = false; create.disabled = !checkedSchedule; } + }; + load(); } function renderLogs() { @@ -286,14 +463,15 @@ .catch(() => null); const logP = api('GET', '/api/asap/log').catch(() => null); Promise.all([manifestP, logP]).then(function (results) { - const manifest = results[0]; + const signedManifest = results[0]; + const manifest = signedManifest && (signedManifest.manifest || signedManifest); const logData = results[1]; let html = ''; /* Dashboard cards */ html += '
'; if (manifest) { - html += '
Agent URN
' + escapeHtml(manifest.urn || manifest.agent_urn || '-') + '
'; - html += '
ASAP Version
' + escapeHtml(manifest.asap_version || '-') + '
'; + html += '
Agent URN
' + escapeHtml(manifest.id || manifest.urn || manifest.agent_urn || '-') + '
'; + html += '
ASAP Version
' + escapeHtml((manifest.capabilities && manifest.capabilities.asap_version) || manifest.asap_version || '-') + '
'; html += '
Agent Name
' + escapeHtml(manifest.name || '-') + '
'; } else { html += '
Manifest
unavailable
'; @@ -301,7 +479,7 @@ html += '
'; /* Manifest detail */ if (manifest) { - html += '

Manifest

' + escapeHtml(JSON.stringify(manifest, null, 2)) + '
'; + html += '

Manifest

' + escapeHtml(JSON.stringify(signedManifest, null, 2)) + '
'; } /* Envelope log table */ html += '

Envelope Log

'; @@ -335,7 +513,10 @@ } const app = document.getElementById('app'); + let pageVersion = 0; + let listVersion = 0; function navigate() { + pageVersion++; stopDashboardLive(); const route = getRoute(); const m = route.match(/^\/skills\/(.+)$/);