xonecas.io
7814
Ta

tiny-c-agent / files

tiny-c-agent / src / tui / usage.c

1.9 KB
1#include "usage.h"
2
3#include <stdio.h>
4#include <stdlib.h>
5#include <string.h>
6
7#include "util.h"
8#include "theme.h"
9
10// Trims trailing zeros from a fixed-decimal expansion.
11static void trim_zeros(char *s) {
12    char *dot = strchr(s, '.');
13    if (!dot) return;
14    char *p = s + strlen(s);
15    while (p > dot + 1 && p[-1] == '0') p--;
16    if (p > dot && p[-1] == '.') p--;
17    *p = '\0';
18}
19
20char *tiny_format_tokens(long n) {
21    char num[48];
22    const char *unit = "";
23    if (n < 1000) {
24        snprintf(num, sizeof num, "%ld", n);
25    } else if (n < 1000000) {
26        snprintf(num, sizeof num, "%.1f", (double)n / 1000.0);
27        unit = "k";
28    } else {
29        snprintf(num, sizeof num, "%.2f", (double)n / 1000000.0);
30        unit = "M";
31    }
32    // Trailing zeros come off the number, before the unit is appended.
33    trim_zeros(num);
34    tui_buf b;
35    buf_init(&b);
36    buf_adds(&b, num);
37    buf_adds(&b, unit);
38    return buf_steal(&b);
39}
40
41char *tiny_context_usage_line(long used, long window, long max_tokens) {
42    if (window <= 0) {
43        char *t = tiny_format_tokens(used);
44        tui_buf b;
45        buf_init(&b);
46        char label[64];
47        snprintf(label, sizeof label, "ctx %s", t);
48        fg_dim(&b, label);
49        free(t);
50        if (!b.data) return strdup("");
51        return buf_steal(&b);
52    }
53    char *u = tiny_format_tokens(used);
54    char *w = tiny_format_tokens(window);
55    tui_buf b;
56    buf_init(&b);
57    if (max_tokens > 0 && used + max_tokens > window) {
58        char line[128];
59        snprintf(line, sizeof line, "ctx full · %s/%s", u, w);
60        fg_red(&b, line);
61    } else {
62        long percent = (long)((double)used / (double)window * 100.0 + 0.5);
63        char line[128];
64        snprintf(line, sizeof line, "ctx %s/%s · %ld%%", u, w, percent);
65        if (percent >= 85) fg_yellow(&b, line);
66        else fg_dim(&b, line);
67    }
68    free(u);
69    free(w);
70    if (!b.data) return strdup("");
71    return buf_steal(&b);
72}