diff --git a/Makefile b/Makefile index 503cce1..3042718 100644 --- a/Makefile +++ b/Makefile @@ -97,6 +97,7 @@ CHANNEL_WEBCHAT_O := $(if $(filter 1,$(GATEWAY)),src/channels/webchat.o,) STATIC_O := $(if $(filter 1,$(GATEWAY)),src/gateway/static.o,) HTTP_O := $(if $(filter 1,$(GATEWAY)),src/gateway/http.o,) HTTP_LWS_O := $(if $(filter 1,$(GATEWAY)),src/gateway/http_lws.o,) +ROUTES_WEBCHAT_O := $(if $(filter 1,$(GATEWAY)),src/gateway/routes_webchat.o,) ROUTES_O := $(if $(filter 1,$(GATEWAY)),src/gateway/routes.o,) ROUTES_HARDWARE_O := $(if $(filter 1,$(GATEWAY)),src/gateway/routes_hardware.o,) WS_O := $(if $(filter 1,$(GATEWAY)),src/gateway/ws.o,) @@ -173,7 +174,7 @@ OBJS := $(CORE_OBJS) $(VENDOR_OBJS) PROVIDER_OBJS := $(PROVIDER_COMMON_O) $(STUB_O) $(ROUTER_O) $(ANTHROPIC_O) $(OPENAI_COMPAT_O) $(OPENAI_O) $(LOCAL_O) CHANNEL_OBJS := $(CHANNEL_COMMON_O) $(CHANNEL_CLI_O) $(CHANNEL_TG_O) $(CHANNEL_DISCORD_O) $(DISCORD_HELPERS_O) $(CHANNEL_HEARTBEAT_O) $(CHANNEL_WEBCHAT_O) ASAP_HTTP_BODY_O := $(if $(filter 1,$(GATEWAY)),src/gateway/asap_http_body.o,) -GATEWAY_OBJS := $(AUTH_O) $(STATIC_O) $(HTTP_O) $(HTTP_LWS_O) $(ASAP_HTTP_BODY_O) $(ROUTES_O) $(ROUTES_HARDWARE_O) $(WS_O) $(RATE_LIMIT_O) +GATEWAY_OBJS := $(AUTH_O) $(STATIC_O) $(HTTP_O) $(HTTP_LWS_O) $(ASAP_HTTP_BODY_O) $(ROUTES_O) $(ROUTES_HARDWARE_O) $(ROUTES_WEBCHAT_O) $(WS_O) $(RATE_LIMIT_O) GATEWAY_OBJS += $(if $(filter 1,$(GATEWAY)),$(WS_RX_O)) TOOL_OBJS := $(SHELL_O) $(WEBSEARCH_O) $(FILE_O) $(REGISTRY_O) $(CONTEXT_O) $(CONTEXT_CACHE_O) $(CONTEXT_HTTP_O) $(CONTEXT_GEO_O) $(CRYPTO_LINK) $(HARDWARE_STUB_O) $(HARDWARE_INIT_O) $(HARDWARE_GPIO_SNAPSHOT_O) $(HARDWARE_TEGRASTATS_O) $(HARDWARE_TOOLS_O) $(BOARD_DETECT_O) $(HARDWARE_I2C_O) $(HARDWARE_CAMERA_O) $(HARDWARE_LIBGPIOD_O) $(CRON_O) $(ASAP_INVOKE_O) ASAP_OBJS := $(MANIFEST_O) $(MANIFEST_PROFILES_O) $(MANIFEST_BUILD_O) $(MANIFEST_SIGN_O) $(MANIFEST_KEYS_O) $(JCS_O) $(ENVELOPE_O) $(ULID_O) $(CLIENT_O) $(ASAP_REGISTRY_O) $(SERVER_O) $(ASAP_LOG_O) @@ -227,7 +228,7 @@ $(RELOAD_CHANNEL_STUB_O): tests/stubs/reload_channel_stub.c src/channels/channel $(HTTP_RELOAD_STUB_O): tests/stubs/http_reload_stub.c src/gateway/http.h src/core/config.h $(CC) $(CFLAGS) $(INC) -c -o $@ tests/stubs/http_reload_stub.c -$(DISPATCH_O): src/core/dispatch.c src/core/dispatch.h src/core/agent.h src/core/bootstrap.h src/core/memory.h src/channels/channel.h src/channels/heartbeat.h src/tools/cron.h +$(DISPATCH_O): src/core/dispatch.c src/channels/webchat.h src/core/dispatch.h src/core/agent.h src/core/bootstrap.h src/core/memory.h src/channels/channel.h src/channels/heartbeat.h src/tools/cron.h $(CC) $(CFLAGS) $(INC) -c -o $@ src/core/dispatch.c $(TOML_O): vendor/tomlc99/toml.c vendor/tomlc99/toml.h @@ -309,7 +310,7 @@ $(HEARTBEAT_TEST_O): src/channels/heartbeat.c src/channels/heartbeat.h src/chann @mkdir -p $(BINDIR) $(CC) $(CFLAGS) $(INC) -DSHELLCLAW_TEST -c -o $@ src/channels/heartbeat.c -$(CHANNEL_WEBCHAT_O): src/channels/webchat.c src/channels/channel.h src/channels/webchat.h src/core/config.h +$(CHANNEL_WEBCHAT_O): src/channels/webchat.c src/channels/channel.h src/channels/webchat.h src/core/config.h src/core/memory.h src/crypto/crypto.h src/gateway/ws.h $(CC) $(CFLAGS) $(INC) $(GATEWAY_CFLAGS) -c -o $@ src/channels/webchat.c $(AUTH_O): src/gateway/auth.c src/gateway/auth.h src/core/config.h src/crypto/crypto.h @@ -373,13 +374,16 @@ $(ASAP_REGISTRY_TEST_O): src/asap/registry.c src/asap/registry.h src/asap/client $(RATE_LIMIT_O): src/gateway/rate_limit.c src/gateway/rate_limit.h $(CC) $(CFLAGS) $(INC) -pthread -c -o $@ src/gateway/rate_limit.c -$(HTTP_O): src/gateway/http.c src/gateway/http.h src/gateway/http_lws.h src/gateway/ws.h src/gateway/ws_rx.h src/providers/provider.h +$(HTTP_O): src/gateway/http.c src/core/memory.h src/gateway/http.h src/gateway/http_lws.h src/gateway/ws.h src/gateway/ws_rx.h src/providers/provider.h $(CC) $(CFLAGS) $(INC) $(GATEWAY_CFLAGS) -pthread -c -o $@ src/gateway/http.c -$(HTTP_LWS_O): src/gateway/http_lws.c src/gateway/http_lws.h src/gateway/asap_http_body.h src/gateway/routes.h src/gateway/auth.h src/gateway/static.h src/gateway/ws.h src/gateway/ws_rx.h +$(HTTP_LWS_O): src/gateway/http_lws.c src/gateway/routes_webchat.h src/gateway/http_lws.h src/gateway/asap_http_body.h src/gateway/routes.h src/gateway/auth.h src/gateway/static.h src/gateway/ws.h src/gateway/ws_rx.h $(CC) $(CFLAGS) $(INC) $(GATEWAY_CFLAGS) -pthread -c -o $@ src/gateway/http_lws.c -$(ROUTES_O): src/gateway/routes.c src/gateway/routes.h src/gateway/routes_hardware.h src/gateway/http.h src/gateway/http_lws.h src/gateway/auth.h src/gateway/rate_limit.h src/tools/context.h src/asap/manifest.h src/asap/envelope.h src/asap/server.h src/asap/log.h src/core/bootstrap.h src/core/agent.h src/core/config.h src/core/config_patch.h src/core/dispatch.h src/core/reload.h src/core/memory.h src/core/skill.h src/providers/provider.h src/channels/channel.h src/tools/cron.h src/tools/tool.h +$(ROUTES_WEBCHAT_O): src/gateway/routes_webchat.c src/gateway/routes_webchat.h src/gateway/routes.h src/channels/webchat.h src/core/memory.h src/vendor/tweetnacl/tweetnacl.h + $(CC) $(CFLAGS) $(INC) $(GATEWAY_CFLAGS) -c -o $@ $< + +$(ROUTES_O): src/gateway/routes.c src/gateway/routes_webchat.h src/gateway/routes.h src/gateway/routes_hardware.h src/gateway/http.h src/gateway/http_lws.h src/gateway/auth.h src/gateway/rate_limit.h src/tools/context.h src/asap/manifest.h src/asap/envelope.h src/asap/server.h src/asap/log.h src/core/bootstrap.h src/core/agent.h src/core/config.h src/core/config_patch.h src/core/dispatch.h src/core/reload.h src/core/memory.h src/core/skill.h src/providers/provider.h src/channels/channel.h src/tools/cron.h src/tools/tool.h $(CC) $(CFLAGS) $(INC) $(GATEWAY_CFLAGS) -pthread -c -o $@ src/gateway/routes.c $(ROUTES_HARDWARE_O): src/gateway/routes_hardware.c src/gateway/routes_hardware.h src/gateway/routes.h src/gateway/http_lws.h src/gateway/uri_match.h src/hardware/hardware.h src/hardware/hardware_gpio_snapshot.h src/hardware/hardware_tegrastats.h src/hardware/board_detect.h src/core/config.h @@ -748,13 +752,13 @@ test_asap_invoke: tests/test_asap_invoke.c $(ASAP_INVOKE_TEST_O) $(ASAP_REGISTRY $(CC) $(CFLAGS) $(LDFLAGS) $(INC) -DSHELLCLAW_ASAP_INVOKE_TEST -DSHELLCLAW_REGISTRY_TEST -o $(BINDIR)/$@ tests/test_asap_invoke.c $(ASAP_INVOKE_TEST_O) $(ASAP_REGISTRY_TEST_O) $(CLIENT_O) $(ENVELOPE_O) $(ULID_O) $(CRYPTO_LINK) $(CJSON_O) $(PROVIDER_COMMON_O) $(CONFIG_O) $(TOML_O) $(LDLIBS) $(DSYM_SCRIPT) -test_gateway_http: shellclaw tests/test_gateway_http.c $(AUTH_O) $(CONFIG_O) $(TOML_O) $(CJSON_O) +test_gateway_http: shellclaw tests/test_gateway_http.c $(AUTH_O) $(CONFIG_O) $(TOML_O) $(CJSON_O) $(SQLITE3_O) @if [ "$(GATEWAY)" != "1" ]; then \ if [ "$(CI)" = "true" ]; then echo "test_gateway_http: GATEWAY=0 in CI — install libwebsockets-dev"; exit 1; fi; \ echo "test_gateway_http: skipped (GATEWAY=0)"; exit 0; \ fi @mkdir -p $(BINDIR) - $(CC) $(CFLAGS) $(LDFLAGS) $(INC) -DSHELLCLAW_GATEWAY -pthread -o $(BINDIR)/$@ tests/test_gateway_http.c $(AUTH_O) $(CRYPTO_LINK) $(CONFIG_O) $(TOML_O) $(CJSON_O) $(LDLIBS) -pthread + $(CC) $(CFLAGS) $(LDFLAGS) $(INC) -DSHELLCLAW_GATEWAY -pthread -o $(BINDIR)/$@ tests/test_gateway_http.c $(AUTH_O) $(CRYPTO_LINK) $(CONFIG_O) $(TOML_O) $(CJSON_O) $(SQLITE3_O) $(LDLIBS) -pthread $(DSYM_SCRIPT) GATEWAY_DB_LOCK_OBJS := $(filter-out src/core/main.o,$(SHELLCLAW_OBJS)) @@ -945,7 +949,7 @@ clean-root-dsym: @rm -f shellclaw test_agent test_anthropic test_channel test_cli test_config test_file test_memory test_local_provider test_openai test_provider test_router test_shell test_skill test_telegram test_web_search test_ws clean: clean-root-dsym - rm -f $(OBJS) $(PROVIDER_COMMON_O) $(STUB_O) $(ANTHROPIC_O) $(OPENAI_COMPAT_O) $(OPENAI_O) $(LOCAL_O) $(ROUTER_O) $(CJSON_O) $(TWEETNACL_O) $(ANTHROPIC_TEST_O) $(OPENAI_TEST_O) $(LOCAL_TEST_O) $(CONTEXT_TEST_OBJS) $(HEARTBEAT_TEST_O) $(CHANNEL_TG_TEST_O) $(CHANNEL_COMMON_O) $(CHANNEL_STUB_O) $(CHANNEL_CLI_O) $(CHANNEL_TG_O) $(CHANNEL_DISCORD_O) $(DISCORD_HELPERS_O) $(CHANNEL_HEARTBEAT_O) $(CHANNEL_WEBCHAT_O) $(AUTH_O) $(STATIC_O) $(HTTP_O) $(HTTP_LWS_O) $(ASAP_HTTP_BODY_O) $(ROUTES_O) $(ROUTES_HARDWARE_O) $(WS_O) $(MANIFEST_O) $(MANIFEST_PROFILES_O) $(MANIFEST_BUILD_O) $(MANIFEST_SIGN_O) $(MANIFEST_KEYS_O) $(ENVELOPE_O) $(ULID_O) $(CLIENT_O) $(ASAP_REGISTRY_O) $(SERVER_O) $(ASAP_LOG_O) $(RATE_LIMIT_O) $(SHELL_O) $(WEBSEARCH_O) $(FILE_O) $(REGISTRY_O) $(CONTEXT_O) $(CONTEXT_CACHE_O) $(CONTEXT_HTTP_O) $(CONTEXT_GEO_O) $(CRYPTO_O) $(JCS_O) $(HARDWARE_STUB_O) $(HARDWARE_INIT_O) $(HARDWARE_GPIO_SNAPSHOT_O) $(HARDWARE_TEGRASTATS_O) $(HARDWARE_TOOLS_O) $(BOARD_DETECT_O) src/hardware/hardware_libgpiod.o $(HARDWARE_I2C_O) $(HARDWARE_CAMERA_O) $(CRON_O) $(ASAP_INVOKE_O) $(SANDBOX_CORE_O) $(SANDBOX_LANDLOCK_O) $(SANDBOX_ENV_O) $(ALLOWLIST_SCAN_O) $(ALLOWLIST_PATH_O) + rm -f $(OBJS) $(PROVIDER_COMMON_O) $(STUB_O) $(ANTHROPIC_O) $(OPENAI_COMPAT_O) $(OPENAI_O) $(LOCAL_O) $(ROUTER_O) $(CJSON_O) $(TWEETNACL_O) $(ANTHROPIC_TEST_O) $(OPENAI_TEST_O) $(LOCAL_TEST_O) $(CONTEXT_TEST_OBJS) $(HEARTBEAT_TEST_O) $(CHANNEL_TG_TEST_O) $(CHANNEL_COMMON_O) $(CHANNEL_STUB_O) $(CHANNEL_CLI_O) $(CHANNEL_TG_O) $(CHANNEL_DISCORD_O) $(DISCORD_HELPERS_O) $(CHANNEL_HEARTBEAT_O) $(CHANNEL_WEBCHAT_O) $(AUTH_O) $(STATIC_O) $(HTTP_O) $(HTTP_LWS_O) $(ASAP_HTTP_BODY_O) $(ROUTES_O) $(ROUTES_HARDWARE_O) $(ROUTES_WEBCHAT_O) $(WS_O) $(MANIFEST_O) $(MANIFEST_PROFILES_O) $(MANIFEST_BUILD_O) $(MANIFEST_SIGN_O) $(MANIFEST_KEYS_O) $(ENVELOPE_O) $(ULID_O) $(CLIENT_O) $(ASAP_REGISTRY_O) $(SERVER_O) $(ASAP_LOG_O) $(RATE_LIMIT_O) $(SHELL_O) $(WEBSEARCH_O) $(FILE_O) $(REGISTRY_O) $(CONTEXT_O) $(CONTEXT_CACHE_O) $(CONTEXT_HTTP_O) $(CONTEXT_GEO_O) $(CRYPTO_O) $(JCS_O) $(HARDWARE_STUB_O) $(HARDWARE_INIT_O) $(HARDWARE_GPIO_SNAPSHOT_O) $(HARDWARE_TEGRASTATS_O) $(HARDWARE_TOOLS_O) $(BOARD_DETECT_O) src/hardware/hardware_libgpiod.o $(HARDWARE_I2C_O) $(HARDWARE_CAMERA_O) $(CRON_O) $(ASAP_INVOKE_O) $(SANDBOX_CORE_O) $(SANDBOX_LANDLOCK_O) $(SANDBOX_ENV_O) $(ALLOWLIST_SCAN_O) $(ALLOWLIST_PATH_O) rm -f src/gateway/ui_assets.h $(WS_RX_O) $(BINDIR)/test_ws_rx find . -name '*.gcno' -o -name '*.gcda' -o -name '*.gcov' | xargs rm -f 2>/dev/null || true rm -f $(WS_TEST_O) $(SANDBOX_TEST_O) $(BINDIR)/asap_registry_test.o $(BINDIR)/asap_invoke_test.o $(CONTEXT_TEST_OBJS) $(HEARTBEAT_TEST_O) $(BINDIR)/shellclaw $(BINDIR)/test_tweetnacl_smoke $(BINDIR)/test_config $(BINDIR)/test_config_patch $(BINDIR)/test_memory $(BINDIR)/test_skill $(BINDIR)/test_provider $(BINDIR)/test_anthropic $(BINDIR)/test_openai $(BINDIR)/test_local_provider $(BINDIR)/test_router $(BINDIR)/test_heartbeat $(BINDIR)/test_crypto $(BINDIR)/test_hardware_stub $(BINDIR)/test_board_detect $(BINDIR)/test_hardware_libgpiod $(BINDIR)/test_hardware_i2c $(BINDIR)/test_hardware_camera $(BINDIR)/test_pin_tables $(BINDIR)/test_hardware_init $(BINDIR)/test_hardware_tools $(BINDIR)/test_registry $(BINDIR)/test_ws $(BINDIR)/test_agent $(BINDIR)/test_channel $(BINDIR)/test_cli $(BINDIR)/test_shell $(BINDIR)/test_file $(BINDIR)/test_telegram $(BINDIR)/test_discord_helpers $(BINDIR)/test_web_search $(BINDIR)/test_cron $(BINDIR)/test_context $(BINDIR)/test_manifest_build $(BINDIR)/test_manifest_keys $(BINDIR)/test_jcs $(BINDIR)/test_asap_envelope $(BINDIR)/test_asap_ulid $(BINDIR)/test_asap_client $(BINDIR)/test_asap_registry $(BINDIR)/test_asap_server $(BINDIR)/test_asap_invoke $(BINDIR)/test_asap_log $(BINDIR)/test_auth $(BINDIR)/test_gateway_http $(BINDIR)/test_gateway_db_lock $(BINDIR)/test_static $(BINDIR)/test_sandbox $(BINDIR)/test_allowlist $(BINDIR)/test_rate_limit diff --git a/README.md b/README.md index bbc1cf5..f7b5679 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,13 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for PR workflow, coding standards, and th **Jetson install (v1.0):** `./scripts/install.sh`, `./scripts/build_llama_jetson.sh`, `./scripts/download_model.sh phi3` — details in [`docs/HARDWARE_JETSON.md`](docs/HARDWARE_JETSON.md) and [`docs/LOCAL_INFERENCE.md`](docs/LOCAL_INFERENCE.md). +**Pair another device.** On the gateway host, confirm that the new device needs access. +Send `SIGUSR1` to the running gateway with `kill -USR1 `. +For the systemd user service, run `systemctl --user kill --kill-whom=main --signal=SIGUSR1 shellclaw.service`. +Read the new code in the gateway console or service journal. +Enter the code on the Pair page within five minutes. The code expires after one use or a gateway restart. +The gateway keeps existing devices paired and accepts up to 16 devices. + **WebSocket authentication.** Pair with the gateway before opening `/ws`. For a browser client, offer both `ws` and `bearer.` as subprotocols. The gateway selects `ws` and reads the token from the other entry. For a native client, offer `ws` and send the token in `Authorization: Bearer `. **Debug (macOS):** Symbols in `tests-dSYM/`. Use `lldb build/test_agent` then `settings set target.debug-file-search-path tests-dSYM`. Old `.dSYM` in repo root? Run `make clean-root-dsym`. diff --git a/src/channels/channel.h b/src/channels/channel.h index cb64cb8..7d1ee61 100644 --- a/src/channels/channel.h +++ b/src/channels/channel.h @@ -7,6 +7,7 @@ #define SHELLCLAW_CHANNEL_H #include +#include #ifdef __cplusplus extern "C" { @@ -32,6 +33,7 @@ typedef struct channel_incoming_msg { char *text; /**< Message text (may be empty for photo-only) */ channel_attachment_t *attachments; size_t attachments_count; + int64_t turn_seq; /**< Persistent turn sequence, or 0 if absent. */ } channel_incoming_msg_t; /** Clear and free incoming message fields. Safe to call repeatedly or on zeroed. */ @@ -122,6 +124,8 @@ typedef struct channel { const channel_attachment_t *attachments, size_t att_count); /** Release channel resources. */ void (*cleanup)(void); + /** Optional. Reply to a specific incoming message. Return 0 on success. */ + int (*reply)(const channel_incoming_msg_t *msg, const char *text); } channel_t; #define MAX_REGISTERED_CHANNELS 8 diff --git a/src/channels/channel_common.c b/src/channels/channel_common.c index bb362a2..d147c2d 100644 --- a/src/channels/channel_common.c +++ b/src/channels/channel_common.c @@ -109,6 +109,7 @@ void channel_incoming_msg_clear(channel_incoming_msg_t *msg) msg->user_id = NULL; free(msg->text); msg->text = NULL; + msg->turn_seq = 0; if (msg->attachments) { for (size_t i = 0; i < msg->attachments_count; i++) free(msg->attachments[i].path_or_base64); diff --git a/src/channels/webchat.c b/src/channels/webchat.c index 2dbc5d6..809b72e 100644 --- a/src/channels/webchat.c +++ b/src/channels/webchat.c @@ -1,6 +1,6 @@ /** * @file webchat.c - * @brief WebChat channel: poll from WS queue, send to WS connection. + * @brief Process WebChat turns and messages from native WebSocket clients. */ #define _POSIX_C_SOURCE 200809L @@ -8,15 +8,52 @@ #include "channels/webchat.h" #include "gateway/ws.h" #include "core/config.h" +#include "core/memory.h" +#include "crypto/crypto.h" +#include #include #include #include #define WEBCHAT_USER_ID "webchat" +#define NATIVE_SESSION_PREFIX "webchat:socket:" +#define WS_SESSION_PREFIX "webchat:" + +static char g_native_prefix[sizeof(NATIVE_SESSION_PREFIX) + 17]; +static int g_prefer_socket; +static int64_t g_pending_seq; +static char g_pending_reply[WS_TEXT_BUF_SIZE]; + +static int webchat_flush_reply(void) +{ + if (!g_pending_seq) return 0; + int rc = webchat_store_finish(g_pending_seq, g_pending_reply); + if (rc >= 0) { + g_pending_seq = 0; + g_pending_reply[0] = '\0'; + } + return rc; +} + +static int webchat_complete_turn(int64_t seq, const char *reply) +{ + size_t size = strlen(reply) + 1; + if (g_pending_seq || size > sizeof(g_pending_reply)) return -1; + g_pending_seq = seq; + memcpy(g_pending_reply, reply, size); + int rc = webchat_flush_reply(); + if (rc < 0) + fprintf(stderr, "Cannot save the WebChat reply. The gateway will retry.\n"); + return rc; +} static int webchat_init(const config_t *cfg) { (void)cfg; + uint64_t id; + if (crypto_read_urandom(&id, sizeof(id)) != 0) return -1; + snprintf(g_native_prefix, sizeof(g_native_prefix), NATIVE_SESSION_PREFIX "%016" PRIx64 ":", id); + g_prefer_socket = 0; return 0; } @@ -25,18 +62,36 @@ static int webchat_poll(channel_incoming_msg_t *out, int timeout_ms) if (!out) return -1; memset(out, 0, sizeof(*out)); char session_id[128]; + char socket_session[32]; char text[WS_TEXT_BUF_SIZE]; - int r = ws_pop_incoming(session_id, sizeof(session_id), text, sizeof(text), timeout_ms); - if (r != 1) return r; + int64_t seq = 0; + int r = 0; + if (g_prefer_socket) + r = ws_pop_incoming(socket_session, sizeof(socket_session), text, sizeof(text), 0); + /* Hold at most one calculated reply while its write is pending. */ + if (r == 0 && webchat_flush_reply() >= 0) + r = webchat_store_claim(&seq, session_id, sizeof(session_id), text, sizeof(text)); + if (r != 1) { + if (r < 0) fprintf(stderr, "Cannot read the WebChat queue.\n"); + r = ws_pop_incoming(socket_session, sizeof(socket_session), text, sizeof(text), timeout_ms); + if (r != 1) return r; + } + if (!seq) { + /* Connection numbers can repeat after restart. Give each run its own prefix. */ + snprintf(session_id, sizeof(session_id), "%s%s", g_native_prefix, + socket_session + sizeof(WS_SESSION_PREFIX) - 1); + } + g_prefer_socket = seq != 0; out->session_id = strdup(session_id); out->user_id = strdup(WEBCHAT_USER_ID); out->text = strdup(text); out->attachments = NULL; out->attachments_count = 0; + out->turn_seq = seq; if (!out->session_id || !out->user_id || !out->text) { - free(out->session_id); - free(out->user_id); - free(out->text); + if (seq) + webchat_complete_turn(seq, "Cannot process the message."); + channel_incoming_msg_clear(out); return -1; } return 1; @@ -48,11 +103,29 @@ static int webchat_send(const char *recipient, const char *text, (void)attachments; (void)att_count; if (!recipient || !text) return -1; - return ws_send_to(recipient, text); + size_t prefix_size = strlen(g_native_prefix); + if (!prefix_size || strncmp(recipient, g_native_prefix, prefix_size) != 0) + return -1; + char socket_session[32]; + int n = snprintf(socket_session, sizeof(socket_session), WS_SESSION_PREFIX "%s", + recipient + prefix_size); + if (n < 0 || (size_t)n >= sizeof(socket_session)) return -1; + return ws_send_to(socket_session, text); +} + +static int webchat_reply(const channel_incoming_msg_t *msg, const char *text) +{ + if (msg->turn_seq) + return webchat_complete_turn(msg->turn_seq, text); + return webchat_send(msg->session_id, text, NULL, 0); } static void webchat_cleanup(void) { + if (webchat_flush_reply() < 0) + fprintf(stderr, "Cannot save the WebChat reply before shutdown.\n"); + g_pending_seq = 0; + memset(g_pending_reply, 0, sizeof(g_pending_reply)); } static const channel_t webchat_channel = { @@ -61,6 +134,7 @@ static const channel_t webchat_channel = { .poll = webchat_poll, .send = webchat_send, .cleanup = webchat_cleanup, + .reply = webchat_reply, }; const channel_t *channel_webchat_get(void) diff --git a/src/channels/webchat.h b/src/channels/webchat.h index 1e750dd..33b32c3 100644 --- a/src/channels/webchat.h +++ b/src/channels/webchat.h @@ -1,6 +1,6 @@ /** * @file webchat.h - * @brief WebChat channel: WebSocket-based channel for agent loop. + * @brief WebChat channel for paired devices and native WebSocket clients. */ #ifndef SHELLCLAW_CHANNEL_WEBCHAT_H @@ -12,7 +12,9 @@ extern "C" { #endif -/** WebChat channel: poll returns from WS queue, send pushes to WS. */ +#define WEBCHAT_DEVICE_PREFIX "webchat:device:" + +/** Return the channel for paired devices and native WebSocket clients. */ const channel_t *channel_webchat_get(void); #ifdef __cplusplus diff --git a/src/core/dispatch.c b/src/core/dispatch.c index 9f51edc..dc48b83 100644 --- a/src/core/dispatch.c +++ b/src/core/dispatch.c @@ -5,6 +5,7 @@ #define _POSIX_C_SOURCE 200809L #include "channels/heartbeat.h" +#include "channels/webchat.h" #include "core/dispatch.h" #include "core/agent.h" #include "core/bootstrap.h" @@ -54,13 +55,13 @@ static int send_then_maybe_ack_cron(const channel_t *ch, const channel_incoming_ { const char *cron_job_id; int send_err; - if (!ch || !ch->send || !msg) + if (!ch || (!ch->reply && !ch->send) || !msg) return -1; cron_job_id = ch->name && strcmp(ch->name, "cron") == 0 ? msg->user_id : NULL; /* Keep a silent job due until its destination is available. */ if (cron_job_id && agent_err == 0 && provider_text_is_blank(text)) return maybe_ack_cron(cron_job_id, msg); - send_err = ch->send(msg->session_id, text, NULL, 0); + send_err = ch->reply ? ch->reply(msg, text) : ch->send(msg->session_id, text, NULL, 0); if (send_err != 0) return send_err; return agent_err == 0 ? maybe_ack_cron(cron_job_id, NULL) : 0; @@ -88,7 +89,10 @@ int handle_message(const channel_t *ch, const channel_incoming_msg_t *msg) agent_lock(); session_delete(msg->session_id); agent_unlock(); - return send_then_maybe_ack_cron(ch, msg, "Session cleared.", 0); + const char *reply = "Session cleared."; + if (msg->session_id && strncmp(msg->session_id, WEBCHAT_DEVICE_PREFIX, sizeof(WEBCHAT_DEVICE_PREFIX) - 1) == 0) + reply = "Model context cleared. The transcript stays visible."; + return send_then_maybe_ack_cron(ch, msg, reply, 0); } if (strcmp(text, "/status") == 0) { char buf[128]; diff --git a/src/core/main.c b/src/core/main.c index 30ae75e..54eecd9 100644 --- a/src/core/main.c +++ b/src/core/main.c @@ -26,6 +26,9 @@ #include "core/version.h" #include "channels/channel.h" #include "hardware/board_detect.h" +#ifdef SHELLCLAW_GATEWAY +#include "gateway/http.h" +#endif #include "providers/provider.h" #include #include @@ -48,6 +51,16 @@ static void on_signal(int sig) g_shutdown = 1; } +#ifdef SHELLCLAW_GATEWAY +static volatile sig_atomic_t g_pair_requested; + +static void on_pair_request(int sig) +{ + (void)sig; + g_pair_requested = 1; +} +#endif + static void setup_signals(void) { struct sigaction sa; @@ -58,6 +71,11 @@ static void setup_signals(void) fprintf(stderr, "warning: sigaction(SIGINT) failed\n"); if (sigaction(SIGTERM, &sa, NULL) != 0) fprintf(stderr, "warning: sigaction(SIGTERM) failed\n"); +#ifdef SHELLCLAW_GATEWAY + sa.sa_handler = on_pair_request; + if (sigaction(SIGUSR1, &sa, NULL) != 0) + fprintf(stderr, "Cannot register SIGUSR1 for device pairing.\n"); +#endif sa.sa_handler = on_hup; if (sigaction(SIGHUP, &sa, NULL) != 0) fprintf(stderr, "warning: sigaction(SIGHUP) failed\n"); @@ -77,13 +95,22 @@ static void main_loop(int one_shot, config_t **pcfg) memset(&msg, 0, sizeof(msg)); int got = 0; const channel_t *which = NULL; + static int next_channel; int nch = bootstrap_channel_count(); - for (int i = 0; i < nch && !got; i++) { + for (int visited = 0; visited < nch && !got; visited++) { + int i = (next_channel + visited) % nch; +#ifdef SHELLCLAW_GATEWAY + if (g_pair_requested) { + g_pair_requested = 0; + http_request_pairing_code(); + } +#endif const channel_t *ch = bootstrap_channel_at(i); if (!ch) continue; int r = ch->poll(&msg, POLL_TIMEOUT_MS); if (r == 1) { + next_channel = (i + 1) % nch; got = 1; which = ch; break; diff --git a/src/core/memory.c b/src/core/memory.c index 91c3567..8bbc6e7 100644 --- a/src/core/memory.c +++ b/src/core/memory.c @@ -82,6 +82,19 @@ static const char *SCHEMA_SESSIONS = " updated_at TEXT" ");"; +static const char *SCHEMA_WEBCHAT = + "CREATE TABLE IF NOT EXISTS webchat_turns (" + " seq INTEGER PRIMARY KEY," + " session TEXT NOT NULL," + " request TEXT NOT NULL," + " text TEXT NOT NULL," + " reply TEXT," + " state INTEGER NOT NULL DEFAULT 0," + " UNIQUE(session, request)" + ");" + "CREATE INDEX IF NOT EXISTS webchat_session_seq ON webchat_turns (session, seq);" + "CREATE INDEX IF NOT EXISTS webchat_pending ON webchat_turns (state, seq) WHERE state < 2;"; + static const char *SCHEMA_CRON_JOBS = "CREATE TABLE IF NOT EXISTS cron_jobs (" " id TEXT PRIMARY KEY," @@ -110,6 +123,7 @@ static int run_schema(void) if (sqlite3_exec(g_db, TRIGGER_MEMORIES_AD, NULL, NULL, &err) != SQLITE_OK) goto fail; if (sqlite3_exec(g_db, TRIGGER_MEMORIES_AU, NULL, NULL, &err) != SQLITE_OK) goto fail; if (sqlite3_exec(g_db, SCHEMA_SESSIONS, NULL, NULL, &err) != SQLITE_OK) goto fail; + if (sqlite3_exec(g_db, SCHEMA_WEBCHAT, NULL, NULL, &err) != SQLITE_OK) goto fail; if (sqlite3_exec(g_db, SCHEMA_CRON_JOBS, NULL, NULL, &err) != SQLITE_OK) goto fail; if (sqlite3_exec(g_db, SCHEMA_CONFIG_KV, NULL, NULL, &err) != SQLITE_OK) goto fail; return 0; @@ -141,7 +155,7 @@ int memory_init(const char *path) if (!path || g_db) return -1; int file_existed = path_exists(path); int recreated = 0; - if (sqlite3_open(path, &g_db) != SQLITE_OK) { + if (sqlite3_open_v2(path, &g_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, NULL) != SQLITE_OK) { /* Never delete an existing DB on open failure (permissions, transient I/O). */ if (file_existed) { fprintf(stderr, "Error: cannot open existing memory DB at %s: %s\n", @@ -151,7 +165,7 @@ int memory_init(const char *path) } if (g_db) { sqlite3_close(g_db); g_db = NULL; } remove(path); - if (sqlite3_open(path, &g_db) != SQLITE_OK) { + if (sqlite3_open_v2(path, &g_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, NULL) != SQLITE_OK) { if (g_db) sqlite3_close(g_db); g_db = NULL; return -1; @@ -170,7 +184,7 @@ int memory_init(const char *path) sqlite3_close(g_db); g_db = NULL; remove(path); - if (sqlite3_open(path, &g_db) != SQLITE_OK) { + if (sqlite3_open_v2(path, &g_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, NULL) != SQLITE_OK) { if (g_db) sqlite3_close(g_db); g_db = NULL; return -1; @@ -326,6 +340,194 @@ int session_list(char **session_ids_out, int max_count) return count; } +/* WebChat uses single statements on the serialized connection. A provider call + * can hold agent_lock while the gateway accepts requests and reads receipts. */ +int webchat_store_accept(const char *session, const char *request, const char *text) +{ + const char *sql = "INSERT INTO webchat_turns(session, request, text) SELECT ?1, ?2, ?3 " + "WHERE EXISTS(SELECT 1 FROM webchat_turns WHERE session=?1 AND request=?2) " + "OR (SELECT count(*) FROM (SELECT 1 FROM webchat_turns WHERE state<2 LIMIT ?4)) < ?4 " + "ON CONFLICT(session, request) DO UPDATE SET request=excluded.request " + "RETURNING state<>3 AND text=?3"; + sqlite3_stmt *stmt = NULL; + if (!g_db) return -1; + sqlite3_mutex *mutex = sqlite3_db_mutex(g_db); + sqlite3_mutex_enter(mutex); + int rc = -1; + if (sqlite3_prepare_v2(g_db, sql, -1, &stmt, NULL) == SQLITE_OK && + sqlite3_bind_text(stmt, 1, session, -1, SQLITE_STATIC) == SQLITE_OK && + sqlite3_bind_text(stmt, 2, request, -1, SQLITE_STATIC) == SQLITE_OK && + sqlite3_bind_text(stmt, 3, text, -1, SQLITE_STATIC) == SQLITE_OK && + sqlite3_bind_int(stmt, 4, WEBCHAT_PENDING_LIMIT) == SQLITE_OK) { + int step = sqlite3_step(stmt); + if (step == SQLITE_ROW) { + int accepted = sqlite3_column_int(stmt, 0); + if (sqlite3_step(stmt) == SQLITE_DONE) + rc = accepted ? 0 : WEBCHAT_ACCEPT_CONFLICT; + } else if (step == SQLITE_DONE) { + rc = WEBCHAT_ACCEPT_FULL; + } + } + if (sqlite3_finalize(stmt) != SQLITE_OK) rc = -1; + sqlite3_mutex_leave(mutex); + return rc; +} + +int webchat_store_claim(int64_t *seq, char *session, size_t session_size, char *text, size_t text_size) +{ + const char *sql = "UPDATE webchat_turns SET state=1 WHERE seq=(" + "SELECT seq FROM webchat_turns WHERE state=0 ORDER BY seq LIMIT 1" + ") AND length(CAST(session AS BLOB)) < ?1 AND length(CAST(text AS BLOB)) < ?2 " + "RETURNING seq, session, text"; + sqlite3_stmt *stmt = NULL; + if (!g_db || !seq || !session || !text) return -1; + sqlite3_mutex *mutex = sqlite3_db_mutex(g_db); + sqlite3_mutex_enter(mutex); + int rc = -1; + if (sqlite3_prepare_v2(g_db, sql, -1, &stmt, NULL) == SQLITE_OK && + sqlite3_bind_int64(stmt, 1, (sqlite3_int64)session_size) == SQLITE_OK && + sqlite3_bind_int64(stmt, 2, (sqlite3_int64)text_size) == SQLITE_OK) { + int step = sqlite3_step(stmt); + if (step == SQLITE_ROW) { + int64_t claimed = sqlite3_column_int64(stmt, 0); + const char *saved_session = (const char *)sqlite3_column_text(stmt, 1); + const char *saved_text = (const char *)sqlite3_column_text(stmt, 2); + if (saved_session && saved_text) { + memcpy(session, saved_session, strlen(saved_session) + 1); + memcpy(text, saved_text, strlen(saved_text) + 1); + if (sqlite3_step(stmt) == SQLITE_DONE) { + *seq = claimed; + rc = 1; + } + } + } else if (step == SQLITE_DONE) { + rc = 0; + } + } + if (sqlite3_finalize(stmt) != SQLITE_OK) rc = -1; + sqlite3_mutex_leave(mutex); + return rc; +} + +int webchat_store_finish(int64_t seq, const char *reply) +{ + const char *sql = "UPDATE webchat_turns SET state=2, reply=?1 WHERE seq=?2 AND state=1"; + sqlite3_stmt *stmt = NULL; + if (!g_db || seq <= 0 || !reply) return -1; + sqlite3_mutex *mutex = sqlite3_db_mutex(g_db); + sqlite3_mutex_enter(mutex); + int rc = -1; + if (sqlite3_prepare_v2(g_db, sql, -1, &stmt, NULL) == SQLITE_OK && + sqlite3_bind_text(stmt, 1, reply, -1, SQLITE_STATIC) == SQLITE_OK && + sqlite3_bind_int64(stmt, 2, seq) == SQLITE_OK && + sqlite3_step(stmt) == SQLITE_DONE) + rc = sqlite3_changes(g_db) == 1 ? 0 : WEBCHAT_FINISH_NOT_RUNNING; + if (sqlite3_finalize(stmt) != SQLITE_OK) rc = -1; + sqlite3_mutex_leave(mutex); + return rc; +} + +int webchat_store_recover(void) +{ + /* Do not replay a turn that could already have run a tool. */ + const char *sql = "UPDATE webchat_turns SET state=2, " + "reply='Gateway restarted before it recorded a reply.' WHERE state=1"; + return g_db && sqlite3_exec(g_db, sql, NULL, NULL, NULL) == SQLITE_OK ? 0 : -1; +} + +static int webchat_store_exists(const char *sql, const char *session) +{ + sqlite3_stmt *stmt = NULL; + if (!g_db || sqlite3_prepare_v2(g_db, sql, -1, &stmt, NULL) != SQLITE_OK) + return -1; + int rc = -1; + if (sqlite3_bind_text(stmt, 1, session, -1, SQLITE_STATIC) == SQLITE_OK) { + int step = sqlite3_step(stmt); + if (step == SQLITE_ROW) rc = 1; + if (step == SQLITE_DONE) rc = 0; + } + return sqlite3_finalize(stmt) == SQLITE_OK ? rc : -1; +} + +int webchat_store_has_history(const char *session) +{ + return webchat_store_exists( + "SELECT 1 FROM webchat_turns WHERE session=?1 AND state<>3 LIMIT 1", session); +} + +int webchat_store_delete(const char *session) +{ + if (!g_db || !session) return -1; + /* Keep only the receipt and its sequence so an old retry cannot run again. */ + char *sql = sqlite3_mprintf("DELETE FROM sessions WHERE id=%Q;" + "UPDATE webchat_turns SET text='', reply=NULL, state=3 WHERE session=%Q AND state=2;", + session, session); + if (!sql) return -1; + + /* Keep other WebChat requests out of the transaction on this connection. */ + sqlite3_mutex *mutex = sqlite3_db_mutex(g_db); + sqlite3_mutex_enter(mutex); + int rc = -1; + if (sqlite3_exec(g_db, "BEGIN IMMEDIATE", NULL, NULL, NULL) == SQLITE_OK) { + int busy = webchat_store_exists( + "SELECT 1 FROM webchat_turns WHERE session=?1 AND state<2 LIMIT 1", session); + if (busy == 1) { + rc = WEBCHAT_DELETE_BUSY; + } else if (busy == 0) { + sqlite3_int64 before = sqlite3_total_changes64(g_db); + if (sqlite3_exec(g_db, sql, NULL, NULL, NULL) == SQLITE_OK && + sqlite3_exec(g_db, "COMMIT", NULL, NULL, NULL) == SQLITE_OK) + rc = sqlite3_total_changes64(g_db) == before ? WEBCHAT_DELETE_NOT_FOUND : 0; + } + if (!sqlite3_get_autocommit(g_db)) + sqlite3_exec(g_db, "ROLLBACK", NULL, NULL, NULL); + } + sqlite3_mutex_leave(mutex); + sqlite3_free(sql); + return rc; +} + +int webchat_store_history(const char *session, int64_t after, char *out, size_t size) +{ + const char *sql = "WITH cleared AS (SELECT MAX(seq) AS seq FROM webchat_turns " + "WHERE session=?1 AND state=3) " + "SELECT json_object('clearedThrough',seq), 3, 0 FROM cleared WHERE seq IS NOT NULL " + "UNION ALL SELECT * FROM (" + "SELECT json_object('seq',seq,'id',request,'text',text,'reply',reply), state, seq " + "FROM webchat_turns WHERE session=?1 AND state<>3 " + "AND seq>MAX(?2, COALESCE((SELECT seq FROM cleared),0)) ORDER BY seq LIMIT 32" + ") ORDER BY 3"; + sqlite3_stmt *stmt = NULL; + if (!g_db || size < 3 || sqlite3_prepare_v2(g_db, sql, -1, &stmt, NULL) != SQLITE_OK) + return -1; + if (sqlite3_bind_text(stmt, 1, session, -1, SQLITE_STATIC) != SQLITE_OK || + sqlite3_bind_int64(stmt, 2, after) != SQLITE_OK) { + sqlite3_finalize(stmt); + return -1; + } + size_t used = 1; + out[0] = '['; + int step; + int rc = 0; + while ((step = sqlite3_step(stmt)) == SQLITE_ROW) { + const char *row = (const char *)sqlite3_column_text(stmt, 0); + size_t len = (size_t)sqlite3_column_bytes(stmt, 0); + if (!row || len + 3 > size - used) { + if (used == 1 || !row) rc = -1; + break; + } + if (used > 1) out[used++] = ','; + memcpy(out + used, row, len); + used += len; + /* The reader must revisit an unfinished turn before advancing. */ + if (sqlite3_column_int(stmt, 1) < 2) break; + } + out[used++] = ']'; + out[used] = '\0'; + if (step != SQLITE_DONE && step != SQLITE_ROW) rc = -1; + return sqlite3_finalize(stmt) == SQLITE_OK ? rc : -1; +} + int config_kv_get(const char *key, char *value_out, size_t max_len) { if (!g_db || !key || !value_out || max_len == 0) return -1; diff --git a/src/core/memory.h b/src/core/memory.h index e2dd963..bd11e78 100644 --- a/src/core/memory.h +++ b/src/core/memory.h @@ -7,6 +7,7 @@ #define SHELLCLAW_MEMORY_H #include +#include #ifdef __cplusplus extern "C" { @@ -110,6 +111,42 @@ void memory_sqlite_entry_set_hook_for_test(void (*hook)(void)); */ int session_list(char **session_ids_out, int max_count); +#define WEBCHAT_PENDING_LIMIT 64 + +enum { WEBCHAT_ACCEPT_CONFLICT = 1, WEBCHAT_ACCEPT_FULL = 2 }; + +/** Accept a WebChat turn. Return 0, WEBCHAT_ACCEPT_CONFLICT, WEBCHAT_ACCEPT_FULL, or -1. */ +int webchat_store_accept(const char *session, const char *request, const char *text); + +/** Claim the next WebChat turn. Return 1 when claimed, 0 when empty, or -1 on error. */ +int webchat_store_claim(int64_t *seq, char *session, size_t session_size, char *text, size_t text_size); + +enum { WEBCHAT_FINISH_NOT_RUNNING = 1 }; + +/** Save the reply for @p seq. Return 0, WEBCHAT_FINISH_NOT_RUNNING, or -1 on error. */ +int webchat_store_finish(int64_t seq, const char *reply); + +/** Finish interrupted turns. Call once after the gateway binds its listen socket. */ +int webchat_store_recover(void); + +/** Return 1 if the WebChat transcript contains a turn, 0 if empty, or -1 on error. */ +int webchat_store_has_history(const char *session); + +enum { WEBCHAT_DELETE_NOT_FOUND = 1, WEBCHAT_DELETE_BUSY = 2 }; + +/** + * Delete the model context and transcript in one transaction. + * Return 0 on success, WEBCHAT_DELETE_NOT_FOUND, WEBCHAT_DELETE_BUSY, or -1 on error. + * Hold the agent lock when you call this function. + */ +int webchat_store_delete(const char *session); + +/** + * Read one page of WebChat history as JSON. @p after is the last completed turn's sequence. + * Return 0 on success or -1 if the page cannot be read. + */ +int webchat_store_history(const char *session, int64_t after, char *out, size_t size); + /** * Get a value from config_kv by key. * diff --git a/src/gateway/asap_http_body.c b/src/gateway/asap_http_body.c index 46f7475..f74d4e4 100644 --- a/src/gateway/asap_http_body.c +++ b/src/gateway/asap_http_body.c @@ -1,29 +1,15 @@ /** * @file asap_http_body.c - * @brief Dynamic POST /asap body handling for libwebsockets HTTP callbacks. + * @brief Dynamic request buffers for libwebsockets HTTP callbacks. */ #define _POSIX_C_SOURCE 200809L #include "gateway/asap_http_body.h" -#include "gateway/uri_match.h" #include #include #include #include -static int asap_is_asap_post(struct lws *wsi) -{ - char uri[256]; - int uri_len; - - if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) <= 0) - return 0; - uri_len = lws_hdr_copy(wsi, uri, sizeof(uri), WSI_TOKEN_POST_URI); - if (uri_len <= 0) - return 0; - return uri_exact_eq(uri, uri_len, "/asap"); -} - int asap_http_body_parse_content_length(const char *cl_buf, long *cl_out) { char *end = NULL; @@ -53,7 +39,7 @@ int asap_http_body_exceeds_static_cap(const asap_http_body_t *body, long content return content_length > (long)BODY_BUF_SIZE; } -int asap_http_body_init_from_request(struct lws *wsi, asap_http_body_t *body) +int asap_http_body_init_from_request(struct lws *wsi, asap_http_body_t *body, size_t limit) { char cl_buf[32] = {0}; long cl = 0; @@ -61,13 +47,11 @@ int asap_http_body_init_from_request(struct lws *wsi, asap_http_body_t *body) if (!body || !wsi) return -2; - if (!asap_is_asap_post(wsi)) - return 0; has_cl = lws_hdr_copy(wsi, cl_buf, sizeof cl_buf, WSI_TOKEN_HTTP_CONTENT_LENGTH) > 0; - if (has_cl && asap_http_body_parse_content_length(cl_buf, &cl) != 0) + if (has_cl && (asap_http_body_parse_content_length(cl_buf, &cl) != 0 || (size_t)cl > limit)) return -1; { - size_t cap = (cl > 0) ? (size_t)cl : (size_t)ASAP_BODY_MAX; + size_t cap = (cl > 0) ? (size_t)cl : limit; body->body_dyn = malloc(cap + 1); if (!body->body_dyn) return -2; diff --git a/src/gateway/asap_http_body.h b/src/gateway/asap_http_body.h index 7728866..090aae0 100644 --- a/src/gateway/asap_http_body.h +++ b/src/gateway/asap_http_body.h @@ -44,10 +44,10 @@ int asap_http_body_parse_content_length(const char *cl_buf, long *cl_out); int asap_http_body_exceeds_static_cap(const asap_http_body_t *body, long content_length); /** - * For POST /asap: validate Content-Length and allocate dynamic buffer. - * @return 0 ok, -1 body too large, -2 allocation failure; non-/asap returns 0. + * Allocate a dynamic buffer for a route with a larger request limit. + * Return 0 on success, -1 for an invalid length, or -2 on allocation failure. */ -int asap_http_body_init_from_request(struct lws *wsi, asap_http_body_t *body); +int asap_http_body_init_from_request(struct lws *wsi, asap_http_body_t *body, size_t limit); void asap_http_body_append(asap_http_body_t *body, const void *in, size_t len); void asap_http_body_free(asap_http_body_t *body); diff --git a/src/gateway/auth.c b/src/gateway/auth.c index cc62ee8..cad5423 100644 --- a/src/gateway/auth.c +++ b/src/gateway/auth.c @@ -23,8 +23,9 @@ #include #define DEFAULT_TOKENS_PATH "~/.shellclaw/auth_tokens.json" -#define PAIRING_CODE_LEN 6 +#define PAIRING_CODE_LEN (PAIR_CODE_SIZE - 1) #define TOKEN_LEN 32 +#define TOKEN_CAP 16 #define LOCKOUT_TABLE_SIZE 32 #define LOCKOUT_IP_SIZE 48 @@ -37,17 +38,29 @@ typedef struct pair_lockout_entry { struct auth_ctx { char *tokens_path; - char *pending_pairing_code; + char pairing_code[PAIR_CODE_SIZE]; + int code_pending; + time_t code_expires_at; pair_lockout_entry_t lockout[LOCKOUT_TABLE_SIZE]; }; -static int is_file_empty_or_missing(const char *path) +/* Return an empty array for a new store. Fail if an existing store is unreadable. */ +static cJSON *read_tokens(const char *path) { + char buf[8192]; FILE *f = fopen(path, "r"); - if (!f) return 1; - int c = fgetc(f); + if (!f) + return errno == ENOENT ? cJSON_CreateArray() : NULL; + size_t n = fread(buf, 1, sizeof(buf) - 1, f); + int complete = feof(f) && !ferror(f); fclose(f); - return (c == EOF); + if (!complete) return NULL; + if (n == 0) return cJSON_CreateArray(); + buf[n] = '\0'; + cJSON *arr = cJSON_ParseWithOpts(buf, NULL, 1); + if (cJSON_IsArray(arr)) return arr; + cJSON_Delete(arr); + return NULL; } static int ensure_tokens_dir(const char *path); @@ -119,20 +132,41 @@ void auth_cleanup(auth_ctx_t *ctx) { if (!ctx) return; free(ctx->tokens_path); - free(ctx->pending_pairing_code); free(ctx); } +static int issue_code(auth_ctx_t *ctx, time_t expires_at, char code[PAIR_CODE_SIZE]) +{ + do { + if (generate_pairing_code(code, PAIR_CODE_SIZE) != 0) return -1; + } while (strcmp(code, ctx->pairing_code) == 0); + memcpy(ctx->pairing_code, code, PAIR_CODE_SIZE); + ctx->code_pending = 1; + ctx->code_expires_at = expires_at; + return 0; +} + +int auth_issue_device_code(auth_ctx_t *ctx, time_t now, char code[PAIR_CODE_SIZE]) +{ + if (!ctx || !code) return -1; + cJSON *tokens = read_tokens(ctx->tokens_path); + if (!tokens) return -1; + int count = cJSON_GetArraySize(tokens); + cJSON_Delete(tokens); + if (count >= TOKEN_CAP) return -1; + return issue_code(ctx, now + PAIR_DEVICE_CODE_SECS, code); +} + char *auth_get_or_create_pairing_code(auth_ctx_t *ctx) { - if (!ctx || !ctx->tokens_path) return NULL; - if (!is_file_empty_or_missing(ctx->tokens_path)) return NULL; - free(ctx->pending_pairing_code); - ctx->pending_pairing_code = NULL; - char code[PAIRING_CODE_LEN + 1]; - if (generate_pairing_code(code, sizeof(code)) != 0) return NULL; - ctx->pending_pairing_code = strdup(code); - if (!ctx->pending_pairing_code) return NULL; + if (!ctx) return NULL; + cJSON *tokens = read_tokens(ctx->tokens_path); + if (!tokens) return NULL; + int count = cJSON_GetArraySize(tokens); + cJSON_Delete(tokens); + if (count != 0) return NULL; + char code[PAIR_CODE_SIZE]; + if (issue_code(ctx, 0, code) != 0) return NULL; printf("ShellClaw pairing code: %s\n", code); fflush(stdout); if (getenv("SHELLCLAW_TEST_MODE")) { @@ -239,37 +273,33 @@ static int write_tokens_atomic(const char *path, const char *json) int auth_pair(auth_ctx_t *ctx, const char *code, char *token_out, size_t token_size) { - if (!ctx || !ctx->tokens_path || !code || !token_out || token_size == 0) return -1; - if (!is_valid_6digit(code)) return -1; - if (!ctx->pending_pairing_code || - !constant_time_cmp(code, ctx->pending_pairing_code, PAIRING_CODE_LEN)) + if (!ctx || !token_out || token_size <= TOKEN_LEN || !ctx->code_pending || + !is_valid_6digit(code)) + return -1; + if (ctx->code_expires_at != 0) { + struct timespec now; + if (clock_gettime(CLOCK_MONOTONIC, &now) != 0 || now.tv_sec >= ctx->code_expires_at) { + ctx->code_pending = 0; + return -1; + } + } + if (!constant_time_cmp(code, ctx->pairing_code, PAIRING_CODE_LEN)) return -1; char new_token[TOKEN_LEN + 1]; - /* Fail closed: never persist or return an uninitialized bearer on RNG/OOM. */ if (generate_random_hex(new_token, TOKEN_LEN) != 0) return -1; - /* Read existing tokens and append (multi-device support). */ - cJSON *arr = NULL; - { - FILE *f = fopen(ctx->tokens_path, "r"); - if (f) { - char buf[8192]; - size_t n = fread(buf, 1, sizeof(buf) - 1, f); - fclose(f); - buf[n] = '\0'; - cJSON *existing = cJSON_Parse(buf); - if (existing && cJSON_IsArray(existing)) - arr = existing; - else if (existing) - cJSON_Delete(existing); - } - } - if (!arr) arr = cJSON_CreateArray(); + cJSON *arr = read_tokens(ctx->tokens_path); if (!arr) return -1; - /* Cap at 16 tokens to prevent unbounded growth. */ - while (cJSON_GetArraySize(arr) >= 16) - cJSON_DeleteItemFromArray(arr, 0); - cJSON_AddItemToArray(arr, cJSON_CreateString(new_token)); + if (cJSON_GetArraySize(arr) >= TOKEN_CAP) { + cJSON_Delete(arr); + return -1; + } + cJSON *item = cJSON_CreateString(new_token); + if (!item || !cJSON_AddItemToArray(arr, item)) { + cJSON_Delete(item); + cJSON_Delete(arr); + return -1; + } char *json = cJSON_PrintUnformatted(arr); cJSON_Delete(arr); if (!json) return -1; @@ -282,28 +312,16 @@ int auth_pair(auth_ctx_t *ctx, const char *code, char *token_out, size_t token_s return -1; } free(json); - size_t copy_len = (size_t)TOKEN_LEN < token_size - 1 ? (size_t)TOKEN_LEN : token_size - 1; - memcpy(token_out, new_token, copy_len); - token_out[copy_len] = '\0'; - free(ctx->pending_pairing_code); - ctx->pending_pairing_code = NULL; + memcpy(token_out, new_token, sizeof(new_token)); + ctx->code_pending = 0; return 0; } int auth_validate_token(auth_ctx_t *ctx, const char *token) { if (!ctx || !ctx->tokens_path || !token || token[0] == '\0') return 0; - FILE *f = fopen(ctx->tokens_path, "r"); - if (!f) return 0; - char buf[8192]; - size_t n = fread(buf, 1, sizeof(buf) - 1, f); - fclose(f); - buf[n] = '\0'; - cJSON *root = cJSON_Parse(buf); - if (!root || !cJSON_IsArray(root)) { - if (root) cJSON_Delete(root); - return 0; - } + cJSON *root = read_tokens(ctx->tokens_path); + if (!root) return 0; int found = 0; int count = cJSON_GetArraySize(root); size_t tok_len = strlen(token); diff --git a/src/gateway/auth.h b/src/gateway/auth.h index cf042ba..e56744b 100644 --- a/src/gateway/auth.h +++ b/src/gateway/auth.h @@ -41,6 +41,23 @@ void auth_cleanup(auth_ctx_t *ctx); */ char *auth_get_or_create_pairing_code(auth_ctx_t *ctx); +/** Buffer size for a pairing code and its terminator. */ +#define PAIR_CODE_SIZE 7 + +/** Lifetime of a code for an additional device, in seconds. */ +#define PAIR_DEVICE_CODE_SECS 300 + +/** + * Issue a temporary code after a local operator authorizes a device. + * Call on the gateway thread. Replace any pending code. + * + * @param ctx Auth context. + * @param now Monotonic clock time in seconds. + * @param code Buffer for the new code. + * @return 0 on success, -1 if the code cannot be issued. + */ +int auth_issue_device_code(auth_ctx_t *ctx, time_t now, char code[PAIR_CODE_SIZE]); + /** * Pair with code: validate 6-digit code, add token to file, copy to token_out. * diff --git a/src/gateway/http.c b/src/gateway/http.c index 6b571ff..e64186f 100644 --- a/src/gateway/http.c +++ b/src/gateway/http.c @@ -6,18 +6,22 @@ #include "gateway/http.h" #include "gateway/http_lws.h" +#include "core/memory.h" #include "gateway/ws.h" #include "gateway/ws_rx.h" #include "providers/provider.h" +#include "gateway/auth.h" #include "cJSON.h" #include #include +#include #include #include #include #include static http_server_ctx_t *g_ctx; +static atomic_int g_pair_requested; http_server_ctx_t *http_ctx_get(void) { @@ -98,11 +102,41 @@ void http_set_live_config(const config_t *cfg) g_ctx->cfg = cfg; } +void http_request_pairing_code(void) +{ + if (!g_ctx) { + fprintf(stderr, "Start the gateway before you authorize device pairing.\n"); + return; + } + atomic_store(&g_pair_requested, 1); + lws_cancel_service(g_ctx->lws_ctx); +} + +static void issue_device_code(auth_ctx_t *auth) +{ + char code[PAIR_CODE_SIZE]; + struct timespec now; + if (clock_gettime(CLOCK_MONOTONIC, &now) != 0 || + auth_issue_device_code(auth, now.tv_sec, code) != 0) { + fprintf(stderr, "Cannot issue a pairing code. Check the token store and device limit.\n"); + return; + } + printf("ShellClaw pairing code: %s\n", code); + fflush(stdout); +} + +static void service_gateway(http_server_ctx_t *ctx) +{ + if (atomic_exchange(&g_pair_requested, 0)) + issue_device_code(ctx->auth); + lws_service(ctx->lws_ctx, 50); +} + static void *http_thread_fn(void *arg) { http_server_ctx_t *ctx = arg; while (ctx->running && ctx->lws_ctx) - lws_service(ctx->lws_ctx, 50); + service_gateway(ctx); return NULL; } @@ -134,7 +168,8 @@ int http_start(const config_t *cfg, struct auth_ctx *auth_ctx, const char *confi #endif info.mounts = &mount_ws; ctx->lws_ctx = lws_create_context(&info); - if (!ctx->lws_ctx) { + if (!ctx->lws_ctx || webchat_store_recover() != 0) { + if (ctx->lws_ctx) lws_context_destroy(ctx->lws_ctx); free(ctx->config_path); free(ctx); return -1; diff --git a/src/gateway/http.h b/src/gateway/http.h index 0753687..ffbe895 100644 --- a/src/gateway/http.h +++ b/src/gateway/http.h @@ -99,6 +99,9 @@ static inline int http_listen_iface(const char *host, int allow_bind_all, */ int http_start(const config_t *cfg, struct auth_ctx *auth_ctx, const char *config_path); +/** Request a temporary pairing code from the main thread. */ +void http_request_pairing_code(void); + /** * Stop HTTP server. Safe to call if not started. */ diff --git a/src/gateway/http_lws.c b/src/gateway/http_lws.c index 478215f..f72bd31 100644 --- a/src/gateway/http_lws.c +++ b/src/gateway/http_lws.c @@ -7,6 +7,7 @@ #include "gateway/http_lws.h" #include "gateway/asap_http_body.h" #include "gateway/routes.h" +#include "gateway/routes_webchat.h" #include "gateway/auth.h" #include "gateway/uri_match.h" #include "gateway/static.h" @@ -212,7 +213,9 @@ int http_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, http_lws_tx_completed(wsi); return 0; } - conn->response = malloc(RESP_BUF_SIZE); + int chat = uri_exact_eq(uri, uri_len, WEBCHAT_ROUTE); + size_t response_size = chat && method == HTTP_GET ? WEBCHAT_RESPONSE_SIZE : RESP_BUF_SIZE; + conn->response = malloc(response_size); if (!conn->response) { free(conn); lws_return_http_status(wsi, 500, "Internal error"); @@ -222,10 +225,10 @@ int http_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, conn->response[0] = '\0'; conn->status = 200; conn->has_body = (method == HTTP_POST || method == HTTP_PUT); - /* For /asap POST: enforce 1 MB body cap via Content-Length and allocate - * a dynamic buffer so large envelopes are not silently truncated. */ - if (conn->has_body && uri_exact_eq(uri, uri_len, "/asap")) { - int body_rc = asap_http_body_init_from_request(wsi, &conn->body); + /* WebChat text can exceed the static cap after JSON escaping. */ + if (method == HTTP_POST && (chat || uri_exact_eq(uri, uri_len, "/asap"))) { + size_t limit = chat ? WEBCHAT_REQUEST_SIZE : ASAP_BODY_MAX; + int body_rc = asap_http_body_init_from_request(wsi, &conn->body, limit); if (body_rc == -1) { free(conn->response); free(conn); @@ -263,7 +266,7 @@ int http_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, } } if (!conn->has_body) { - dispatch_route(ctx, wsi, method, uri, uri_len, NULL, 0, conn->response, RESP_BUF_SIZE, &conn->status); + dispatch_route(ctx, wsi, method, uri, uri_len, NULL, 0, conn->response, response_size, &conn->status); conn->response_len = strlen(conn->response); lws_set_wsi_user(wsi, conn); lws_callback_on_writable(wsi); diff --git a/src/gateway/routes.c b/src/gateway/routes.c index e53b975..7820694 100644 --- a/src/gateway/routes.c +++ b/src/gateway/routes.c @@ -6,6 +6,7 @@ #include "gateway/routes.h" #include "gateway/routes_hardware.h" +#include "gateway/routes_webchat.h" #include "gateway/http.h" #include "gateway/auth.h" #include "gateway/rate_limit.h" @@ -531,7 +532,17 @@ static void handle_memory_get(const char *query, int limit, char *buf, size_t si } } -static void handle_sessions_list(char *buf, size_t size, int *status) +static int is_device_session(const char *id) +{ + return strncmp(id, WEBCHAT_DEVICE_PREFIX, sizeof(WEBCHAT_DEVICE_PREFIX) - 1) == 0; +} + +static int can_access_session(const char *id, const char *device_session) +{ + return !is_device_session(id) || strcmp(id, device_session) == 0; +} + +static void handle_sessions_list(const char *device_session, char *buf, size_t size, int *status) { char *ids[64]; int n; @@ -540,10 +551,16 @@ static void handle_sessions_list(char *buf, size_t size, int *status) agent_unlock(); cJSON *arr = cJSON_CreateArray(); if (!arr) { json_error(buf, size, status, 500, "Internal error"); return; } + int listed_device = 0; for (int i = 0; i < n; i++) { - cJSON_AddItemToArray(arr, cJSON_CreateString(ids[i])); + if (can_access_session(ids[i], device_session)) + cJSON_AddItemToArray(arr, cJSON_CreateString(ids[i])); + if (strcmp(ids[i], device_session) == 0) + listed_device = 1; free(ids[i]); } + if (!listed_device && device_session[0] && webchat_store_has_history(device_session) == 1) + cJSON_AddItemToArray(arr, cJSON_CreateString(device_session)); char *s = cJSON_PrintUnformatted(arr); cJSON_Delete(arr); if (s) { @@ -556,7 +573,20 @@ static void handle_sessions_list(char *buf, size_t size, int *status) static void handle_session_delete(const char *id, char *buf, size_t size, int *status) { - if (dispatch_delete_session(id) != 0) { + if (is_device_session(id)) { + agent_lock(); + int rc = webchat_store_delete(id); + agent_unlock(); + if (rc == WEBCHAT_DELETE_BUSY) { + json_error(buf, size, status, 409, "Wait for the current message before you delete this conversation"); + return; + } + if (rc != 0) { + int code = rc == WEBCHAT_DELETE_NOT_FOUND ? 404 : 500; + json_error(buf, size, status, code, code == 404 ? "Session not found" : "Cannot delete the conversation"); + return; + } + } else if (dispatch_delete_session(id) != 0) { json_error(buf, size, status, 404, "Session not found"); return; } @@ -1042,8 +1072,14 @@ int dispatch_route(http_server_ctx_t *ctx, struct lws *wsi, int method, handle_memory_get(qbuf[0] ? qbuf : NULL, limit, buf, size, status); return 0; } + if (uri_exact_eq(uri, uri_len, WEBCHAT_ROUTE)) { + handle_webchat(wsi, method, body, body_len, buf, size, status); + return 0; + } if (uri_exact_eq(uri, uri_len, "/api/sessions")) { - if (method == HTTP_GET) handle_sessions_list(buf, size, status); + char session[WEBCHAT_SESSION_SIZE] = {0}; + webchat_request_session(wsi, session); + if (method == HTTP_GET) handle_sessions_list(session, buf, size, status); else json_error(buf, size, status, 405, "Method not allowed"); return 0; } @@ -1054,7 +1090,10 @@ int dispatch_route(http_server_ctx_t *ctx, struct lws *wsi, int method, json_error(buf, size, status, 404, "Not found"); return 0; } - handle_session_delete(id, buf, size, status); + char session[WEBCHAT_SESSION_SIZE] = {0}; + webchat_request_session(wsi, session); + if (can_access_session(id, session)) handle_session_delete(id, buf, size, status); + else json_error(buf, size, status, 404, "Session not found"); return 0; } if (uri_exact_eq(uri, uri_len, "/api/cron")) { diff --git a/src/gateway/routes_webchat.c b/src/gateway/routes_webchat.c new file mode 100644 index 0000000..1d8d5b0 --- /dev/null +++ b/src/gateway/routes_webchat.c @@ -0,0 +1,92 @@ +/** + * @file routes_webchat.c + * @brief WebChat history and message receipts for an authenticated device. + */ +#define _POSIX_C_SOURCE 200809L + +#include "core/memory.h" +#include "gateway/routes.h" +#include "gateway/routes_webchat.h" +#include "providers/provider.h" +#include "tweetnacl.h" +#include +#include +#include +#include + +int webchat_request_session(struct lws *wsi, char session[WEBCHAT_SESSION_SIZE]) +{ + char auth[256]; + const char *token = wsi ? http_request_bearer_token(wsi, auth, sizeof(auth)) : NULL; + if (!token) return -1; + unsigned char digest[crypto_hash_BYTES]; + if (crypto_hash(digest, (const unsigned char *)token, strlen(token)) != 0) return -1; + memcpy(session, WEBCHAT_DEVICE_PREFIX, sizeof(WEBCHAT_DEVICE_PREFIX)); + for (size_t i = 0; i < 32; i++) + snprintf(session + sizeof(WEBCHAT_DEVICE_PREFIX) - 1 + 2 * i, 3, "%02x", digest[i]); + return 0; +} + +static void handle_history(struct lws *wsi, const char *session, char *buf, size_t size, int *status) +{ + char value[32]; + int64_t after = 0; + const char *cursor = lws_get_urlarg_by_name(wsi, "after=", value, sizeof(value)); + if (cursor) { + char *end; + errno = 0; + after = strtoll(cursor, &end, 10); + if (errno || end == cursor || *end || after < 0) { + json_error(buf, size, status, 400, "Invalid history cursor"); + return; + } + } + if (webchat_store_history(session, after, buf, size) != 0) + json_error(buf, size, status, 500, "Cannot read the conversation"); + else + *status = 200; +} + +static int valid_id(const char *id) +{ + return id && strlen(id) == 32 && strspn(id, "0123456789abcdef") == 32; +} + +static void handle_send(const char *session, const char *body, size_t body_len, + char *buf, size_t size, int *status) +{ + cJSON *obj = body && body_len && !memchr(body, '\0', body_len) + ? cJSON_ParseWithLengthOpts(body, body_len + 1, NULL, 1) : NULL; + const char *id = cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(obj, "id")); + const char *text = cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(obj, "text")); + if (!valid_id(id) || !text || provider_text_is_blank(text) || strlen(text) > WS_TEXT_MAX) { + json_error(buf, size, status, 400, "Invalid chat message"); + } else { + int rc = webchat_store_accept(session, id, text); + if (rc == WEBCHAT_ACCEPT_CONFLICT) + json_error(buf, size, status, 409, "The message ID is already in use"); + else if (rc == WEBCHAT_ACCEPT_FULL) + json_error(buf, size, status, 503, "The chat queue is full. Try again shortly."); + else if (rc != 0) + json_error(buf, size, status, 500, "Cannot save the message"); + else { + snprintf(buf, size, "{\"accepted\":true}"); + *status = 200; + } + } + cJSON_Delete(obj); +} + +void handle_webchat(struct lws *wsi, int method, const char *body, size_t body_len, + char *buf, size_t size, int *status) +{ + char session[WEBCHAT_SESSION_SIZE]; + if (webchat_request_session(wsi, session) != 0) + json_error(buf, size, status, 401, "Unauthorized"); + else if (method == HTTP_GET) + handle_history(wsi, session, buf, size, status); + else if (method == HTTP_POST) + handle_send(session, body, body_len, buf, size, status); + else + json_error(buf, size, status, 405, "Method not allowed"); +} diff --git a/src/gateway/routes_webchat.h b/src/gateway/routes_webchat.h new file mode 100644 index 0000000..c5884f2 --- /dev/null +++ b/src/gateway/routes_webchat.h @@ -0,0 +1,24 @@ +/** + * @file routes_webchat.h + * @brief WebChat routes for an authenticated device. + */ +#ifndef SHELLCLAW_ROUTES_WEBCHAT_H +#define SHELLCLAW_ROUTES_WEBCHAT_H + +#include "channels/webchat.h" +#include "gateway/http_lws.h" +#include "gateway/ws.h" + +#define WEBCHAT_ROUTE "/api/chat" +#define WEBCHAT_SESSION_SIZE (sizeof(WEBCHAT_DEVICE_PREFIX) + 64) +#define WEBCHAT_REQUEST_SIZE (6u * WS_TEXT_MAX + 256u) +#define WEBCHAT_RESPONSE_SIZE (12u * WS_TEXT_MAX + 1024u) + +/** Derive the session ID from the validated bearer credential in the HTTP request. */ +int webchat_request_session(struct lws *wsi, char session[WEBCHAT_SESSION_SIZE]); + +/** Handle a history or send request after the gateway authenticates the device. */ +void handle_webchat(struct lws *wsi, int method, const char *body, size_t body_len, + char *buf, size_t size, int *status); + +#endif diff --git a/tests/test_auth.c b/tests/test_auth.c index 85001cb..64ed8fc 100644 --- a/tests/test_auth.c +++ b/tests/test_auth.c @@ -27,7 +27,7 @@ static void format_dummy_token(char *out, size_t out_size, int index) { - /* Deterministic 32-char hex so eviction of index 0 is observable. */ + /* Use deterministic tokens to verify that all devices remain paired. */ snprintf(out, out_size, "%032d", index); } @@ -273,17 +273,31 @@ static int test_auth_multi_token(void) ASSERT(auth_validate_token(ctx1, token1) == 1); free(code1); auth_cleanup(ctx1); - /* Second pairing — need to delete tokens file to trigger new pairing code. */ - /* But we want to test that tokens accumulate, so we re-init and manually write - a state that allows a new pairing (empty tokens file but keep existing tokens - by writing them back after getting the code). Instead, test via validate: */ - /* Verify first token still works after file exists. */ + /* An existing token does not open pairing automatically after restart. */ auth_ctx_t *ctx2 = auth_init(path); ASSERT(ctx2 != NULL); ASSERT(auth_validate_token(ctx2, token1) == 1); - /* No new pairing available since file is non-empty (expected behavior). */ - char *code2 = auth_get_or_create_pairing_code(ctx2); - ASSERT(code2 == NULL); + ASSERT(auth_get_or_create_pairing_code(ctx2) == NULL); + + char expired[7]; + struct timespec now; + ASSERT(clock_gettime(CLOCK_MONOTONIC, &now) == 0); + ASSERT(auth_issue_device_code(ctx2, now.tv_sec - PAIR_DEVICE_CODE_SECS, expired) == 0); + char token2[64] = {0}; + ASSERT(auth_pair(ctx2, expired, token2, sizeof(token2)) != 0); + ASSERT(auth_validate_token(ctx2, token1) == 1); + + char code2[7]; + char code3[7]; + ASSERT(auth_issue_device_code(ctx2, now.tv_sec, code2) == 0); + ASSERT(auth_issue_device_code(ctx2, now.tv_sec, code3) == 0); + ASSERT(strcmp(code2, code3) != 0); + ASSERT(auth_pair(ctx2, code2, token2, sizeof(token2)) != 0); + ASSERT(auth_pair(ctx2, code3, token2, sizeof(token2)) == 0); + ASSERT(strcmp(token1, token2) != 0); + ASSERT(auth_pair(ctx2, code3, token2, sizeof(token2)) != 0); + ASSERT(auth_validate_token(ctx2, token1) == 1); + ASSERT(auth_validate_token(ctx2, token2) == 1); auth_cleanup(ctx2); unlink(path); return 0; @@ -439,7 +453,7 @@ static int test_auth_pair_rejects_malformed_code(void) return 0; } -static int test_auth_pair_evicts_oldest_at_cap(void) +static int test_auth_pair_preserves_tokens_at_cap(void) { const char *path = "/tmp/shellclaw_test_tokens_cap.json"; auth_ctx_t *ctx; @@ -459,17 +473,20 @@ static int test_auth_pair_evicts_oldest_at_cap(void) * seed 16 tokens on disk before auth_pair appends (multi-device cap). */ ASSERT(write_token_array(path, TEST_AUTH_TOKEN_CAP) == 0); + struct timespec now; + char extra[PAIR_CODE_SIZE]; + ASSERT(clock_gettime(CLOCK_MONOTONIC, &now) == 0); + ASSERT(auth_issue_device_code(ctx, now.tv_sec, extra) != 0); format_dummy_token(oldest, sizeof(oldest), 0); format_dummy_token(newest_seed, sizeof(newest_seed), TEST_AUTH_TOKEN_CAP - 1); ASSERT(auth_validate_token(ctx, oldest) == 1); ASSERT(auth_validate_token(ctx, newest_seed) == 1); memset(token, 0, sizeof(token)); - ASSERT(auth_pair(ctx, code, token, sizeof(token)) == 0); - ASSERT(strlen(token) == TEST_TOKEN_HEX_LEN); - ASSERT(auth_validate_token(ctx, token) == 1); + ASSERT(auth_pair(ctx, code, token, sizeof(token)) != 0); + ASSERT(token[0] == '\0'); ASSERT(read_token_array_size(path) == TEST_AUTH_TOKEN_CAP); - ASSERT(auth_validate_token(ctx, oldest) == 0); + ASSERT(auth_validate_token(ctx, oldest) == 1); ASSERT(auth_validate_token(ctx, newest_seed) == 1); free(code); @@ -581,7 +598,7 @@ int main(void) if (test_pair_lockout_null_ip() != 0) { fprintf(stderr, "test_pair_lockout_null_ip failed\n"); failed++; } if (test_auth_pair_fails_closed_on_urandom_failure() != 0) { fprintf(stderr, "test_auth_pair_fails_closed_on_urandom_failure failed\n"); failed++; } if (test_auth_pair_rejects_malformed_code() != 0) { fprintf(stderr, "test_auth_pair_rejects_malformed_code failed\n"); failed++; } - if (test_auth_pair_evicts_oldest_at_cap() != 0) { fprintf(stderr, "test_auth_pair_evicts_oldest_at_cap failed\n"); failed++; } + if (test_auth_pair_preserves_tokens_at_cap() != 0) { fprintf(stderr, "test_auth_pair_preserves_tokens_at_cap failed\n"); failed++; } if (test_auth_validate_token_rejects_length_mismatch() != 0) { fprintf(stderr, "test_auth_validate_token_rejects_length_mismatch failed\n"); failed++; } if (test_pair_lockout_table_full_evicts_slot_zero() != 0) { fprintf(stderr, "test_pair_lockout_table_full_evicts_slot_zero failed\n"); failed++; } if (failed == 0) diff --git a/tests/test_gateway_db_lock.c b/tests/test_gateway_db_lock.c index df5889e..4742e8c 100644 --- a/tests/test_gateway_db_lock.c +++ b/tests/test_gateway_db_lock.c @@ -7,9 +7,14 @@ #include "channels/channel.h" #include "channels/webchat.h" #include "core/agent.h" +#include "core/dispatch.h" #include "core/memory.h" #include "gateway/http_lws.h" #include "gateway/routes.h" +#include "gateway/ws.h" +#include "sqlite3.h" +#include +#include #include #include @@ -93,10 +98,88 @@ static int test_dashboard_sqlite_holds_agent_lock(void) return 0; } +static int test_webchat_retries_reply(void) +{ + char path[] = "/tmp/shellclaw_test_webchat_retry_XXXXXX"; + const char *session = WEBCHAT_DEVICE_PREFIX "test-device"; + const char *reject_reply = "CREATE TRIGGER reject_chat_reply BEFORE UPDATE ON webchat_turns " + "WHEN new.state=2 BEGIN SELECT RAISE(ABORT,'Test failed reply write'); END;"; + sqlite3 *maintenance = NULL; + channel_incoming_msg_t msg = {0}; + char history[2048]; + const channel_t *chat = channel_webchat_get(); + int fd = mkstemp(path); + ASSERT(fd >= 0); + close(fd); + ASSERT(memory_init(path) == 0); + ASSERT(chat->init(NULL) == 0); + ASSERT(webchat_store_accept(session, "first", "/status") == 0); + ASSERT(webchat_store_accept(session, "second", "/reset") == 0); + ASSERT(chat->poll(&msg, 0) == 1); + ASSERT(strcmp(msg.text, "/status") == 0); + ASSERT(sqlite3_open(path, &maintenance) == SQLITE_OK); + ASSERT(sqlite3_exec(maintenance, reject_reply, NULL, NULL, NULL) == SQLITE_OK); + (void)handle_message(chat, &msg); + channel_incoming_msg_clear(&msg); + ASSERT(webchat_store_history(session, 0, history, sizeof(history)) == 0); + ASSERT(strstr(history, "\"reply\":null") != NULL); + ASSERT(!strstr(history, "second")); + ASSERT(sqlite3_exec(maintenance, "DROP TRIGGER reject_chat_reply", NULL, NULL, NULL) == SQLITE_OK); + + ASSERT(chat->poll(&msg, 0) == 1); + ASSERT(strcmp(msg.text, "/reset") == 0); + ASSERT(webchat_store_history(session, 0, history, sizeof(history)) == 0); + int saved_before_next = strstr(history, "\"id\":\"first\",\"text\":\"/status\",\"reply\":\"ShellClaw ") != NULL; + ASSERT(sqlite3_exec(maintenance, reject_reply, NULL, NULL, NULL) == SQLITE_OK); + (void)handle_message(chat, &msg); + channel_incoming_msg_clear(&msg); + ASSERT(sqlite3_exec(maintenance, "DROP TRIGGER reject_chat_reply", NULL, NULL, NULL) == SQLITE_OK); + ASSERT(sqlite3_close(maintenance) == SQLITE_OK); + chat->cleanup(); + + ASSERT(webchat_store_recover() == 0); + ASSERT(webchat_store_history(session, 0, history, sizeof(history)) == 0); + int separate_replies = strstr(history, "\"id\":\"first\",\"text\":\"/status\",\"reply\":\"ShellClaw ") && + strstr(history, "\"id\":\"second\",\"text\":\"/reset\",\"reply\":\"Model context cleared."); + ASSERT(webchat_store_delete(session) == 0); + memory_cleanup(); + remove(path); + ASSERT(saved_before_next && separate_replies); + return 0; +} + +static int test_webchat_alternates_with_websocket(void) +{ + const char *session = WEBCHAT_DEVICE_PREFIX "test-device"; + const channel_t *chat = channel_webchat_get(); + channel_incoming_msg_t msg = {0}; + ASSERT(memory_init(":memory:") == 0); + ASSERT(chat->init(NULL) == 0); + ASSERT(webchat_store_accept(session, "first", "/status") == 0); + ASSERT(webchat_store_accept(session, "second", "/reset") == 0); + ws_push_incoming(14, "/status"); + + int socket_turn = -1; + for (int turn = 0; turn < 3; turn++) { + ASSERT(chat->poll(&msg, 0) == 1); + if (strncmp(msg.session_id, "webchat:socket:", sizeof("webchat:socket:") - 1) == 0) + socket_turn = turn; + ASSERT(handle_message(chat, &msg) == 0); + channel_incoming_msg_clear(&msg); + } + chat->cleanup(); + ws_cleanup(); + memory_cleanup(); + ASSERT(socket_turn == 1); + return 0; +} + int main(void) { - if (test_dashboard_sqlite_holds_agent_lock() != 0) - return 1; + int failed = test_dashboard_sqlite_holds_agent_lock(); + failed |= test_webchat_retries_reply(); + failed |= test_webchat_alternates_with_websocket(); + if (failed) return 1; printf("test_gateway_db_lock: all tests passed\n"); return 0; } diff --git a/tests/test_gateway_http.c b/tests/test_gateway_http.c index a1e61bc..35087df 100644 --- a/tests/test_gateway_http.c +++ b/tests/test_gateway_http.c @@ -11,6 +11,7 @@ #include "core/config.h" #include "core/version.h" #include "cJSON.h" +#include "sqlite3.h" #include #include #include @@ -1439,6 +1440,98 @@ static int test_api_cron_toggle_post(const char *token) return 0; } +static int test_webchat_accepts_escaped_text(const char *token) +{ + char text[32 * 1024 + 1]; + memset(text, 1, sizeof(text) - 1); + text[sizeof(text) - 1] = '\0'; + cJSON *request = cJSON_CreateObject(); + ASSERT(request != NULL); + ASSERT(cJSON_AddStringToObject(request, "id", "00000000000000000000000000000001")); + ASSERT(cJSON_AddStringToObject(request, "text", text)); + char *json = cJSON_PrintUnformatted(request); + cJSON_Delete(request); + ASSERT(json && strlen(json) > 65536); + long status; + char *body = NULL; + int posted = http_post_auth(gw_url("/api/chat"), token, json, &status, &body); + cJSON_free(json); + free(body); + ASSERT(posted == 0 && status == 200); + + ASSERT(http_get_auth(gw_url("/api/chat"), token, &status, &body) == 0); + ASSERT(status == 200 && body); + cJSON *history = cJSON_Parse(body); + free(body); + const cJSON *turn = cJSON_GetArrayItem(history, 0); + const char *saved = cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(turn, "text")); + int same = saved && strcmp(saved, text) == 0; + cJSON_Delete(history); + ASSERT(same); + return 0; +} + +static int webchat_post_status(const char *token, unsigned int id, const char *message) +{ + char json[128]; + char *body = NULL; + long status; + snprintf(json, sizeof(json), "{\"id\":\"%032x\",\"text\":\"%s\"}", id, message); + int rc = http_post_auth(gw_url("/api/chat"), token, json, &status, &body); + free(body); + return rc == 0 ? (int)status : -1; +} + +static int test_webchat_backlog(const char *token, const char *db_path) +{ + sqlite3 *db = NULL; + ASSERT(sqlite3_open(db_path, &db) == SQLITE_OK); + ASSERT(sqlite3_busy_timeout(db, 3000) == SQLITE_OK); + const char *prepare = + "CREATE TRIGGER defer_chat_claim BEFORE UPDATE ON webchat_turns " + "WHEN old.state=0 AND new.state=1 BEGIN SELECT RAISE(ABORT, 'Pause queue'); END;" + "CREATE TABLE chat_test_observations(pending INTEGER);" + "CREATE TRIGGER start_cron_after_chat AFTER UPDATE ON webchat_turns " + "WHEN new.session='chat-test-fixture' AND new.request='1' AND new.state=2 " + "BEGIN INSERT INTO cron_jobs(id,schedule,message,channel,recipient,next_run) " + "VALUES('webchat-fair-cron','at:1','/status','cli','default',1); END;" + "CREATE TRIGGER observe_cron AFTER DELETE ON cron_jobs WHEN old.id='webchat-fair-cron' " + "BEGIN INSERT INTO chat_test_observations SELECT COUNT(*) FROM webchat_turns " + "WHERE session='chat-test-fixture' AND state=0; END;" + "WITH RECURSIVE turns(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM turns WHERE n<64) " + "INSERT INTO webchat_turns(session,request,text) " + "SELECT 'chat-test-fixture',CAST(n AS TEXT),'/status' FROM turns;"; + ASSERT(webchat_post_status(token, 2, "/status") == 200); + ASSERT(sqlite3_exec(db, prepare, NULL, NULL, NULL) == SQLITE_OK); + int receipt = webchat_post_status(token, 2, "/status"); + int conflict = webchat_post_status(token, 2, "/reset"); + int capacity = webchat_post_status(token, 3, "/status"); + + ASSERT(sqlite3_exec(db, "DROP TRIGGER defer_chat_claim", NULL, NULL, NULL) == SQLITE_OK); + int pending = -1; + for (int attempt = 0; attempt < 60 && pending < 0; attempt++) { + sqlite3_stmt *check = NULL; + ASSERT(sqlite3_prepare_v2(db, "SELECT pending FROM chat_test_observations", -1, &check, NULL) == SQLITE_OK); + if (sqlite3_step(check) == SQLITE_ROW) + pending = sqlite3_column_int(check, 0); + ASSERT(sqlite3_finalize(check) == SQLITE_OK); + if (pending < 0) + nanosleep(&(const struct timespec){.tv_nsec = 50000000L}, NULL); + } + + const char *cleanup = + "DELETE FROM webchat_turns WHERE session='chat-test-fixture';" + "DROP TRIGGER start_cron_after_chat; DROP TRIGGER observe_cron; DROP TABLE chat_test_observations;"; + ASSERT(sqlite3_exec(db, cleanup, NULL, NULL, NULL) == SQLITE_OK); + ASSERT(sqlite3_close(db) == SQLITE_OK); + int retry = webchat_post_status(token, 3, "/status"); + if (capacity != 503 || pending != 63) + fprintf(stderr, "WebChat capacity status = %d, queued when cron ran = %d\n", capacity, pending); + ASSERT(receipt == 200 && conflict == 409 && capacity == 503 && retry == 200); + ASSERT(pending == 63); + return 0; +} + static int test_api_sessions(const char *token) { long code; @@ -1892,6 +1985,14 @@ int main(int argc, char **argv) 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++; } + if (test_webchat_accepts_escaped_text(token) != 0) { + fprintf(stderr, "test_webchat_accepts_escaped_text failed\n"); + failed++; + } + if (test_webchat_backlog(token, db_path) != 0) { + fprintf(stderr, "test_webchat_backlog failed\n"); + failed++; + } if (test_api_asap_log(token) != 0) { fprintf(stderr, "test_api_asap_log failed\n"); failed++; } if (test_api_hardware_board_get(token) != 0) { fprintf(stderr, "test_api_hardware_board_get failed\n"); diff --git a/tests/test_memory.c b/tests/test_memory.c index 8b0c7b5..cafca51 100644 --- a/tests/test_memory.c +++ b/tests/test_memory.c @@ -212,6 +212,85 @@ static int test_existing_db_preserved_on_open_failure(void) return 0; } +static int test_webchat_turn_recovery(void) +{ + const char *path = "/tmp/shellclaw_test_webchat_turns.db"; + char id[128], text[128], history[1024]; + int64_t seq; + remove(path); + ASSERT(memory_init(path) == 0); + ASSERT(webchat_store_accept("device-a", "id-a", "A private draft") == 0); + ASSERT(webchat_store_accept("device-a", "id-a", "A private draft") == 0); + ASSERT(webchat_store_accept("device-a", "id-a", "Different content") == 1); + ASSERT(webchat_store_accept("device-b", "id-a", "Other device") == 0); + ASSERT(webchat_store_claim(&seq, id, sizeof(id), text, sizeof(text)) == 1); + ASSERT(strcmp(id, "device-a") == 0 && strcmp(text, "A private draft") == 0); + int64_t interrupted = seq; + memory_cleanup(); + + ASSERT(memory_init(path) == 0); + ASSERT(webchat_store_recover() == 0); + ASSERT(webchat_store_history("device-a", 0, history, sizeof(history)) == 0); + ASSERT(strstr(history, "A private draft") && strstr(history, "Gateway restarted")); + ASSERT(!strstr(history, "Other device")); + ASSERT(webchat_store_history("device-b", 0, history, sizeof(history)) == 0); + ASSERT(strstr(history, "Other device") && !strstr(history, "A private draft")); + ASSERT(webchat_store_claim(&seq, id, sizeof(id), text, sizeof(text)) == 1); + ASSERT(strcmp(id, "device-b") == 0 && strcmp(text, "Other device") == 0); + ASSERT(seq > interrupted); + ASSERT(webchat_store_finish(interrupted, "Stale reply") == WEBCHAT_FINISH_NOT_RUNNING); + ASSERT(webchat_store_finish(seq, "Persisted reply") == 0); + ASSERT(webchat_store_finish(seq, "Other reply") == WEBCHAT_FINISH_NOT_RUNNING); + ASSERT(webchat_store_claim(&seq, id, sizeof(id), text, sizeof(text)) == 0); + ASSERT(webchat_store_accept("device-b", "id-a", "Other device") == 0); + ASSERT(webchat_store_claim(&seq, id, sizeof(id), text, sizeof(text)) == 0); + ASSERT(webchat_store_history("device-b", 0, history, sizeof(history)) == 0); + ASSERT(strstr(history, "Persisted reply")); + memory_cleanup(); + remove(path); + return 0; +} + +static int test_webchat_delete_transaction(void) +{ + const char *path = "/tmp/shellclaw_test_webchat_delete.db"; + char id[128], text[128], history[1024]; + int64_t seq; + sqlite3 *db = NULL; + remove(path); + ASSERT(memory_init(path) == 0); + ASSERT(session_save("device-a", "[1]") == 0); + ASSERT(session_save("device-b", "[2]") == 0); + ASSERT(webchat_store_accept("device-a", "id-a", "A private draft") == 0); + ASSERT(webchat_store_accept("device-b", "id-b", "Other device") == 0); + ASSERT(webchat_store_delete("device-a") == WEBCHAT_DELETE_BUSY); + ASSERT(webchat_store_claim(&seq, id, sizeof(id), text, sizeof(text)) == 1); + ASSERT(webchat_store_finish(seq, "A private reply") == 0); + + ASSERT(sqlite3_open(path, &db) == SQLITE_OK); + const char *abort_delete = "CREATE TRIGGER block_webchat_delete BEFORE UPDATE ON webchat_turns " + "WHEN new.state=3 BEGIN SELECT RAISE(ABORT,'Test rollback'); END;"; + ASSERT(sqlite3_exec(db, abort_delete, NULL, NULL, NULL) == SQLITE_OK); + ASSERT(webchat_store_delete("device-a") == -1); + ASSERT(session_load("device-a", text, sizeof(text)) == 0); + ASSERT(webchat_store_has_history("device-a") == 1); + ASSERT(sqlite3_exec(db, "DROP TRIGGER block_webchat_delete", NULL, NULL, NULL) == SQLITE_OK); + ASSERT(sqlite3_close(db) == SQLITE_OK); + + ASSERT(webchat_store_delete("device-a") == 0); + ASSERT(session_load("device-a", text, sizeof(text)) == -1); + ASSERT(webchat_store_history("device-a", 1, history, sizeof(history)) == 0); + ASSERT(strstr(history, "clearedThrough") && !strstr(history, "A private")); + ASSERT(webchat_store_has_history("device-a") == 0); + ASSERT(webchat_store_accept("device-a", "id-a", "A private draft") == 1); + ASSERT(webchat_store_delete("device-a") == WEBCHAT_DELETE_NOT_FOUND); + ASSERT(session_load("device-b", text, sizeof(text)) == 0 && strcmp(text, "[2]") == 0); + ASSERT(webchat_store_has_history("device-b") == 1); + memory_cleanup(); + remove(path); + return 0; +} + int main(void) { RUN(test_schema_and_fts5()); @@ -223,6 +302,8 @@ int main(void) RUN(test_session_load_rejects_oversized()); RUN(test_gateway_schema_new_db()); RUN(test_gateway_schema_migration_v01()); + RUN(test_webchat_turn_recovery()); + RUN(test_webchat_delete_transaction()); printf("test_memory: all tests passed\n"); return 0; } diff --git a/tests/test_web_dashboard.js b/tests/test_web_dashboard.js index 4723668..36269d6 100644 --- a/tests/test_web_dashboard.js +++ b/tests/test_web_dashboard.js @@ -22,36 +22,42 @@ function assert(cond, msg) { } } -function testPairedChatDisplaysRepliesAsText() { - let connection; +async function testPairedChatDisplaysRepliesAsText() { + const requests = []; + const turns = []; const location = { protocol: 'https:', host: 'localhost', hash: '#/chat' }; - const log = { textContent: '' }; - const elements = { app: {}, 'chat-log': log, 'chat-input': {} }; + const elements = { + app: {}, 'chat-log': { appendChild: turn => turns.push(turn) }, 'chat-input': {}, 'chat-status': {} + }; + const replies = ['The card is blue.', '{"type":"provider_status","providers":[]}', + '"Café" azul']; const token = '1234567890abcdef1234567890abcdef'; const script = fs.readFileSync(path.join(__dirname, '../web/js/app.js'), 'utf8'); vm.runInNewContext(script, { location, - window: { location, addEventListener() {} }, - document: { getElementById: id => elements[id], querySelectorAll: () => [] }, + window: { location, addEventListener() {}, setTimeout() {} }, + document: { getElementById: id => elements[id], querySelectorAll: () => [], createElement: () => ({}) }, localStorage: { getItem: key => key === 'shellclaw_token' ? token : null }, - WebSocket: function (url, protocols) { - this.url = url; - this.protocols = protocols; - connection = this; + sessionStorage: { getItem: () => null }, + AbortController, + clearTimeout, + fetch: async (url, options) => { + requests.push({ url, options }); + return { ok: true, json: async () => replies.map((reply, seq) => ({ + seq: seq + 1, text: 'Example', reply + })) }; }, }); - const replies = ['The card is blue.', '{"type":"provider_status","providers":[]}', - '"Café" azul']; - replies.forEach(text => connection.onmessage({ data: text })); - assert(log.textContent === replies.join('\n') + '\n', 'chat displays each reply as text'); - assert(log.innerHTML === undefined, 'chat does not insert reply markup'); - assert(connection.url === 'wss://localhost/ws?view=chat', 'chat requests the replies-only socket'); - assert(connection.protocols.length === 2 && connection.protocols[0] === 'ws' && - connection.protocols[1] === 'bearer.' + token, 'paired chat offers both WebSocket protocols'); + await new Promise(resolve => setImmediate(resolve)); + assert(turns.length === replies.length, 'chat renders every stored turn'); + replies.forEach((reply, i) => { + assert(turns[i].textContent === 'You: Example\n' + reply + '\n', 'chat displays each reply as text'); + assert(turns[i].innerHTML === undefined, 'chat does not insert reply markup'); + }); + assert(requests.length === 1 && requests[0].url === '/api/chat?after=0', 'chat loads history'); + assert(requests[0].options.headers.Authorization === 'Bearer ' + token, 'chat authenticates history'); } -testPairedChatDisplaysRepliesAsText(); - assert(escapeHtml(null) === '', 'null'); assert(escapeHtml(undefined) === '', 'undefined'); assert(escapeHtml('').indexOf('