Skip to content

Commit b1c0807

Browse files
fix(companion): timeline cache isolation, other-fold aggregation, ocx companion set/reset
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent c914ea1 commit b1c0807

14 files changed

Lines changed: 170 additions & 31 deletions

File tree

‎scripts/test-layout/layout.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,7 @@
186186
"hub-usage.test.ts": "server",
187187
"client-hub-usage.test.ts": "clients",
188188
"cli-usage-hub.test.ts": "cli",
189+
"cli-companion.test.ts": "cli",
189190
"abort-idle-deadline.test.ts": "lib",
190191
"abort-race.test.ts": "adapters",
191192
"account-import.test.ts": "server",

‎skills/ocx/references/01_management_surface.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,9 @@ Inspect and configure menu-bar and widget companion usage settings.
553553

554554
JSON mode: `payload`.
555555

556+
- `show` (the default) reads settings; `set key=value ...` updates selected settings; `reset` restores defaults.
557+
- Values accepted by `set` are parsed as JSON when valid, so booleans, numbers, arrays, objects, and null can be passed directly.
558+
556559
### `ocx account main reauth`
557560

558561
Reauthenticate the native main Codex login with a device code (#3898); headless hubs need no Codex App or keyring.

‎src/cli/capabilities.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,10 @@ export const CAPABILITIES: readonly Capability[] = [
325325
flags: [{ name: "--json", value: "boolean", summary: "Emit companion settings as JSON." }],
326326
mutates: true,
327327
json: "payload",
328+
details: [
329+
"`show` (the default) reads settings; `set key=value ...` updates selected settings; `reset` restores defaults.",
330+
"Values accepted by `set` are parsed as JSON when valid, so booleans, numbers, arrays, objects, and null can be passed directly.",
331+
],
328332
},
329333
{
330334
command: ["account", "history"],

‎src/cli/companion.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import { CliUsageError, printData, rejectArgs, runCliAction, runtimeRequest, takeFlag, type RuntimeApiDeps } from "./runtime-api";
2+
3+
const USAGE = `Usage:
4+
ocx companion [show] [--json]
5+
ocx companion set <key>=<value> [...] [--json]
6+
ocx companion reset [--json]`;
7+
8+
function parseValue(raw: string): unknown {
9+
if (raw === "null") return null;
10+
try { return JSON.parse(raw); } catch { return raw; }
11+
}
12+
13+
async function show(argv: string[], deps: RuntimeApiDeps): Promise<void> {
14+
const args = [...argv];
15+
const wantsJson = takeFlag(args, "--json");
16+
rejectArgs(args, USAGE);
17+
printData(await runtimeRequest("/api/companion/settings", {}, deps), wantsJson);
18+
}
19+
20+
async function set(argv: string[], deps: RuntimeApiDeps): Promise<void> {
21+
const args = [...argv];
22+
const wantsJson = takeFlag(args, "--json");
23+
if (args.length === 0) throw new CliUsageError("companion set requires key=value assignments", USAGE);
24+
const patch: Record<string, unknown> = {};
25+
for (const assignment of args) {
26+
const separator = assignment.indexOf("=");
27+
if (separator <= 0) throw new CliUsageError(`invalid companion setting "${assignment}"; use key=value`, USAGE);
28+
patch[assignment.slice(0, separator)] = parseValue(assignment.slice(separator + 1));
29+
}
30+
printData(await runtimeRequest("/api/companion/settings", {
31+
method: "PUT",
32+
body: JSON.stringify({ settings: patch }),
33+
}, deps), wantsJson, ["Companion settings saved."]);
34+
}
35+
36+
async function reset(argv: string[], deps: RuntimeApiDeps): Promise<void> {
37+
const args = [...argv];
38+
const wantsJson = takeFlag(args, "--json");
39+
rejectArgs(args, USAGE);
40+
printData(await runtimeRequest("/api/companion/settings", {
41+
method: "PUT",
42+
body: JSON.stringify({ reset: true }),
43+
}, deps), wantsJson, ["Companion settings reset."]);
44+
}
45+
46+
export async function handleCompanionCommand(argv: string[], deps: RuntimeApiDeps = {}): Promise<number> {
47+
return runCliAction(async () => {
48+
const [sub = "show", ...rest] = argv;
49+
if (sub === "show") await show(rest, deps);
50+
else if (sub === "set") await set(rest, deps);
51+
else if (sub === "reset") await reset(rest, deps);
52+
else throw new CliUsageError(`unknown companion command ${sub}`, USAGE);
53+
});
54+
}
55+
56+
export const COMPANION_USAGE = USAGE;

‎src/cli/dispatch.ts‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -783,16 +783,8 @@ const commandRunners: Record<string, CommandRunner> = {
783783
return await handleComboCommand(deps.args.slice(1));
784784
},
785785
companion: async deps => {
786-
const { printData, runtimeRequest, takeFlag } = await import("./runtime-api");
787-
const args = deps.args.slice(1);
788-
const wantsJson = takeFlag(args, "--json");
789-
if (args.length) {
790-
console.error("Usage: ocx companion [--json]");
791-
return 64;
792-
}
793-
const payload = await runtimeRequest("/api/companion/settings");
794-
printData(payload, wantsJson);
795-
return 0;
786+
const { handleCompanionCommand } = await import("./companion");
787+
return await handleCompanionCommand(deps.args.slice(1));
796788
},
797789
route: async deps => {
798790
if (deps.args[1] !== "combo" && deps.args[1] !== "policy") {

‎src/cli/registry.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -300,8 +300,13 @@ export const CLI_COMMANDS: CliCommandEntry[] = [
300300
},
301301
{
302302
name: "companion",
303-
usage: "ocx companion [--json]",
304-
summary: "Inspect menu-bar and widget companion usage settings.",
303+
usage: "ocx companion <show|set|reset> ...",
304+
summary: "Inspect and configure menu-bar and widget companion usage settings.",
305+
details: [
306+
"ocx companion and ocx companion show read settings; use --json for machine-readable output.",
307+
"ocx companion set accepts one or more key=value assignments; values are parsed as JSON when possible.",
308+
"ocx companion reset restores the default settings.",
309+
],
305310
},
306311
{
307312
name: "combo",

‎src/companion/settings.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -106,16 +106,16 @@ export function applyCompanionSettingsPatch(
106106
return { ...current, ...values } as CompanionSettings;
107107
}
108108

109-
export function loadCompanionSettings(): { settings: CompanionSettings; updatedAt: number | null } {
109+
export function loadCompanionSettings(): { settings: CompanionSettings; updatedAt: number | null; corrupt?: true } {
110110
const path = companionSettingsPath();
111111
if (!existsSync(path)) return { settings: { ...DEFAULT_COMPANION_SETTINGS }, updatedAt: null };
112112
try {
113113
const parsed = JSON.parse(readFileSync(path, "utf8")) as unknown;
114114
const settings = applyCompanionSettingsPatch(DEFAULT_COMPANION_SETTINGS, parsed);
115-
if ("error" in settings) return { settings: { ...DEFAULT_COMPANION_SETTINGS }, updatedAt: null };
115+
if ("error" in settings) return { settings: { ...DEFAULT_COMPANION_SETTINGS }, updatedAt: null, corrupt: true };
116116
return { settings, updatedAt: statSync(path).mtimeMs };
117117
} catch {
118-
return { settings: { ...DEFAULT_COMPANION_SETTINGS }, updatedAt: null };
118+
return { settings: { ...DEFAULT_COMPANION_SETTINGS }, updatedAt: null, corrupt: true };
119119
}
120120
}
121121

‎src/server/management/companion-routes.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,12 @@ import type { ManagementContext } from "./context";
1010

1111
function response(): Response {
1212
const loaded = loadCompanionSettings();
13-
return jsonResponse({ settings: loaded.settings, updatedAt: loaded.updatedAt, defaults: DEFAULT_COMPANION_SETTINGS });
13+
return jsonResponse({
14+
settings: loaded.settings,
15+
updatedAt: loaded.updatedAt,
16+
defaults: DEFAULT_COMPANION_SETTINGS,
17+
...(loaded.corrupt ? { corrupt: true } : {}),
18+
});
1419
}
1520

1621
export async function handleCompanionRoutes(ctx: ManagementContext): Promise<Response | null> {

‎src/server/management/usage-timeline-routes.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,15 @@ export async function handleUsageTimelineRoutes(ctx: ManagementContext): Promise
1313
if ("error" in query) return jsonResponse(query, 400, req, ctx.config);
1414
const bucketMs = query.bucketMinutes * 60_000;
1515
const roundedNow = Math.floor(query.now / bucketMs) * bucketMs;
16-
const key = JSON.stringify({ ...query, now: roundedNow });
16+
const normalized = { ...query, now: roundedNow };
17+
const key = JSON.stringify(normalized);
1718
const current = Date.now();
1819
const cached = cache.get(key);
1920
if (cached && cached.expiresAt > current) return jsonResponse(await cached.promise, 200, req, ctx.config);
2021
let promise: Promise<ReturnType<ReturnType<typeof createTimelineAccumulator>["finish"]>>;
2122
promise = (async () => {
22-
const accumulator = createTimelineAccumulator(query);
23+
const accumulator = createTimelineAccumulator(normalized);
2324
const snapshot = await readUsageSnapshotForManagement(ctx.config.managementUsageMaxReadBytes);
24-
if (req.signal.aborted) throw req.signal.reason ?? new Error("usage timeline request aborted");
2525
for (const entry of snapshot.entries) accumulator.add(entry);
2626
return {
2727
...accumulator.finish(),

‎src/usage/timeline.ts‎

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ export function createTimelineAccumulator(query: TimelineQuery): { add(entry: Pe
158158
}
159159

160160
function finish(): UsageTimeline {
161-
const rows = [...series].map(([id, state]): TimelineSeries => {
161+
const rows = [...series].map(([id, state]): { row: TimelineSeries; state: SeriesState } => {
162162
if (query.aggregation !== "sum") {
163163
for (const [bucket, requests] of state.requests) {
164164
const values = [...requests.values()];
@@ -169,19 +169,34 @@ export function createTimelineAccumulator(query: TimelineQuery): { add(entry: Pe
169169
}
170170
const total = state.points.reduce((sum, value) => sum + value, 0);
171171
return {
172-
id,
173-
provider: state.provider,
174-
model: state.model,
175-
...(state.accountLogLabel !== undefined ? { accountLogLabel: state.accountLogLabel } : {}),
176-
total,
177-
points: state.points,
172+
row: {
173+
id,
174+
provider: state.provider,
175+
model: state.model,
176+
...(state.accountLogLabel !== undefined ? { accountLogLabel: state.accountLogLabel } : {}),
177+
total,
178+
points: state.points,
179+
},
180+
state,
178181
};
179-
}).sort((left, right) => right.total - left.total || left.id.localeCompare(right.id));
180-
const kept = rows.length > 24 ? rows.slice(0, 23) : rows;
182+
}).sort((left, right) => right.row.total - left.row.total || left.row.id.localeCompare(right.row.id));
183+
const kept = (rows.length > 24 ? rows.slice(0, 23) : rows).map(({ row }) => row);
181184
if (rows.length > 24) {
182185
const otherPoints = Array<number>(buckets).fill(0);
183-
for (const row of rows.slice(23)) {
184-
for (let index = 0; index < buckets; index += 1) otherPoints[index] = (otherPoints[index] ?? 0) + (row.points[index] ?? 0);
186+
const folded = rows.slice(23);
187+
if (query.aggregation === "sum") {
188+
for (const { row } of folded) {
189+
for (let index = 0; index < buckets; index += 1) otherPoints[index] = (otherPoints[index] ?? 0) + (row.points[index] ?? 0);
190+
}
191+
} else {
192+
for (let index = 0; index < buckets; index += 1) {
193+
const values = folded.flatMap(({ state }) => [...(state.requests.get(index)?.values() ?? [])]);
194+
if (values.length > 0) {
195+
otherPoints[index] = query.aggregation === "max"
196+
? Math.max(...values)
197+
: values.reduce((sum, value) => sum + value, 0) / values.length;
198+
}
199+
}
185200
}
186201
kept.push({ id: "other", provider: "", model: "other", total: otherPoints.reduce((sum, value) => sum + value, 0), points: otherPoints });
187202
}

0 commit comments

Comments
 (0)