fix(server): keep Grok effort and rewind aligned with the live session
Do not carry an old effort onto a new model. Count steered prompts when rewinding. Lock rollback against a replaced session. Keep one default effort in the composer menu. Made with Grok 4.6.
This commit is contained in:
5 files changed
+164
-66
No files matched your search
@@ -59,6 +59,7 @@ import {
|
||||
currentGrokMaxTokensFromSessionSetup,
|
||||
currentGrokModelIdFromSessionSetup,
|
||||
currentGrokReasoningEffortFromSessionSetup,
|
||||
grokMaxTokensByModelFromSessionSetup,
|
||||
grokReasoningEffortMenusFromSessionSetup,
|
||||
makeGrokAcpRuntime,
|
||||
requestedGrokReasoningEffort,
|
||||
@@ -67,6 +68,7 @@ import {
|
||||
import {
|
||||
extractGrokTokenUsage,
|
||||
extractXAiAskUserQuestions,
|
||||
grokPromptCountForTurns,
|
||||
grokRewindTargetForTurnCount,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
@@ -128,6 +130,7 @@ interface GrokSessionContext {
|
||||
currentModelId: string | undefined;
|
||||
currentReasoningEffort: string | undefined;
|
||||
reasoningEffortMenus: Map<string, ReadonlyArray<string>>;
|
||||
maxTokensByModel: Map<string, number>;
|
||||
maxTokens: number | undefined;
|
||||
stopped: boolean;
|
||||
}
|
||||
@@ -772,6 +775,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
|
||||
});
|
||||
const boundModelId = boundSelection.modelId;
|
||||
const maxTokensByModel = grokMaxTokensByModelFromSessionSetup(started.sessionSetupResult);
|
||||
|
||||
const now = yield* nowIso;
|
||||
const session: ProviderSession = {
|
||||
@@ -809,7 +813,10 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
reasoningEffortMenus: grokReasoningEffortMenusFromSessionSetup(
|
||||
started.sessionSetupResult,
|
||||
),
|
||||
maxTokens: currentGrokMaxTokensFromSessionSetup(started.sessionSetupResult),
|
||||
maxTokensByModel,
|
||||
maxTokens:
|
||||
(boundModelId ? maxTokensByModel.get(boundModelId) : undefined) ??
|
||||
currentGrokMaxTokensFromSessionSetup(started.sessionSetupResult),
|
||||
stopped: false,
|
||||
};
|
||||
|
||||
@@ -974,14 +981,11 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const requestedTurnModelId = turnModelSelection?.model
|
||||
? resolveGrokAcpBaseModelId(turnModelSelection.model)
|
||||
: undefined;
|
||||
const advertisedTurnEfforts =
|
||||
(requestedTurnModelId
|
||||
? ctx.reasoningEffortMenus.get(requestedTurnModelId)
|
||||
: undefined) ??
|
||||
(ctx.currentModelId
|
||||
? ctx.reasoningEffortMenus.get(ctx.currentModelId)
|
||||
: undefined) ??
|
||||
[];
|
||||
const advertisedTurnEfforts = requestedTurnModelId
|
||||
? (ctx.reasoningEffortMenus.get(requestedTurnModelId) ?? [])
|
||||
: ctx.currentModelId
|
||||
? (ctx.reasoningEffortMenus.get(ctx.currentModelId) ?? [])
|
||||
: [];
|
||||
const turnSelection = yield* applyGrokAcpModelSelection({
|
||||
runtime: ctx.acp,
|
||||
currentModelId: ctx.currentModelId,
|
||||
@@ -995,7 +999,11 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
|
||||
});
|
||||
const currentModelId = turnSelection.modelId;
|
||||
ctx.currentModelId = currentModelId;
|
||||
ctx.currentReasoningEffort = turnSelection.reasoningEffort;
|
||||
if (currentModelId) {
|
||||
ctx.maxTokens = ctx.maxTokensByModel.get(currentModelId) ?? ctx.maxTokens;
|
||||
}
|
||||
|
||||
const text = input.input?.trim();
|
||||
const imagePromptParts = yield* Effect.forEach(
|
||||
@@ -1456,55 +1464,89 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
});
|
||||
|
||||
const rollbackThread: GrokAdapterShape["rollbackThread"] = (threadId, numTurns) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer >= 1.",
|
||||
});
|
||||
}
|
||||
const pointsPayload = yield* ctx.acp
|
||||
.request("_x.ai/rewind/points", {
|
||||
sessionId: ctx.acpSessionId,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, threadId, "_x.ai/rewind/points", error),
|
||||
),
|
||||
withThreadLock(
|
||||
threadId,
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer >= 1.",
|
||||
});
|
||||
}
|
||||
const promptCount = grokPromptCountForTurns(ctx.turns, numTurns);
|
||||
if (promptCount < 1) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "_x.ai/rewind/execute",
|
||||
detail: "Grok has no rewind point for that many turns.",
|
||||
});
|
||||
}
|
||||
const acpSessionId = ctx.acpSessionId;
|
||||
const pointsPayload = yield* ctx.acp
|
||||
.request("_x.ai/rewind/points", {
|
||||
sessionId: acpSessionId,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, threadId, "_x.ai/rewind/points", error),
|
||||
),
|
||||
);
|
||||
const liveCtx = yield* requireSession(threadId);
|
||||
if (liveCtx.acpSessionId !== acpSessionId) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "_x.ai/rewind/execute",
|
||||
detail: "Grok session changed before rewind completed.",
|
||||
});
|
||||
}
|
||||
const target = grokRewindTargetForTurnCount(
|
||||
parseGrokRewindPoints(pointsPayload),
|
||||
promptCount,
|
||||
);
|
||||
const target = grokRewindTargetForTurnCount(parseGrokRewindPoints(pointsPayload), numTurns);
|
||||
if (!target) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "_x.ai/rewind/execute",
|
||||
detail: "Grok has no rewind point for that many turns.",
|
||||
});
|
||||
}
|
||||
const executePayload = yield* ctx.acp
|
||||
.request("_x.ai/rewind/execute", {
|
||||
sessionId: ctx.acpSessionId,
|
||||
targetPromptIndex: target.promptIndex,
|
||||
mode: "conversation_only",
|
||||
force: true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, threadId, "_x.ai/rewind/execute", error),
|
||||
),
|
||||
if (!target) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "_x.ai/rewind/execute",
|
||||
detail: "Grok has no rewind point for that many turns.",
|
||||
});
|
||||
}
|
||||
const executePayload = yield* liveCtx.acp
|
||||
.request("_x.ai/rewind/execute", {
|
||||
sessionId: acpSessionId,
|
||||
targetPromptIndex: target.promptIndex,
|
||||
mode: "conversation_only",
|
||||
force: true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, threadId, "_x.ai/rewind/execute", error),
|
||||
),
|
||||
);
|
||||
const committedCtx = yield* requireSession(threadId);
|
||||
if (committedCtx.acpSessionId !== acpSessionId) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "_x.ai/rewind/execute",
|
||||
detail: "Grok session changed before rewind completed.",
|
||||
});
|
||||
}
|
||||
const executed = parseGrokRewindExecute(executePayload);
|
||||
if (!executed?.success) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "_x.ai/rewind/execute",
|
||||
detail: executed?.error ?? "Grok rewind did not succeed.",
|
||||
});
|
||||
}
|
||||
committedCtx.turns = committedCtx.turns.slice(
|
||||
0,
|
||||
Math.max(0, committedCtx.turns.length - numTurns),
|
||||
);
|
||||
const executed = parseGrokRewindExecute(executePayload);
|
||||
if (!executed?.success) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "_x.ai/rewind/execute",
|
||||
detail: executed?.error ?? "Grok rewind did not succeed.",
|
||||
});
|
||||
}
|
||||
ctx.turns = ctx.turns.slice(0, Math.max(0, ctx.turns.length - numTurns));
|
||||
return { threadId, turns: ctx.turns };
|
||||
});
|
||||
return { threadId, turns: committedCtx.turns };
|
||||
}),
|
||||
);
|
||||
|
||||
const stopSession: GrokAdapterShape["stopSession"] = (threadId) =>
|
||||
withThreadLock(
|
||||
|
||||
@@ -58,7 +58,7 @@ describe("parseGrokAcpModelMeta", () => {
|
||||
reasoningEffort: "high",
|
||||
totalContextTokens: 500000,
|
||||
reasoningEfforts: [
|
||||
{ id: "xhigh", value: "xhigh", label: "Extra High Effort" },
|
||||
{ id: "xhigh", value: "xhigh", label: "Extra High Effort", default: true },
|
||||
{ id: "high", value: "high", label: "High Effort", default: true },
|
||||
{ id: "medium", value: "medium", label: "Medium Effort" },
|
||||
],
|
||||
@@ -67,6 +67,9 @@ describe("parseGrokAcpModelMeta", () => {
|
||||
expect(meta.reasoningEffort).toBe("high");
|
||||
expect(meta.totalContextTokens).toBe(500000);
|
||||
expect(meta.reasoningEfforts.map((choice) => choice.id)).toEqual(["xhigh", "high", "medium"]);
|
||||
expect(
|
||||
meta.reasoningEfforts.filter((choice) => choice.isDefault).map((choice) => choice.id),
|
||||
).toEqual(["high"]);
|
||||
expect(grokReasoningEffortCapabilities(meta.reasoningEfforts).optionDescriptors?.[0]?.id).toBe(
|
||||
GROK_REASONING_EFFORT_OPTION_ID,
|
||||
);
|
||||
@@ -144,6 +147,21 @@ describe("applyGrokAcpModelSelection", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not carry the previous effort across a model switch", () =>
|
||||
Effect.gen(function* () {
|
||||
const { runtime, modelCalls } = makeRecordingRuntime();
|
||||
const result = yield* applyGrokAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: "grok-4.6",
|
||||
requestedModelId: "grok-4.5",
|
||||
currentReasoningEffort: "xhigh",
|
||||
mapError: (cause) => cause.message,
|
||||
});
|
||||
expect(modelCalls).toEqual([{ modelId: "grok-4.5" }]);
|
||||
expect(result).toEqual({ modelId: "grok-4.5", reasoningEffort: undefined });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("calls session/set_model when only effort changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const { runtime, modelCalls } = makeRecordingRuntime();
|
||||
|
||||
@@ -201,6 +201,7 @@ export function parseGrokAcpModelMeta(meta: unknown): GrokAcpModelMeta {
|
||||
}
|
||||
const choices = [...unique.values()];
|
||||
const current = trimmedString(meta.reasoningEffort);
|
||||
const defaultId = current ?? choices.find((choice) => choice.isDefault)?.id;
|
||||
const supportsReasoningEffort = meta.supportsReasoningEffort === true || choices.length > 0;
|
||||
const totalContextTokens =
|
||||
typeof meta.totalContextTokens === "number" &&
|
||||
@@ -212,11 +213,12 @@ export function parseGrokAcpModelMeta(meta: unknown): GrokAcpModelMeta {
|
||||
return {
|
||||
supportsReasoningEffort,
|
||||
...(current ? { reasoningEffort: current } : {}),
|
||||
reasoningEfforts: choices.map((choice) =>
|
||||
current && choice.id === current && choice.isDefault !== true
|
||||
? { ...choice, isDefault: true }
|
||||
: choice,
|
||||
),
|
||||
reasoningEfforts: choices.map((choice) => ({
|
||||
id: choice.id,
|
||||
label: choice.label,
|
||||
...(choice.description ? { description: choice.description } : {}),
|
||||
...(choice.id === defaultId ? { isDefault: true } : {}),
|
||||
})),
|
||||
...(totalContextTokens !== undefined ? { totalContextTokens } : {}),
|
||||
};
|
||||
}
|
||||
@@ -261,12 +263,31 @@ export function requestedGrokReasoningEffort(
|
||||
if (!requested) {
|
||||
return undefined;
|
||||
}
|
||||
if (advertised.length === 0 || advertised.includes(requested)) {
|
||||
if (advertised.includes(requested)) {
|
||||
return requested;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function grokMaxTokensByModelFromSessionSetup(
|
||||
sessionSetupResult:
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse,
|
||||
): Map<string, number> {
|
||||
const maxTokens = new Map<string, number>();
|
||||
for (const model of sessionSetupResult.models?.availableModels ?? []) {
|
||||
const tokens = parseGrokAcpModelMeta(model._meta).totalContextTokens;
|
||||
if (tokens === undefined) {
|
||||
continue;
|
||||
}
|
||||
const slug = resolveGrokAcpBaseModelId(model.modelId);
|
||||
maxTokens.set(slug, tokens);
|
||||
maxTokens.set(model.modelId, tokens);
|
||||
}
|
||||
return maxTokens;
|
||||
}
|
||||
|
||||
export function grokReasoningEffortMenusFromSessionSetup(
|
||||
sessionSetupResult:
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
@@ -346,9 +367,11 @@ export function applyGrokAcpModelSelection<E>(input: {
|
||||
readonly mapError: (cause: EffectAcpErrors.AcpError) => E;
|
||||
}): Effect.Effect<GrokAcpSelection, E> {
|
||||
const nextModelId = input.requestedModelId ?? input.currentModelId;
|
||||
const nextEffort = input.requestedReasoningEffort ?? input.currentReasoningEffort;
|
||||
const shouldSwitchModel =
|
||||
input.requestedModelId !== undefined && input.requestedModelId !== input.currentModelId;
|
||||
const nextEffort = shouldSwitchModel
|
||||
? input.requestedReasoningEffort
|
||||
: (input.requestedReasoningEffort ?? input.currentReasoningEffort);
|
||||
const shouldSwitchEffort =
|
||||
input.requestedReasoningEffort !== undefined &&
|
||||
input.requestedReasoningEffort !== input.currentReasoningEffort;
|
||||
|
||||
@@ -11,6 +11,7 @@ import { describe, expect } from "vite-plus/test";
|
||||
import {
|
||||
extractGrokTokenUsage,
|
||||
extractXAiAskUserQuestions,
|
||||
grokPromptCountForTurns,
|
||||
grokRewindTargetForTurnCount,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
@@ -345,6 +346,8 @@ describe("Grok rewind and usage helpers", () => {
|
||||
});
|
||||
expect(grokRewindTargetForTurnCount(points, 1)?.promptIndex).toBe(2);
|
||||
expect(grokRewindTargetForTurnCount(points, 2)?.promptIndex).toBe(1);
|
||||
expect(grokRewindTargetForTurnCount(points, 4)).toBeUndefined();
|
||||
expect(grokPromptCountForTurns([{ items: [1] }, { items: [2, 3] }], 1)).toBe(2);
|
||||
});
|
||||
|
||||
it("reads Grok token usage from prompt _meta", () => {
|
||||
|
||||
@@ -506,8 +506,20 @@ export function grokRewindTargetForTurnCount(
|
||||
return undefined;
|
||||
}
|
||||
const ordered = [...points].sort((left, right) => left.promptIndex - right.promptIndex);
|
||||
const target = ordered[Math.max(0, ordered.length - numTurns)];
|
||||
return target;
|
||||
if (numTurns > ordered.length) {
|
||||
return undefined;
|
||||
}
|
||||
return ordered[ordered.length - numTurns];
|
||||
}
|
||||
|
||||
export function grokPromptCountForTurns(
|
||||
turns: ReadonlyArray<{ readonly items: ReadonlyArray<unknown> }>,
|
||||
numTurns: number,
|
||||
): number {
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
return 0;
|
||||
}
|
||||
return turns.slice(-numTurns).reduce((count, turn) => count + turn.items.length, 0);
|
||||
}
|
||||
|
||||
export function parseGrokRewindExecute(payload: unknown): GrokRewindExecuteResult | undefined {
|
||||
|
||||
Reference in new issue
Block a user