ceulen 0.1.0 → 0.5.1
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 +150 -0
- package/README.md +103 -14
- package/extensions/index.ts +113 -0
- package/extensions/lib/env.ts +75 -0
- package/extensions/lib/panel.ts +1720 -0
- package/extensions/lib/registry.ts +182 -0
- package/extensions/modules/composer/index.ts +128 -0
- package/extensions/modules/composer/lib/settings.ts +55 -0
- package/extensions/modules/composer/lib/shapes.ts +436 -0
- package/extensions/modules/composer/test/editor.test.ts +138 -0
- package/extensions/modules/composer/test/module.test.ts +218 -0
- package/extensions/modules/composer/test/screen.test.ts +195 -0
- package/extensions/modules/composer/test/shapes.test.ts +175 -0
- package/extensions/modules/config/index.ts +298 -0
- package/extensions/modules/config/piSettings.ts +467 -0
- package/extensions/modules/config/plugins.ts +290 -0
- package/extensions/modules/config/test/kernel.test.ts +523 -0
- package/extensions/modules/config/test/kernelV4.test.ts +196 -0
- package/extensions/modules/config/test/menu.test.ts +226 -0
- package/extensions/modules/config/test/panel.test.ts +395 -0
- package/extensions/modules/config/test/piSettings.test.ts +185 -0
- package/extensions/modules/config/test/plugins.test.ts +181 -0
- package/extensions/modules/config/test/preview-block.test.ts +88 -0
- package/extensions/modules/ponytail/UPSTREAM +26 -0
- package/extensions/modules/ponytail/index.ts +336 -0
- package/extensions/modules/ponytail/lib/config.ts +149 -0
- package/extensions/modules/ponytail/lib/instructions.ts +98 -0
- package/extensions/modules/ponytail/lib/subagent.ts +31 -0
- package/extensions/modules/ponytail/test/extension.test.ts +422 -0
- package/extensions/modules/ponytail/test/helpers.test.ts +163 -0
- package/extensions/modules/ponytail/test/subagent.test.ts +33 -0
- package/extensions/modules/router/commands/commands.ts +99 -0
- package/extensions/modules/router/configPanel.ts +89 -0
- package/extensions/modules/router/index.ts +75 -0
- package/extensions/modules/router/lib/client.ts +390 -0
- package/extensions/modules/router/lib/config.ts +142 -0
- package/extensions/modules/router/lib/migrate.ts +92 -0
- package/extensions/modules/router/lib/provider.ts +138 -0
- package/extensions/modules/router/lib/refresh.ts +19 -0
- package/extensions/modules/router/test/guard.test.ts +77 -0
- package/extensions/modules/router/test/unit.test.ts +1126 -0
- package/extensions/modules/usage/index.ts +1975 -0
- package/extensions/modules/usage/test/context.test.ts +387 -0
- package/extensions/modules/usage/test/env-gating.test.ts +113 -0
- package/extensions/modules/usage/test/opencode-go-usage.test.ts +139 -0
- package/extensions/modules/usage/test/parsers.test.ts +244 -0
- package/extensions/modules/usage/test/stale-ctx-regression.test.ts +294 -0
- package/extensions/modules/usage/test/zai-anthropic-adapter.test.ts +40 -0
- package/package.json +15 -3
- package/skills/ponytail/SKILL.md +124 -0
- package/skills/ponytail-audit/SKILL.md +41 -0
- package/skills/ponytail-debt/SKILL.md +44 -0
- package/skills/ponytail-gain/SKILL.md +51 -0
- package/skills/ponytail-help/SKILL.md +73 -0
- package/skills/ponytail-review/SKILL.md +57 -0
- package/extensions/index.js +0 -42
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import {
|
|
4
|
+
computeContextBreakdown,
|
|
5
|
+
shortSource,
|
|
6
|
+
formatCtxTokens,
|
|
7
|
+
formatCtxPercent,
|
|
8
|
+
ctxWaffle,
|
|
9
|
+
renderContextPanel,
|
|
10
|
+
resolveReserveTokens,
|
|
11
|
+
type ContextBreakdownInput,
|
|
12
|
+
} from "../index.ts";
|
|
13
|
+
|
|
14
|
+
/** Fixture ctx with a structured system-prompt system message + tools. */
|
|
15
|
+
function fixtureCtx(overrides: Partial<ContextBreakdownInput["ctx"]> = {}): ContextBreakdownInput["ctx"] {
|
|
16
|
+
const systemSections: Record<string, string | null> = {
|
|
17
|
+
preamble: "p".repeat(400), // 100 tokens
|
|
18
|
+
project_context: "m".repeat(8000), // 2000 tokens
|
|
19
|
+
skills: "<skill><name>a</name></skill>\n<skill><name>b</name></skill>" + "s".repeat(800), // ~204 tokens, 2 skills
|
|
20
|
+
rules: null, // removed section — must be skipped
|
|
21
|
+
};
|
|
22
|
+
const tools = [
|
|
23
|
+
{ name: "read", description: "d".repeat(400), parameters: { type: "object" }, sourceInfo: { source: "pi" } },
|
|
24
|
+
{ name: "web_search", description: "d".repeat(800), parameters: { type: "object", properties: { q: {} } }, sourceInfo: { source: "@bacnh85/pi-web" } },
|
|
25
|
+
{ name: "web_extract", description: "d".repeat(800), parameters: {}, sourceInfo: { source: "@bacnh85/pi-web" } },
|
|
26
|
+
];
|
|
27
|
+
const messages: Array<Record<string, unknown>> = [
|
|
28
|
+
{ role: "system", sections: systemSections },
|
|
29
|
+
{ role: "user", content: "u".repeat(200) }, // 50 tokens
|
|
30
|
+
{ role: "assistant", content: [{ type: "text", text: "a".repeat(400) }] }, // 100 tokens
|
|
31
|
+
];
|
|
32
|
+
return {
|
|
33
|
+
getContextUsage: () => ({ tokens: 5000, contextWindow: 200000, percent: 2.5 }),
|
|
34
|
+
getSystemPrompt: () => "x".repeat(40000),
|
|
35
|
+
getAllTools: () => tools as never,
|
|
36
|
+
getActiveTools: () => ["read", "web_search"],
|
|
37
|
+
sessionManager: { buildSessionProjection: () => ({ messages }) as never },
|
|
38
|
+
...overrides,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function fixtureInput(overrides: Partial<ContextBreakdownInput> = {}): ContextBreakdownInput {
|
|
43
|
+
const ctx = fixtureCtx();
|
|
44
|
+
const { getAllTools, getActiveTools, ...rest } = ctx as Record<string, unknown>;
|
|
45
|
+
return {
|
|
46
|
+
ctx: rest as unknown as ContextBreakdownInput["ctx"],
|
|
47
|
+
allTools: (getAllTools as () => unknown[])(),
|
|
48
|
+
activeTools: (getActiveTools as () => string[])(),
|
|
49
|
+
...overrides,
|
|
50
|
+
} as unknown as ContextBreakdownInput;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
test("formatCtxTokens compact formatting", () => {
|
|
54
|
+
assert.equal(formatCtxTokens(999), "999");
|
|
55
|
+
assert.equal(formatCtxTokens(5340), "5.3K");
|
|
56
|
+
assert.equal(formatCtxTokens(21450), "21K");
|
|
57
|
+
assert.equal(formatCtxTokens(157000), "157K");
|
|
58
|
+
assert.equal(formatCtxTokens(1048576), "1m");
|
|
59
|
+
assert.equal(formatCtxTokens(200000), "200K");
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("formatCtxPercent slivers and normal cases", () => {
|
|
63
|
+
assert.equal(formatCtxPercent(328, 1048576), "<0.1%");
|
|
64
|
+
assert.equal(formatCtxPercent(21450, 1048576), "2.0%");
|
|
65
|
+
assert.equal(formatCtxPercent(157000, 1048576), "15.0%");
|
|
66
|
+
assert.equal(formatCtxPercent(500, 0), "?");
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test("ctxWaffle renders an OMP 4x10 grid that always fills the canvas", () => {
|
|
70
|
+
const grid = ctxWaffle([{ tokens: 21450, glyph: "⛁" }, { tokens: 870000, glyph: "⛶" }, { tokens: 157286, glyph: "⛝" }], 1048576, 10, 4);
|
|
71
|
+
assert.equal(grid.length, 4);
|
|
72
|
+
assert.ok(grid.every((row) => [...row].length === 10), grid.join("|"));
|
|
73
|
+
const flat = grid.join("");
|
|
74
|
+
assert.ok(flat.includes("⛁"), "used cells render ⛁");
|
|
75
|
+
assert.ok(flat.includes("⛶"), "free cells render ⛶");
|
|
76
|
+
assert.ok(flat.includes("⛝"), "autocompact buffer renders ⛝ at the end");
|
|
77
|
+
assert.equal([...flat].length, 40, "exactly rows × cols cells");
|
|
78
|
+
// Buffer is the final slice of the window → painted at the end of the grid.
|
|
79
|
+
assert.equal([...flat].pop(), "⛝");
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test("ctxWaffle visibility-scales tiny slices to one cell and hands slack to free space", () => {
|
|
83
|
+
// 0.05% used still gets a cell (>=0.5% threshold is one cell either way here);
|
|
84
|
+
// an empty session shows no used cell at all.
|
|
85
|
+
const tiny = ctxWaffle([{ tokens: 500, glyph: "⛁" }, { tokens: 196000, glyph: "⛶" }], 196608).join("");
|
|
86
|
+
assert.equal(tiny.split("⛁").length - 1, 1, "tiny used slice keeps one visible cell");
|
|
87
|
+
const empty = ctxWaffle([{ tokens: 0, glyph: "⛁" }, { tokens: 180224, glyph: "⛶" }, { tokens: 16384, glyph: "⛝" }], 196608).join("");
|
|
88
|
+
assert.equal(empty.split("⛁").length - 1, 0, "zero used renders no filled cells");
|
|
89
|
+
assert.equal(empty.split("⛝").length - 1, 3, "16K/192K buffer ≈ 3 cells");
|
|
90
|
+
assert.equal([...empty].length, 40);
|
|
91
|
+
// Unknown window → all free.
|
|
92
|
+
assert.deepEqual(ctxWaffle([{ tokens: 5, glyph: "⛁" }], 0), Array(4).fill("⛶".repeat(10)));
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
test("resolveReserveTokens mirrors pi's resolution order", () => {
|
|
96
|
+
// default when nothing configured / settings unreadable
|
|
97
|
+
assert.equal(resolveReserveTokens(undefined), 16384);
|
|
98
|
+
assert.equal(resolveReserveTokens({}), 16384);
|
|
99
|
+
// ordinary compaction.reserveTokens
|
|
100
|
+
assert.equal(resolveReserveTokens({ compaction: { reserveTokens: 50000 } }), 50000);
|
|
101
|
+
// per-model override wins over the ordinary value
|
|
102
|
+
assert.equal(
|
|
103
|
+
resolveReserveTokens(
|
|
104
|
+
{ compaction: { reserveTokens: 50000, modelOverrides: { "zai/glm-5.3": { reserveTokens: 100000 } } } },
|
|
105
|
+
{ provider: "zai", id: "glm-5.3" },
|
|
106
|
+
),
|
|
107
|
+
100000,
|
|
108
|
+
);
|
|
109
|
+
// invalid values fall back to the default (mirrors pi's validation skip)
|
|
110
|
+
assert.equal(resolveReserveTokens({ compaction: { reserveTokens: -5 } }), 16384);
|
|
111
|
+
assert.equal(resolveReserveTokens({ compaction: { reserveTokens: "big" } }), 16384);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("computeContextBreakdown splits sections, groups tools by source, reserves budget", () => {
|
|
115
|
+
const b = computeContextBreakdown(fixtureInput({ model: { maxTokens: 8192, contextWindow: 200000 } }));
|
|
116
|
+
// System prompt: sections only (blob fallback NOT used), null section skipped.
|
|
117
|
+
// skills string = 59 chars of tags + 800 filler = 859 → 215 tokens.
|
|
118
|
+
assert.equal(b.systemPrompt.total, 100 + 2000 + 215);
|
|
119
|
+
assert.equal(b.systemPrompt.sections.preamble, 100);
|
|
120
|
+
assert.equal(b.systemPrompt.sections.project_context, 2000);
|
|
121
|
+
assert.equal(b.systemPrompt.sections.rules, undefined);
|
|
122
|
+
// Tools: (400 + ~22)/4=106, (800 + ~43)/4=211, 800/4=200 → grouped by source.
|
|
123
|
+
assert.equal(b.tools.registeredCount, 3);
|
|
124
|
+
assert.equal(b.tools.activeCount, 2);
|
|
125
|
+
assert.equal(b.tools.bySource["@bacnh85/pi-web"].count, 2);
|
|
126
|
+
assert.equal(b.tools.bySource.pi.count, 1);
|
|
127
|
+
assert.equal(b.tools.total, b.tools.bySource.pi.tokens + b.tools.bySource["@bacnh85/pi-web"].tokens);
|
|
128
|
+
// Skills parsed from the skills section.
|
|
129
|
+
assert.equal(b.skills.count, 2);
|
|
130
|
+
assert.ok(b.skills.total > 0 && b.skills.total < 300);
|
|
131
|
+
// Memory files: project_context (+ addendum when present).
|
|
132
|
+
assert.equal(b.memoryFiles.total, 2000);
|
|
133
|
+
assert.deepEqual(b.memoryFiles.files.map((f) => f.name), ["project_context"]);
|
|
134
|
+
// Messages: user + assistant, system excluded (counted as systemPrompt).
|
|
135
|
+
assert.equal(b.messages.count, 2);
|
|
136
|
+
assert.equal(b.messages.total, 50 + 100);
|
|
137
|
+
// Per-tool costs, descending (powers the top-tools list).
|
|
138
|
+
assert.deepEqual(b.toolCosts.map((t) => t.name), ["web_search", "web_extract", "read"]);
|
|
139
|
+
// Reserved is the compaction slice only; free space excludes it (pi's trigger:
|
|
140
|
+
// tokens > window - reserveTokens). Model output is NOT reserved.
|
|
141
|
+
assert.deepEqual(b.reserved, { compaction: 16384 });
|
|
142
|
+
assert.equal(b.compactionDisabled, false);
|
|
143
|
+
assert.equal(b.freeSpace, 200000 - 5000 - 16384);
|
|
144
|
+
// Slices are disjoint and account for the window.
|
|
145
|
+
assert.equal(5000 + b.reserved.compaction + b.freeSpace, 200000);
|
|
146
|
+
// Authoritative usage rides through.
|
|
147
|
+
assert.equal(b.usedTokens, 5000);
|
|
148
|
+
assert.equal(b.percent, 2.5);
|
|
149
|
+
assert.equal(b.contextWindow, 200000);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
test("computeContextBreakdown honors configured reserve and compaction-disabled", () => {
|
|
153
|
+
const configured = computeContextBreakdown(fixtureInput({
|
|
154
|
+
model: { provider: "zai", id: "glm-5.3", maxTokens: 8192, contextWindow: 200000 },
|
|
155
|
+
settings: { compaction: { reserveTokens: 60000, modelOverrides: { "zai/glm-5.3": { reserveTokens: 90000 } } } },
|
|
156
|
+
}));
|
|
157
|
+
assert.equal(configured.reserved.compaction, 90000);
|
|
158
|
+
assert.equal(configured.freeSpace, 200000 - 5000 - 90000);
|
|
159
|
+
|
|
160
|
+
const disabled = computeContextBreakdown(fixtureInput({ settings: { compaction: { enabled: false } } }));
|
|
161
|
+
assert.equal(disabled.compactionDisabled, true);
|
|
162
|
+
assert.equal(disabled.freeSpace, 200000 - 5000); // no reserve withheld
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
test("computeContextBreakdown falls back to whole-prompt blob before sections exist", () => {
|
|
166
|
+
const ctx = fixtureCtx();
|
|
167
|
+
ctx.sessionManager.buildSessionProjection = () => ({ messages: [{ role: "user", content: "hi" }] }) as never;
|
|
168
|
+
const b = computeContextBreakdown(fixtureInput({ ctx }));
|
|
169
|
+
assert.equal(b.systemPrompt.total, 10000); // 40000 chars / 4
|
|
170
|
+
assert.equal(b.systemPrompt.sections.skills, undefined);
|
|
171
|
+
assert.equal(b.skills.total, 0);
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
test("computeContextBreakdown tolerates a throwing projection and missing usage", () => {
|
|
175
|
+
const ctx = fixtureCtx({
|
|
176
|
+
// Real after-compaction shape: contextWindow known, tokens null.
|
|
177
|
+
getContextUsage: () => ({ tokens: null, contextWindow: 200000, percent: null }),
|
|
178
|
+
});
|
|
179
|
+
ctx.sessionManager.buildSessionProjection = () => { throw new Error("no session"); };
|
|
180
|
+
const b = computeContextBreakdown(fixtureInput({ ctx }));
|
|
181
|
+
assert.equal(b.usedTokens, null);
|
|
182
|
+
assert.equal(b.percent, null);
|
|
183
|
+
assert.equal(b.systemPrompt.total, 10000);
|
|
184
|
+
// Fallback used-tokens path: system + tools + messages, no throw.
|
|
185
|
+
const lines = renderContextPanel(b);
|
|
186
|
+
assert.ok(lines.some((l) => l.includes("Category splits are estimates")), lines.join("\n"));
|
|
187
|
+
assert.equal(b.freeSpace, Math.max(0, 200000 - (10000 + b.tools.total) - 16384));
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
test("renderContextPanel matches the OMP layout and fires recommendations", () => {
|
|
191
|
+
// Tiny-ish window so the 516-token tool fixture crosses the 40% recommendation threshold.
|
|
192
|
+
const b = computeContextBreakdown(fixtureInput({ ctx: fixtureCtx(), model: { maxTokens: 8192, contextWindow: 1200 } }));
|
|
193
|
+
const lines = renderContextPanel(b);
|
|
194
|
+
assert.equal(lines[0], "Context Usage");
|
|
195
|
+
// Header: 4 waffle rows (10 cells each) with model info on the right.
|
|
196
|
+
const gridRows = lines.slice(2, 6);
|
|
197
|
+
assert.ok(gridRows.every((l) => /^[⛁⛶⛝]{10}/.test(l)), gridRows.join("|"));
|
|
198
|
+
assert.ok(lines.some((l) => l.includes("5.0K/1.2K tokens (416.7%)")), lines.join("\n"));
|
|
199
|
+
// Disjoint, glyph-prefixed category block (core prompt excludes context + skills).
|
|
200
|
+
assert.ok(lines.some((l) => l.startsWith(" ⛁ System prompt:")), lines.join("\n"));
|
|
201
|
+
assert.ok(lines.some((l) => l.startsWith(" ⛁ System tools:")));
|
|
202
|
+
assert.ok(lines.some((l) => l.startsWith(" ⛁ System context:")));
|
|
203
|
+
assert.ok(lines.some((l) => l.startsWith(" ⛁ Skills:")));
|
|
204
|
+
assert.ok(lines.some((l) => l.startsWith(" ⛁ Messages:")));
|
|
205
|
+
assert.ok(lines.some((l) => l.startsWith(" ⛶ Free space:")));
|
|
206
|
+
assert.ok(lines.some((l) => l.startsWith(" ⛝ Autocompact buffer:")));
|
|
207
|
+
// Detail lists.
|
|
208
|
+
assert.ok(lines.some((l) => l.includes("pi-web:")), lines.join("\n"));
|
|
209
|
+
assert.ok(!lines.some((l) => l.includes("@bacnh85/")), "package labels are shortened");
|
|
210
|
+
assert.ok(lines.some((l) => l.includes("project_context: 2.0K")));
|
|
211
|
+
// tools (516) > 40% of the 1200-token window → recommendation fires.
|
|
212
|
+
assert.ok(lines.some((l) => l.startsWith("- ") && l.includes("setActiveTools")), lines.join("\n"));
|
|
213
|
+
assert.ok(!lines.some((l) => l.includes("trimming AGENTS.md")));
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
test("renderContextPanel fires memory + skills recommendations above thresholds", () => {
|
|
217
|
+
const ctx = fixtureCtx();
|
|
218
|
+
const big = "m".repeat(4 * 4000); // 4000 tokens
|
|
219
|
+
(ctx.sessionManager.buildSessionProjection().messages[0] as Record<string, unknown>).sections = {
|
|
220
|
+
project_context: big,
|
|
221
|
+
skills: "<skill><name>a</name></skill>" + "s".repeat(4 * 2500),
|
|
222
|
+
};
|
|
223
|
+
const b = computeContextBreakdown(fixtureInput({ ctx }));
|
|
224
|
+
const lines = renderContextPanel(b);
|
|
225
|
+
assert.ok(lines.some((l) => l.includes("trimming AGENTS.md")));
|
|
226
|
+
assert.ok(lines.some((l) => l.includes("disable-model-invocation")));
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
test("/context handler posts a transcript message; renderer tints glyphs", async () => {
|
|
230
|
+
const { default: extension } = await import("../index.ts");
|
|
231
|
+
const commands: Record<string, { handler: (args: string, ctx: unknown) => Promise<void> }> = {};
|
|
232
|
+
const renderers: Record<string, (m: unknown, o: unknown, t: unknown) => { render(w: number): string[] } | undefined> = {};
|
|
233
|
+
const sent: Array<{ customType: string; content: string; display?: boolean; details?: { lines?: string[] } }> = [];
|
|
234
|
+
const fakePi = {
|
|
235
|
+
on: () => {},
|
|
236
|
+
registerCommand: (name: string, def: { handler: (args: string, ctx: unknown) => Promise<void> }) => { commands[name] = def; },
|
|
237
|
+
registerTool: () => {},
|
|
238
|
+
registerMessageRenderer: (type: string, renderer: never) => { renderers[type] = renderer; },
|
|
239
|
+
sendMessage: (msg: { customType: string; content: string; display?: boolean; details?: { lines?: string[] } }) => { sent.push(msg); },
|
|
240
|
+
getAllTools: () => (fixtureCtx() as never as { getAllTools(): unknown[] }).getAllTools(),
|
|
241
|
+
getActiveTools: () => ["read", "web_search"],
|
|
242
|
+
};
|
|
243
|
+
(extension as unknown as (pi: unknown) => void)(fakePi);
|
|
244
|
+
const handler = commands.context?.handler;
|
|
245
|
+
assert.ok(handler, "/context registered");
|
|
246
|
+
assert.ok(renderers["ceulen-usage-context"], "transcript renderer registered");
|
|
247
|
+
|
|
248
|
+
const mkCtx = (mode: string) => ({
|
|
249
|
+
mode,
|
|
250
|
+
model: { maxTokens: 8192, contextWindow: 200000 },
|
|
251
|
+
getContextUsage: () => ({ tokens: 5000, contextWindow: 200000, percent: 2.5 }),
|
|
252
|
+
getSystemPrompt: () => "x".repeat(40000),
|
|
253
|
+
sessionManager: { buildSessionProjection: () => ({ messages: [] }) },
|
|
254
|
+
ui: { notify: () => {}, theme: { fg: (_c: string, s: string) => s } },
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
// TUI: panel posted as a displayable transcript message carrying the lines.
|
|
258
|
+
await handler!("", mkCtx("tui"));
|
|
259
|
+
assert.equal(sent.length, 1);
|
|
260
|
+
assert.equal(sent[0].customType, "ceulen-usage-context");
|
|
261
|
+
assert.equal(sent[0].display, true, "message is displayed in the transcript");
|
|
262
|
+
const lines = sent[0].details?.lines ?? [];
|
|
263
|
+
assert.ok(lines.some((l) => l.startsWith(" ⛁ System prompt:")), lines.join("\n"));
|
|
264
|
+
assert.ok(lines.some((l) => l.startsWith(" ⛶ Free space:")));
|
|
265
|
+
|
|
266
|
+
// Renderer: colors the glyph, keeps the body plain, and clamps to width.
|
|
267
|
+
const comp = renderers["ceulen-usage-context"]!({ details: { lines: [" ⛁ System prompt: 1K tokens (1.0%)"] } }, {}, { fg: (c: string, s: string) => `<${c}>${s}</>` });
|
|
268
|
+
const out = comp!.render(200);
|
|
269
|
+
assert.ok(out[0].includes("<accent>⛁</>"), out[0]);
|
|
270
|
+
assert.ok(out[0].includes("System prompt: 1K tokens"), out[0]);
|
|
271
|
+
// Width clamp applies to the source line (before ANSI codes are added).
|
|
272
|
+
const narrow = comp!.render(10);
|
|
273
|
+
assert.ok(narrow[0].includes("⛁"), "glyph survives the clamp");
|
|
274
|
+
assert.ok(!narrow[0].includes("System prompt"), "body beyond the width is dropped");
|
|
275
|
+
|
|
276
|
+
// Plain-text content always rides along as the renderer-less fallback.
|
|
277
|
+
assert.ok(sent[0].content.includes("Context Usage"), "content carries a plain-text fallback");
|
|
278
|
+
assert.ok(sent[0].content.includes("⛁ System prompt:"), sent[0].content);
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
test("categories are disjoint, reconcile with usage, and partition the window", () => {
|
|
282
|
+
const b = computeContextBreakdown(fixtureInput());
|
|
283
|
+
const core = b.categories.find((c) => c.label === "System prompt")!.tokens;
|
|
284
|
+
const context = b.categories.find((c) => c.label === "System context")!.tokens;
|
|
285
|
+
const skills = b.categories.find((c) => c.label === "Skills")!.tokens;
|
|
286
|
+
// No double-counting: core + context + skills reconstruct the system prompt.
|
|
287
|
+
assert.equal(core + context + skills, b.systemPrompt.total);
|
|
288
|
+
// The buffer is a fixed reserve — estimation drift must never inflate it.
|
|
289
|
+
assert.equal(b.categories.find((c) => c.label === "Autocompact buffer")?.tokens, 16384);
|
|
290
|
+
// Whatever the drift sign, the slices always add up to the whole window.
|
|
291
|
+
assert.equal(b.categories.reduce((a, c) => a + c.tokens, 0), b.contextWindow);
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
test("Messages is a residual so no row exceeds the headline total", () => {
|
|
295
|
+
// Authoritative total far above the prompt-side estimates → the difference is
|
|
296
|
+
// real transcript weight and lands on Messages (the residual row).
|
|
297
|
+
const high = computeContextBreakdown(fixtureInput({ ctx: fixtureCtx({ getContextUsage: () => ({ tokens: 60000, contextWindow: 200000, percent: 30 }) }) }));
|
|
298
|
+
const msgsHigh = high.categories.find((c) => c.label === "Messages")!.tokens;
|
|
299
|
+
assert.ok(msgsHigh > 0, "residual messages weight is reported");
|
|
300
|
+
assert.ok(high.categories.every((c) => c.tokens <= high.contextWindow), "no row exceeds the window");
|
|
301
|
+
assert.ok(high.usedTokens! >= msgsHigh, "Messages never exceeds the measured total");
|
|
302
|
+
assert.equal(high.categories.reduce((a, c) => a + c.tokens, 0), 200000, "rows partition the window");
|
|
303
|
+
|
|
304
|
+
// Estimates ABOVE the measured total (chars/4 over-counts thinking blocks):
|
|
305
|
+
// the prompt rows stay as measured, Messages floors at 0, no phantom row.
|
|
306
|
+
const low = computeContextBreakdown(fixtureInput({ ctx: fixtureCtx({ getContextUsage: () => ({ tokens: 1000, contextWindow: 200000, percent: 0.5 }) }) }));
|
|
307
|
+
assert.equal(low.categories.find((c) => c.label === "Messages")!.tokens, 0, "residual floors at zero");
|
|
308
|
+
assert.equal(low.categories.reduce((a, c) => a + c.tokens, 0), 200000);
|
|
309
|
+
assert.ok(low.categories.every((c) => c.tokens <= 200000));
|
|
310
|
+
|
|
311
|
+
// A stale figure above the window cannot make the partition over-sum.
|
|
312
|
+
const over = computeContextBreakdown(fixtureInput({ ctx: fixtureCtx({ getContextUsage: () => ({ tokens: 999999, contextWindow: 200000, percent: 500 }) }) }));
|
|
313
|
+
assert.equal(over.categories.reduce((a, c) => a + c.tokens, 0), 200000);
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
test("/context handler posts a transcript message; renderer tints glyphs", async () => {
|
|
317
|
+
const { default: extension } = await import("../index.ts");
|
|
318
|
+
const commands: Record<string, { handler: (args: string, ctx: unknown) => Promise<void> }> = {};
|
|
319
|
+
const renderers: Record<string, (m: unknown, o: unknown, t: unknown) => { render(w: number): string[] } | undefined> = {};
|
|
320
|
+
const sent: Array<{ customType: string; content: string; display?: boolean; details?: { lines?: string[] } }> = [];
|
|
321
|
+
const fakePi = {
|
|
322
|
+
on: () => {},
|
|
323
|
+
registerCommand: (name: string, def: { handler: (args: string, ctx: unknown) => Promise<void> }) => { commands[name] = def; },
|
|
324
|
+
registerTool: () => {},
|
|
325
|
+
registerMessageRenderer: (type: string, renderer: never) => { renderers[type] = renderer; },
|
|
326
|
+
sendMessage: (msg: { customType: string; content: string; display?: boolean; details?: { lines?: string[] } }) => { sent.push(msg); },
|
|
327
|
+
getAllTools: () => (fixtureCtx() as never as { getAllTools(): unknown[] }).getAllTools(),
|
|
328
|
+
getActiveTools: () => ["read", "web_search"],
|
|
329
|
+
};
|
|
330
|
+
(extension as unknown as (pi: unknown) => void)(fakePi);
|
|
331
|
+
const handler = commands.context?.handler;
|
|
332
|
+
assert.ok(handler, "/context registered");
|
|
333
|
+
assert.ok(renderers["ceulen-usage-context"], "transcript renderer registered");
|
|
334
|
+
|
|
335
|
+
const mkCtx = (mode: string) => ({
|
|
336
|
+
mode,
|
|
337
|
+
model: { maxTokens: 8192, contextWindow: 200000 },
|
|
338
|
+
getContextUsage: () => ({ tokens: 5000, contextWindow: 200000, percent: 2.5 }),
|
|
339
|
+
getSystemPrompt: () => "x".repeat(40000),
|
|
340
|
+
sessionManager: { buildSessionProjection: () => ({ messages: [] }) },
|
|
341
|
+
ui: { notify: () => {}, theme: { fg: (_c: string, s: string) => s } },
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
// TUI: panel posted as a displayable transcript message carrying the lines.
|
|
345
|
+
await handler!("", mkCtx("tui"));
|
|
346
|
+
assert.equal(sent.length, 1);
|
|
347
|
+
assert.equal(sent[0].customType, "ceulen-usage-context");
|
|
348
|
+
assert.equal(sent[0].display, true, "message is displayed in the transcript");
|
|
349
|
+
const lines = sent[0].details?.lines ?? [];
|
|
350
|
+
assert.ok(lines.some((l) => l.startsWith(" ⛁ System prompt:")), lines.join("\n"));
|
|
351
|
+
assert.ok(lines.some((l) => l.startsWith(" ⛶ Free space:")));
|
|
352
|
+
|
|
353
|
+
// Renderer: colors the glyph, keeps the body plain, and clamps to width.
|
|
354
|
+
const comp = renderers["ceulen-usage-context"]!({ details: { lines: [" ⛁ System prompt: 1K tokens (1.0%)"] } }, {}, { fg: (c: string, s: string) => `<${c}>${s}</>` });
|
|
355
|
+
const out = comp!.render(200);
|
|
356
|
+
assert.ok(out[0].includes("<accent>⛁</>"), out[0]);
|
|
357
|
+
assert.ok(out[0].includes("System prompt: 1K tokens"), out[0]);
|
|
358
|
+
// Width clamp applies to the source line (before ANSI codes are added).
|
|
359
|
+
const narrow = comp!.render(10);
|
|
360
|
+
assert.ok(narrow[0].includes("⛁"), "glyph survives the clamp");
|
|
361
|
+
assert.ok(!narrow[0].includes("System prompt"), "body beyond the width is dropped");
|
|
362
|
+
|
|
363
|
+
// Plain-text content always rides along as the renderer-less fallback.
|
|
364
|
+
assert.ok(sent[0].content.includes("Context Usage"), "content carries a plain-text fallback");
|
|
365
|
+
assert.ok(sent[0].content.includes("⛁ System prompt:"), sent[0].content);
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
test("categories are disjoint, reconcile with usage, and partition the window", () => {
|
|
369
|
+
const b = computeContextBreakdown(fixtureInput());
|
|
370
|
+
const core = b.categories.find((c) => c.label === "System prompt")!.tokens;
|
|
371
|
+
const context = b.categories.find((c) => c.label === "System context")!.tokens;
|
|
372
|
+
const skills = b.categories.find((c) => c.label === "Skills")!.tokens;
|
|
373
|
+
// No double-counting: core + context + skills reconstruct the system prompt.
|
|
374
|
+
assert.equal(core + context + skills, b.systemPrompt.total);
|
|
375
|
+
// The buffer is a fixed reserve — estimation drift must never inflate it.
|
|
376
|
+
assert.equal(b.categories.find((c) => c.label === "Autocompact buffer")?.tokens, 16384);
|
|
377
|
+
// Whatever the drift sign, the slices always add up to the whole window.
|
|
378
|
+
assert.equal(b.categories.reduce((a, c) => a + c.tokens, 0), b.contextWindow);
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
test("shortSource reduces local paths and scoped specs to a short label", () => {
|
|
382
|
+
assert.equal(shortSource("../../../../Volumes/Dev/agents/pi-extensions/pi-web"), "pi-web");
|
|
383
|
+
assert.equal(shortSource("@bacnh85/pi-web"), "pi-web");
|
|
384
|
+
assert.equal(shortSource("pi"), "pi");
|
|
385
|
+
assert.equal(shortSource("builtin"), "builtin");
|
|
386
|
+
assert.equal(shortSource(""), "");
|
|
387
|
+
});
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { accountFromPiAuth, REFRESH_INTERVAL_MS } from "../index.ts";
|
|
7
|
+
import { loadCwdEnvFilesIfTrusted } from "../../../lib/env.ts";
|
|
8
|
+
|
|
9
|
+
const tmpdir = () => fs.mkdtempSync(path.join(os.tmpdir(), "ceulen-usage-env-"));
|
|
10
|
+
|
|
11
|
+
function makeCtx(trusted: boolean) {
|
|
12
|
+
return { isProjectTrusted: () => trusted };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// ── loadCwdEnvFilesIfTrusted — cwd .env only for trusted projects ───────────
|
|
16
|
+
|
|
17
|
+
test("cwd .env is NOT ingested when project is untrusted", () => {
|
|
18
|
+
const dir = tmpdir();
|
|
19
|
+
fs.writeFileSync(path.join(dir, ".env"), "PI_SUB_PROBE_UNTRUSTED=1\n");
|
|
20
|
+
const cwd = process.cwd();
|
|
21
|
+
process.chdir(dir);
|
|
22
|
+
try {
|
|
23
|
+
loadCwdEnvFilesIfTrusted(makeCtx(false));
|
|
24
|
+
assert.equal(process.env.PI_SUB_PROBE_UNTRUSTED, undefined);
|
|
25
|
+
} finally {
|
|
26
|
+
process.chdir(cwd);
|
|
27
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
// Idempotence folded in: module-level one-shot state persists across tests in
|
|
32
|
+
// this file, so the first trusted load must be the one that proves all three:
|
|
33
|
+
// ingestion, real-env protection, and one-shot no-op on a second call.
|
|
34
|
+
test("cwd .env IS ingested when trusted, exactly once; real env wins over it", () => {
|
|
35
|
+
const dir = tmpdir();
|
|
36
|
+
fs.writeFileSync(path.join(dir, ".env"), "PI_SUB_PROBE_TRUSTED=from-file\nPI_SUB_PROBE_REAL=from-file\n");
|
|
37
|
+
const cwd = process.cwd();
|
|
38
|
+
process.chdir(dir);
|
|
39
|
+
delete process.env.PI_SUB_PROBE_TRUSTED;
|
|
40
|
+
// Real shell environment — a trusted repo's .env must never clobber it.
|
|
41
|
+
process.env.PI_SUB_PROBE_REAL = "from-shell";
|
|
42
|
+
try {
|
|
43
|
+
loadCwdEnvFilesIfTrusted(makeCtx(true));
|
|
44
|
+
assert.equal(process.env.PI_SUB_PROBE_TRUSTED, "from-file");
|
|
45
|
+
assert.equal(process.env.PI_SUB_PROBE_REAL, "from-shell");
|
|
46
|
+
// Second call must be a no-op even though the file changed underneath.
|
|
47
|
+
fs.writeFileSync(path.join(dir, ".env"), "PI_SUB_PROBE_LATE=2\n");
|
|
48
|
+
loadCwdEnvFilesIfTrusted(makeCtx(true));
|
|
49
|
+
assert.equal(process.env.PI_SUB_PROBE_LATE, undefined);
|
|
50
|
+
} finally {
|
|
51
|
+
delete process.env.PI_SUB_PROBE_TRUSTED;
|
|
52
|
+
delete process.env.PI_SUB_PROBE_REAL;
|
|
53
|
+
delete process.env.PI_SUB_PROBE_LATE;
|
|
54
|
+
process.chdir(cwd);
|
|
55
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
// The global-vs-cwd precedence branch needs a module instance whose import-time
|
|
60
|
+
// global pass ran against a controlled PI_CODING_AGENT_DIR — hence a fresh
|
|
61
|
+
// query-string import (new module record, new one-shot state).
|
|
62
|
+
test("trusted cwd .env overrides a key injected by the global agent-dir pass (cwd-first)", async () => {
|
|
63
|
+
const globalDir = tmpdir();
|
|
64
|
+
const cwdDir = tmpdir();
|
|
65
|
+
fs.writeFileSync(path.join(globalDir, ".env"), "PI_SUB_PROBE_GLOBAL=from-global\n");
|
|
66
|
+
fs.writeFileSync(path.join(cwdDir, ".env"), "PI_SUB_PROBE_GLOBAL=from-cwd\n");
|
|
67
|
+
const prevAgentDir = process.env.PI_CODING_AGENT_DIR;
|
|
68
|
+
const cwd = process.cwd();
|
|
69
|
+
process.env.PI_CODING_AGENT_DIR = globalDir;
|
|
70
|
+
delete process.env.PI_SUB_PROBE_GLOBAL;
|
|
71
|
+
process.chdir(cwdDir);
|
|
72
|
+
try {
|
|
73
|
+
const fresh = await import(`../../../lib/env.ts?probe-global-${Date.now()}`);
|
|
74
|
+
assert.equal(process.env.PI_SUB_PROBE_GLOBAL, "from-global"); // import-time global pass ran
|
|
75
|
+
fresh.loadCwdEnvFilesIfTrusted(makeCtx(true));
|
|
76
|
+
assert.equal(process.env.PI_SUB_PROBE_GLOBAL, "from-cwd"); // trusted cwd file overrides the global-file value
|
|
77
|
+
} finally {
|
|
78
|
+
if (prevAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
79
|
+
else process.env.PI_CODING_AGENT_DIR = prevAgentDir;
|
|
80
|
+
delete process.env.PI_SUB_PROBE_GLOBAL;
|
|
81
|
+
process.chdir(cwd);
|
|
82
|
+
fs.rmSync(globalDir, { recursive: true, force: true });
|
|
83
|
+
fs.rmSync(cwdDir, { recursive: true, force: true });
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
// ── Expired Codex access token → plan renders "expired" ─────────────────────
|
|
88
|
+
|
|
89
|
+
function b64urlJwt(payload: object): string {
|
|
90
|
+
return `h.${Buffer.from(JSON.stringify(payload)).toString("base64url")}.s`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
test("expired Codex access token → plan is 'expired', not the stale plan label", () => {
|
|
94
|
+
const account = accountFromPiAuth({
|
|
95
|
+
type: "oauth",
|
|
96
|
+
access: b64urlJwt({
|
|
97
|
+
exp: Math.floor(Date.now() / 1000) - 10,
|
|
98
|
+
"https://api.openai.com/auth": { chatgpt_plan_type: "plus" },
|
|
99
|
+
}),
|
|
100
|
+
});
|
|
101
|
+
assert.equal(account.plan, "expired");
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test("valid Codex access token keeps the real plan label", () => {
|
|
105
|
+
const account = accountFromPiAuth({
|
|
106
|
+
type: "oauth",
|
|
107
|
+
access: b64urlJwt({
|
|
108
|
+
exp: Math.floor(Date.now() / 1000) + 3600,
|
|
109
|
+
"https://api.openai.com/auth": { chatgpt_plan_type: "plus" },
|
|
110
|
+
}),
|
|
111
|
+
});
|
|
112
|
+
assert.equal(account.plan, "Plus");
|
|
113
|
+
});
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { after, before, test } from "node:test";
|
|
6
|
+
import { fetchOpenCodeGoUsage, opcWindowToUsageWindow } from "../index.ts";
|
|
7
|
+
|
|
8
|
+
const AUTH_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "ceulen-usage-opc-test-"));
|
|
9
|
+
const AUTH_PATH = path.join(AUTH_DIR, "auth.json");
|
|
10
|
+
const AUTH_ENV = process.env.PI_CODING_AGENT_DIR;
|
|
11
|
+
|
|
12
|
+
before(() => {
|
|
13
|
+
process.env.PI_CODING_AGENT_DIR = AUTH_DIR;
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
after(() => {
|
|
17
|
+
if (AUTH_ENV === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
18
|
+
else process.env.PI_CODING_AGENT_DIR = AUTH_ENV;
|
|
19
|
+
fs.rmSync(AUTH_DIR, { recursive: true, force: true });
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
const REAL_FETCH = globalThis.fetch;
|
|
23
|
+
function mockFetch(responder: (url: string, init?: RequestInit) => Response | Promise<Response>) {
|
|
24
|
+
globalThis.fetch = ((url: string | URL, init?: RequestInit) => responder(String(url), init)) as typeof fetch;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function writeAuth(entry: unknown): void {
|
|
28
|
+
fs.writeFileSync(AUTH_PATH, JSON.stringify({ "opencode-go": entry }));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const LIVE_BODY = {
|
|
32
|
+
usage: {
|
|
33
|
+
rolling: { status: "ok", percent: 1, resetsAt: "2026-09-13T10:42:47.510Z" },
|
|
34
|
+
weekly: { status: "ok", percent: 39, resetsAt: "2026-09-14T00:00:00.510Z" },
|
|
35
|
+
monthly: { status: "ok", percent: 80, resetsAt: "2026-09-26T09:38:03.000Z" },
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// Live shape verified 2026-09-21 via GET /zen/go/v1/usage (paseo #4779,
|
|
40
|
+
// opencode-bar PR #154): percent = used 0-100, resetsAt = ISO 8601.
|
|
41
|
+
test("opc window parser maps the live response shape", () => {
|
|
42
|
+
const w = opcWindowToUsageWindow({ status: "ok", percent: 39, resetsAt: "2026-09-14T00:00:00.510Z" });
|
|
43
|
+
assert.ok(w);
|
|
44
|
+
assert.equal(w.percent, 39);
|
|
45
|
+
assert.equal(w.remaining, 61);
|
|
46
|
+
assert.equal(typeof w.resetLabel, "string");
|
|
47
|
+
assert.ok((w.resetLabel ?? "").length > 0);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test("opc parser clamps remaining to 0-100 on out-of-range percent", () => {
|
|
51
|
+
// Undocumented API: percent is not guaranteed in 0-100.
|
|
52
|
+
assert.equal(opcWindowToUsageWindow({ percent: 100 })?.remaining, 0);
|
|
53
|
+
assert.equal(opcWindowToUsageWindow({ percent: -5 })?.remaining, 100);
|
|
54
|
+
assert.equal(opcWindowToUsageWindow({ percent: 150 })?.remaining, 0);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test("opc parser skips windows with no numeric percent", () => {
|
|
58
|
+
assert.equal(opcWindowToUsageWindow(undefined), undefined);
|
|
59
|
+
assert.equal(opcWindowToUsageWindow({ status: "limited" }), undefined);
|
|
60
|
+
assert.equal(opcWindowToUsageWindow({ percent: "39" as unknown as number }), undefined);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
function assertAuthOnly(snapshot: Awaited<ReturnType<typeof fetchOpenCodeGoUsage>>) {
|
|
64
|
+
assert.equal(snapshot.error, undefined);
|
|
65
|
+
const account = snapshot.activeAccount;
|
|
66
|
+
assert.ok(account);
|
|
67
|
+
assert.ok(account.accountLabel);
|
|
68
|
+
assert.equal(account.fiveHour, undefined);
|
|
69
|
+
assert.equal(account.weekly, undefined);
|
|
70
|
+
assert.equal(account.monthly, undefined);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
test("fetch maps the live response to rolling/weekly/monthly windows", async () => {
|
|
74
|
+
writeAuth({ type: "api", key: "sk-test" });
|
|
75
|
+
let authHeader: string | undefined;
|
|
76
|
+
mockFetch((_url, init) => {
|
|
77
|
+
authHeader = (init?.headers as Record<string, string>)?.Authorization;
|
|
78
|
+
return new Response(JSON.stringify(LIVE_BODY), { status: 200 });
|
|
79
|
+
});
|
|
80
|
+
try {
|
|
81
|
+
const snapshot = await fetchOpenCodeGoUsage();
|
|
82
|
+
assert.equal(authHeader, "Bearer sk-test");
|
|
83
|
+
assert.equal(snapshot.error, undefined);
|
|
84
|
+
assert.equal(snapshot.activeAccount?.fiveHour?.remaining, 99);
|
|
85
|
+
assert.equal(snapshot.activeAccount?.weekly?.remaining, 61);
|
|
86
|
+
assert.equal(snapshot.activeAccount?.monthly?.remaining, 20);
|
|
87
|
+
} finally {
|
|
88
|
+
globalThis.fetch = REAL_FETCH;
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test("keyless accountId-only auth keeps the auth-only snapshot (session cost path)", async () => {
|
|
93
|
+
writeAuth({ type: "api", accountId: "acc-123" });
|
|
94
|
+
try {
|
|
95
|
+
const snapshot = await fetchOpenCodeGoUsage();
|
|
96
|
+
assertAuthOnly(snapshot);
|
|
97
|
+
} finally {
|
|
98
|
+
globalThis.fetch = REAL_FETCH;
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test("fetch failure falls back to auth-only snapshot instead of an empty error", async () => {
|
|
103
|
+
// Reviewer regression 0.1.46: the error branch renders only
|
|
104
|
+
// "Sub … usage unavailable", dropping the account label, session cost,
|
|
105
|
+
// and tok/s that the 0.1.44 footer always showed.
|
|
106
|
+
writeAuth({ type: "api", key: "sk-test" });
|
|
107
|
+
mockFetch(() => {
|
|
108
|
+
throw new TypeError("fetch failed");
|
|
109
|
+
});
|
|
110
|
+
try {
|
|
111
|
+
const snapshot = await fetchOpenCodeGoUsage();
|
|
112
|
+
assertAuthOnly(snapshot);
|
|
113
|
+
} finally {
|
|
114
|
+
globalThis.fetch = REAL_FETCH;
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test("HTTP 401 falls back to auth-only snapshot (redaction keeps auth details out)", async () => {
|
|
119
|
+
writeAuth({ type: "api", key: "sk-test" });
|
|
120
|
+
mockFetch(() => new Response("unauthorized", { status: 401 }));
|
|
121
|
+
try {
|
|
122
|
+
assertAuthOnly(await fetchOpenCodeGoUsage());
|
|
123
|
+
} finally {
|
|
124
|
+
globalThis.fetch = REAL_FETCH;
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test("all-empty windows error the footer (shape drift signal)", async () => {
|
|
129
|
+
writeAuth({ type: "api", key: "sk-test" });
|
|
130
|
+
mockFetch(() => new Response(JSON.stringify({ usage: {} }), { status: 200 }));
|
|
131
|
+
try {
|
|
132
|
+
const snapshot = await fetchOpenCodeGoUsage();
|
|
133
|
+
assert.ok(snapshot.error);
|
|
134
|
+
assert.match(snapshot.error, /OpenCode Go/);
|
|
135
|
+
assert.equal(snapshot.accounts.length, 0);
|
|
136
|
+
} finally {
|
|
137
|
+
globalThis.fetch = REAL_FETCH;
|
|
138
|
+
}
|
|
139
|
+
});
|