From 177386a85fb86fd435ca2382698790ff4e18bf06 Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:32:19 -0300 Subject: [PATCH 01/16] fix(cron): page scheduled jobs without truncating responses --- docs/ARCHITECTURE.md | 10 ++++ src/core/memory.c | 38 ++++++++----- src/core/memory.h | 3 + src/gateway/routes.c | 112 +++++++++++++++++++++++--------------- tests/test_gateway_http.c | 53 ++++++++++++++++++ 5 files changed, 158 insertions(+), 58 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a198f3b..95d5399 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -180,3 +180,13 @@ 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 an ID, URL-encode it and send `GET /api/cron/page?after=ID`. +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. diff --git a/src/core/memory.c b/src/core/memory.c index 91c3567..5ae95eb 100644 --- a/src/core/memory.c +++ b/src/core/memory.c @@ -490,26 +490,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, 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/routes.c b/src/gateway/routes.c index e53b975..64d1b92 100644 --- a/src/gateway/routes.c +++ b/src/gateway/routes.c @@ -564,57 +564,65 @@ 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 }; + +static cJSON *cron_list_item(const cron_job_row_t *row, int preview) { - int i; - if (!rows || n <= 0) return; - for (i = 0; i < n; i++) - cron_job_row_free(&rows[i]); + cJSON *obj = cJSON_CreateObject(); + if (obj && cJSON_AddStringToObject(obj, "id", row->id) && + cJSON_AddStringToObject(obj, preview ? "schedule_preview" : "schedule", row->schedule) && + cJSON_AddStringToObject(obj, preview ? "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)) + return obj; + cJSON_Delete(obj); + return NULL; } -static void handle_cron_list(char *buf, size_t size, int *status) +static void handle_cron_list(const char *after, char *buf, size_t size, int *status) { - 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; } + 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; + 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); 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) { + root = cJSON_CreateObject(); + jobs = root ? cJSON_AddArrayToObject(root, "jobs") : NULL; + if (!jobs || !(n > limit ? cJSON_AddStringToObject(root, "next_after", rows[limit - 1].id) + : 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 != 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_create(const char *body, size_t body_len, char *buf, size_t size, int *status) @@ -1058,11 +1066,25 @@ 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_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)); + if (n >= 128 || (n >= 0 && strlen(after) != (size_t)n)) + json_error(buf, size, status, 400, "Invalid page cursor."); + else + handle_cron_list(n < 0 ? "" : after, buf, size, status); + 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/tests/test_gateway_http.c b/tests/test_gateway_http.c index a1e61bc..acaf0f3 100644 --- a/tests/test_gateway_http.c +++ b/tests/test_gateway_http.c @@ -1362,6 +1362,58 @@ 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[256], cursor[128] = ""; + 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_api_cron_create_delete(const char *token) { long code; @@ -1889,6 +1941,7 @@ 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_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++; } From 9c8ecbff045a3595630d4c29177ad80fc8c1d6e2 Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:35:10 -0300 Subject: [PATCH 02/16] fix(cron): show the next run and channel availability --- docs/ARCHITECTURE.md | 7 +++++++ src/gateway/routes.c | 33 ++++++++++++++++++++++++++++----- src/tools/cron.c | 10 ++++++++++ src/tools/cron.h | 5 +++++ tests/test_gateway_http.c | 39 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 89 insertions(+), 5 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 95d5399..896680a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -190,3 +190,10 @@ 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. diff --git a/src/gateway/routes.c b/src/gateway/routes.c index 64d1b92..e6c582b 100644 --- a/src/gateway/routes.c +++ b/src/gateway/routes.c @@ -566,16 +566,17 @@ static void handle_session_delete(const char *id, char *buf, size_t size, int *s enum { CRON_LEGACY_LIMIT = 64, CRON_PAGE_SIZE = 16 }; -static cJSON *cron_list_item(const cron_job_row_t *row, int preview) +static cJSON *cron_list_item(const cron_job_row_t *row, const char *delivery_state) { cJSON *obj = cJSON_CreateObject(); if (obj && cJSON_AddStringToObject(obj, "id", row->id) && - cJSON_AddStringToObject(obj, preview ? "schedule_preview" : "schedule", row->schedule) && - cJSON_AddStringToObject(obj, preview ? "message_preview" : "message", row->message) && + 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)) + cJSON_AddBoolToObject(obj, "enabled", row->enabled) && + (!delivery_state || cJSON_AddStringToObject(obj, "delivery_status", delivery_state))) return obj; cJSON_Delete(obj); return NULL; @@ -588,9 +589,13 @@ static void handle_cron_list(const char *after, char *buf, size_t size, int *sta cJSON *root = NULL, *jobs; char *serialized = NULL; int n = 0; + const char *states[CRON_PAGE_SIZE]; if (!rows) goto fail; agent_lock(); 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) goto fail; if (!after && n > limit) goto too_large; @@ -604,7 +609,7 @@ static void handle_cron_list(const char *after, char *buf, size_t size, int *sta if (!jobs) goto fail; } for (int i = 0; i < n && i < limit; i++) { - cJSON *item = cron_list_item(&rows[i], after != NULL); + cJSON *item = cron_list_item(&rows[i], after ? states[i] : NULL); if (!item) goto fail; cJSON_AddItemToArray(jobs, item); } @@ -625,6 +630,20 @@ static void handle_cron_list(const char *after, char *buf, size_t size, int *sta free(rows); } +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) { cJSON *root = body ? cJSON_ParseWithLength(body, body_len) : NULL; @@ -1071,6 +1090,10 @@ int dispatch_route(http_server_ctx_t *ctx, struct lws *wsi, int method, 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; diff --git a/src/tools/cron.c b/src/tools/cron.c index 806276c..452ddda 100644 --- a/src/tools/cron.c +++ b/src/tools/cron.c @@ -291,6 +291,16 @@ static cron_target_status_t cron_stored_target(const char *channel, const char * return cron_resolve_target(channel, recipient, CRON_TARGET_STORED, NULL); } +const char *cron_job_delivery_state(const struct cron_job_row *row) +{ + if (!row->enabled) return "paused"; + switch (cron_stored_target(row->channel, row->recipient, row->channel_truncated, row->recipient_truncated)) { + case CRON_TARGET_READY: return "scheduled"; + case CRON_TARGET_DEFERRED: return "waiting_for_channel"; + default: return "invalid_destination"; + } +} + int cron_create_job(const char *schedule, const char *message, const char *channel, const char *recipient, char *id_out, size_t id_size) diff --git a/src/tools/cron.h b/src/tools/cron.h index a45caa1..f578752 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. diff --git a/tests/test_gateway_http.c b/tests/test_gateway_http.c index acaf0f3..ce89696 100644 --- a/tests/test_gateway_http.c +++ b/tests/test_gateway_http.c @@ -1414,6 +1414,44 @@ static int test_api_cron_pages(const char *token) 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; @@ -1941,6 +1979,7 @@ 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_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++; } From 6f24539ed866e29edf684ac8a89e64a2e6540a7c Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:48:55 -0300 Subject: [PATCH 03/16] fix(cron): preserve full job IDs in pages and actions --- docs/ARCHITECTURE.md | 3 +- src/gateway/http_lws.c | 8 ++-- src/gateway/routes.c | 87 +++++++++++++++++++++++++++++++++++---- tests/test_gateway_http.c | 31 +++++++++++++- 4 files changed, 117 insertions(+), 12 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 896680a..4f12a56 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -185,7 +185,8 @@ Never commit credentials; use `.env.example` as reference. 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 an ID, URL-encode it and send `GET /api/cron/page?after=ID`. +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. 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 e6c582b..243574d 100644 --- a/src/gateway/routes.c +++ b/src/gateway/routes.c @@ -566,10 +566,58 @@ static void handle_session_delete(const char *id, char *buf, size_t size, int *s 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]) +{ + 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 int cron_decode_key(const char *key, char id[128]) +{ + 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(); - if (obj && cJSON_AddStringToObject(obj, "id", row->id) && + 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) && @@ -600,9 +648,11 @@ static void handle_cron_list(const char *after, char *buf, size_t size, int *sta 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", rows[limit - 1].id) + if (!jobs || !(n > limit ? cJSON_AddStringToObject(root, "next_after", next) : cJSON_AddNullToObject(root, "next_after"))) goto fail; } else { root = jobs = cJSON_CreateArray(); @@ -659,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; @@ -1102,10 +1157,28 @@ int dispatch_route(http_server_ctx_t *ctx, struct lws *wsi, int method, return 0; } if (wsi) n = lws_get_urlarg_by_name_safe(wsi, "after=", after, sizeof(after)); - if (n >= 128 || (n >= 0 && strlen(after) != (size_t)n)) + 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 ? "" : after, buf, size, status); + 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/")) { diff --git a/tests/test_gateway_http.c b/tests/test_gateway_http.c index ce89696..e6b8b47 100644 --- a/tests/test_gateway_http.c +++ b/tests/test_gateway_http.c @@ -1364,7 +1364,7 @@ static int test_api_cron_list(const char *token) static int test_api_cron_pages(const char *token) { - char message[6001], json[6500], path[256], cursor[128] = ""; + char message[6001], json[6500], path[512], cursor[256] = ""; char *body = NULL; long status; int seen = 0; @@ -1414,6 +1414,34 @@ static int test_api_cron_pages(const char *token) 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; @@ -1979,6 +2007,7 @@ 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++; } From 326a1c5b1c2f0e3482098851631ce8163d1073a5 Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:44:10 -0300 Subject: [PATCH 04/16] fix(cron): reject invalid absolute times and extra fields --- src/tools/cron.c | 8 +++++--- tests/test_cron.c | 3 +++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/tools/cron.c b/src/tools/cron.c index 452ddda..ca2416b 100644 --- a/src/tools/cron.c +++ b/src/tools/cron.c @@ -89,9 +89,10 @@ 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; + if (n != 5 || p) return -1; int lo, hi; if (parse_range(tokens[0], &lo, &hi, 0, 59) != 0) return -1; fields[0] = lo; fields[1] = hi; @@ -162,8 +163,9 @@ 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; } diff --git a/tests/test_cron.c b/tests/test_cron.c index 34c1817..c45e9bc 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); From 0f11cf955bff1989ced45198af39fbf931a6ac58 Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:49:24 -0300 Subject: [PATCH 05/16] fix(cron): manage scheduled jobs from the dashboard --- web/css/style.css | 7 +++ web/js/app.js | 153 ++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 156 insertions(+), 4 deletions(-) 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..144cd8a 100644 --- a/web/js/app.js +++ b/web/js/app.js @@ -252,10 +252,155 @@ } function renderCron() { - const token = getToken(); - if (!token) { window.location.hash = '#/pair'; return; } - api('GET', '/api/cron').then(() => {}).catch(() => {}); - render(app, '
GET /api/cron returns 501 Not Implemented. Placeholder for create/delete/toggle.
'); + if (!getToken()) { window.location.hash = '#/pair'; return; } + render(app, '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, '' + escapeHtml(err || 'Load failed') + '
'); }); } From 5d75db3716922cc60b6582d866828fd4729d917e Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:35:36 -0300 Subject: [PATCH 08/16] fix(dashboard): refresh skills and sessions after changes --- src/gateway/routes.c | 2 +- tests/test_gateway_http.c | 2 +- web/js/app.js | 21 ++++++++++++++------- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/gateway/routes.c b/src/gateway/routes.c index 243574d..175e0b9 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, diff --git a/tests/test_gateway_http.c b/tests/test_gateway_http.c index e6b8b47..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); diff --git a/web/js/app.js b/web/js/app.js index db5cbaf..8f1b5a6 100644 --- a/web/js/app.js +++ b/web/js/app.js @@ -189,26 +189,28 @@ function renderSkills() { const token = getToken(); if (!token) { window.location.hash = '#/pair'; return; } + const page = pageVersion; api('GET', '/api/skills').then(arr => { + if (page !== pageVersion) return; let html = '' + escapeHtml(e || 'Load failed') + '
'); }); + }).catch(e => { if (page === pageVersion) render(app, '' + escapeHtml(e || 'Load failed') + '
'); }); } function renderSkillView(name) { @@ -241,19 +243,22 @@ function renderSessions() { const token = getToken(); if (!token) { window.location.hash = '#/pair'; return; } + const page = pageVersion; api('GET', '/api/sessions').then(arr => { + if (page !== pageVersion) return; let html = '' + escapeHtml(e || 'Load failed') + '
'); }); + }).catch(e => { if (page === pageVersion) render(app, '' + escapeHtml(e || 'Load failed') + '
'); }); } function renderCron() { @@ -491,7 +496,9 @@ } const app = document.getElementById('app'); + let pageVersion = 0; function navigate() { + pageVersion++; stopDashboardLive(); const route = getRoute(); const m = route.match(/^\/skills\/(.+)$/); From 6334aeb29944163ed81bb54196e25b33aabd3361 Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:36:04 -0300 Subject: [PATCH 09/16] fix(dashboard): read agent details from the signed manifest --- tests/test_web_dashboard.js | 20 ++++++++++++++++++++ web/js/app.js | 9 +++++---- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/tests/test_web_dashboard.js b/tests/test_web_dashboard.js index 5ca02e6..9cc2be5 100644 --- a/tests/test_web_dashboard.js +++ b/tests/test_web_dashboard.js @@ -49,6 +49,26 @@ async function testDashboardResponseAfterNavigation() { } 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; }); + function testPairedChatDisplaysRepliesAsText() { let connection; const location = { protocol: 'https:', host: 'localhost', hash: '#/chat' }; diff --git a/web/js/app.js b/web/js/app.js index 8f1b5a6..f260194 100644 --- a/web/js/app.js +++ b/web/js/app.js @@ -447,14 +447,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 += '' + escapeHtml(JSON.stringify(manifest, null, 2)) + ''; + html += '
' + escapeHtml(JSON.stringify(signedManifest, null, 2)) + ''; } /* Envelope log table */ html += '
' + escapeHtml(e || 'Load failed') + '
'); }); + }).catch(e => { if (current()) render(app, '' + escapeHtml(e || 'Load failed') + '
'); }); } function renderSkillView(name) { @@ -244,8 +248,12 @@ 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) alert('Error: ' + err); }; api('GET', '/api/sessions').then(arr => { - if (page !== pageVersion) return; + if (!current()) return; let html = '' + escapeHtml(e || 'Load failed') + '
'); }); + }).catch(e => { if (current()) render(app, '' + escapeHtml(e || 'Load failed') + '
'); }); } function renderCron() { @@ -498,6 +506,7 @@ const app = document.getElementById('app'); let pageVersion = 0; + let listVersion = 0; function navigate() { pageVersion++; stopDashboardLive(); From 4ec6643e86ddc8dfb13dcdecdff03692a814186b Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:54:50 -0300 Subject: [PATCH 11/16] fix(dashboard): explain what deleting a conversation removes --- tests/test_web_dashboard.js | 94 ++++++++++++++++++------------------- web/js/app.js | 11 ++++- 2 files changed, 56 insertions(+), 49 deletions(-) diff --git a/tests/test_web_dashboard.js b/tests/test_web_dashboard.js index 9cc2be5..c262c72 100644 --- a/tests/test_web_dashboard.js +++ b/tests/test_web_dashboard.js @@ -22,53 +22,6 @@ function assert(cond, msg) { } } -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: (_, cb) => { 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('