Skip to content

Commit 77e770e

Browse files
committed
merge: surface execute-threshold clamp in status surfaces (#241)
2 parents 749eabd + c18cb62 commit 77e770e

12 files changed

Lines changed: 222 additions & 22 deletions

File tree

‎packages/pi-plugin/src/dialogs/status-dialog.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,12 @@ import { getOrCreateSessionMeta } from "@magic-context/core/features/magic-conte
1717
import { getSessionWorkMetrics } from "@magic-context/core/features/magic-context/storage-meta-persisted";
1818
import { getNotes } from "@magic-context/core/features/magic-context/storage-notes";
1919
import { getTagsBySession } from "@magic-context/core/features/magic-context/storage-tags";
20-
import { resolveExecuteThresholdDetail } from "@magic-context/core/hooks/magic-context/event-resolvers";
20+
import { MAX_EXECUTE_THRESHOLD, resolveExecuteThresholdDetail } from "@magic-context/core/hooks/magic-context/event-resolvers";
2121
import { formatBytes } from "@magic-context/core/hooks/magic-context/format-bytes";
2222
import { computeM0BlockTokens } from "@magic-context/core/hooks/magic-context/m0-token-breakdown";
2323
import { estimateTokens } from "@magic-context/core/hooks/magic-context/read-session-formatting";
2424
import { countCompartmentsNeedingUpgrade } from "@magic-context/core/hooks/magic-context/upgrade-reminder";
25-
import { formatThresholdPercent } from "@magic-context/core/shared/format-threshold";
25+
import { formatThresholdClampNote, formatThresholdPercent } from "@magic-context/core/shared/format-threshold";
2626

2727
import packageJson from "../../package.json";
2828
import { resolveSessionId } from "../commands/pi-command-utils";
@@ -84,6 +84,12 @@ interface StatusDialogDetail {
8484
isSubagent: boolean;
8585
contextLimit: number;
8686
executeThreshold: number;
87+
/** Which config source produced `executeThreshold` (tokens vs percentage). */
88+
executeThresholdMode: "percentage" | "tokens";
89+
/** True when `executeThreshold` was clamped down from a higher configured value (#241). */
90+
executeThresholdClamped?: boolean;
91+
/** Raw configured value before clamping, for showing the math in the clamp note. */
92+
executeThresholdConfigured?: number;
8793
protectedTagCount: number;
8894
historyBlockTokens: number;
8995
compressionBudget: number | null;
@@ -324,7 +330,13 @@ function renderInner(
324330
// Context / thresholds
325331
lines.push(theme.fg("muted", "Context"));
326332
lines.push(
327-
`Execute threshold ${formatThresholdPercent(s.executeThreshold)}%`,
333+
`Execute threshold ${formatThresholdPercent(s.executeThreshold)}%${formatThresholdClampNote({
334+
clamped: s.executeThresholdClamped,
335+
mode: s.executeThresholdMode,
336+
configuredValue: s.executeThresholdConfigured,
337+
contextLimit: s.contextLimit,
338+
maxPercentage: MAX_EXECUTE_THRESHOLD,
339+
})}`,
328340
);
329341
lines.push(
330342
`Protected tags ${s.protectedTagCount} · Subagent ${s.isSubagent ? "yes" : "no"} · History block ~${fmt(s.historyBlockTokens)} tok${
@@ -563,6 +575,9 @@ export function buildPiStatusDetail(
563575
isSubagent: meta.isSubagent,
564576
contextLimit,
565577
executeThreshold: threshold.percentage,
578+
executeThresholdMode: threshold.mode,
579+
executeThresholdClamped: threshold.clamped,
580+
executeThresholdConfigured: threshold.configuredValue,
566581
protectedTagCount: deps.protectedTags ?? 20,
567582
historyBlockTokens,
568583
compressionBudget,

‎packages/plugin/src/hooks/magic-context/event-resolvers.test.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,58 @@ describe("event-resolvers", () => {
511511
expect(a).toEqual(b);
512512
expect(b).toEqual(c);
513513
});
514+
515+
it("sets clamped + configuredValue when a tokens config is reduced to the cap (#241)", () => {
516+
//#when — 190K requested on a 128K model → cap is 80% × 128K = 102.4K
517+
const detail = resolveExecuteThresholdDetail(65, "some/model", 65, {
518+
tokensConfig: { "some/model": 190_000 },
519+
contextLimit: 128_000,
520+
sessionId: "ses-test-clamped-flag-tokens",
521+
});
522+
523+
//#then — clamp surfaced with the original value so displays can show the math
524+
expect(detail.mode).toBe("tokens");
525+
expect(detail.clamped).toBe(true);
526+
expect(detail.configuredValue).toBe(190_000);
527+
expect(detail.absoluteTokens).toBe(102_400);
528+
expect(detail.percentage).toBe(80);
529+
});
530+
531+
it("leaves clamped unset when a tokens config fits under the cap (#241)", () => {
532+
//#when — 100K on a 200K model = 50%, well under the 80% cap
533+
const detail = resolveExecuteThresholdDetail(65, "some/model", 65, {
534+
tokensConfig: { "some/model": 100_000 },
535+
contextLimit: 200_000,
536+
});
537+
538+
//#then — no clamp occurred, no clamp metadata attached
539+
expect(detail.mode).toBe("tokens");
540+
expect(detail.clamped).toBeUndefined();
541+
expect(detail.configuredValue).toBeUndefined();
542+
expect(detail.absoluteTokens).toBe(100_000);
543+
});
544+
545+
it("sets clamped + configuredValue when a percentage config is capped at 80 (#241)", () => {
546+
//#when — a runtime-derived percentage above the 80% cap
547+
const detail = resolveExecuteThresholdDetail(95, "some/model", 65);
548+
549+
//#then — capped to 80, original 95 surfaced for display
550+
expect(detail.mode).toBe("percentage");
551+
expect(detail.clamped).toBe(true);
552+
expect(detail.configuredValue).toBe(95);
553+
expect(detail.percentage).toBe(80);
554+
});
555+
556+
it("leaves clamped unset for an in-range percentage config (#241)", () => {
557+
//#when
558+
const detail = resolveExecuteThresholdDetail(65, "some/model", 65);
559+
560+
//#then
561+
expect(detail.mode).toBe("percentage");
562+
expect(detail.clamped).toBeUndefined();
563+
expect(detail.configuredValue).toBeUndefined();
564+
expect(detail.percentage).toBe(65);
565+
});
514566
});
515567

516568
describe("resolveModelKey", () => {

‎packages/plugin/src/hooks/magic-context/event-resolvers.ts‎

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { log, sessionLog } from "../../shared/logger";
77
import { getSdkContextLimit, isSaneLimit } from "../../shared/models-dev-cache";
88

99
export const DEFAULT_CONTEXT_LIMIT = 128_000;
10-
const MAX_EXECUTE_THRESHOLD = 80;
10+
export const MAX_EXECUTE_THRESHOLD = 80;
1111

1212
type CacheTtlConfig = string | Record<string, string>;
1313

@@ -169,6 +169,20 @@ export interface ExecuteThresholdDetail {
169169
absoluteTokens?: number;
170170
/** The config key that matched, if any (for display/debugging). `"default"` when default fallback. */
171171
matchedKey?: string;
172+
/**
173+
* True when the user's configured value exceeded the safe cap and was reduced.
174+
* Tokens mode: configured tokens > 80% × contextLimit. Percentage mode:
175+
* configured percentage > MAX_EXECUTE_THRESHOLD (80). Display surfaces read this
176+
* to tell the user their value was clamped instead of silently ignoring it (#241).
177+
* Only present (true) when a clamp actually happened; absent otherwise.
178+
*/
179+
clamped?: boolean;
180+
/**
181+
* The raw configured value before clamping — a token count in tokens mode, a
182+
* percentage in percentage mode. Populated only alongside `clamped` so display
183+
* surfaces can show the math (e.g. "190,000 > 80% of 128,000").
184+
*/
185+
configuredValue?: number;
172186
}
173187

174188
// Module-level dedupe for clamp warnings. Key: `${sessionId}|${modelKey}|${tokenVal}|${cap}`.
@@ -257,12 +271,20 @@ export function resolveExecuteThresholdDetail(
257271
}
258272
}
259273
const percentage = (effectiveTokens / contextLimit) * 100;
260-
return {
274+
const detail: ExecuteThresholdDetail = {
261275
percentage: Math.min(percentage, MAX_EXECUTE_THRESHOLD),
262276
mode: "tokens",
263277
absoluteTokens: Math.floor(effectiveTokens),
264278
matchedKey: tokenMatch.matchedKey,
265279
};
280+
// effectiveTokens < requested means Math.min(value, cap) clamped the
281+
// user's token budget down to 80% × contextLimit. Record the original
282+
// value so status surfaces can show "190000 > 80% of 128000" (#241).
283+
if (effectiveTokens < tokenMatch.value) {
284+
detail.clamped = true;
285+
detail.configuredValue = tokenMatch.value;
286+
}
287+
return detail;
266288
}
267289
}
268290

@@ -305,7 +327,8 @@ export function resolveExecuteThresholdDetail(
305327
// load normally rejects >80 via zod, but a runtime-derived value can still
306328
// exceed it, so we clamp + warn here too.)
307329
const cappedPercentage = Math.min(resolved, MAX_EXECUTE_THRESHOLD);
308-
if (cappedPercentage < resolved) {
330+
const percentageClamped = cappedPercentage < resolved;
331+
if (percentageClamped) {
309332
const dedupeKey = `pct|${options?.sessionId ?? "__global__"}|${modelKey ?? "__default__"}|${resolved}`;
310333
if (!clampWarnSeen.has(dedupeKey)) {
311334
clampWarnSeen.add(dedupeKey);
@@ -317,11 +340,18 @@ export function resolveExecuteThresholdDetail(
317340
}
318341
}
319342
}
320-
return {
343+
const detail: ExecuteThresholdDetail = {
321344
percentage: cappedPercentage,
322345
mode: "percentage",
323346
matchedKey,
324347
};
348+
// A runtime-derived percentage above the 80% cap was reduced. Record the
349+
// original so status surfaces can show "95% > 80%" alongside the value (#241).
350+
if (percentageClamped) {
351+
detail.clamped = true;
352+
detail.configuredValue = resolved;
353+
}
354+
return detail;
325355
}
326356

327357
/**

‎packages/plugin/src/hooks/magic-context/execute-status.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,51 @@ describe("executeStatus", () => {
2222
expect(status).toContain(`- History block: ~${expected.toLocaleString()} tokens`);
2323
db.close();
2424
});
25+
26+
test("annotates the execute threshold when a tokens config is clamped (#241)", () => {
27+
const db = new Database(":memory:");
28+
initializeDatabase(db);
29+
getOrCreateSessionMeta(db, SESSION_ID);
30+
31+
// 190K requested on a 128K model → clamped to 80% × 128K. The status must
32+
// say so explicitly (configured value + cap) rather than silently showing
33+
// the reduced value, which is what confused users in issue #241.
34+
const status = executeStatus(
35+
db,
36+
SESSION_ID,
37+
20,
38+
65,
39+
"some/model",
40+
undefined,
41+
undefined,
42+
{ "some/model": 190_000 },
43+
128_000,
44+
);
45+
46+
expect(status).toContain("[token-mode] [clamped:");
47+
expect(status).toContain("> 80% of");
48+
db.close();
49+
});
50+
51+
test("omits the clamp annotation when the threshold is not clamped (#241)", () => {
52+
const db = new Database(":memory:");
53+
initializeDatabase(db);
54+
getOrCreateSessionMeta(db, SESSION_ID);
55+
56+
const status = executeStatus(
57+
db,
58+
SESSION_ID,
59+
20,
60+
65,
61+
"some/model",
62+
undefined,
63+
undefined,
64+
undefined,
65+
128_000,
66+
);
67+
68+
expect(status).toContain("Execute threshold:");
69+
expect(status).not.toContain("[clamped:");
70+
db.close();
71+
});
2572
});

‎packages/plugin/src/hooks/magic-context/execute-status.ts‎

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,30 +5,45 @@ import { getPendingOps } from "../../features/magic-context/storage";
55
import { getOrCreateSessionMeta } from "../../features/magic-context/storage-meta";
66
import { getTagsBySession } from "../../features/magic-context/storage-tags";
77
import { getErrorMessage } from "../../shared/error-message";
8+
import { formatThresholdClampNote } from "../../shared/format-threshold";
89
import { sessionLog } from "../../shared/logger";
910
import type { Database } from "../../shared/sqlite";
1011
import {
1112
getProactiveCompartmentTriggerPercentage,
1213
POST_DROP_TARGET_RATIO,
1314
} from "./compartment-trigger";
14-
import { resolveExecuteThresholdDetail } from "./event-resolvers";
15+
import {
16+
MAX_EXECUTE_THRESHOLD,
17+
resolveExecuteThresholdDetail,
18+
type ExecuteThresholdDetail,
19+
} from "./event-resolvers";
1520
import { formatBytes } from "./format-bytes";
1621
import { estimateTokens } from "./read-session-formatting";
1722

1823
function formatExecuteThreshold(
19-
thresholdPercentage: number,
20-
mode: "tokens" | "percentage",
24+
detail: ExecuteThresholdDetail,
2125
contextLimit: number,
2226
): string {
27+
const { percentage, mode } = detail;
28+
// Surfaces the silent clamp from issue #241: when the configured value exceeded
29+
// the 80% safety cap, append a note showing the configured value and the cap so
30+
// the user sees the math (e.g. "190,000 > 80% of 128,000"). "" when not clamped.
31+
const clampNote = formatThresholdClampNote({
32+
clamped: detail.clamped,
33+
mode,
34+
configuredValue: detail.configuredValue,
35+
contextLimit,
36+
maxPercentage: MAX_EXECUTE_THRESHOLD,
37+
});
2338
if (mode === "tokens" && contextLimit > 0) {
24-
const tokens = Math.floor((thresholdPercentage / 100) * contextLimit);
25-
return `${tokens.toLocaleString()} tokens (${thresholdPercentage.toFixed(1)}% of ${contextLimit.toLocaleString()}) [token-mode]`;
39+
const tokens = Math.floor((percentage / 100) * contextLimit);
40+
return `${tokens.toLocaleString()} tokens (${percentage.toFixed(1)}% of ${contextLimit.toLocaleString()}) [token-mode]${clampNote}`;
2641
}
2742
if (contextLimit > 0) {
28-
const tokens = Math.floor((thresholdPercentage / 100) * contextLimit);
29-
return `${thresholdPercentage}% (${tokens.toLocaleString()} of ${contextLimit.toLocaleString()})`;
43+
const tokens = Math.floor((percentage / 100) * contextLimit);
44+
return `${percentage}% (${tokens.toLocaleString()} of ${contextLimit.toLocaleString()})${clampNote}`;
3045
}
31-
return `${thresholdPercentage}%`;
46+
return `${percentage}%${clampNote}`;
3247
}
3348

3449
export function executeStatus(
@@ -59,7 +74,6 @@ export function executeStatus(
5974
},
6075
);
6176
const executeThresholdPercentage = thresholdDetail.percentage;
62-
const thresholdMode: "tokens" | "percentage" = thresholdDetail.mode;
6377
try {
6478
const meta = getOrCreateSessionMeta(db, sessionId);
6579
const tags = getTagsBySession(db, sessionId);
@@ -120,7 +134,7 @@ export function executeStatus(
120134
`- Queue will auto-execute: ${cacheExpired ? "yes (cache expired)" : `when TTL expires or context >= ${executeThresholdPercentage}%`}`,
121135
"",
122136
"### Execute Threshold",
123-
`- Execute threshold: ${formatExecuteThreshold(executeThresholdPercentage, thresholdMode, displayContextLimit)}`,
137+
`- Execute threshold: ${formatExecuteThreshold(thresholdDetail, displayContextLimit)}`,
124138
`- Last input tokens: ${meta.lastInputTokens.toLocaleString()} tokens`,
125139
"",
126140
`**Protected tags:** ${protectedTags}`,

‎packages/plugin/src/plugin/rpc-handlers.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,7 @@ export function buildSidebarSnapshot(
421421
// or when no config was passed in. Mirrors the resolution flow
422422
// used by `buildStatusDetail` so the dialog and sidebar agree.
423423
let executeThreshold = 65;
424+
let executeThresholdClamped = false;
424425
if (config) {
425426
const modelKey =
426427
activeProviderID && activeModelID
@@ -439,6 +440,7 @@ export function buildSidebarSnapshot(
439440
sessionId,
440441
});
441442
executeThreshold = thresholdDetail.percentage;
443+
executeThresholdClamped = thresholdDetail.clamped === true;
442444
}
443445

444446
const calibration = resolveModelCalibration(activeProviderID, activeModelID);
@@ -482,6 +484,7 @@ export function buildSidebarSnapshot(
482484
toolCallTokens: calibrated.toolCallTokens,
483485
toolDefinitionTokens: calibrated.toolDefinitionTokens,
484486
executeThreshold,
487+
executeThresholdClamped,
485488
boundaryPresent: moduleStatus?.boundary_present,
486489
coverageOrdinal: moduleStatus?.coverage_ordinal,
487490
newWorkTokens,
@@ -671,6 +674,7 @@ export function buildStatusDetail(
671674
});
672675
detail.executeThreshold = thresholdDetail.percentage;
673676
detail.executeThresholdMode = thresholdDetail.mode;
677+
detail.executeThresholdClamped = thresholdDetail.clamped;
674678
if (thresholdDetail.absoluteTokens !== undefined) {
675679
detail.executeThresholdTokens = thresholdDetail.absoluteTokens;
676680
}

‎packages/plugin/src/shared/format-threshold.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,29 @@ export function formatThresholdPercent(value: number | undefined | null): string
2626
if (Math.abs(value - rounded) < 0.05) return String(rounded);
2727
return value.toFixed(1);
2828
}
29+
30+
/**
31+
* Build a terse "clamped" annotation for execute-threshold display, or "" when the
32+
* configured value was not clamped. Status surfaces (/ctx-status text, pi status
33+
* dialog) append this so a user who configured e.g. 190000 tokens on a 128K model
34+
* sees that it was reduced to the 80% safety cap, instead of the value being
35+
* silently ignored (issue #241). The note includes the configured value and the cap
36+
* so the user can see the math.
37+
*
38+
* `maxPercentage` is passed in (rather than imported) to keep this shared module
39+
* free of a dependency on the resolver that owns the cap constant.
40+
*/
41+
export function formatThresholdClampNote(opts: {
42+
clamped?: boolean;
43+
mode: "tokens" | "percentage";
44+
/** Raw configured value before clamping (tokens in tokens mode, % in percentage mode). */
45+
configuredValue?: number;
46+
contextLimit: number;
47+
maxPercentage: number;
48+
}): string {
49+
if (!opts.clamped || opts.configuredValue === undefined) return "";
50+
if (opts.mode === "tokens" && opts.contextLimit > 0) {
51+
return ` [clamped: ${opts.configuredValue.toLocaleString()} > ${opts.maxPercentage}% of ${opts.contextLimit.toLocaleString()}]`;
52+
}
53+
return ` [clamped: ${opts.configuredValue}% > ${opts.maxPercentage}%]`;
54+
}

‎packages/plugin/src/shared/rpc-types.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,14 @@ export interface SidebarSnapshot {
6767
* scheduler and transform paths.
6868
*/
6969
executeThreshold: number;
70+
/**
71+
* True when `executeThreshold` was clamped down from a higher configured value
72+
* (tokens config above 80% × contextLimit, or a percentage above the 80% cap).
73+
* The sidebar/status dialog append a small marker so the user knows their
74+
* configured value was reduced rather than applied verbatim (issue #241).
75+
* Absent when no clamp occurred.
76+
*/
77+
executeThresholdClamped?: boolean;
7078
/** Rust module cache boundary state, when the session uses Rust authority mode. */
7179
boundaryPresent?: boolean;
7280
coverageOrdinal?: number | null;

0 commit comments

Comments
 (0)