diff --git a/plugins/lcm/lcm.c b/plugins/lcm/lcm.c index 93f3381..bc86d5a 100644 --- a/plugins/lcm/lcm.c +++ b/plugins/lcm/lcm.c @@ -193,6 +193,26 @@ lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, pinned = pin_content != NULL; } drop = keep_from - first; + /* + * A summary and the pinned question are messages too. If the cut would + * remove no more than it adds, the count grows (N -> N+1 was the + * /resume loop) and the context never shrinks. Keep the output trim, + * skip the message rewrite. + */ + if (drop <= (size_t)1 + (pinned ? 1 : 0)) { + free(pin_content); + free(pin_name); + if (trimmed > 0) { + pthread_mutex_lock(&lcm_lock); + compactions++; + last_msgs_from = last_msgs_to = conv->n; + last_bytes_from = bytes_before; + last_bytes_to = sp_conv_bytes(conv); + pthread_mutex_unlock(&lcm_lock); + return 1; + } + return 0; + } oldest = conv->v[first].content; /* the oldest one that goes */ for (i = first; i < keep_from; i++) { diff --git a/tests/test_compactor.c b/tests/test_compactor.c index 6df0e53..70fa0e2 100644 --- a/tests/test_compactor.c +++ b/tests/test_compactor.c @@ -291,6 +291,44 @@ main(void) CHECK(sp_host_add_status(host, &d) == 0); } + /* + * A cut that removes one message and adds a summary plus the pinned + * question would grow the conversation. /resume did that every time + * (N -> N+1). It must leave the conversation alone instead. + */ + sp_conv_init(&conv); + CHECK(sp_conv_push(&conv, "system", NULL, "you are a harness") == 0); + CHECK(sp_conv_push(&conv, "user", NULL, "the question") == 0); + { + size_t i; + + for (i = 0; i < 6; i++) + CHECK(sp_conv_push(&conv, "assistant", NULL, + "message number x") == 0); + } + before = sp_conv_bytes(&conv); + CHECK(sp_host_compact(host, &conv, before - 100) == 0); + CHECK(conv.n == 8); + CHECK(strstr(conv.v[1].content, "[lcm]") == NULL); + sp_conv_free(&conv); + + /* one more old turn makes the cut a real reduction again */ + sp_conv_init(&conv); + CHECK(sp_conv_push(&conv, "system", NULL, "you are a harness") == 0); + CHECK(sp_conv_push(&conv, "user", NULL, "the question") == 0); + { + size_t i; + + for (i = 0; i < 8; i++) + CHECK(sp_conv_push(&conv, "assistant", NULL, + "message number x") == 0); + } + before = sp_conv_bytes(&conv); + CHECK(sp_host_compact(host, &conv, before - 100) == 1); + CHECK(conv.n == 9); + CHECK(strstr(conv.v[1].content, "[lcm]") != NULL); + sp_conv_free(&conv); + /* * The sidebar shows those numbers, not an estimate: the widget is the * compactor's own counter, and the status line carries one segment.