tokenusage-cli 0.2.6 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +70 -0
- package/README.md +52 -11
- package/bin/tokenusage.js +14 -2
- package/package.json +1 -2
- package/src/cli.js +325 -78
- package/src/commands/device-login.js +3 -3
- package/src/commands/init.js +343 -153
- package/src/commands/pause.js +11 -23
- package/src/commands/reconcile.js +485 -0
- package/src/commands/sessions.js +57 -14
- package/src/commands/status.js +5 -2
- package/src/commands/sync.js +77 -18
- package/src/commands/uninstall.js +6 -9
- package/src/commands/upload.js +147 -0
- package/src/lib/cli-errors.js +33 -0
- package/src/lib/cli-ui.js +93 -0
- package/src/lib/ingest-sanitize.js +9 -0
- package/src/lib/queue-row-normalize.js +55 -0
- package/src/lib/rollout.js +39 -2
- package/src/lib/scheduled-task.js +597 -75
- package/src/lib/session-analytics.js +171 -3
- package/src/lib/session-upload.js +6 -0
- package/src/lib/sync-report.js +8 -2
- package/src/lib/trae-db.js +6 -1
- package/src/lib/antigravity-paths.js +0 -48
- package/src/lib/async-queue-reader.js +0 -138
- package/src/lib/atomic-json.js +0 -27
- package/src/lib/bearer-token.js +0 -11
- package/src/lib/cloud-account.js +0 -541
- package/src/lib/codex-context-breakdown.js +0 -806
- package/src/lib/context-health.js +0 -124
- package/src/lib/grok-context-breakdown.js +0 -890
- package/src/lib/heatmap-compact.js +0 -114
- package/src/lib/local-api.js +0 -3574
- package/src/lib/outcomes-engine.js +0 -253
- package/src/lib/pet-packages.js +0 -722
- package/src/lib/skill-usage.js +0 -267
- package/src/lib/skills-manager.js +0 -1591
- package/src/lib/source-metadata.js +0 -48
- package/src/lib/subscription-manager.js +0 -293
- package/src/lib/wrapped-aggregator.js +0 -236
- package/test/audit-fixes.test.js +0 -249
- package/test/branding.test.js +0 -24
- package/test/cli-options.test.js +0 -43
- package/test/cli-smoke.test.js +0 -53
- package/test/cli-ui.test.js +0 -47
- package/test/collection-controls.test.js +0 -255
- package/test/ingest-sanitize.test.js +0 -162
- package/test/packaging.test.js +0 -107
- package/test/quiet-warnings.test.js +0 -53
- package/test/runtime-copy.test.js +0 -111
- package/test/session-upload.test.js +0 -427
- package/test/zstd-native.test.js +0 -36
package/test/audit-fixes.test.js
DELETED
|
@@ -1,249 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
// Regression tests for the five audit P2 fixes shipped in 0.2.0
|
|
4
|
-
// (docs/cli-release.md §四 "正确性修复"):
|
|
5
|
-
// 1. init.js dead constant www.tokenusage.cc (stale domain gone);
|
|
6
|
-
// 2. zcode restoration rows carry billable_total_tokens / total_cost_usd;
|
|
7
|
-
// 3. bucket-key `|` round-trip with model names that contain `|`;
|
|
8
|
-
// 4. OpenCode signed-delta chain never leaves negative bucket totals;
|
|
9
|
-
// 5. runtime-config env names TOKENUSAGE_BASE_URL / TOKENUSAGE_ANON_KEY
|
|
10
|
-
// (INSFORGE_* stay as legacy fallbacks).
|
|
11
|
-
|
|
12
|
-
const assert = require("node:assert/strict");
|
|
13
|
-
const fs = require("node:fs");
|
|
14
|
-
const os = require("node:os");
|
|
15
|
-
const path = require("node:path");
|
|
16
|
-
const { test } = require("node:test");
|
|
17
|
-
|
|
18
|
-
const {
|
|
19
|
-
zcodeRowTotals,
|
|
20
|
-
buildZcodeRestorationRow,
|
|
21
|
-
} = require("../src/commands/sync");
|
|
22
|
-
const {
|
|
23
|
-
installLocalTrackerApp,
|
|
24
|
-
} = require("../src/commands/init");
|
|
25
|
-
const {
|
|
26
|
-
parseBucketKey,
|
|
27
|
-
bucketKey,
|
|
28
|
-
diffOpencodeTotals,
|
|
29
|
-
clampTotalsNonNegative,
|
|
30
|
-
} = require("../src/lib/rollout");
|
|
31
|
-
const {
|
|
32
|
-
DEFAULT_BASE_URL,
|
|
33
|
-
DEFAULT_DASHBOARD_URL,
|
|
34
|
-
resolveRuntimeConfig,
|
|
35
|
-
} = require("../src/lib/runtime-config");
|
|
36
|
-
|
|
37
|
-
test("fix 1: init.js no longer ships the stale www.tokenusage.cc constant", () => {
|
|
38
|
-
const source = fs.readFileSync(
|
|
39
|
-
path.join(__dirname, "..", "src", "commands", "init.js"),
|
|
40
|
-
"utf8",
|
|
41
|
-
);
|
|
42
|
-
assert.ok(!source.includes("www.tokenusage.cc"), "stale domain must not reappear in init.js");
|
|
43
|
-
// The effective default stays the production deployment in runtime-config.
|
|
44
|
-
assert.equal(DEFAULT_BASE_URL, "https://token-usage.baiwumm.com");
|
|
45
|
-
assert.equal(DEFAULT_DASHBOARD_URL, DEFAULT_BASE_URL);
|
|
46
|
-
});
|
|
47
|
-
|
|
48
|
-
test("fix 2: zcode totals fill billable/cost so restoration rows match the queue schema", () => {
|
|
49
|
-
// A legacy backup row without the two columns…
|
|
50
|
-
const legacy = {
|
|
51
|
-
input_tokens: 100,
|
|
52
|
-
cached_input_tokens: 0,
|
|
53
|
-
cache_creation_input_tokens: 0,
|
|
54
|
-
output_tokens: 50,
|
|
55
|
-
reasoning_output_tokens: 0,
|
|
56
|
-
total_tokens: 150,
|
|
57
|
-
conversation_count: 1,
|
|
58
|
-
};
|
|
59
|
-
const totals = zcodeRowTotals(legacy);
|
|
60
|
-
// …restores with billable = total (zcode plan-included usage counts) and a
|
|
61
|
-
// defined cost column (read-side pricing recomputes it).
|
|
62
|
-
assert.equal(totals.billable_total_tokens, 150);
|
|
63
|
-
assert.equal(totals.total_cost_usd, 0);
|
|
64
|
-
|
|
65
|
-
const row = buildZcodeRestorationRow({
|
|
66
|
-
model: "glm-4.6",
|
|
67
|
-
hour_start: "2026-10-27T09:30:00.000Z",
|
|
68
|
-
totals,
|
|
69
|
-
});
|
|
70
|
-
assert.equal(row.source, "zcode");
|
|
71
|
-
assert.equal(row.model, "glm-4.6");
|
|
72
|
-
assert.equal(row.hour_start, "2026-10-27T09:30:00.000Z");
|
|
73
|
-
assert.equal(row.billable_total_tokens, 150);
|
|
74
|
-
assert.equal(row.total_cost_usd, 0);
|
|
75
|
-
assert.equal(row.conversation_count, 1);
|
|
76
|
-
|
|
77
|
-
// Rows that DO carry the columns keep their values.
|
|
78
|
-
const modern = zcodeRowTotals({
|
|
79
|
-
total_tokens: 10,
|
|
80
|
-
billable_total_tokens: 4,
|
|
81
|
-
total_cost_usd: 0.25,
|
|
82
|
-
});
|
|
83
|
-
assert.equal(modern.billable_total_tokens, 4);
|
|
84
|
-
assert.equal(modern.total_cost_usd, 0.25);
|
|
85
|
-
});
|
|
86
|
-
|
|
87
|
-
test("fix 3: bucket keys round-trip model names containing the | separator", () => {
|
|
88
|
-
const model = "deepseek|v3.2";
|
|
89
|
-
const hour = "2026-10-27T09:30:00.000Z";
|
|
90
|
-
const key = bucketKey("opencode", model, hour);
|
|
91
|
-
assert.equal(key, `opencode|${model}|${hour}`);
|
|
92
|
-
|
|
93
|
-
const parsed = parseBucketKey(key);
|
|
94
|
-
assert.equal(parsed.source, "opencode");
|
|
95
|
-
assert.equal(parsed.model, model);
|
|
96
|
-
assert.equal(parsed.hourStart, hour);
|
|
97
|
-
|
|
98
|
-
// Group keys (source|hour) keep parsing without a model segment…
|
|
99
|
-
const group = parseBucketKey("zcode|2026-10-27T09:30:00.000Z");
|
|
100
|
-
assert.equal(group.source, "zcode");
|
|
101
|
-
assert.equal(group.model, "unknown");
|
|
102
|
-
assert.equal(group.hourStart, "2026-10-27T09:30:00.000Z");
|
|
103
|
-
|
|
104
|
-
// …and the zcode rebuild helper in sync.js shares the last-segment rule.
|
|
105
|
-
// (zcodeHourFromMainBucketKey is covered indirectly via the exported pure
|
|
106
|
-
// helpers; the semantics are identical: hour = after the LAST separator.)
|
|
107
|
-
const zcodeKey = `zcode|glm|4.5|${hour}`;
|
|
108
|
-
assert.equal(parseBucketKey(zcodeKey).hourStart, hour);
|
|
109
|
-
assert.equal(parseBucketKey(zcodeKey).model, "glm|4.5");
|
|
110
|
-
});
|
|
111
|
-
|
|
112
|
-
test("fix 4: signed OpenCode deltas never leave negative bucket totals", () => {
|
|
113
|
-
const previous = {
|
|
114
|
-
input_tokens: 100,
|
|
115
|
-
cached_input_tokens: 10,
|
|
116
|
-
cache_creation_input_tokens: 0,
|
|
117
|
-
output_tokens: 60,
|
|
118
|
-
reasoning_output_tokens: 20,
|
|
119
|
-
total_tokens: 190,
|
|
120
|
-
};
|
|
121
|
-
const corrected = {
|
|
122
|
-
input_tokens: 10,
|
|
123
|
-
cached_input_tokens: 0,
|
|
124
|
-
cache_creation_input_tokens: 0,
|
|
125
|
-
output_tokens: 5,
|
|
126
|
-
reasoning_output_tokens: 0,
|
|
127
|
-
total_tokens: 15,
|
|
128
|
-
};
|
|
129
|
-
const delta = diffOpencodeTotals(corrected, previous);
|
|
130
|
-
assert.ok(delta, "a correction produces a signed delta");
|
|
131
|
-
assert.equal(delta.total_tokens, -175);
|
|
132
|
-
|
|
133
|
-
// A correction whose prior contribution is NOT in the bucket anymore (lost
|
|
134
|
-
// cursor, fork-dedup removal) drives the bucket negative without the clamp.
|
|
135
|
-
const bucketTotals = {
|
|
136
|
-
input_tokens: 60,
|
|
137
|
-
cached_input_tokens: 0,
|
|
138
|
-
cache_creation_input_tokens: 0,
|
|
139
|
-
output_tokens: 40,
|
|
140
|
-
reasoning_output_tokens: 0,
|
|
141
|
-
total_tokens: 100,
|
|
142
|
-
billable_total_tokens: 100,
|
|
143
|
-
total_cost_usd: 0.2,
|
|
144
|
-
conversation_count: 2,
|
|
145
|
-
};
|
|
146
|
-
for (const key of Object.keys(delta)) {
|
|
147
|
-
bucketTotals[key] = (bucketTotals[key] || 0) + delta[key];
|
|
148
|
-
}
|
|
149
|
-
clampTotalsNonNegative(bucketTotals);
|
|
150
|
-
for (const key of ["input_tokens", "cached_input_tokens", "cache_creation_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens", "billable_total_tokens", "total_cost_usd", "conversation_count"]) {
|
|
151
|
-
assert.ok(bucketTotals[key] >= 0, `${key} must stay non-negative (got ${bucketTotals[key]})`);
|
|
152
|
-
}
|
|
153
|
-
assert.equal(bucketTotals.total_tokens, 0);
|
|
154
|
-
|
|
155
|
-
// A correction that stays positive passes through untouched (no clamp).
|
|
156
|
-
const healthy = {
|
|
157
|
-
input_tokens: 150,
|
|
158
|
-
cached_input_tokens: 10,
|
|
159
|
-
cache_creation_input_tokens: 0,
|
|
160
|
-
output_tokens: 80,
|
|
161
|
-
reasoning_output_tokens: 20,
|
|
162
|
-
total_tokens: 260,
|
|
163
|
-
};
|
|
164
|
-
for (const key of Object.keys(delta)) {
|
|
165
|
-
healthy[key] = (healthy[key] || 0) + delta[key];
|
|
166
|
-
}
|
|
167
|
-
clampTotalsNonNegative(healthy);
|
|
168
|
-
assert.equal(healthy.total_tokens, 85);
|
|
169
|
-
assert.equal(healthy.input_tokens, 60);
|
|
170
|
-
});
|
|
171
|
-
|
|
172
|
-
test("fix 5: TOKENUSAGE_BASE_URL/TOKENUSAGE_ANON_KEY win; INSFORGE_* remain legacy fallbacks", () => {
|
|
173
|
-
// New primary name.
|
|
174
|
-
const primary = resolveRuntimeConfig({
|
|
175
|
-
env: { TOKENUSAGE_BASE_URL: "https://self-hosted.example" },
|
|
176
|
-
});
|
|
177
|
-
assert.equal(primary.baseUrl, "https://self-hosted.example");
|
|
178
|
-
assert.equal(primary.sources.baseUrl, "env");
|
|
179
|
-
|
|
180
|
-
// New anon-key name resolves alongside the new base-url name.
|
|
181
|
-
const withKey = resolveRuntimeConfig({
|
|
182
|
-
env: {
|
|
183
|
-
TOKENUSAGE_BASE_URL: "https://self-hosted.example",
|
|
184
|
-
TOKENUSAGE_ANON_KEY: "anon_" + "a".repeat(64),
|
|
185
|
-
},
|
|
186
|
-
});
|
|
187
|
-
assert.equal(withKey.anonKey, "anon_" + "a".repeat(64));
|
|
188
|
-
assert.equal(withKey.configurationError, null);
|
|
189
|
-
|
|
190
|
-
// Legacy INSFORGE_* names keep working (existing scripts/installs).
|
|
191
|
-
const legacy = resolveRuntimeConfig({
|
|
192
|
-
env: { TOKENUSAGE_INSFORGE_BASE_URL: "https://legacy.example" },
|
|
193
|
-
});
|
|
194
|
-
assert.equal(legacy.baseUrl, "https://legacy.example");
|
|
195
|
-
|
|
196
|
-
// The new name wins when both are set.
|
|
197
|
-
const both = resolveRuntimeConfig({
|
|
198
|
-
env: {
|
|
199
|
-
TOKENUSAGE_BASE_URL: "https://new.example",
|
|
200
|
-
TOKENUSAGE_INSFORGE_BASE_URL: "https://old.example",
|
|
201
|
-
},
|
|
202
|
-
});
|
|
203
|
-
assert.equal(both.baseUrl, "https://new.example");
|
|
204
|
-
});
|
|
205
|
-
|
|
206
|
-
test("no stale dashboard constants in init output", () => {
|
|
207
|
-
const source = fs.readFileSync(
|
|
208
|
-
path.join(__dirname, "..", "src", "commands", "init.js"),
|
|
209
|
-
"utf8",
|
|
210
|
-
);
|
|
211
|
-
// The welcome/success banners print the configured dashboard URL; the old
|
|
212
|
-
// hardcoded TokenTracker default must not reappear in either renderer.
|
|
213
|
-
assert.ok(!source.includes("localhost:7680"), "stale localhost dashboard must not reappear in init.js");
|
|
214
|
-
});
|
|
215
|
-
|
|
216
|
-
test("init's runtime copy works from the published layout (bin/tokenusage.js)", async () => {
|
|
217
|
-
// 0.1.0–0.2.1 shipped without bin/tracker.js (the fork renamed the bin to
|
|
218
|
-
// tokenusage.js but the installer kept the old name), so `tokenusage init`
|
|
219
|
-
// crashed with ENOENT on every fresh npm install. The unit suite never ran
|
|
220
|
-
// this path: init tests set TOKENUSAGE_SKIP_LOCAL_RUNTIME_COPY=1.
|
|
221
|
-
const home = fs.mkdtempSync(path.join(os.tmpdir(), "tu-init-copy-"));
|
|
222
|
-
const appDir = path.join(home, "tracker", "app");
|
|
223
|
-
try {
|
|
224
|
-
const result = await installLocalTrackerApp({ appDir });
|
|
225
|
-
assert.equal(result.ok, true, `installation reported a failure: ${JSON.stringify(result)}`);
|
|
226
|
-
assert.ok(fs.existsSync(path.join(appDir, "bin", "tracker.js")), "app/bin/tracker.js copied");
|
|
227
|
-
assert.ok(fs.existsSync(path.join(appDir, "src", "cli.js")), "app/src copied");
|
|
228
|
-
assert.ok(fs.existsSync(path.join(appDir, "package.json")), "app/package.json copied");
|
|
229
|
-
// 0.2.4: the copy must be self-contained. npm links nothing, but pnpm links
|
|
230
|
-
// deps as junctions into a shared store — copying those links produced a
|
|
231
|
-
// runtime that died with MODULE_NOT_FOUND (one node_modules entry, no deps).
|
|
232
|
-
assert.ok(
|
|
233
|
-
fs.existsSync(path.join(appDir, "node_modules", "smol-toml")),
|
|
234
|
-
"declared dependency copied as a real directory",
|
|
235
|
-
);
|
|
236
|
-
assert.ok(
|
|
237
|
-
fs.existsSync(path.join(appDir, "node_modules", "pend")),
|
|
238
|
-
"transitive dependency of yauzl copied too (flattened closure)",
|
|
239
|
-
);
|
|
240
|
-
// The marker is what every spawn point probes: without it hooks fall back
|
|
241
|
-
// to the installed CLI instead of spawning a half copy.
|
|
242
|
-
const markerPath = path.join(appDir, ".runtime-ready");
|
|
243
|
-
assert.ok(fs.existsSync(markerPath), ".runtime-ready written only after the copy booted");
|
|
244
|
-
const marker = JSON.parse(fs.readFileSync(markerPath, "utf8"));
|
|
245
|
-
assert.equal(marker.version, require("../package.json").version);
|
|
246
|
-
} finally {
|
|
247
|
-
fs.rmSync(home, { recursive: true, force: true });
|
|
248
|
-
}
|
|
249
|
-
});
|
package/test/branding.test.js
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
// Branding guard (AGENTS.md 硬性约束 9): the product is "Token Usage"; the
|
|
2
|
-
// tokentracker name may only survive as a legacy path alias. The vendored
|
|
3
|
-
// upstream banner still spelled TOKEN TRACKER until 0.2.3.
|
|
4
|
-
|
|
5
|
-
const assert = require("node:assert/strict");
|
|
6
|
-
const fs = require("node:fs");
|
|
7
|
-
const path = require("node:path");
|
|
8
|
-
const { test } = require("node:test");
|
|
9
|
-
|
|
10
|
-
function readSource(...segments) {
|
|
11
|
-
return fs.readFileSync(path.join(__dirname, "..", "src", ...segments), "utf8");
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
test("init's welcome banner uses the Token Usage name", () => {
|
|
15
|
-
const initSource = readSource("commands", "init.js");
|
|
16
|
-
assert.match(initSource, /Token Usage/);
|
|
17
|
-
assert.ok(!initSource.includes("Token Tracker"), "fork branding must not reappear in init");
|
|
18
|
-
assert.ok(!initSource.includes("TRACKER"), "the ASCII logo must spell TOKEN USAGE");
|
|
19
|
-
});
|
|
20
|
-
|
|
21
|
-
test("local-api's fallback device name no longer says Token Tracker", () => {
|
|
22
|
-
const source = readSource("lib", "local-api.js");
|
|
23
|
-
assert.ok(!source.includes("Token Tracker"));
|
|
24
|
-
});
|
package/test/cli-options.test.js
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
// `sync --watch --interval <ms>`: README promises values below the 1-minute
|
|
2
|
-
// floor fall back to 15 min. The flag used to survive into cmdSync's args when
|
|
3
|
-
// the value was rejected, so every pass failed with "Unknown option".
|
|
4
|
-
|
|
5
|
-
const assert = require("node:assert/strict");
|
|
6
|
-
const { test } = require("node:test");
|
|
7
|
-
|
|
8
|
-
const { resolveWatchInterval } = require("../src/cli");
|
|
9
|
-
|
|
10
|
-
const FALLBACK_MS = 15 * 60_000;
|
|
11
|
-
|
|
12
|
-
test("a valid --interval is adopted and removed from the sync args", () => {
|
|
13
|
-
assert.deepEqual(resolveWatchInterval(["--watch", "--interval", "120000"]), {
|
|
14
|
-
args: [],
|
|
15
|
-
intervalMs: 120_000,
|
|
16
|
-
});
|
|
17
|
-
});
|
|
18
|
-
|
|
19
|
-
test("--interval=<ms> works too and never leaks into the sync args", () => {
|
|
20
|
-
assert.deepEqual(resolveWatchInterval(["--watch", "--interval=300000", "--no-sessions"]), {
|
|
21
|
-
args: ["--no-sessions"],
|
|
22
|
-
intervalMs: 300_000,
|
|
23
|
-
});
|
|
24
|
-
assert.deepEqual(resolveWatchInterval(["--interval=1000"]), {
|
|
25
|
-
args: [],
|
|
26
|
-
intervalMs: FALLBACK_MS,
|
|
27
|
-
});
|
|
28
|
-
});
|
|
29
|
-
|
|
30
|
-
test("a sub-floor or missing --interval falls back to 15 min but is still removed", () => {
|
|
31
|
-
for (const rest of [["--watch", "--interval", "1000"], ["--interval", "0"], ["--watch", "--interval"], ["--interval", "abc"]]) {
|
|
32
|
-
const parsed = resolveWatchInterval(rest);
|
|
33
|
-
assert.equal(parsed.intervalMs, FALLBACK_MS, `intervalMs for ${JSON.stringify(rest)}`);
|
|
34
|
-
assert.deepEqual(parsed.args, [], `leftover args for ${JSON.stringify(rest)}`);
|
|
35
|
-
}
|
|
36
|
-
});
|
|
37
|
-
|
|
38
|
-
test("unrelated sync flags survive untouched", () => {
|
|
39
|
-
assert.deepEqual(resolveWatchInterval(["--watch", "--drain", "--no-sessions"]), {
|
|
40
|
-
args: ["--drain", "--no-sessions"],
|
|
41
|
-
intervalMs: FALLBACK_MS,
|
|
42
|
-
});
|
|
43
|
-
});
|
package/test/cli-smoke.test.js
DELETED
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
// Smoke: the vendored CLI boots against the token-usage contract — the entry
|
|
4
|
-
// loads, help/version print, and the device-flow authorize request matches
|
|
5
|
-
// docs/cli-contract.md §2.1 (client_info + machine_id, no credentials).
|
|
6
|
-
|
|
7
|
-
const assert = require("node:assert/strict");
|
|
8
|
-
const { test } = require("node:test");
|
|
9
|
-
|
|
10
|
-
test("cli entry loads and prints version + help", async () => {
|
|
11
|
-
const { run } = require("../src/cli.js");
|
|
12
|
-
|
|
13
|
-
let out = "";
|
|
14
|
-
const originalWrite = process.stdout.write;
|
|
15
|
-
process.stdout.write = (chunk) => {
|
|
16
|
-
out += String(chunk);
|
|
17
|
-
return true;
|
|
18
|
-
};
|
|
19
|
-
try {
|
|
20
|
-
await run(["--version"]);
|
|
21
|
-
assert.match(out, /^v\d+\.\d+\.\d+\n$/);
|
|
22
|
-
out = "";
|
|
23
|
-
await run(["--help"]);
|
|
24
|
-
assert.match(out, /tokenusage/);
|
|
25
|
-
assert.match(out, /--watch/);
|
|
26
|
-
assert.ok(!out.includes("serve"));
|
|
27
|
-
} finally {
|
|
28
|
-
process.stdout.write = originalWrite;
|
|
29
|
-
}
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
test("device-flow authorize request matches the contract shape", async () => {
|
|
33
|
-
const captured = [];
|
|
34
|
-
// Narrow seam: device-login reads fetchFunctionResponse through lib.
|
|
35
|
-
const { functionUrlFor } = require("../src/lib/function-url");
|
|
36
|
-
|
|
37
|
-
assert.equal(
|
|
38
|
-
functionUrlFor("https://token-usage.baiwumm.com", "token-usage-device-flow-authorize"),
|
|
39
|
-
"https://token-usage.baiwumm.com/api/functions/token-usage-device-flow-authorize",
|
|
40
|
-
);
|
|
41
|
-
|
|
42
|
-
const { resolveRuntimeConfig } = require("../src/lib/runtime-config");
|
|
43
|
-
const runtime = resolveRuntimeConfig({});
|
|
44
|
-
assert.equal(runtime.baseUrl, "https://token-usage.baiwumm.com");
|
|
45
|
-
// Pre-GA deployments fall back to the production domain.
|
|
46
|
-
assert.equal(
|
|
47
|
-
resolveRuntimeConfig({ config: { baseUrl: "https://token-usage-delta.vercel.app" } }).baseUrl,
|
|
48
|
-
"https://token-usage.baiwumm.com",
|
|
49
|
-
);
|
|
50
|
-
assert.ok(runtime.anonKey && runtime.anonKey.startsWith("sb_publishable_"));
|
|
51
|
-
assert.equal(runtime.configurationError, null);
|
|
52
|
-
assert.ok(captured.length === 0);
|
|
53
|
-
});
|
package/test/cli-ui.test.js
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
// init summary rows: skipped call-sites already include a "Skipped (...)"
|
|
4
|
-
// detail, while formatSummaryLine added its own "Skipped - " prefix. The
|
|
5
|
-
// result was "Skipped - Skipped (--no-integrations)" (0.2.4 acceptance).
|
|
6
|
-
// Keep the double prefix out without changing the success rows.
|
|
7
|
-
|
|
8
|
-
const assert = require("node:assert/strict");
|
|
9
|
-
const { test } = require("node:test");
|
|
10
|
-
|
|
11
|
-
const { formatSummaryLine } = require("../src/lib/cli-ui");
|
|
12
|
-
|
|
13
|
-
test("a detail that already starts with Skipped is not prefixed twice", () => {
|
|
14
|
-
const line = formatSummaryLine({
|
|
15
|
-
label: "Integrations",
|
|
16
|
-
status: "skipped",
|
|
17
|
-
detail: "Skipped (--no-integrations); tool configs stay untouched",
|
|
18
|
-
});
|
|
19
|
-
assert.ok(line.includes("[Skipped (--no-integrations); tool configs stay untouched]"), line);
|
|
20
|
-
assert.ok(!line.includes("Skipped - Skipped"), line);
|
|
21
|
-
});
|
|
22
|
-
|
|
23
|
-
test("a plain skipped detail still gets the Skipped - prefix", () => {
|
|
24
|
-
const line = formatSummaryLine({
|
|
25
|
-
label: "Runtime copy",
|
|
26
|
-
status: "skipped",
|
|
27
|
-
detail: "not installed",
|
|
28
|
-
});
|
|
29
|
-
assert.ok(line.includes("[Skipped - not installed]"), line);
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
test("skipped rows without a detail keep the bare label", () => {
|
|
33
|
-
const line = formatSummaryLine({
|
|
34
|
-
label: "Scheduled task",
|
|
35
|
-
status: "skipped",
|
|
36
|
-
});
|
|
37
|
-
assert.ok(line.includes("[Skipped]"), line);
|
|
38
|
-
});
|
|
39
|
-
|
|
40
|
-
test("success rows keep their detail text untouched", () => {
|
|
41
|
-
const line = formatSummaryLine({
|
|
42
|
-
label: "Claude Code",
|
|
43
|
-
status: "installed",
|
|
44
|
-
detail: "hook -> ~/.claude/settings.json",
|
|
45
|
-
});
|
|
46
|
-
assert.ok(line.includes("[hook -> ~/.claude/settings.json]"), line);
|
|
47
|
-
});
|
|
@@ -1,255 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
// Regression tests for the 0.2.0 collection controls (docs/cli-contract.md
|
|
4
|
-
// §2.11 client semantics): the pause flag + run-report preference in
|
|
5
|
-
// ~/.tokenusage, the §2.11 telemetry builder (trigger resolution, idempotency
|
|
6
|
-
// run_id shape, best-effort report), and the scheduled-task takeover's pure
|
|
7
|
-
// parts (VBS wrapper, task naming).
|
|
8
|
-
|
|
9
|
-
const assert = require("node:assert/strict");
|
|
10
|
-
const fs = require("node:fs");
|
|
11
|
-
const os = require("node:os");
|
|
12
|
-
const path = require("node:path");
|
|
13
|
-
const { test, beforeEach, afterEach } = require("node:test");
|
|
14
|
-
|
|
15
|
-
const {
|
|
16
|
-
isCollectionPaused,
|
|
17
|
-
isRunReportEnabled,
|
|
18
|
-
setCollectionPaused,
|
|
19
|
-
pauseFilePath,
|
|
20
|
-
} = require("../src/lib/collection-pause");
|
|
21
|
-
const {
|
|
22
|
-
buildRunId,
|
|
23
|
-
resolveSyncTrigger,
|
|
24
|
-
createSyncRunTelemetry,
|
|
25
|
-
} = require("../src/lib/sync-report");
|
|
26
|
-
const {
|
|
27
|
-
TASK_NAME,
|
|
28
|
-
cliEntryPath,
|
|
29
|
-
buildHiddenRunnerVbs,
|
|
30
|
-
} = require("../src/lib/scheduled-task");
|
|
31
|
-
|
|
32
|
-
let tmpDir;
|
|
33
|
-
|
|
34
|
-
beforeEach(() => {
|
|
35
|
-
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "tokenusage-collection-controls-"));
|
|
36
|
-
});
|
|
37
|
-
|
|
38
|
-
afterEach(() => {
|
|
39
|
-
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
40
|
-
});
|
|
41
|
-
|
|
42
|
-
test("pause flag round-trips and defaults to unpaused on missing/corrupt state", () => {
|
|
43
|
-
assert.equal(isCollectionPaused(tmpDir), false);
|
|
44
|
-
|
|
45
|
-
setCollectionPaused(tmpDir, true);
|
|
46
|
-
assert.equal(isCollectionPaused(tmpDir), true);
|
|
47
|
-
const raw = JSON.parse(fs.readFileSync(pauseFilePath(tmpDir), "utf8"));
|
|
48
|
-
assert.equal(raw.paused, true);
|
|
49
|
-
assert.ok(typeof raw.at === "string");
|
|
50
|
-
|
|
51
|
-
setCollectionPaused(tmpDir, false);
|
|
52
|
-
assert.equal(isCollectionPaused(tmpDir), false);
|
|
53
|
-
assert.equal(fs.existsSync(pauseFilePath(tmpDir)), false);
|
|
54
|
-
|
|
55
|
-
// A corrupt flag must never silently stop collection.
|
|
56
|
-
fs.mkdirSync(tmpDir, { recursive: true });
|
|
57
|
-
fs.writeFileSync(pauseFilePath(tmpDir), "{not json");
|
|
58
|
-
assert.equal(isCollectionPaused(tmpDir), false);
|
|
59
|
-
});
|
|
60
|
-
|
|
61
|
-
test("run-report preference defaults to on and honors runReport:false in config.json", () => {
|
|
62
|
-
assert.equal(isRunReportEnabled(tmpDir), true);
|
|
63
|
-
|
|
64
|
-
fs.writeFileSync(
|
|
65
|
-
path.join(tmpDir, "config.json"),
|
|
66
|
-
JSON.stringify({ runReport: false }),
|
|
67
|
-
);
|
|
68
|
-
assert.equal(isRunReportEnabled(tmpDir), false);
|
|
69
|
-
|
|
70
|
-
fs.writeFileSync(
|
|
71
|
-
path.join(tmpDir, "config.json"),
|
|
72
|
-
JSON.stringify({ runReport: true }),
|
|
73
|
-
);
|
|
74
|
-
assert.equal(isRunReportEnabled(tmpDir), true);
|
|
75
|
-
|
|
76
|
-
// Corrupt config must not disable reporting (default on).
|
|
77
|
-
fs.writeFileSync(path.join(tmpDir, "config.json"), "{broken");
|
|
78
|
-
assert.equal(isRunReportEnabled(tmpDir), true);
|
|
79
|
-
});
|
|
80
|
-
|
|
81
|
-
test("trigger resolution folds the auto-ish flavors into the §2.11 enum", () => {
|
|
82
|
-
assert.equal(resolveSyncTrigger({}), "manual");
|
|
83
|
-
assert.equal(resolveSyncTrigger({ auto: true }), "scheduled");
|
|
84
|
-
assert.equal(resolveSyncTrigger({ auto: true, background: true }), "scheduled");
|
|
85
|
-
assert.equal(resolveSyncTrigger({ auto: true, fromRetry: true }), "scheduled");
|
|
86
|
-
assert.equal(resolveSyncTrigger({ auto: true, fromNotify: true }), "notify");
|
|
87
|
-
assert.equal(resolveSyncTrigger({ auto: true, fromOpenclaw: true }), "notify");
|
|
88
|
-
assert.equal(resolveSyncTrigger({}, { trigger: "watch" }), "watch");
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
test("run_id follows the <started_at epoch ms>-<4hex> idempotency shape", () => {
|
|
92
|
-
const runId = buildRunId(1730000000000);
|
|
93
|
-
assert.match(runId, /^1730000000000-[0-9a-f]{4}$/);
|
|
94
|
-
const other = buildRunId(1730000000000);
|
|
95
|
-
assert.notEqual(runId, other);
|
|
96
|
-
});
|
|
97
|
-
|
|
98
|
-
test("telemetry snapshots carry exactly the §2.11 whitelist shape", () => {
|
|
99
|
-
const telemetry = createSyncRunTelemetry({
|
|
100
|
-
trigger: "scheduled",
|
|
101
|
-
startedAtMs: 1730000000000,
|
|
102
|
-
runId: "1730000000000-ab12",
|
|
103
|
-
cliVersion: "0.2.0",
|
|
104
|
-
osLabel: "win32 10.0.26200",
|
|
105
|
-
});
|
|
106
|
-
telemetry.noteParsedFiles(12);
|
|
107
|
-
telemetry.noteUpload({ inserted: 3, tokens: 4500 });
|
|
108
|
-
telemetry.noteSessions({ upserted: 2, skipped: 1 });
|
|
109
|
-
telemetry.noteQueueBytes(512);
|
|
110
|
-
|
|
111
|
-
const snapshot = telemetry.snapshot();
|
|
112
|
-
assert.deepEqual(snapshot, {
|
|
113
|
-
run_id: "1730000000000-ab12",
|
|
114
|
-
started_at: new Date(1730000000000).toISOString(),
|
|
115
|
-
ended_at: snapshot.ended_at,
|
|
116
|
-
trigger: "scheduled",
|
|
117
|
-
result: "ok",
|
|
118
|
-
parsed_files: 12,
|
|
119
|
-
buckets_uploaded: 3,
|
|
120
|
-
tokens_ingested: 4500,
|
|
121
|
-
sessions_uploaded: 2,
|
|
122
|
-
sessions_skipped: 1,
|
|
123
|
-
queue_bytes: 512,
|
|
124
|
-
cli_version: "0.2.0",
|
|
125
|
-
os: "win32 10.0.26200",
|
|
126
|
-
});
|
|
127
|
-
|
|
128
|
-
// An empty run derives exactly like the server-side rule expects clients
|
|
129
|
-
// NOT to send: no empty field, derived by the server from zero counters.
|
|
130
|
-
const empty = createSyncRunTelemetry({ trigger: "manual", cliVersion: "0.2.0" });
|
|
131
|
-
empty.noteUpload({ inserted: 0, tokens: 0 });
|
|
132
|
-
empty.noteSessions({ upserted: 0, skipped: 0 });
|
|
133
|
-
assert.equal(empty.snapshot().tokens_ingested, 0);
|
|
134
|
-
assert.equal(empty.snapshot().sessions_uploaded, 0);
|
|
135
|
-
});
|
|
136
|
-
|
|
137
|
-
test("report() is strictly best-effort: never throws, skips unpaired runs, logs failures", async () => {
|
|
138
|
-
const logs = [];
|
|
139
|
-
const telemetry = createSyncRunTelemetry({
|
|
140
|
-
trigger: "manual",
|
|
141
|
-
cliVersion: "0.2.0",
|
|
142
|
-
log: (line) => logs.push(line),
|
|
143
|
-
});
|
|
144
|
-
|
|
145
|
-
// Unpaired: no token/baseUrl — silent skip, no log noise.
|
|
146
|
-
assert.equal(await telemetry.report({}), false);
|
|
147
|
-
assert.equal(logs.length, 0);
|
|
148
|
-
|
|
149
|
-
// Paired but unreachable: logs locally, resolves false, never throws.
|
|
150
|
-
const failing = createSyncRunTelemetry({
|
|
151
|
-
trigger: "manual",
|
|
152
|
-
cliVersion: "0.2.0",
|
|
153
|
-
log: (line) => logs.push(line),
|
|
154
|
-
});
|
|
155
|
-
assert.equal(
|
|
156
|
-
await failing.report({ baseUrl: "http://127.0.0.1:9", deviceToken: "fake-token" }),
|
|
157
|
-
false,
|
|
158
|
-
);
|
|
159
|
-
assert.equal(logs.length, 1);
|
|
160
|
-
assert.match(logs[0], /Run report failed/);
|
|
161
|
-
|
|
162
|
-
// Only the first report() of a telemetry object ever attempts the network;
|
|
163
|
-
// later calls are silent no-ops (a run reports at most once).
|
|
164
|
-
assert.equal(
|
|
165
|
-
await failing.report({ baseUrl: "http://127.0.0.1:9", deviceToken: "fake-token" }),
|
|
166
|
-
false,
|
|
167
|
-
);
|
|
168
|
-
assert.equal(logs.length, 1);
|
|
169
|
-
});
|
|
170
|
-
|
|
171
|
-
test("hidden-runner VBS quotes paths individually and propagates the exit code", () => {
|
|
172
|
-
const vbs = buildHiddenRunnerVbs({
|
|
173
|
-
nodeExe: "C:\\Program Files\\nodejs\\node.exe",
|
|
174
|
-
cliJs: "C:\\Users\\me\\AppData\\tokenusage-cli\\bin\\tokenusage.js",
|
|
175
|
-
});
|
|
176
|
-
// Chr(34) builds the quotes: no VBS quote-escaping, no cmd /c layer, and
|
|
177
|
-
// paths with spaces stay intact.
|
|
178
|
-
assert.match(vbs, /q = Chr\(34\)/);
|
|
179
|
-
assert.ok(vbs.includes('nodeExe = "C:\\Program Files\\nodejs\\node.exe"'));
|
|
180
|
-
assert.ok(vbs.includes('cliJs = "C:\\Users\\me\\AppData\\tokenusage-cli\\bin\\tokenusage.js"'));
|
|
181
|
-
assert.ok(vbs.includes('cmd = q & nodeExe & q & " " & q & cliJs & q & " sync --from-scheduled"'));
|
|
182
|
-
// Hidden window (0) + wait for completion (True).
|
|
183
|
-
assert.match(vbs, /WScript\.Quit shell\.Run\(cmd, 0, True\)/);
|
|
184
|
-
// The task name stays stable — pause/resume and uninstall toggle by name.
|
|
185
|
-
assert.equal(TASK_NAME, "TokenUsageSync");
|
|
186
|
-
});
|
|
187
|
-
|
|
188
|
-
// nvm-windows installs npm globals into a version-specific prefix, so the
|
|
189
|
-
// recorded package path vanishes after `nvm use` and the hourly run failed
|
|
190
|
-
// every time with "file not found". The VBS now falls back to the
|
|
191
|
-
// init-copied runtime, which lives under the data dir.
|
|
192
|
-
test("hidden-runner VBS falls back to the init runtime when the package path disappears", () => {
|
|
193
|
-
const fallback = "C:\\Users\\me\\.tokenusage\\tracker\\app\\bin\\tracker.js";
|
|
194
|
-
const vbs = buildHiddenRunnerVbs({
|
|
195
|
-
nodeExe: "C:\\Program Files\\nodejs\\node.exe",
|
|
196
|
-
cliJs: "C:\\Users\\me\\AppData\\Roaming\\npm\\node_modules\\tokenusage-cli\\bin\\tokenusage.js",
|
|
197
|
-
fallbackCliJs: fallback,
|
|
198
|
-
});
|
|
199
|
-
assert.ok(
|
|
200
|
-
vbs.includes(`If Not fso.FileExists(cliJs) Then cliJs = "${fallback}"`),
|
|
201
|
-
"the runtime copy must be the fallback target",
|
|
202
|
-
);
|
|
203
|
-
// Non-nvm layouts have nothing to fall back to; the line stays out.
|
|
204
|
-
const plain = buildHiddenRunnerVbs({ nodeExe: "node.exe", cliJs: "C:\\a\\b.js" });
|
|
205
|
-
assert.ok(!plain.includes("FileExists"), "no fallback probe without a fallback path");
|
|
206
|
-
});
|
|
207
|
-
|
|
208
|
-
// 0.2.2 regression: init registered src/cli.js instead of the bin entry. That
|
|
209
|
-
// file only exports run(), so the hidden task exited 0 within ~0.1 s without
|
|
210
|
-
// collecting or logging anything — a silent, permanently "successful" task.
|
|
211
|
-
test("scheduled task launches the CLI entry, never the inert src/cli.js", () => {
|
|
212
|
-
const entry = cliEntryPath().replace(/\\/g, "/");
|
|
213
|
-
assert.match(entry, /\/bin\/tokenusage\.js$/);
|
|
214
|
-
assert.ok(fs.existsSync(cliEntryPath()), "the registered entry must exist in the package");
|
|
215
|
-
|
|
216
|
-
const vbs = buildHiddenRunnerVbs({ nodeExe: "node.exe", cliJs: cliEntryPath() });
|
|
217
|
-
assert.doesNotMatch(vbs, /src[\\/]cli\.js/);
|
|
218
|
-
});
|
|
219
|
-
|
|
220
|
-
test("--from-scheduled reports as scheduled, unlike a plain manual run", () => {
|
|
221
|
-
assert.equal(resolveSyncTrigger({ fromScheduled: true }), "scheduled");
|
|
222
|
-
// The scheduled task must upload on default installs, so --from-scheduled
|
|
223
|
-
// deliberately does NOT map onto the cloud-sync-gated auto/background flags.
|
|
224
|
-
assert.equal(resolveSyncTrigger({ auto: true }), "scheduled");
|
|
225
|
-
assert.equal(resolveSyncTrigger({}), "manual");
|
|
226
|
-
});
|
|
227
|
-
|
|
228
|
-
// Runtime-require depth guard: a `require("../package.json")` inside src/commands
|
|
229
|
-
// or src/lib resolves to a nonexistent src/package.json and only explodes when
|
|
230
|
-
// the lazy call site runs (0.2.0 shipped exactly this in sync.js's report tail —
|
|
231
|
-
// the smoke tests never execute it). Only src/cli.js sits at the depth where the
|
|
232
|
-
// one-level form is valid; everything nested deeper must use ../../.
|
|
233
|
-
test("no nested module resolves package.json at the wrong depth", () => {
|
|
234
|
-
const srcDir = path.join(__dirname, "..", "src");
|
|
235
|
-
const offenders = [];
|
|
236
|
-
|
|
237
|
-
const walk = (dir) => {
|
|
238
|
-
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
239
|
-
const full = path.join(dir, entry.name);
|
|
240
|
-
if (entry.isDirectory()) {
|
|
241
|
-
walk(full);
|
|
242
|
-
} else if (entry.name.endsWith(".js")) {
|
|
243
|
-
const source = fs.readFileSync(full, "utf8");
|
|
244
|
-
if (source.includes('require("../package.json")')) {
|
|
245
|
-
const relative = path.relative(srcDir, full).split(path.sep).join("/");
|
|
246
|
-
|
|
247
|
-
if (relative !== "cli.js") offenders.push(relative);
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
};
|
|
252
|
-
|
|
253
|
-
walk(srcDir);
|
|
254
|
-
assert.deepEqual(offenders, []);
|
|
255
|
-
});
|