From 0f46c22a5869ed9f6eeda9e5fd107befa5b5b83f Mon Sep 17 00:00:00 2001 From: lotherk Date: Tue, 17 Nov 2026 11:46:11 +0000 Subject: [PATCH] model picker, steer feedback, tolerant SSE with retries, junction headers - /model in the curses chat opens a picker: Up/Down, typing filters by provider/model, Enter takes the selector, Esc cancels. The list comes from the backend (sp_engine_models -> sp_provider_choices), not from a text scrape; the socket has a `models` command, so --attach gets the same picker, and the switch is still the ordinary "/model " input. - steering: Enter during a turn now says so twice - a "steering queued: ..." row in the transcript and "Ns steering queued (n) steer>" in the input line until the step boundary picks it up; a rejected steer is an error entry. - input lag: typing during a turn is echoed immediately (the input line is redrawn per key, not at the next 100 ms frame), and the history is only repainted when its generation changed, so a streaming turn no longer repaints the whole transcript on every clock tick. - sidebar: the first line of every widget is bold, like its heading, so a plugin block has a title instead of a wall of small print. - junction plugin: keeps every response header from /mcp, the status route and /v1/models; the widget shows the X-Junction-* routing stats, /junction lists all headers per source. It reads the status aliases (/status, /v1/status, /queue, /v1/queue) and remembers the one that answered, parses queue, endpoint p95/exhausted counts, and counts the models (/v1/models, probed on its own slower interval because it goes upstream). - SSE: blank lines no longer abort a pretty-printed object, a truncated tail is dropped instead of failing the turn ("incomplete data line" is gone), and a [DONE] with a fragment clears it. - retries: a request that fails before anything streamed (connection, missing status, 5xx) is tried three more times, 5 s apart; 4xx is not retried, and after the first chunk the error is reported instead of printing the answer twice. Ctrl-C ends a wait at once; SPLINTER_RETRY_WAIT_MS overrides the wait. - tests: test_sse (split object across events, truncated tail), test_agent (four 500s = four requests; two 500s then an answer), test_engine and test_protocol (models list), test_junction (headers, aliases, models), test_ui (/model picker), test_focus (status keys). make check: all tests passed. --- README.md | 25 +- docs/CONFIG.md | 4 +- docs/PLUGINS.md | 27 ++- docs/PROTOCOL.md | 9 + include/splinter.h | 12 + include/splinter_engine.h | 8 + plugins/focus/focus.c | 8 +- plugins/junction/junction.c | 471 ++++++++++++++++++++++++++++-------- share/locale/de.msg | 7 + share/locale/en.msg | 7 + share/locale/pt_BR.msg | 7 + src/backend/agent.c | 186 ++++++++++---- src/backend/engine.c | 8 + src/backend/providers.c | 36 +++ src/backend/providers.h | 10 + src/backend/sse.c | 48 ++-- src/frontend/curses.c | 396 +++++++++++++++++++++++++++--- src/frontend/protocol.c | 32 +++ src/frontend/ui_backend.h | 4 + src/frontend/ui_local.c | 14 ++ src/frontend/ui_remote.c | 51 ++++ tests/fake_junction.py | 48 +++- tests/test_agent.c | 23 +- tests/test_engine.c | 28 +++ tests/test_junction.c | 14 +- tests/test_protocol.sh | 12 + tests/test_sse.c | 24 +- tests/test_ui.sh | 7 +- 28 files changed, 1282 insertions(+), 244 deletions(-) diff --git a/README.md b/README.md index 50965a9..426ca29 100644 --- a/README.md +++ b/README.md @@ -308,9 +308,19 @@ line, and a reasoning model's own `reasoning_content` is shown dimmed, in sequence, instead of being hidden. In one-shot mode the text goes straight to stdout as it comes. -Both directions are covered by `test_sse`, which feeds recorded lines: plain -text, a tool call split across three chunks, two calls in one turn, a broken -data line, and the keepalive lines that carry nothing. +A data object split across SSE events, a blank line between its lines and a +truncated trailing fragment are all tolerated: the parser buffers until the +object is complete and drops a fragment that never is, instead of failing a +turn that already has its answer. `test_sse` feeds recorded lines: plain text, +a tool call split across three chunks, two calls in one turn, a pretty-printed +object across events, a truncated tail, and the keepalive lines that carry +nothing. + +A request that fails before anything was streamed is tried again three times, +five seconds apart; a broken connection, a missing status and a 5xx qualify, a +401 or 404 does not. After the first streamed chunk the retry stops, because +printing the same answer twice is worse than reporting the provider's error. +Ctrl-C during a wait ends it at once. ## Colour, measured @@ -517,8 +527,13 @@ one you press. The choice is written to `.d/90-model.conf` as `default = PROVIDER[/MODEL]`, so the next start uses it too; picking `main` deletes that file. `/model ` keeps the endpoint and takes another model from it. `/model probe` asks every endpoint -`/v1/models` and offers what it really serves. The TUI has the same `/model` -(list, or `/model `), without buttons. +`/v1/models` and offers what it really serves. + +In the curses chat, `/model` alone opens a picker: Up/Down move, typing filters +by provider or model, Enter takes the highlighted selector, Esc cancels. It is +the same list the clients get from the `models` protocol command, so `--attach` +has it too, and the actual switch is still the ordinary `/model ` +command. `/connect` works the same in the TUI, one answer per line. It adds a provider in four answers — name, endpoint, model, key diff --git a/docs/CONFIG.md b/docs/CONFIG.md index 9cc5672..9d4c2e9 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -371,7 +371,9 @@ server it already uses; its own block may override them: plugin junction { url = http://127.0.0.1:8090/mcp header = "Authorization: Bearer ${JUNCTION_TOKEN}" - interval = 5000 # ms between checks, default 5000 + interval = 5000 # ms between /mcp and status checks + models_interval = 60000 # ms between /v1/models probes + status_path = /status # first alias; /v1/status, /queue, /v1/queue follow } ``` diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md index cf5d6be..91c57eb 100644 --- a/docs/PLUGINS.md +++ b/docs/PLUGINS.md @@ -262,23 +262,34 @@ X-Junction-Mcp: 1 and that header is the identity: a 200 with the header is junction, a 200 without it is "not junction, or a proxy in front of it" — a health check that -trusts any answer is wrong exactly when it matters. The plugin checks `/mcp` -for the header and reads `/status` for junction's own counters (uptime, how -many MCP servers answer, queue, requests, endpoints). It does not count a -second time. +trusts any answer is wrong exactly when it matters. + +Every response header is kept, not only the identity one. The model route adds +the routing statistics (`X-Junction-Endpoint`, `X-Junction-Ms`, +`X-Junction-Cache`), `/status` adds the ordinary HTTP headers. The widget shows +the junction ones as one compact stats line; `/junction` prints every header of +every probe, grouped by source. ``` -junction: 20m up mcp 5/5 -q 1/32 req 11 ok 0 fail ep 25 -hdr X-Junction-Mcp seen +junction +20m up mcp 5/5 models 9 +endpoint=opencode-go ms=449 cache=off mcp=1 +q 1/32 req 11 ok 0 fail ep 25 (3 ex) p95 500ms ``` +The numbers come from the status route (uptime, MCP servers, queue, requests, +endpoints, p95) and `/v1/models` (how many models it serves). junction accepts +`/status`, `/v1/status`, `/queue` and `/v1/queue` as the same route; the plugin +remembers which one answered and only tries the whole list when it stops. It +does not count a second time. + That is a widget, a status segment (`junction 20m up`), the tool `junction_status` and `/junction`. The address and the key come from the plugin's own block, else from the `mcp junction` server, else from `SPLINTER_JUNCTION_URL` / `SPLINTER_JUNCTION_TOKEN`. The header is never printed: it carries the key. `interval` (milliseconds, default 5000) sets how -often the tick asks. +often the tick asks; `models_interval` (default 60000) how often the model +route is probed, because that one goes upstream and the other two do not. ## sysinfo diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index ce5c3d1..06a4aad 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -156,6 +156,15 @@ Ask what a command palette may offer: `"ev":"commands"`, `"names":["agent","connect","model",...]` — the same list Tab completes in the curses front end, plugin commands and `commands/` programs included. +### `{"cmd":"models"}` + +The list `/model` takes, for a picker: `"ev":"models"` with +`"items":[{"sel":"junction","label":"junction qwen3.6-35b","current":true},...]`. +`sel` is what goes after `/model `, `label` is what the picker shows, and +`current` marks the model the run is on. It is the configuration (providers, +then pools), not a network probe, so it answers at once; `/model ` +through `input` does the switch. + ### `{"cmd":"ping"}` / `{"cmd":"quit"}` `pong`; and a clean shutdown: `quit` event, server closes the socket and exits diff --git a/include/splinter.h b/include/splinter.h index 1ac0d61..b98783e 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -59,6 +59,18 @@ enum sp_auth { struct sp_tool; +/* + * One choice /model takes, for a picker: the selector to type after /model, + * a label to show, and whether it is the current one. SP_MODEL_CHOICES is the + * most a caller's array has to hold (main + delegates + exits + pools). + */ +#define SP_MODEL_CHOICES 96 +struct sp_model_choice { + char sel[320]; + char label[512]; + int current; +}; + /* Return 0 on success. The observation is written into out. */ typedef int (*sp_tool_run)(const char *args_json, struct sp_buf *out, void *ctx); diff --git a/include/splinter_engine.h b/include/splinter_engine.h index 1c22e09..0173bb7 100644 --- a/include/splinter_engine.h +++ b/include/splinter_engine.h @@ -126,6 +126,14 @@ struct sp_engine_state { int sp_engine_state(struct sp_engine *, struct sp_engine_state *); +/* + * The choices /model takes - every provider, then every pool - with the model + * as the label and the current one marked. Configuration, not a network probe: + * a picker must open at once. Returns how many were written. + */ +size_t sp_engine_models(struct sp_engine *, struct sp_model_choice *, + size_t max); + /* -------------------------------------------------------------- lifecycle */ int sp_engine_open(struct sp_engine **, const struct sp_engine_opts *, diff --git a/plugins/focus/focus.c b/plugins/focus/focus.c index cb6613b..bd5ecc4 100644 --- a/plugins/focus/focus.c +++ b/plugins/focus/focus.c @@ -481,9 +481,11 @@ focus_command(struct sp_host *h, const char *args, struct sp_buf *out, pthread_mutex_unlock(&focus_lock); if (g[0] == '\0') return sp_buf_puts(out, sp_td("focus.none", "no goal set (/goal )")); - return sp_buf_printf(out, sp_td(done ? "focus.status_done" : - "focus.status", done ? - "goal: %s [succeeded] (%u recaps, every %u turns)" : + if (done) + return sp_buf_printf(out, sp_td("focus.status_done", + "goal: %s [succeeded] (%u recaps, every %u turns)"), + g, n, every); + return sp_buf_printf(out, sp_td("focus.status", "goal: %s (%u recaps, every %u turns)"), g, n, every); } snprintf(goal, sizeof(goal), "%.*s", GOAL_MAX, args); diff --git a/plugins/junction/junction.c b/plugins/junction/junction.c index 2d6b232..5b293ac 100644 --- a/plugins/junction/junction.c +++ b/plugins/junction/junction.c @@ -17,16 +17,26 @@ * "not junction", not as "up" - a health check that trusts any answer is a * health check that is wrong exactly when it matters. * + * Every response header is kept, not only the identity one: the model route + * adds the routing statistics (X-Junction-Endpoint, X-Junction-Ms, + * X-Junction-Cache), /status adds the ordinary HTTP headers. The widget shows + * the junction ones as one compact statistics line, /junction prints every + * header of every probe grouped by source. + * * The numbers come from /status (uptime, the MCP servers it aggregates, the - * queue, request counts, endpoints). They are junction's own counters; this - * plugin does not count requests a second time. + * queue, request counts, endpoints) and /v1/models (how many models it + * serves). junction accepts /status, /v1/status, /queue and /v1/queue as the + * same route; the plugin remembers which one answered, so a changed alias does + * not cost a probe on every tick. * * Configuration, in the plugin's own block or the MCP server it already has: * * plugin junction { - * url = http://127.0.0.1:8090/mcp - * header = "Authorization: Bearer ${JUNCTION_TOKEN}" - * interval = 5000 # ms, default 5000 + * url = http://127.0.0.1:8090/mcp # the MCP endpoint + * header = "Authorization: Bearer ${JUNCTION_TOKEN}" + * interval = 5000 # ms between MCP/status checks, default 5000 + * models_interval = 60000 # ms between /v1/models probes, default 60000 + * status_path = /status # first alias to try * } * * Without a block the `mcp junction { url = ... header = ... }` server is used, @@ -52,7 +62,22 @@ #define J_URL_MAX 512 #define J_HDR_MAX 512 #define J_DEFAULT_MS 5000 +#define J_MODELS_MS 60000 #define J_TIMEOUT_S "4" +#define J_MAX_HEADERS 24 +#define J_STAT_MAX 768 +#define J_ALIASES 4 + +struct jhead { + char name[80]; + char value[200]; +}; + +struct jset { + struct jhead v[J_MAX_HEADERS]; + size_t n; + long http; +}; /* Everything the tick thread writes and the UI thread reads lives here. */ static struct { @@ -60,20 +85,33 @@ static struct { char url[J_URL_MAX]; char header[J_HDR_MAX]; unsigned interval_ms; + unsigned models_ms; + char status_path[24]; /* the alias that answered last */ + int status_alias; /* index into aliases, -1 unknown */ char widget[1024]; /* the sidebar block, no colon in line 2+ */ + char stats[J_STAT_MAX]; /* the X-Junction-* statistics */ char status[160]; /* the status segment */ int identity; /* X-Junction-Mcp was seen */ int body_ok; /* /status answered JSON */ long http_mcp; /* HTTP status of GET /mcp */ - long http_status; /* HTTP status of GET /status */ + long http_status; /* HTTP status of the status route */ + long http_models; /* HTTP status of /v1/models */ unsigned long uptime_s; unsigned mcp_ok, mcp_total; - unsigned queue_inflight, queue_max; + unsigned queue_inflight, queue_waiting, queue_max; unsigned req_ok, req_fail; - unsigned endpoints; + unsigned endpoints, exhausted; + long p95_ms; + unsigned models; + struct jset h_mcp, h_status, h_models; + time_t next_models; time_t checked; -} j = { .lock = PTHREAD_MUTEX_INITIALIZER }; +} j = { .lock = PTHREAD_MUTEX_INITIALIZER, .status_alias = -1 }; + +static const char *const status_aliases[J_ALIASES] = { + "/status", "/v1/status", "/queue", "/v1/queue" +}; /* "1d4h", "2h07m", "20m", "41s" */ static void @@ -90,7 +128,7 @@ human_duration(unsigned long s, char *buf, size_t len) snprintf(buf, len, "%lus", s); } -/* the address without its /mcp tail: /status and /mcp are two routes on it */ +/* the address without its /mcp tail: the other routes live beside it */ static void base_url(char *buf, size_t len) { @@ -118,50 +156,84 @@ header_status(const char *headers) return sp != NULL ? strtol(sp + 1, NULL, 10) : 0; } -/* one response header, case-blind; 1 when it is there */ -static int -header_value(const char *headers, const char *name, char *out, size_t cap) +static void +set_clear(struct jset *s) { - const char *p = headers; - size_t n = strlen(name); + s->n = 0; + s->http = 0; +} - while (p != NULL && *p != '\0') { +/* + * The whole response header block into a set: the status line is not a header, + * a folded line (continuation) is joined to the header before it. The block is + * "Name: value" lines; every one of them is kept, not only X-Junction-*. + */ +static void +set_parse(const char *block, struct jset *s) +{ + const char *p = block; + + set_clear(s); + s->http = header_status(block); + while (p != NULL && *p != '\0' && s->n < J_MAX_HEADERS) { const char *nl = strchr(p, '\n'); size_t len = nl != NULL ? (size_t)(nl - p) : strlen(p); + const char *colon; + char *name, *value; + size_t nl2, vl; - if (len > n && strncasecmp(p, name, n) == 0 && p[n] == ':') { - const char *v = p + n + 1; - size_t vl; - - while (*v == ' ' || *v == '\t') - v++; - vl = len - (size_t)(v - p); - while (vl > 0 && (v[vl - 1] == '\r' || v[vl - 1] == ' ' || - v[vl - 1] == '\t')) - vl--; - snprintf(out, cap, "%.*s", (int)vl, v); - return 1; + while (len > 0 && (p[len - 1] == '\r' || p[len - 1] == ' ' || + p[len - 1] == '\t')) + len--; + colon = memchr(p, ':', len); + if (colon != NULL && (size_t)(colon - p) < sizeof(s->v[0].name)) { + nl2 = (size_t)(colon - p); + name = s->v[s->n].name; + memcpy(name, p, nl2); + name[nl2] = '\0'; + value = s->v[s->n].value; + while ((size_t)(colon + 1 - p) < len && + (colon[1] == ' ' || colon[1] == '\t')) + colon++; + vl = len - (size_t)(colon + 1 - p); + if (vl >= sizeof(s->v[0].value)) + vl = sizeof(s->v[0].value) - 1; + memcpy(value, colon + 1, vl); + value[vl] = '\0'; + s->n++; } p = nl != NULL ? nl + 1 : NULL; } +} + +/* the value of the first header with this name in a set */ +static int +set_value(const struct jset *s, const char *name, char *out, size_t cap) +{ + size_t i; + + for (i = 0; i < s->n; i++) { + if (strcasecmp(s->v[i].name, name) == 0) { + snprintf(out, cap, "%s", s->v[i].value); + return 1; + } + } return 0; } /* - * One GET. headers_only returns the response headers instead of the body; - * otherwise the body is returned and the HTTP status is appended by curl's -w - * on its own last line, the same shape the MCP client uses. + * One request. The output is the header block and, unless headers_only, the + * body; curl's -w appends the status code on its own last line. The two parts + * are split at the empty line, so callers get both without a second request - + * the routing headers are the reason this exists. */ static char * -junction_get(const char *url, int headers_only, long *http) +junction_get(const char *url, struct jset *set, char **bodyp) { - static const char *const args_headers[] = { - "-s", "-S", "-m", J_TIMEOUT_S, "-o", "/dev/null", "-D", "-", + static const char *const args[] = { + "-s", "-S", "-m", J_TIMEOUT_S, "-D", "-", "-w", "\n%{http_code}", NULL }; - static const char *const args_body[] = { - "-s", "-S", "-m", J_TIMEOUT_S, "-w", "\n%{http_code}", NULL - }; const char *hdrs[2]; char hdr[J_HDR_MAX]; struct sp_buf out, err; @@ -169,9 +241,11 @@ junction_get(const char *url, int headers_only, long *http) ssize_t got; pid_t pid; int fd, st = 0; - char *ret; + char *raw, *body = NULL, *sep; + size_t hlen; - *http = 0; + *bodyp = NULL; + set_clear(set); if (sp_buf_init(&out) != 0) return NULL; (void)sp_buf_init(&err); @@ -181,8 +255,7 @@ junction_get(const char *url, int headers_only, long *http) hdrs[0] = hdr[0] != '\0' ? hdr : NULL; hdrs[1] = NULL; - fd = sp_curl_start(headers_only ? args_headers : args_body, url, hdrs, - 1, &pid, &err); + fd = sp_curl_start(args, url, hdrs, 1, &pid, &err); if (fd < 0) { sp_buf_free(&err); sp_buf_free(&out); @@ -199,20 +272,39 @@ junction_get(const char *url, int headers_only, long *http) sp_buf_free(&out); return NULL; } - if (headers_only) { - *http = header_status(out.p); - } else { - char *nl = strrchr(out.p, '\n'); + sp_buf_free(&err); + raw = out.p; + + /* the header block ends at the first empty line */ + hlen = 0; + sep = strstr(raw, "\r\n\r\n"); + if (sep != NULL) { + hlen = (size_t)(sep - raw); + body = sep + 4; + } else if ((sep = strstr(raw, "\n\n")) != NULL) { + hlen = (size_t)(sep - raw); + body = sep + 2; + } + { + char block[16384]; + + if (hlen >= sizeof(block)) + hlen = sizeof(block) - 1; + memcpy(block, raw, hlen); + block[hlen] = '\0'; + set_parse(block, set); + } + if (body != NULL) { + char *nl = strrchr(body, '\n'); if (nl != NULL) { - *http = strtol(nl + 1, NULL, 10); + set->http = strtol(nl + 1, NULL, 10); *nl = '\0'; - out.len = (size_t)(nl - out.p); } - } - sp_buf_free(&err); - ret = out.p != NULL ? out.p : calloc(1, 1); - return ret; + *bodyp = body; + } else + set->http = header_status(raw); + return raw; } /* junction's /status: the counters it publishes, read once per tick */ @@ -221,7 +313,7 @@ read_status(const char *body) { mcp_json *root = mcp_parse(body); const mcp_json *m; - unsigned ok = 0, total = 0; + unsigned ok = 0, total = 0, exhausted = 0; size_t i; if (root == NULL) @@ -229,9 +321,10 @@ read_status(const char *body) pthread_mutex_lock(&j.lock); j.uptime_s = (unsigned long)mcp_arg_int(root, "uptime_s", 0); j.req_ok = j.req_fail = 0; - j.endpoints = 0; + j.endpoints = j.exhausted = 0; j.mcp_ok = j.mcp_total = 0; - j.queue_inflight = j.queue_max = 0; + j.queue_inflight = j.queue_waiting = j.queue_max = 0; + j.p95_ms = 0; m = mcp_arg(root, "requests"); if (m != NULL) { @@ -241,6 +334,7 @@ read_status(const char *body) m = mcp_arg(root, "queue"); if (m != NULL) { j.queue_inflight = (unsigned)mcp_arg_int(m, "inflight", 0); + j.queue_waiting = (unsigned)mcp_arg_int(m, "waiting", 0); j.queue_max = (unsigned)mcp_arg_int(m, "max_inflight", 0); } m = mcp_arg(root, "mcp"); @@ -254,15 +348,90 @@ read_status(const char *body) } } m = mcp_arg(root, "endpoints"); - if (m != NULL) + if (m != NULL) { j.endpoints = (unsigned)mcp_array_len(m); + for (i = 0; i < j.endpoints; i++) { + const mcp_json *e = mcp_array_at(m, i); + long p95; + + if (e == NULL) + continue; + if (mcp_arg_int(e, "exhausted", 0) == 1) + exhausted++; + p95 = (long)mcp_arg_int(e, "p95_ms", 0); + if (p95 > j.p95_ms) + j.p95_ms = p95; + } + } j.mcp_ok = ok; j.mcp_total = total; + j.exhausted = exhausted; j.body_ok = 1; pthread_mutex_unlock(&j.lock); mcp_json_free(root); } +/* how many models the router serves; the list itself is /model's business */ +static void +read_models(const char *body) +{ + mcp_json *root = mcp_parse(body); + const mcp_json *m; + + if (root == NULL) + return; + m = mcp_arg(root, "data"); + pthread_mutex_lock(&j.lock); + j.models = m != NULL ? (unsigned)mcp_array_len(m) : 0; + pthread_mutex_unlock(&j.lock); + mcp_json_free(root); +} + +/* "X-Junction-Mcp: 1" -> "mcp=1", all sets, first one per name wins */ +static void +compose_stats(void) +{ + static const struct jset *sets[3]; + struct jhead seen[J_MAX_HEADERS]; + size_t nseen = 0, off = 0, s, i, k; + char buf[J_STAT_MAX]; + + sets[0] = &j.h_models; + sets[1] = &j.h_status; + sets[2] = &j.h_mcp; + buf[0] = '\0'; + for (s = 0; s < 3; s++) { + const struct jset *set = sets[s]; + + for (i = 0; i < set->n; i++) { + const char *name = set->v[i].name; + char key[40]; + size_t kl; + + if (strncasecmp(name, "X-Junction-", 11) != 0) + continue; + for (k = 0; k < nseen; k++) + if (strcasecmp(seen[k].name, name) == 0) + break; + if (k < nseen) + continue; /* same header from another route */ + if (nseen < J_MAX_HEADERS) + snprintf(seen[nseen++].name, sizeof(seen[0].name), + "%s", name); + snprintf(key, sizeof(key), "%s", name + 11); + for (kl = 0; key[kl] != '\0'; kl++) + if (key[kl] >= 'A' && key[kl] <= 'Z') + key[kl] = (char)(key[kl] - 'A' + 'a'); + off += (size_t)snprintf(buf + off, sizeof(buf) - off, + "%s%s=%s", off > 0 ? " " : "", key, + set->v[i].value); + if (off >= sizeof(buf)) + break; + } + } + snprintf(j.stats, sizeof(j.stats), "%s", buf); +} + /* the text the sidebar, the status segment and /junction show; lock held */ static void compose(void) @@ -270,6 +439,7 @@ compose(void) char d[32]; human_duration(j.uptime_s, d, sizeof(d)); + compose_stats(); if (!j.identity) { /* * Continuation lines carry no colon: the sidebar reads a line @@ -277,27 +447,29 @@ compose(void) */ snprintf(j.widget, sizeof(j.widget), "no X-Junction-Mcp header\n" - "mcp http %ld status http %ld\n" + "mcp http %ld status http %ld models http %ld\n" "not junction, or a proxy in front of it", - j.http_mcp, j.http_status); + j.http_mcp, j.http_status, j.http_models); snprintf(j.status, sizeof(j.status), "junction not recognised"); return; } if (!j.body_ok) { snprintf(j.widget, sizeof(j.widget), - "identified, but /status did not answer\n" - "mcp http %ld status http %ld", - j.http_mcp, j.http_status); + "identified, but the status route did not answer\n" + "mcp http %ld status http %ld (%s)", + j.http_mcp, j.http_status, j.status_path); snprintf(j.status, sizeof(j.status), "junction up, status http %ld", j.http_status); return; } snprintf(j.widget, sizeof(j.widget), - "%s up mcp %u/%u\n" - "q %u/%u req %u ok %u fail ep %u\n" - "hdr X-Junction-Mcp %s", - d, j.mcp_ok, j.mcp_total, j.queue_inflight, j.queue_max, - j.req_ok, j.req_fail, j.endpoints, j.identity ? "seen" : "missing"); + "%s up mcp %u/%u models %u\n" + "%s\n" + "q %u/%u req %u ok %u fail ep %u (%u ex) p95 %ldms", + d, j.mcp_ok, j.mcp_total, j.models, + j.stats[0] != '\0' ? j.stats : "(no X-Junction headers)", + j.queue_inflight, j.queue_max, j.req_ok, j.req_fail, + j.endpoints, j.exhausted, j.p95_ms); if (j.mcp_total > 0 && j.mcp_ok < j.mcp_total) snprintf(j.status, sizeof(j.status), "junction %s up, mcp %u/%u", d, j.mcp_ok, j.mcp_total); @@ -305,14 +477,41 @@ compose(void) snprintf(j.status, sizeof(j.status), "junction %s up", d); } +/* GET one alias of the status route; 1 when it answered JSON */ +static int +probe_status(const char *base, const char *path, struct jset *set) +{ + char url[J_URL_MAX + 40]; + char *body = NULL; + char *raw; + int ok = 0; + + snprintf(url, sizeof(url), "%s%s", base, path); + raw = junction_get(url, set, &body); + if (raw != NULL) { + if (body != NULL && set->http == 200 && body[0] == '{') { + read_status(body); + ok = 1; + } + free(raw); + } + return ok; +} + static void probe(void) { - char base[J_URL_MAX], url[J_URL_MAX + 32]; - char hval[64] = ""; - char *headers = NULL, *body = NULL; - long http_mcp = 0, http_status = 0; - int identity = 0, body_ok = 0; + char base[J_URL_MAX], url[J_URL_MAX + 40]; + char hval[64] = "", path[24]; + char *body = NULL, *raw; + long http_mcp = 0, http_models = 0; + int identity = 0, body_ok = 0, i; + struct jset hmcp, hstatus, hmodels; + time_t now = time(NULL); + + set_clear(&hmcp); + set_clear(&hstatus); + set_clear(&hmodels); base_url(base, sizeof(base)); if (base[0] == '\0') { @@ -327,23 +526,62 @@ probe(void) return; } snprintf(url, sizeof(url), "%s/mcp", base); - headers = junction_get(url, 1, &http_mcp); - if (headers != NULL) { - if (header_value(headers, "X-Junction-Mcp", hval, sizeof(hval))) + raw = junction_get(url, &hmcp, &body); + if (raw != NULL) { + http_mcp = hmcp.http; + if (set_value(&hmcp, "X-Junction-Mcp", hval, sizeof(hval))) identity = 1; - free(headers); + free(raw); } - snprintf(url, sizeof(url), "%s/status", base); - body = junction_get(url, 0, &http_status); - if (body != NULL) { - read_status(body); - body_ok = 1; - free(body); + + /* + * /status, /v1/status, /queue and /v1/queue are the same route on + * junction. Remember the one that answered; try the whole list from + * the start only when it stops answering. + */ + if (j.status_alias >= 0 && j.status_alias < J_ALIASES) { + snprintf(path, sizeof(path), "%s", + status_aliases[j.status_alias]); + body_ok = probe_status(base, path, &hstatus); + } + for (i = 0; !body_ok && i < J_ALIASES; i++) { + if (j.status_alias == i) + continue; + snprintf(path, sizeof(path), "%s", status_aliases[i]); + body_ok = probe_status(base, path, &hstatus); + if (body_ok) { + j.status_alias = i; + break; + } + } + if (!body_ok) { + j.status_alias = -1; + snprintf(path, sizeof(path), "%s", status_aliases[0]); + } + + /* the model route carries the routing headers; less often than the rest */ + if (now >= j.next_models) { + snprintf(url, sizeof(url), "%s/v1/models", base); + raw = junction_get(url, &hmodels, &body); + if (raw != NULL) { + http_models = hmodels.http; + if (body != NULL && hmodels.http == 200 && + body[0] == '{') + read_models(body); + free(raw); + } + j.next_models = now + (time_t)(j.models_ms / 1000); } pthread_mutex_lock(&j.lock); + snprintf(j.status_path, sizeof(j.status_path), "%s", path); + j.h_mcp = hmcp; + j.h_status = hstatus; + if (http_models != 0) + j.h_models = hmodels; j.http_mcp = http_mcp; - j.http_status = http_status; + j.http_status = hstatus.http; + j.http_models = http_models != 0 ? http_models : j.h_models.http; j.identity = identity; j.body_ok = body_ok; j.checked = time(NULL); @@ -355,39 +593,53 @@ probe(void) static void snapshot_text(struct sp_buf *out) { - char d[32], url[J_URL_MAX], hdr[8]; - int identity, body_ok; - long hm, hs; - unsigned ok, total, inflight, qmax, rok, rfail, eps; + char d[32], url[J_URL_MAX], hdr[8], status_path[24]; + int identity, body_ok; + struct jset hm, hs, hmod; + size_t src, i; pthread_mutex_lock(&j.lock); snprintf(url, sizeof(url), "%s", j.url); + snprintf(status_path, sizeof(status_path), "%s", j.status_path); identity = j.identity; body_ok = j.body_ok; - hm = j.http_mcp; - hs = j.http_status; - ok = j.mcp_ok; - total = j.mcp_total; - inflight = j.queue_inflight; - qmax = j.queue_max; - rok = j.req_ok; - rfail = j.req_fail; - eps = j.endpoints; snprintf(hdr, sizeof(hdr), "%s", j.header[0] != '\0' ? "yes" : "no"); + hm = j.h_mcp; + hs = j.h_status; + hmod = j.h_models; human_duration(j.uptime_s, d, sizeof(d)); - pthread_mutex_unlock(&j.lock); sp_buf_printf(out, "junction: %s\n", identity && body_ok ? "up" : identity ? "identified, status unreadable" : "not recognised"); sp_buf_printf(out, " url: %s\n", url[0] != '\0' ? url : "(none)"); sp_buf_printf(out, " header: %s (X-Junction-Mcp %s)\n", hdr, identity ? "seen" : "missing"); - sp_buf_printf(out, " http: /mcp %ld, /status %ld\n", hm, hs); + sp_buf_printf(out, " http: /mcp %ld, %s %ld, /v1/models %ld\n", + hm.http, status_path, hs.http, hmod.http); sp_buf_printf(out, " uptime: %s\n", d); - sp_buf_printf(out, " mcp: %u/%u answering\n", ok, total); - sp_buf_printf(out, " queue: %u/%u\n", inflight, qmax); - sp_buf_printf(out, " requests: %u ok, %u fail endpoints: %u\n", - rok, rfail, eps); + sp_buf_printf(out, " mcp: %u/%u answering\n", j.mcp_ok, j.mcp_total); + sp_buf_printf(out, " queue: %u/%u, %u waiting\n", j.queue_inflight, + j.queue_max, j.queue_waiting); + sp_buf_printf(out, " requests: %u ok, %u fail\n", j.req_ok, + j.req_fail); + sp_buf_printf(out, " endpoints: %u, %u exhausted, p95 %ldms\n", + j.endpoints, j.exhausted, j.p95_ms); + sp_buf_printf(out, " models: %u\n", j.models); + sp_buf_printf(out, " statistics: %s\n", + j.stats[0] != '\0' ? j.stats : "(no X-Junction headers)"); + for (src = 0; src < 3; src++) { + const struct jset *s = src == 0 ? &hm : + (src == 1 ? &hs : &hmod); + const char *label = src == 0 ? "/mcp" : + (src == 1 ? status_path : "/v1/models"); + + sp_buf_printf(out, " headers %s (http %ld, %zu):\n", label, + s->http, s->n); + for (i = 0; i < s->n; i++) + sp_buf_printf(out, " %s: %s\n", s->v[i].name, + s->v[i].value); + } + pthread_mutex_unlock(&j.lock); } static void @@ -503,6 +755,17 @@ resolve_config(struct sp_host *h) j.interval_ms = 1000; if (j.interval_ms > 600000) j.interval_ms = 600000; + v = sp_host_plugin_config(h, "junction", "models_interval"); + if (v != NULL && atoi(v) > 0) + j.models_ms = (unsigned)atoi(v); + if (j.models_ms < 10000) + j.models_ms = J_MODELS_MS; + v = sp_host_plugin_config(h, "junction", "status_path"); + if (v != NULL && *v == '/') + snprintf(j.status_path, sizeof(j.status_path), "%s", v); + else + snprintf(j.status_path, sizeof(j.status_path), "%s", + status_aliases[0]); } static int @@ -513,8 +776,9 @@ junction_init(struct sp_host *h) static const struct sp_tool tool = { "junction_status", "The fleet router's health: whether it answers, the X-Junction-Mcp " - "identity header, uptime, how many MCP servers answer, the queue " - "and the request counts from junction's own /status.", + "identity header, every response header, uptime, how many MCP " + "servers answer, the queue, request counts, endpoints and the " + "number of models it serves.", "{\"type\":\"object\",\"properties\":{}}", SP_AUTH_READ, junction_tool, @@ -522,6 +786,7 @@ junction_init(struct sp_host *h) }; j.interval_ms = J_DEFAULT_MS; + j.models_ms = J_MODELS_MS; resolve_config(h); memset(&w, 0, sizeof(w)); w.name = "junction"; @@ -539,7 +804,7 @@ junction_init(struct sp_host *h) } static const struct sp_plugin junction_plugin = { - SP_PLUGIN_ABI, "junction", "1.0.0", junction_init, NULL, NULL + SP_PLUGIN_ABI, "junction", "1.2.0", junction_init, NULL, NULL }; const struct sp_plugin * diff --git a/share/locale/de.msg b/share/locale/de.msg index 81b0713..e5af5b5 100644 --- a/share/locale/de.msg +++ b/share/locale/de.msg @@ -16,6 +16,13 @@ ui.session_opened = Sitzung geoeffnet ui.session_gone = Sitzung %s ist weg - jetzt auf %s ui.compacted = Kontext kompaktiert: %zu->%zu Nachrichten, %s->%s (%s->%s) ui.steering_queued = Steuerung eingereiht +ui.steer_queued_line = Steuerung eingereiht: %s +ui.steer_failed = Steuerung nicht angenommen (kein Turn laeuft) +ui.model_title = Modell +ui.model_filter = filter: +ui.model_hint = tippen filtert Pfeile bewegen Enter waehlt Esc bricht ab +ui.model_empty = keine Modelle konfiguriert +ui.model_none = kein Treffer sidebar.session = Sitzung sidebar.cwd = Verzeichnis diff --git a/share/locale/en.msg b/share/locale/en.msg index 5c4041d..0e97043 100644 --- a/share/locale/en.msg +++ b/share/locale/en.msg @@ -15,6 +15,13 @@ ui.session_opened = session opened ui.session_gone = session %s is gone - now on %s ui.compacted = context compacted: %zu->%zu msgs, %s->%s (%s->%s) ui.steering_queued = steering queued +ui.steer_queued_line = steering queued: %s +ui.steer_failed = steering not accepted (no turn is running) +ui.model_title = model +ui.model_filter = filter: +ui.model_hint = type to filter Up/Down move Enter selects Esc cancels +ui.model_empty = no models configured +ui.model_none = no match sidebar.session = session sidebar.cwd = dir diff --git a/share/locale/pt_BR.msg b/share/locale/pt_BR.msg index 6238d5f..48cedd9 100644 --- a/share/locale/pt_BR.msg +++ b/share/locale/pt_BR.msg @@ -16,6 +16,13 @@ ui.session_opened = sessao aberta ui.session_gone = sessao %s sumiu - agora em %s ui.compacted = contexto compactado: %zu->%zu msgs, %s->%s (%s->%s) ui.steering_queued = direcionamento na fila +ui.steer_queued_line = direcionamento na fila: %s +ui.steer_failed = direcionamento nao aceito (nenhum turno em andamento) +ui.model_title = modelo +ui.model_filter = filtro: +ui.model_hint = digite para filtrar setas movem Enter escolhe Esc cancela +ui.model_empty = nenhum modelo configurado +ui.model_none = nenhum resultado ui.prompt_mark = > ui.steer_mark = direcionar> ui.swarm_locked = [enxame bloqueado] diff --git a/src/backend/agent.c b/src/backend/agent.c index 318bf5e..73237a0 100644 --- a/src/backend/agent.c +++ b/src/backend/agent.c @@ -22,6 +22,7 @@ #include #include +#include #include #include @@ -407,6 +408,144 @@ limit_retry(struct sp_agent *a, struct sp_buf *err, long status, return 1; } +#define SP_NET_RETRIES 3 +#define SP_NET_WAIT_S 5 + +/* mark whether anything was streamed before an error: a retry after that + * would print the same answer a second time */ +struct stream_guard { + sp_stream_cb cb; + void *ctx; + int produced; +}; + +static void +guarded_stream(void *ctx, int kind, const char *text) +{ + struct stream_guard *g = ctx; + + g->produced = 1; + if (g->cb != NULL) + g->cb(g->ctx, kind, text); +} + +/* + * Five seconds between retries; SPLINTER_RETRY_WAIT_MS overrides it so the + * tests do not sleep through their own suite, and an operator can shorten a + * long wait on a flaky link. + */ +static int +retry_wait_ms(void) +{ + static int ms = -1; + + if (ms < 0) { + const char *v = getenv("SPLINTER_RETRY_WAIT_MS"); + + ms = v != NULL && atoi(v) >= 0 ? atoi(v) : SP_NET_WAIT_S * 1000; + } + return ms; +} + +/* sleep in small steps, so Ctrl-C does not have to wait out a retry */ +static int +retry_sleep(struct sp_agent *a, int ms) +{ + int left = ms; + + while (left > 0) { + struct timespec ts; + int step = left > 100 ? 100 : left; + + if (a->cfg->cancel != NULL && *a->cfg->cancel) + return 0; + ts.tv_sec = 0; + ts.tv_nsec = (long)step * 1000000L; + (void)nanosleep(&ts, NULL); + left -= step; + } + return 1; +} + +/* + * One request, with the retry policy: a failure that left no text on the + * screen is tried again up to three times, five seconds apart. After the + * first streamed chunk a retry would duplicate the answer, so the turn fails + * with the provider's error instead. A 401 or 404 is the configuration's + * answer, not a transient fault, and is not repeated. + * + * 0: reply is the answer; 1: a usage limit was waited out, ask again; + * -1: failed, err explains. + */ +static int +agent_request(struct sp_agent *a, struct sp_conv *conv, struct sp_reply *reply, + struct sp_buf *err, int *limit_tries) +{ + struct stream_guard guard; + int attempt; + + memset(reply, 0, sizeof(*reply)); + guard.cb = a->cfg->stream; + guard.ctx = a->cfg->stream_ctx; + for (attempt = 0; ; attempt++) { + int sent_rc; + + guard.produced = 0; + if (guard.cb != NULL && a->tr.send_stream != NULL) + sent_rc = a->tr.send_stream(a->tr.ctx, conv, reply, err, + guarded_stream, &guard); + else + sent_rc = a->tr.send(a->tr.ctx, conv, reply, err); + if (sent_rc == 0 && reply->status >= 200 && + reply->status <= 299) + return 0; + if (sent_rc != 0) { + sp_host_provider_account(a->host, a->tr.provider, + a->tr.key_id, reply->status, 0, 0); + } else { + sp_host_provider_account(a->host, a->tr.provider, + a->tr.key_id, reply->status, + (size_t)(reply->tokens_in > 0 ? + reply->tokens_in : 0), + (size_t)(reply->tokens_out > 0 ? + reply->tokens_out : 0)); + quota_hint(a->tr.provider, a->tr.key_id, reply->status, + reply->retry_after_s); + /* a refused call benches the provider the run is on */ + if (reply->status == 429 || reply->status == 402 || + reply->status == 529) + sp_cooldown_set(sp_usage_active(), + (long)time(NULL) + + (reply->retry_after_s > 0 ? + reply->retry_after_s : 300), + "refused (HTTP limit)"); + sp_buf_printf(err, "agent: transport status %ld", + reply->status); + } + if (limit_retry(a, err, reply->status, reply->retry_after_s, + 0, limit_tries)) { + sp_reply_free(reply); + return 1; + } + if (attempt < SP_NET_RETRIES && !guard.produced && + (sent_rc != 0 || reply->status == 0 || + reply->status >= 500)) { + sp_logf("agent", "retry %d/%d in %dms: %s", + attempt + 1, SP_NET_RETRIES, retry_wait_ms(), + err->p != NULL ? err->p : "?"); + sp_buf_clear(err); + sp_reply_free(reply); + if (!retry_sleep(a, retry_wait_ms())) { + sp_buf_puts(err, + "agent: cancelled by operator"); + return -1; + } + continue; + } + return -1; + } +} + static int agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision, struct sp_buf *answer, struct sp_buf *err) @@ -530,53 +669,16 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision, } } { - int sent_rc; + int req_rc = agent_request(a, conv, &reply, err, + &limit_tries); - if (a->cfg->stream != NULL && - a->tr.send_stream != NULL) - sent_rc = a->tr.send_stream(a->tr.ctx, conv, - &reply, err, a->cfg->stream, - a->cfg->stream_ctx); - else - sent_rc = a->tr.send(a->tr.ctx, conv, &reply, - err); - if (sent_rc != 0) { - sp_host_provider_account(a->host, a->tr.provider, - a->tr.key_id, reply.status, 0, 0); - if (limit_retry(a, err, reply.status, - reply.retry_after_s, 0, &limit_tries)) { - sp_reply_free(&reply); - a->stats.steps--; - step--; - continue; - } - sp_reply_free(&reply); - goto out; - } - } - if (reply.status < 200 || reply.status > 299) { - sp_host_provider_account(a->host, a->tr.provider, - a->tr.key_id, reply.status, - (size_t)(reply.tokens_in > 0 ? reply.tokens_in : 0), - (size_t)(reply.tokens_out > 0 ? reply.tokens_out : 0)); - quota_hint(a->tr.provider, a->tr.key_id, reply.status, reply.retry_after_s); - /* a refused call benches the provider the run is on */ - if (reply.status == 429 || reply.status == 402 || - reply.status == 529) - sp_cooldown_set(sp_usage_active(), - (long)time(NULL) + (reply.retry_after_s > 0 ? - reply.retry_after_s : 300), "refused (HTTP limit)"); - sp_buf_printf(err, "agent: transport status %ld", - reply.status); - if (limit_retry(a, err, reply.status, reply.retry_after_s, - 0, &limit_tries)) { - sp_reply_free(&reply); + if (req_rc == 1) { /* limit waited out: ask again */ a->stats.steps--; step--; continue; } - sp_reply_free(&reply); - goto out; + if (req_rc != 0) + goto out; } sp_usage_record(sp_usage_active(), reply.tokens_in, diff --git a/src/backend/engine.c b/src/backend/engine.c index 93fbef9..957f7e0 100644 --- a/src/backend/engine.c +++ b/src/backend/engine.c @@ -280,6 +280,14 @@ sp_engine_set_stream(struct sp_engine *e, sp_stream_cb cb, void *ctx) const char * sp_engine_state_dir(struct sp_engine *e) { return e->sess.dir; } +size_t +sp_engine_models(struct sp_engine *e, struct sp_model_choice *v, size_t max) +{ + if (e == NULL) + return 0; + return sp_provider_choices(e->conf, e->cur_model, v, max); +} + /* /.agent: the profile a session was left in */ static void profile_path(struct sp_engine *e, char *buf, size_t cap) diff --git a/src/backend/providers.c b/src/backend/providers.c index 4da74a4..ad8863b 100644 --- a/src/backend/providers.c +++ b/src/backend/providers.c @@ -139,6 +139,42 @@ sp_provider_find(const struct sp_config *cfg, const char *id, size_t *idx) return 0; } +size_t +sp_provider_choices(const struct sp_config *cfg, const char *cur_model, + struct sp_model_choice *v, size_t max) +{ + struct sp_provider p; + size_t n, i, k = 0; + + if (cfg == NULL || v == NULL || max == 0) + return 0; + n = sp_provider_count(cfg); + for (i = 0; i < n && k < max; i++) { + if (sp_provider_at(cfg, i, &p) != 0) + continue; + snprintf(v[k].sel, sizeof(v[k].sel), "%s", p.id); + snprintf(v[k].label, sizeof(v[k].label), "%s %s", p.id, + p.model); + v[k].current = cur_model != NULL && *cur_model != '\0' && + strcmp(p.model, cur_model) == 0; + k++; + } + for (i = 0; i < cfg->npools && k < max; i++) { + const struct sp_pool *pl = &cfg->pool[i]; + size_t j, off; + + snprintf(v[k].sel, sizeof(v[k].sel), "%s", pl->id); + off = (size_t)snprintf(v[k].label, sizeof(v[k].label), + "%s pool (%s):", pl->id, pl->strategy); + for (j = 0; j < pl->nmembers && off < sizeof(v[k].label); j++) + off += (size_t)snprintf(v[k].label + off, + sizeof(v[k].label) - off, " %s", pl->member[j]); + v[k].current = 0; + k++; + } + return k; +} + int sp_provider_select(const struct sp_config *cfg, const char *sel, struct sp_provider *out, char *model, size_t modelcap) diff --git a/src/backend/providers.h b/src/backend/providers.h index fb7a10f..0dacaba 100644 --- a/src/backend/providers.h +++ b/src/backend/providers.h @@ -10,6 +10,7 @@ struct sp_pool; struct sp_agent; struct sp_transport; struct sp_buf; +struct sp_model_choice; /* * One reachable model: the endpoint, the model name and the variable the key @@ -32,6 +33,15 @@ size_t sp_provider_count(const struct sp_config *); int sp_provider_at(const struct sp_config *, size_t, struct sp_provider *); int sp_provider_find(const struct sp_config *, const char *id, size_t *idx); +/* + * The list /model shows: every provider (selector = its id) followed by every + * pool (selector = the pool id), with the model as the label and a marker for + * the one the run is on. No network: it is the configuration, not the answer + * to "what does the endpoint really serve". + */ +size_t sp_provider_choices(const struct sp_config *, const char *cur_model, + struct sp_model_choice *, size_t max); + /* * A selector (-m, /model) as one provider to switch to: a pool, a provider, * "provider/model" or a model name one provider has. Fills 'out' with that diff --git a/src/backend/sse.c b/src/backend/sse.c index 55bbfad..84c4f83 100644 --- a/src/backend/sse.c +++ b/src/backend/sse.c @@ -157,17 +157,15 @@ sp_sse_line(struct sp_sse *s, const char *line, struct sp_buf *out, s->last = 0; while (*line == ' ' || *line == '\t') line++; - /* An empty line ends an SSE event. If a data object never became JSON, - * that event is the error, not a keepalive. */ - if (*line == '\0' || *line == '\n') { - if (s->pending.len > 0) { - sp_buf_printf(err, "sse: unparseable data line: %.200s", - s->pending.p); - sp_buf_clear(&s->pending); - return -1; - } + /* + * An empty line ends an SSE event. A data object that is still growing + * is kept across the boundary: proxies insert blank lines between the + * lines of a pretty-printed object, and a blank line is not a reason + * to throw the answer away. Nothing is an error here; an object that + * never completes is dropped in sp_sse_finish(). + */ + if (*line == '\0' || *line == '\n') return 0; - } if (*line == ':') return 0; if (strncmp(line, "data:", 5) != 0) { @@ -180,12 +178,11 @@ sp_sse_line(struct sp_sse *s, const char *line, struct sp_buf *out, if (*payload == '\0') return 0; /* an empty data line is a keepalive */ if (strncmp(payload, "[DONE]", 6) == 0) { - if (s->pending.len > 0) { - sp_buf_printf(err, "sse: unparseable data line: %.200s", - s->pending.p); - sp_buf_clear(&s->pending); - return -1; - } + /* + * A fragment that never became an object cannot be used; drop + * it rather than failing a turn that already has its answer. + */ + sp_buf_clear(&s->pending); s->done = 1; return 0; } @@ -221,10 +218,9 @@ sp_sse_line(struct sp_sse *s, const char *line, struct sp_buf *out, return 0; } if (s->pending.len > PENDING_MAX) { - sp_buf_printf(err, "sse: unparseable data line: %.200s", - s->pending.p); + /* not a kept promise: drop it, keep the turn alive */ sp_buf_clear(&s->pending); - return -1; + return 0; } return 0; } @@ -371,12 +367,14 @@ sp_sse_finish(struct sp_sse *s, struct sp_reply *out, struct sp_buf *err) if (s == NULL || out == NULL) return -1; - if (s->pending.len > 0) { - if (err != NULL) - sp_buf_printf(err, "sse: incomplete data line: %.200s", - s->pending.p); - return -1; - } + /* + * A trailing fragment (the stream ended in the middle of an object) is + * dropped: whatever arrived before it is the answer. This used to fail + * the turn with "incomplete data line", an error the operator can do + * nothing about and the provider can cause with one lost chunk. + */ + if (s->pending.len > 0) + sp_buf_clear(&s->pending); out->status = 200; out->tokens_in = s->tokens_in; out->tokens_out = s->tokens_out; diff --git a/src/frontend/curses.c b/src/frontend/curses.c index f6ac8de..e65df1b 100644 --- a/src/frontend/curses.c +++ b/src/frontend/curses.c @@ -35,6 +35,7 @@ * Keys: Enter sends, Ctrl-L redraws, Ctrl-C drops the input line, Ctrl-D quits. */ #include +#include #include #include #include "decomp.h" @@ -109,6 +110,8 @@ struct ui_state { size_t next_id; /* ids start at 1 */ size_t scroll; /* lines scrolled back from the bottom */ size_t scroll_max; /* maxscroll of the last frame */ + size_t gen; /* history changed since painted */ + size_t painted; /* the generation last drawn */ long last_ms; size_t tokens_in; size_t tokens_out; @@ -1039,14 +1042,19 @@ sidebar_heading(int *y, int cols, const char *text) wattron(ui_side, COLOR_PAIR(PAIR_SIDE)); } -/* wrap 'text' into the sidebar from row *y, at most 'maxrows' rows */ +/* + * Wrap 'text' into the sidebar from row *y, at most 'maxrows' rows. The + * first row of a widget is its title line: bold, so a plugin block reads as a + * block and not as a wall of small print. + */ static void -side_text(int *y, int cols, const char *text, int maxrows) +side_text(int *y, int cols, const char *text, int maxrows, int bold_first) { int rows = 0; while (*text != '\0' && rows < maxrows && *y < getmaxy(ui_side)) { size_t n = strlen(text), take = n; + int bold = bold_first && rows == 0; if (take > (size_t)cols - 1) { take = (size_t)cols - 1; @@ -1055,7 +1063,11 @@ side_text(int *y, int cols, const char *text, int maxrows) if (take == 0) take = (size_t)cols - 1; } + if (bold) + wattron(ui_side, A_BOLD); mvwaddnstr(ui_side, (*y)++, 0, text, (int)take); + if (bold) + wattroff(ui_side, A_BOLD); rows++; text += take; while (*text == ' ') @@ -1145,7 +1157,7 @@ draw_sidebar(struct ui_state *s, const char *id, const char *dir, snprintf(line, sizeof(line), "%s / %.120s", act, g_model); else snprintf(line, sizeof(line), "%.200s", g_model); - side_text(&y, cols, line, 2); + side_text(&y, cols, line, 2, 0); } y++; @@ -1204,7 +1216,7 @@ draw_sidebar(struct ui_state *s, const char *id, const char *dir, if (colon == NULL) { if (cont_name[0] != '\0' && *line != '\0' && y < getmaxy(ui_side) - 2) - side_text(&y, cols, line, 1); + side_text(&y, cols, line, 1, 0); continue; } nl = (size_t)(colon - line); @@ -1228,7 +1240,7 @@ draw_sidebar(struct ui_state *s, const char *id, const char *dir, y++; snprintf(key, sizeof(key), "widget.%s", name); sidebar_heading(&y, cols, sp_td(key, name)); - side_text(&y, cols, text, 4); + side_text(&y, cols, text, 6, 1); snprintf(cont_name, sizeof(cont_name), "%s", name); } if (cont_name[0] != '\0' && y < getmaxy(ui_side) - 2) @@ -1242,11 +1254,11 @@ draw_sidebar(struct ui_state *s, const char *id, const char *dir, sidebar_heading(&y, cols, sp_t("sidebar.last_turn")); snprintf(line, sizeof(line), sp_t("sidebar.turn_line"), (double)s->last_ms / 1000.0, s->last_steps, s->last_calls); - side_text(&y, cols, line, 2); + side_text(&y, cols, line, 2, 0); if (s->tokens_out > 0) { snprintf(line, sizeof(line), sp_t("sidebar.tokens"), s->tokens_out, s->tokens_in); - side_text(&y, cols, line, 1); + side_text(&y, cols, line, 1, 0); } y++; } @@ -1254,7 +1266,7 @@ draw_sidebar(struct ui_state *s, const char *id, const char *dir, if (id != NULL && y < getmaxy(ui_side) - 2) { sidebar_heading(&y, cols, sp_t("sidebar.session")); wattron(ui_side, COLOR_PAIR(PAIR_SIDE)); - side_text(&y, cols, id, 1); + side_text(&y, cols, id, 1, 0); } /* * Where this splinter runs. Every tool acts relative to it, so it has to @@ -1465,6 +1477,7 @@ entry_set_text(struct ui_state *s, size_t id, const char *text) free(s->entries[i - 1].cache); s->entries[i - 1].cache = NULL; } + s->gen++; } /* @@ -1538,6 +1551,7 @@ add_entry(struct ui_state *s, const char *role, const char *text) } s->last_day = day; } + s->gen++; return id; } @@ -1617,6 +1631,7 @@ static void redraw(struct ui_state *s, const struct ui_backend *be) { draw_history(s); + s->painted = s->gen; draw_sidebar(s, SESS_ID(be), SESS_DIR(be), be->host(be->ctx)); draw_statusbar(s); doupdate(); @@ -1657,6 +1672,238 @@ draw_prompt(const char *input) free(ascii); } +/* ---- /model: a picker, not a printed list ------------------------------ */ + +struct pick_list { + struct sp_model_choice v[SP_MODEL_CHOICES]; + size_t n; +}; + +static void +pick_add(void *ctx, const char *sel, const char *label, int current) +{ + struct pick_list *l = ctx; + + if (l->n >= SP_MODEL_CHOICES || sel == NULL) + return; + snprintf(l->v[l->n].sel, sizeof(l->v[l->n].sel), "%s", sel); + snprintf(l->v[l->n].label, sizeof(l->v[l->n].label), "%s", + label != NULL && *label != '\0' ? label : sel); + l->v[l->n].current = current; + l->n++; +} + +/* case-blind substring; an empty filter matches every entry */ +static int +ci_contains(const char *hay, const char *needle) +{ + size_t n = strlen(needle), i; + const char *p; + + if (n == 0) + return 1; + for (p = hay; *p != '\0'; p++) { + for (i = 0; i < n && p[i] != '\0'; i++) + if (tolower((unsigned char)p[i]) != + tolower((unsigned char)needle[i])) + break; + if (i == n) + return 1; + } + return 0; +} + +static size_t +pick_match(const struct pick_list *l, const char *filter, size_t *match) +{ + size_t i, n = 0; + + for (i = 0; i < l->n; i++) + if (ci_contains(l->v[i].sel, filter) || + ci_contains(l->v[i].label, filter)) + match[n++] = i; + return n; +} + +static WINDOW * +pick_window(int *wp, int *hp) +{ + int rows, cols, w, h; + WINDOW *win; + + getmaxyx(stdscr, rows, cols); + w = cols - 4; + if (w > 68) + w = 68; + if (w < 26) + w = cols - 2; + h = rows - 4; + if (h > 18) + h = 18; + if (h < 8) + h = rows - 2; + if (w < 12 || h < 6) + return NULL; + win = newwin(h, w, (rows - h) / 2, (cols - w) / 2); + if (win == NULL) + return NULL; + wbkgd(win, COLOR_PAIR(PAIR_MAIN)); + keypad(win, TRUE); + *wp = w; + *hp = h; + return win; +} + +static void +pick_draw(WINDOW *win, const struct pick_list *l, const size_t *match, + size_t nmatch, size_t cur, size_t top, const char *filter) +{ + int h = getmaxy(win), w = getmaxx(win), listh = h - 4, y; + const char *label = sp_t("ui.model_filter"); + int fw = 2 + (int)strlen(label) + 1; + char line[1100]; + + werase(win); + /* + * No box(): the vendored curses draws ACS corners as letters, so a + * frame that is meant to be a frame reads as "lq...k". Two filled + * rows do the same job and look like a title bar and a footer. + */ + wattrset(win, COLOR_PAIR(PAIR_STATUS) | A_BOLD); + mvwhline(win, 0, 0, ' ', w); + mvwaddnstr(win, 0, 1, sp_t("ui.model_title"), w - 2); + wattrset(win, COLOR_PAIR(PAIR_MAIN)); + mvwaddnstr(win, 1, 2, label, w - 4); + if (fw < w - 2) + mvwaddnstr(win, 1, fw, filter, w - 2 - fw); + if (l->n == 0) + mvwaddnstr(win, 3, 2, sp_t("ui.model_empty"), w - 4); + else if (nmatch == 0) + mvwaddnstr(win, 3, 2, sp_t("ui.model_none"), w - 4); + for (y = 0; y < listh; y++) { + size_t pos = top + (size_t)y, idx; + int row = 2 + y; + + if (pos >= nmatch) + break; + idx = match[pos]; + snprintf(line, sizeof(line), "%s%s", + l->v[idx].current ? "* " : " ", l->v[idx].label); + if (pos == cur) { + wattrset(win, COLOR_PAIR(PAIR_STATUS)); + mvwhline(win, row, 1, ' ', w - 2); + mvwaddnstr(win, row, 1, line, w - 2); + wattrset(win, COLOR_PAIR(PAIR_MAIN)); + } else + mvwaddnstr(win, row, 1, line, w - 2); + } + wattrset(win, COLOR_PAIR(PAIR_DIM)); + mvwhline(win, h - 2, 0, ' ', w); + mvwaddnstr(win, h - 2, 1, sp_t("ui.model_hint"), w - 2); + wattrset(win, COLOR_PAIR(PAIR_MAIN)); + wmove(win, 1, fw + (int)strlen(filter) < w - 1 ? + fw + (int)strlen(filter) : w - 2); + wnoutrefresh(win); + doupdate(); +} + +/* + * The picker behind /model: Up/Down move, typing filters by selector or model, + * Enter takes the highlighted one, Esc cancels. It never talks to the network; + * the list is the configuration (be->models), and the switch itself is the + * ordinary "/model " command, so local and --attach behave the same. + */ +static int +model_picker(const struct ui_backend *be, char *sel, size_t cap) +{ + struct pick_list list; + char filter[64]; + size_t flen = 0, match[SP_MODEL_CHOICES], nmatch; + size_t cur = 0, top = 0; + WINDOW *win; + int w = 0, h = 0, rc = -1, c; + + if (be == NULL || be->models == NULL) + return -1; + memset(&list, 0, sizeof(list)); + filter[0] = '\0'; + be->models(be->ctx, pick_add, &list); + nmatch = pick_match(&list, filter, match); + win = pick_window(&w, &h); + if (win == NULL) + return -1; + for (;;) { + int changed = 0; + int listh = h - 4; + + if (nmatch == 0) + cur = 0; + else if (cur >= nmatch) + cur = nmatch - 1; + if (cur < top) + top = cur; + if (listh > 0 && cur >= top + (size_t)listh) + top = cur - (size_t)listh + 1; + pick_draw(win, &list, match, nmatch, cur, top, filter); + c = wgetch(win); + if (c == 27 || c == 3 || c == 4) + break; + if (c == '\n' || c == '\r' || c == KEY_ENTER) { + if (nmatch > 0) { + snprintf(sel, cap, "%s", + list.v[match[cur]].sel); + rc = 0; + break; + } + continue; + } + if (c == KEY_RESIZE) { + delwin(win); + win = pick_window(&w, &h); + if (win == NULL) + break; + changed = 1; + } else if (c == KEY_UP || c == 16) { + if (cur > 0) + cur--; + } else if (c == KEY_DOWN || c == 14) { + if (nmatch > 0 && cur + 1 < nmatch) + cur++; + } else if (c == KEY_PPAGE) { + cur = cur > 5 ? cur - 5 : 0; + } else if (c == KEY_NPAGE) { + cur = nmatch > 5 && cur + 5 < nmatch ? cur + 5 : + (nmatch > 0 ? nmatch - 1 : 0); + } else if (c == KEY_HOME) { + cur = 0; + } else if (c == KEY_END) { + cur = nmatch > 0 ? nmatch - 1 : 0; + } else if (c == KEY_BACKSPACE || c == 127 || c == 8) { + if (flen > 0) { + do + flen--; + while (flen > 0 && + ((unsigned char)filter[flen] & 0xc0) == + 0x80); + filter[flen] = '\0'; + changed = 1; + } + } else if (c >= 32 && c < 256 && flen + 1 < sizeof(filter)) { + filter[flen++] = (char)c; + filter[flen] = '\0'; + changed = 1; + } + if (changed) { + nmatch = pick_match(&list, filter, match); + cur = 0; + top = 0; + } + } + if (win != NULL) + delwin(win); + return rc; +} + /* * Read one line at the prompt. Enter ends it; Ctrl-D sets s->quit. While no * key comes, the read times out every 500 ms and repaints sidebar and status @@ -1711,7 +1958,10 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input, * not only when a widget had something to say. */ (void)got; - draw_history(s); + if (s->gen != s->painted) { + draw_history(s); + s->painted = s->gen; + } } draw_sidebar(s, SESS_ID(be), SESS_DIR(be), host); draw_statusbar(s); @@ -2126,6 +2376,8 @@ struct turn_view { char line[1024]; /* steering text being typed */ size_t llen; char note[600]; /* a usage-limit wait, or "" */ + char steer[160]; /* "steering queued (n)", or "" */ + unsigned steers; /* how many went out this turn */ int rc; int got_end; }; @@ -2168,6 +2420,7 @@ drain_idle(struct ui_state *s) case SP_EV_CLEAR: s->n = 0; s->scroll = 0; + s->gen++; break; case SP_EV_STATE: sync_state(s); @@ -2211,6 +2464,7 @@ finalize_turn(struct ui_state *s, struct turn_view *v, int rc, const char *answe sp_buf_clear(&v->thinkbuf); sp_buf_clear(&v->live); v->note[0] = '\0'; + v->steer[0] = '\0'; } /* @@ -2248,6 +2502,7 @@ drain_events(struct ui_state *s, struct turn_view *v) seg_show(s, &v->ans, "agent", ev.b); v->think.id = v->think.off = v->think.shown = 0; v->ans.id = v->ans.off = v->ans.shown = 0; + v->steer[0] = '\0'; sp_buf_clear(&v->thinkbuf); sp_buf_clear(&v->live); break; @@ -2287,6 +2542,7 @@ drain_events(struct ui_state *s, struct turn_view *v) case SP_EV_CLEAR: s->n = 0; s->scroll = 0; + s->gen++; break; case SP_EV_QUIT: s->quit = 1; @@ -2300,45 +2556,32 @@ drain_events(struct ui_state *s, struct turn_view *v) } /* - * One tick without a key: the turn so far, on screen. The turn is not drawn - * into a box of its own: it is two entries that grow in place, the reasoning - * first, the answer after the tool calls. Nothing moves when the turn ends. + * The steering line: elapsed seconds, an engine note (a usage-limit wait), the + * steer confirmation, then "steer>" and what is typed. One row, never wrapped. + * Called every tick and, without a history repaint, after every key: typing + * must not wait for the next 100 ms frame. */ static void -turn_paint(struct ui_state *s, struct turn_view *v) +turn_draw_input(struct ui_state *s, struct turn_view *v) { - struct timespec now; - long ms; - int w, used; - struct swarm *sw = s->be->swarm(s->be->ctx); + struct timespec now; + long ms; + int w, used; - /* the meter lives in the engine; ask it before drawing, not after */ - sync_state(s); - draw_history(s); - draw_sidebar(s, SESS_ID(s->be), SESS_DIR(s->be), - s->be->host(s->be->ctx)); - if (sw != NULL) - swarm_poll(sw); - - /* - * The prompt becomes the steering line: elapsed seconds, the tool that - * is running, then what is typed. One row, never wrapped. - */ clock_gettime(CLOCK_MONOTONIC, &now); ms = (long)((now.tv_sec - v->t0.tv_sec) * 1000 + (now.tv_nsec - v->t0.tv_nsec) / 1000000); s->last_ms = ms; - update_meter(s, s->be->host(s->be->ctx)); - draw_statusbar(s); werase(ui_input); w = getmaxx(ui_input) - 1; { /* * No status bar: the input line leads with how long the turn - * has been running and the steer prompt. The note is the one - * exception - a usage-limit wait says when it goes on there. + * has been running and the steer prompt. The notes are the + * exception - a usage-limit wait and a queued steer say so + * here, because that is where the operator is looking. */ - char note[600], mark[700], steer[32]; + char note[900], mark[1000], steer[32], extra[200]; snprintf(steer, sizeof(steer), "%s", sp_td("ui.steer_mark", "steer> ")); @@ -2353,8 +2596,11 @@ turn_paint(struct ui_state *s, struct turn_view *v) steer[sl + 1] = '\0'; } } - snprintf(note, sizeof(note), "%lds%s%.500s", ms / 1000, - v->note[0] != '\0' ? " " : "", v->note); + extra[0] = '\0'; + if (v->steer[0] != '\0') + snprintf(extra, sizeof(extra), " %s", v->steer); + snprintf(note, sizeof(note), "%lds%s%.500s%s", ms / 1000, + v->note[0] != '\0' ? " " : "", v->note, extra); cut_line(note, w > (int)strlen(steer) + 2 ? (size_t)w - strlen(steer) - 2 : 0); snprintf(mark, sizeof(mark), "%s %s", note, steer); @@ -2368,6 +2614,37 @@ turn_paint(struct ui_state *s, struct turn_view *v) doupdate(); } +/* + * One tick without a key: the turn so far, on screen. The turn is not drawn + * into a box of its own: it is two entries that grow in place, the reasoning + * first, the answer after the tool calls. Nothing moves when the turn ends. + */ +static void +turn_paint(struct ui_state *s, struct turn_view *v) +{ + struct swarm *sw = s->be->swarm(s->be->ctx); + + /* the meter lives in the engine; ask it before drawing, not after */ + sync_state(s); + /* + * A frame that only advances the clock must not repaint a long + * transcript: the history is drawn when something was appended, the + * input line and the meters every tick. + */ + if (s->gen != s->painted) { + draw_history(s); + s->painted = s->gen; + } + draw_sidebar(s, SESS_ID(s->be), SESS_DIR(s->be), + s->be->host(s->be->ctx)); + if (sw != NULL) + swarm_poll(sw); + + update_meter(s, s->be->host(s->be->ctx)); + draw_statusbar(s); + turn_draw_input(s, v); +} + /* * A tool needs permission. The engine parked the turn; the question goes where * the prompt is, and y/N answers it. It names the call the way the transcript @@ -2452,12 +2729,28 @@ turn_key(struct ui_state *s, struct turn_view *v, int c) } if (c == '\n' || c == '\r' || c == KEY_ENTER) { if (v->llen > 0) { - (void)s->be->steer(s->be->ctx, v->line); + char line[600]; + + if (s->be->steer(s->be->ctx, v->line) == 0) { + /* + * Say it twice: in the transcript, where the + * steer is a message to the model, and in the + * input line, which stays visible while the + * answer streams. + */ + v->steers++; + snprintf(v->steer, sizeof(v->steer), + "%s (%u)", sp_t("ui.steering_queued"), + v->steers); + snprintf(line, sizeof(line), + sp_t("ui.steer_queued_line"), v->line); + cut_line(line, 240); + add_entry(s, "splinter", line); + } else + add_entry(s, "error", + sp_t("ui.steer_failed")); v->llen = 0; v->line[0] = '\0'; - mvwaddstr(ui_input, 0, 0, sp_t("ui.steering_queued")); - wclrtoeol(ui_input); - wrefresh(ui_input); } return 0; } @@ -2511,6 +2804,8 @@ ui_turn(struct ui_state *s, const char *text) cancelled = 1; break; } + /* echo the key now, not at the next 100 ms frame */ + turn_draw_input(s, &v); } /* * A cancelled turn: wait for the engine with the screen alive. Every @@ -2672,6 +2967,27 @@ sp_ui_run(const struct ui_backend *be, const char *theme_name) if (input[0] == '\0') continue; } + /* + * /model without an argument is the picker: the list is shown, + * typed text filters it, Enter turns the choice into the same + * "/model " the operator could have typed. + */ + if (strcmp(input, "/model") == 0) { + char sel[320]; + + if (model_picker(be, sel, sizeof(sel)) == 0) { + snprintf(input, sizeof(input), "/model %s", sel); + clearok(curscr, TRUE); + redraw(&s, be); + werase(ui_input); + mvwaddstr(ui_input, 0, 0, prompt_mark()); + wnoutrefresh(ui_input); + doupdate(); + } else { + clearok(curscr, TRUE); + continue; + } + } if (sp_buf_init(&reply) != 0) break; if (strcmp(input, "/sessions") == 0) { diff --git a/src/frontend/protocol.c b/src/frontend/protocol.c index fbbf4ce..7cc3296 100644 --- a/src/frontend/protocol.c +++ b/src/frontend/protocol.c @@ -469,6 +469,36 @@ send_sessions(struct client *c, struct proto *p) return rc; } +/* what a /model picker may offer; no network, the configuration is the list */ +static int +send_models(struct client *c, struct proto *p) +{ + struct sp_model_choice v[SP_MODEL_CHOICES]; + size_t n, i; + struct sp_buf b; + int rc; + + n = sp_engine_models(p->eng, v, SP_MODEL_CHOICES); + if (sp_buf_init(&b) != 0) + return -1; + ev_start(&b, "models"); + sp_buf_puts(&b, ",\"items\":["); + for (i = 0; i < n; i++) { + if (i > 0) + sp_buf_puts(&b, ","); + sp_buf_puts(&b, "{\"sel\":\""); + (void)sp_json_escape(&b, v[i].sel); + sp_buf_puts(&b, "\",\"label\":\""); + (void)sp_json_escape(&b, v[i].label); + sp_buf_printf(&b, "\",\"current\":%s}", + v[i].current ? "true" : "false"); + } + sp_buf_puts(&b, "]}"); + rc = send_line(c, &b); + sp_buf_free(&b); + return rc; +} + /* * Switch this connection to another session. sp_engine_switch closes the old * engine before it opens the next (plugins keep globals) and puts the engine @@ -658,6 +688,8 @@ handle_line(struct client *c, struct proto *p, const char *line) (void)send_state(c, eng, "state"); } else if (strcmp(cmd, "sessions") == 0) { (void)send_sessions(c, p); + } else if (strcmp(cmd, "models") == 0) { + (void)send_models(c, p); } else if (strcmp(cmd, "open") == 0) { (void)proto_open(c, p, mcp_arg_string(v, "session"), mcp_arg_bool(v, "new", 0)); diff --git a/src/frontend/ui_backend.h b/src/frontend/ui_backend.h index 0ccc7d8..ddd8cbd 100644 --- a/src/frontend/ui_backend.h +++ b/src/frontend/ui_backend.h @@ -59,6 +59,10 @@ struct ui_backend { int (*agent_cur)(void *ctx); int (*agent_switch)(void *ctx, int idx); int (*command_names)(void *ctx, char (*names)[64], int max); + /* the choices /model takes; cb per entry: selector, label, current */ + int (*models)(void *ctx, + void (*cb)(void *cbctx, const char *sel, const char *label, + int current), void *cbctx); /* the sessions in this backend's directory; cb per entry */ int (*sessions)(void *ctx, void (*cb)(void *cbctx, const char *id, const char *title, diff --git a/src/frontend/ui_local.c b/src/frontend/ui_local.c index c1df592..16052b9 100644 --- a/src/frontend/ui_local.c +++ b/src/frontend/ui_local.c @@ -144,6 +144,19 @@ static int loc_command_names(void *ctx, char (*names)[64], int max) return sp_engine_command_names(ENG(ctx), names, max); } +static int +loc_models(void *ctx, void (*cb)(void *, const char *, const char *, int), + void *cbctx) +{ + struct sp_model_choice v[SP_MODEL_CHOICES]; + size_t n, i; + + n = sp_engine_models(ENG(ctx), v, SP_MODEL_CHOICES); + for (i = 0; i < n; i++) + cb(cbctx, v[i].sel, v[i].label, v[i].current); + return (int)n; +} + static int loc_history(void *ctx, void (*cb)(void *, const char *, const char *), void *cbctx) @@ -243,6 +256,7 @@ static const struct ui_backend local = { .agent_cur = loc_agent_cur, .agent_switch = loc_agent_switch, .command_names = loc_command_names, + .models = loc_models, .sessions = loc_sessions, .open_session = loc_open_session, .history = loc_history, diff --git a/src/frontend/ui_remote.c b/src/frontend/ui_remote.c index bffc423..0d2f2ec 100644 --- a/src/frontend/ui_remote.c +++ b/src/frontend/ui_remote.c @@ -710,6 +710,56 @@ rem_command_names(void *ctx, char (*names)[64], int max) return n; } +/* + * The picker's list from the server: `models` answers one event with every + * selector. Other events that arrive while we wait (state, busy) still go + * through dispatch, so nothing is lost. + */ +static int +rem_models(void *ctx, void (*cb)(void *, const char *, const char *, int), + void *cbctx) +{ + struct rem *r = ctx; + long deadline; + int n = 0; + + if (r->fd < 0 || send_cmd(r, "models", NULL, NULL) != 0) + return 0; + deadline = now_ms() + 5000; + while (now_ms() < deadline) { + mcp_json *v; + const char *ev; + int rc = next_line(r, 5000); + + if (rc <= 0) + break; + v = mcp_parse(r->line.p); + ev = v != NULL ? mcp_arg_string(v, "ev") : NULL; + if (ev != NULL && strcmp(ev, "models") == 0) { + const mcp_json *items = mcp_arg(v, "items"); + size_t i, len = mcp_array_len(items); + + for (i = 0; i < len; i++) { + const mcp_json *it = mcp_array_at(items, i); + const char *sel = mcp_arg_string(it, "sel"); + const char *label = mcp_arg_string(it, + "label"); + + if (sel == NULL) + continue; + cb(cbctx, sel, label != NULL ? label : sel, + mcp_arg_bool(it, "current", 0)); + n++; + } + mcp_json_free(v); + break; + } + (void)dispatch(r, r->line.p); + mcp_json_free(v); + } + return n; +} + static void emit_history(struct rem *r) { @@ -1053,6 +1103,7 @@ sp_ui_backend_remote(const char *socket_path, struct sp_buf *err) be.agent_cur = rem_agent_cur; be.agent_switch = rem_agent_switch; be.command_names = rem_command_names; + be.models = rem_models; be.sessions = rem_sessions; be.open_session = rem_open_session; be.take_steer = rem_take_steer; diff --git a/tests/fake_junction.py b/tests/fake_junction.py index 8b9746b..5a77e08 100644 --- a/tests/fake_junction.py +++ b/tests/fake_junction.py @@ -2,9 +2,11 @@ """A stand-in for junction, for tests/test_junction. It answers exactly what the plugin reads: the X-Junction-Mcp identity header on -/mcp (with 405, as the real one does for a GET) and a /status body with the -counters the plugin publishes. No token is required; the test is about reading -the header and the JSON, not about authentication. +/mcp (with 405, as the real one does for a GET), the status JSON only under the +/v1/status alias (so the fallback is exercised), and /v1/models with the +routing headers (so the header statistics have something to show). No token is +required; the test is about reading the headers and the JSON, not about +authentication. """ import json import sys @@ -14,7 +16,11 @@ STATUS = { "uptime_s": 1211, "requests": {"ok": 11, "fail": 0}, "queue": {"inflight": 1, "waiting": 0, "max_inflight": 32}, - "endpoints": [{"name": "a"}, {"name": "b"}, {"name": "c"}], + "endpoints": [ + {"name": "a", "exhausted": 0, "p95_ms": 500}, + {"name": "b", "exhausted": 1, "p95_ms": 900}, + {"name": "c", "exhausted": 0, "p95_ms": 300}, + ], "mcp": [ {"name": "tasksd", "ok": 1, "fail": 0, "tools": 9}, {"name": "skilld", "ok": 1, "fail": 0, "tools": 10}, @@ -24,24 +30,44 @@ STATUS = { ], } +MODELS = { + "object": "list", + "data": [ + {"id": "qwen3.6-35b"}, + {"id": "beam-free"}, + {"id": "iceman-contributor-free"}, + ], +} + class Handler(BaseHTTPRequestHandler): def log_message(self, *args): pass + def json(self, obj, headers=()): + body = json.dumps(obj).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + for k, v in headers: + self.send_header(k, v) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + def do_GET(self): if self.path == "/mcp": self.send_response(405) self.send_header("X-Junction-Mcp", "1") self.send_header("Content-Length", "0") self.end_headers() - elif self.path == "/status": - body = json.dumps(STATUS).encode() - self.send_response(200) - self.send_header("Content-Type", "application/json") - self.send_header("Content-Length", str(len(body))) - self.end_headers() - self.wfile.write(body) + elif self.path == "/v1/status": + self.json(STATUS) + elif self.path == "/v1/models": + self.json(MODELS, [ + ("X-Junction-Endpoint", "fake"), + ("X-Junction-Ms", "12"), + ("X-Junction-Cache", "off"), + ]) else: self.send_response(404) self.send_header("Content-Length", "0") diff --git a/tests/test_agent.c b/tests/test_agent.c index c2ed3a9..51be563 100644 --- a/tests/test_agent.c +++ b/tests/test_agent.c @@ -179,14 +179,35 @@ main(void) CHECK(m.requests == 0); sp_mock_free(&m); - /* 9. a non-2xx reply fails the turn instead of being treated as text */ + /* + * 9. a non-2xx reply fails the turn instead of being treated as text, + * but not before three retries: four 500s are queued and four + * requests must be made. The wait is 0 here; the default is 5 s. + */ + (void)setenv("SPLINTER_RETRY_WAIT_MS", "0", 1); sp_buf_clear(&err); CHECK(sp_mock_init(&m) == 0); CHECK(sp_mock_push(&m, 500, "boom") == 0); + CHECK(sp_mock_push(&m, 500, "boom") == 0); + CHECK(sp_mock_push(&m, 500, "boom") == 0); + CHECK(sp_mock_push(&m, 500, "boom") == 0); CHECK(run_turn(&m, &r, "hi", 1, 8, 0, &answer, &err, &st) != 0); CHECK(strstr(err.p, "status 500") != NULL); + CHECK(m.requests == 4); sp_mock_free(&m); + /* 9b. two transient failures, then the answer: the retry recovers */ + sp_buf_clear(&err); + CHECK(sp_mock_init(&m) == 0); + CHECK(sp_mock_push(&m, 500, "boom") == 0); + CHECK(sp_mock_push(&m, 500, "boom") == 0); + CHECK(sp_mock_push(&m, 200, "answer nach zwei fehlern") == 0); + CHECK(run_turn(&m, &r, "hi", 1, 8, 0, &answer, &err, &st) == 0); + CHECK(strstr(answer.p, "nach zwei fehlern") != NULL); + CHECK(m.requests == 3); + sp_mock_free(&m); + (void)unsetenv("SPLINTER_RETRY_WAIT_MS"); + /* * 10. max_steps counts tool rounds, not requests: a turn that spends * its whole round budget and then answers must still answer. The diff --git a/tests/test_engine.c b/tests/test_engine.c index 1ed4615..8cdf98b 100644 --- a/tests/test_engine.c +++ b/tests/test_engine.c @@ -150,6 +150,21 @@ main(void) if (sp_buf_init(&err) != 0 || sp_buf_init(&out) != 0) return 1; sp_config_init(&conf); + /* + * One provider and one pool, so the picker's list is not empty: the + * front end asks the engine, never the config file it may not have. + */ + snprintf(conf.endpoint, sizeof(conf.endpoint), + "http://127.0.0.1:1/v1"); + snprintf(conf.model, sizeof(conf.model), "test-model"); + snprintf(conf.default_id, sizeof(conf.default_id), "main"); + conf.npools = 1; + snprintf(conf.pool[0].id, sizeof(conf.pool[0].id), "testpool"); + snprintf(conf.pool[0].strategy, sizeof(conf.pool[0].strategy), + "balance"); + snprintf(conf.pool[0].member[0], sizeof(conf.pool[0].member[0]), + "main"); + conf.pool[0].nmembers = 1; memset(&base, 0, sizeof(base)); base.max_steps = 10; base.system_prompt = "test"; @@ -166,6 +181,19 @@ main(void) } run_turn(eng); + /* the /model picker's list: providers first, then pools */ + { + struct sp_model_choice mv[SP_MODEL_CHOICES]; + size_t mn = sp_engine_models(eng, mv, + SP_MODEL_CHOICES); + + CHECK(mn == 2); + CHECK(strcmp(mv[0].sel, "main") == 0); + CHECK(contains(mv[0].label, "test-model")); + CHECK(strcmp(mv[1].sel, "testpool") == 0); + CHECK(contains(mv[1].label, "pool")); + } + kind = sp_engine_input(eng, "/status", &out); CHECK(kind == SP_INPUT_HANDLED); CHECK(contains(out.p, "session sess-engine")); diff --git a/tests/test_junction.c b/tests/test_junction.c index a8b6dc4..756c1de 100644 --- a/tests/test_junction.c +++ b/tests/test_junction.c @@ -86,8 +86,12 @@ main(int argc, char **argv) CHECK(sp_host_widget_snapshot(host, snap, sizeof(snap)) > 0); CHECK(strstr(snap, "junction: ") != NULL); CHECK(strstr(snap, "up") != NULL); - CHECK(strstr(snap, "X-Junction-Mcp") != NULL); + CHECK(strstr(snap, "mcp=1") != NULL); CHECK(strstr(snap, "mcp 4/5") != NULL); + /* the alias /v1/status answered, and the model route's headers are shown */ + CHECK(strstr(snap, "models 3") != NULL); + CHECK(strstr(snap, "endpoint=fake") != NULL); + CHECK(strstr(snap, "1 ex") != NULL); CHECK(!continuation_has_colon(snap)); /* the status segment the status line and /status show */ @@ -107,6 +111,14 @@ main(int argc, char **argv) CHECK(strstr(out.p, "mcp: 4/5 answering") != NULL); CHECK(strstr(out.p, "header: no") != NULL); /* no token was set */ CHECK(strstr(out.p, "Authorization") == NULL); + /* every header of every probe, and the status alias that answered */ + CHECK(strstr(out.p, "/v1/status 200") != NULL); + CHECK(strstr(out.p, "headers /mcp") != NULL); + CHECK(strstr(out.p, "headers /v1/models") != NULL); + CHECK(strstr(out.p, "X-Junction-Endpoint: fake") != NULL); + CHECK(strstr(out.p, "statistics: ") != NULL); + CHECK(strstr(out.p, "endpoint=fake") != NULL); + CHECK(strstr(out.p, "models: 3") != NULL); /* the tool is registered and returns the same snapshot */ CHECK(sp_registry_find(®, "junction_status") != NULL); diff --git a/tests/test_protocol.sh b/tests/test_protocol.sh index fc1f15d..7ab6339 100755 --- a/tests/test_protocol.sh +++ b/tests/test_protocol.sh @@ -107,6 +107,18 @@ while True: seen.append("commands") break +f.write(json.dumps({"cmd": "models"}) + "\n") +f.flush() +while True: + ev = json.loads(f.readline()) + if ev.get("ev") == "models": + sels = [it.get("sel") for it in ev.get("items", [])] + if "main" not in sels: + print("models incomplete", ev, file=sys.stderr) + sys.exit(1) + seen.append("models") + break + f.write(json.dumps({"cmd": "say", "text": "hallo"}) + "\n") f.flush() while True: diff --git a/tests/test_sse.c b/tests/test_sse.c index 9b08258..2809fee 100644 --- a/tests/test_sse.c +++ b/tests/test_sse.c @@ -151,12 +151,30 @@ main(void) CHECK(sp_sse_line(s, "\n", &out, &err) == 0); sp_sse_free(s); - /* ---- a broken data line is an error when its event ends ---- */ + /* + * ---- a data object split across events, and a trailing fragment ---- + * + * Real proxies put blank lines between the lines of a pretty-printed + * object and may truncate the last one. Neither is a failed turn: the + * blank line keeps the buffer, and a fragment that never completes is + * dropped at the end. + */ s = sp_sse_new(); + sp_buf_clear(&out); sp_buf_clear(&err); + CHECK(sp_sse_line(s, "data: {\"choices\":\n", &out, &err) == 0); + CHECK(sp_sse_line(s, "\n", &out, &err) == 0); + CHECK(sp_sse_line(s, "data: [{\"delta\":{\"content\":\"ok\"}}]}\n", + &out, &err) == 1); + CHECK(strcmp(out.p, "ok") == 0); CHECK(sp_sse_line(s, "data: {kaputt\n", &out, &err) == 0); - CHECK(sp_sse_line(s, "\n", &out, &err) == -1); - CHECK(strstr(err.p, "unparseable data line") != NULL); + CHECK(sp_sse_line(s, "\n", &out, &err) == 0); + CHECK(err.len == 0); + memset(&r, 0, sizeof(r)); + CHECK(sp_sse_finish(s, &r, &err) == 0); + CHECK(err.len == 0); + CHECK(r.content != NULL && strcmp(r.content, "ok") == 0); + sp_reply_free(&r); sp_sse_free(s); /* ---- non-data lines carry nothing and are not errors ---- */ diff --git a/tests/test_ui.sh b/tests/test_ui.sh index 66cbd63..b3d3101 100755 --- a/tests/test_ui.sh +++ b/tests/test_ui.sh @@ -102,9 +102,14 @@ typed '!echo hallo-shell'; key Enter check shows 'hallo-shell' typed '/xyz'; key Enter check shows 'unknown command: /xyz' +# /model alone opens the picker: it lists the providers, typing filters, +# Enter takes the highlighted one and runs the ordinary /model typed '/model'; key Enter +check shows 'type to filter' check shows 'main m' -check shows 'Choose a model' +typed 'main'; key Enter +check shows 'Model: m (provider main' +# an argument still switches directly, without the picker typed '/model andere'; key Enter check shows 'Model: andere (provider main' typed '/new'; key Enter