Skip to content

Commit 3b04d3f

Browse files
committed
fix(responses): scope Cursor continuation owners
1 parent 7fedda4 commit 3b04d3f

3 files changed

Lines changed: 216 additions & 8 deletions

File tree

‎src/oauth/index.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -302,9 +302,11 @@ export class OAuthLoginRequiredError extends Error {
302302

303303
function accessSnapshot(provider: string, accountId: string, cred: OAuthCredentials): OAuthAccessSnapshot {
304304
// Email is not an immutable upstream subject: multiple accounts may share or later reuse it.
305-
// Fail closed unless the provider supplied its stable account id.
305+
// Fail closed unless the provider supplied its stable account id. Preserve the exact stored
306+
// subject because the credential store also matches it exactly; trimming only here would make
307+
// two distinct slots share one continuation owner.
306308
const stableCredentialSubject = cred.accountId?.trim()
307-
? ["account-id", cred.accountId.trim()]
309+
? ["account-id", cred.accountId]
308310
: undefined;
309311
const storedKiroRouting = {
310312
...(cred.kiro?.profileArn ? { profileArn: cred.kiro.profileArn } : {}),

‎src/server/responses/core.ts‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ import { buildWebSearchTool, planWebSearch, runWithWebSearch, shouldResolveOpenA
8686
import { buildImageTool, buildVideoTool, planImageBridge, planVideoBridge, runWithImageBridge, clampImageMaxRounds, IMAGE_GEN_TOOL_NAME, VIDEO_GEN_TOOL_NAME } from "../../images";
8787
import { describeImagesInPlace, isModelTextOnly, planVisionSidecar, resolveOpenAiVisionModel, shouldResolveOpenAiVisionSidecar, stripImagesInPlace } from "../../vision";
8888
import { createAdapterEventQueue, preflightAdapterEvents, type AdapterEventQueue } from "../../adapters/run-turn-queue";
89+
import { resolveCursorToken } from "../../adapters/cursor/live-transport";
8990
import {
9091
applyCodexAuthContextToProvider,
9192
CodexAccountCooldownError,
@@ -458,6 +459,46 @@ function bindRouteReasoningReplayScope(args: {
458459
credentialIdentity = reasoningReplayKeyCredentialIdentity(provider);
459460
}
460461
const providerDestinationIdentity = reasoningReplayDestinationIdentity(provider.baseUrl);
462+
const continuationOwner = providerContinuationOwnerForRoute(args);
463+
if (adapterName === "cursor") {
464+
let cursorCredentialIdentity = continuationOwner?.credentialIdentity ?? credentialIdentity;
465+
if (!cursorCredentialIdentity) {
466+
try {
467+
cursorCredentialIdentity = `cursor-token:${continuationIdentity(
468+
"cursor-route-token",
469+
resolveCursorToken(provider, args.forwardHeaders),
470+
)}`;
471+
} catch {
472+
// Keep the adapter's existing missing-token failure path. In particular, do not
473+
// collapse ownerless local routes into a shared deterministic conversation scope.
474+
delete parsed._cursorIdentityScope;
475+
}
476+
}
477+
// Cursor derives a stable conversation id from the client thread. Namespace that derivation
478+
// by the final physical route owner, not merely the token, so rejecting a stored continuation
479+
// cannot recreate the same provider-private id for another destination/model/account.
480+
if (cursorCredentialIdentity) {
481+
const owner = continuationOwner ?? {
482+
version: 1,
483+
providerName,
484+
providerDestinationIdentity: providerDestinationIdentity ?? "unbound-destination",
485+
adapterName,
486+
modelId: parsed.modelId,
487+
credentialIdentity: cursorCredentialIdentity,
488+
} satisfies OcxProviderContinuationOwner;
489+
parsed._cursorIdentityScope = `cursor-route:${continuationIdentity(
490+
"cursor-route-owner",
491+
JSON.stringify([
492+
owner.version,
493+
owner.providerName,
494+
owner.providerDestinationIdentity,
495+
owner.adapterName,
496+
owner.modelId,
497+
owner.credentialIdentity,
498+
]),
499+
)}`;
500+
}
501+
}
461502
bindReasoningReplayScope(
462503
parsed._reasoningReplayScope,
463504
credentialIdentity && providerDestinationIdentity
@@ -470,7 +511,7 @@ function bindRouteReasoningReplayScope(args: {
470511
}
471512
: undefined,
472513
);
473-
bindProviderContinuationForRoute(parsed, providerContinuationOwnerForRoute(args));
514+
bindProviderContinuationForRoute(parsed, continuationOwner);
474515
}
475516

476517
function isFixedCodexAccount(authCtx: CodexAuthContext): boolean {

‎tests/server-combo-failover-e2e.test.ts‎

Lines changed: 170 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { afterEach, beforeEach, describe, expect, mock, setDefaultTimeout, test } from "bun:test";
22
import { logsFromApiBody } from "./helpers/logs-api";
33
import { managementFetch as fetch, ManagementRequest as Request } from "./helpers/management-auth";
4-
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
4+
import { mkdtempSync, readFileSync } from "node:fs";
55
import { tmpdir } from "node:os";
66
import { join } from "node:path";
77
import {
@@ -29,6 +29,13 @@ import {
2929
import { startServer } from "../src/server";
3030
import { fakeChatGptJwt } from "./helpers/fake-chatgpt-jwt";
3131
import { catalogConvergenceFactory } from "./helpers/catalog-convergence";
32+
import { removeTreeWithRetry } from "./helpers/remove-tree";
33+
import {
34+
clearResponseStateForTests,
35+
flushResponseState,
36+
responseStatePersistPendingForTests,
37+
} from "../src/responses/state";
38+
import { clearCursorThreadContinuityForTests } from "../src/adapters/cursor/thread-continuity";
3239

3340
// Full-suite Windows load: startServer + combo rename/delete management flows exceed the
3441
// default 5s per-test budget (same flake class as 810fa115 / claude-management-api).
@@ -139,19 +146,25 @@ beforeEach(() => {
139146
customUsageEstimate = undefined;
140147
customCursorTransportFactory = undefined;
141148
clearRequestLogsForTests();
149+
clearResponseStateForTests();
150+
clearCursorThreadContinuityForTests();
142151
});
143152

144153
afterEach(async () => {
154+
for (const server of servers.splice(0)) await server.stop(true);
155+
await flushResponseState();
156+
expect(responseStatePersistPendingForTests()).toBe(false);
157+
clearResponseStateForTests();
158+
clearCursorThreadContinuityForTests();
145159
globalThis.fetch = originalFetch;
146160
Date.now = originalNow;
147-
for (const server of servers.splice(0)) await server.stop(true);
148161
if (previousHome === undefined) delete process.env.OPENCODEX_HOME;
149162
else process.env.OPENCODEX_HOME = previousHome;
150163
if (previousCursorToken === undefined) delete process.env.OPENCODEX_CURSOR_TEST_TOKEN;
151164
else process.env.OPENCODEX_CURSOR_TEST_TOKEN = previousCursorToken;
152165
isolatedCodexHome?.restore();
153166
isolatedCodexHome = null;
154-
if (testDir) rmSync(testDir, { recursive: true, force: true });
167+
if (testDir) removeTreeWithRetry(testDir);
155168
clearComboSelectionState();
156169
clearComboTargetCooldowns();
157170
clearCodexUpstreamHealth();
@@ -1980,6 +1993,53 @@ describe("server combo failover 030 activation matrix", () => {
19801993
expect(seen).toEqual([undefined, "kiro-oauth-conversation", undefined, undefined]);
19811994
});
19821995

1996+
test("OAuth continuation owners distinguish exact stored account ids", async () => {
1997+
const seen: Array<string | undefined> = [];
1998+
customRunTurn = async (parsed, _incoming, emit) => {
1999+
const conversationId = parsed._providerContinuation?.kiro?.conversationId;
2000+
seen.push(conversationId);
2001+
emit({ type: "text_delta", text: "continued" });
2002+
emit({
2003+
type: "done",
2004+
providerState: { kiro: { conversationId: conversationId ?? "exact-oauth-subject" } },
2005+
});
2006+
};
2007+
const config = comboConfig({
2008+
xai: provider("openai-chat", "https://api.x.ai/v1", "unused", {
2009+
authMode: "oauth",
2010+
note: "test-kiro-oauth",
2011+
}),
2012+
}, [{ provider: "xai", model: "m1" }]);
2013+
2014+
await saveCredential("xai", {
2015+
access: "exact-subject-access-one",
2016+
refresh: "exact-subject-refresh-one",
2017+
expires: Date.now() + 3_600_000,
2018+
accountId: "acct-exact-subject",
2019+
source: "oauth",
2020+
});
2021+
const first = await post(config, { store: false, input: "first" });
2022+
expect(first.status).toBe(200);
2023+
const firstJson = await first.json() as { id: string };
2024+
2025+
await saveCredential("xai", {
2026+
access: "exact-subject-access-two",
2027+
refresh: "exact-subject-refresh-two",
2028+
expires: Date.now() + 3_600_000,
2029+
accountId: " acct-exact-subject ",
2030+
source: "oauth",
2031+
});
2032+
expect(getAccountSet("xai")?.accounts).toHaveLength(2);
2033+
const second = await post(config, {
2034+
store: false,
2035+
previous_response_id: firstJson.id,
2036+
input: "second",
2037+
});
2038+
2039+
expect(second.status).toBe(200);
2040+
expect(seen).toEqual([undefined, undefined]);
2041+
});
2042+
19832043
test("OAuth credentials without immutable account ids do not inherit provider continuation state", async () => {
19842044
const seen: Array<string | undefined> = [];
19852045
const {
@@ -2649,10 +2709,19 @@ describe("cursor conversation continuity across store:false chains", () => {
26492709
});
26502710
}
26512711

2652-
async function postCursor(config: OcxConfig, raw: Record<string, unknown>): Promise<Response> {
2712+
async function postCursor(
2713+
config: OcxConfig,
2714+
raw: Record<string, unknown>,
2715+
clientThreadId?: string,
2716+
bearerToken?: string,
2717+
): Promise<Response> {
26532718
return handleResponses(new Request("http://localhost/v1/responses", {
26542719
method: "POST",
2655-
headers: { "content-type": "application/json" },
2720+
headers: {
2721+
"content-type": "application/json",
2722+
...(clientThreadId ? { "x-codex-parent-thread-id": clientThreadId } : {}),
2723+
...(bearerToken ? { authorization: `Bearer ${bearerToken}` } : {}),
2724+
},
26562725
body: JSON.stringify({ stream: false, store: false, ...raw }),
26572726
}), config, { model: "", provider: "" }, {});
26582727
}
@@ -2718,6 +2787,102 @@ describe("cursor conversation continuity across store:false chains", () => {
27182787
expect(seen[1]).toBe(seen[0]);
27192788
});
27202789

2790+
test("owner mismatch rekeys Cursor parent-thread continuity to the new route", async () => {
2791+
const seen: string[] = [];
2792+
customCursorTransportFactory = fakeCursorTransportFactory(seen);
2793+
const config = cursorConfig();
2794+
const threadId = "cursor-route-owner-thread";
2795+
2796+
const first = await postCursor(config, {
2797+
model: "cursortest/composer-2",
2798+
input: "first",
2799+
}, threadId);
2800+
expect(first.status).toBe(200);
2801+
const firstJson = await first.json() as { id: string };
2802+
2803+
config.providers.cursortest!.baseUrl = "https://cursor-other.example/v1";
2804+
const second = await postCursor(config, {
2805+
model: "cursortest/composer-2",
2806+
previous_response_id: firstJson.id,
2807+
input: "second",
2808+
}, threadId);
2809+
expect(second.status).toBe(200);
2810+
2811+
const third = await postCursor(config, {
2812+
model: "cursortest/composer-2",
2813+
input: [
2814+
{ role: "user", content: "first" },
2815+
{ role: "assistant", content: "cursor ok" },
2816+
{ role: "user", content: "third" },
2817+
],
2818+
}, threadId);
2819+
expect(third.status).toBe(200);
2820+
2821+
expect(seen).toHaveLength(3);
2822+
expect(seen[1]).not.toBe(seen[0]);
2823+
expect(seen[2]).toBe(seen[1]);
2824+
});
2825+
2826+
test("ownerless local Cursor parent-thread continuity is scoped by route and bearer token", async () => {
2827+
const seen: string[] = [];
2828+
customCursorTransportFactory = fakeCursorTransportFactory(seen);
2829+
const config = cursorConfig();
2830+
config.providers.cursortest = {
2831+
...config.providers.cursortest!,
2832+
authMode: "local",
2833+
};
2834+
delete config.providers.cursortest.apiKey;
2835+
const threadId = "cursor-ownerless-token-thread";
2836+
2837+
const first = await postCursor(config, {
2838+
model: "cursortest/composer-2",
2839+
input: "first",
2840+
}, threadId, "cursor-token-a");
2841+
expect(first.status).toBe(200);
2842+
2843+
config.providers.cursortest!.baseUrl = "https://cursor-local-other.example/v1";
2844+
const second = await postCursor(config, {
2845+
model: "cursortest/composer-2",
2846+
input: [
2847+
{ role: "user", content: "first" },
2848+
{ role: "assistant", content: "cursor ok" },
2849+
{ role: "user", content: "second" },
2850+
],
2851+
}, threadId, "cursor-token-a");
2852+
expect(second.status).toBe(200);
2853+
2854+
const third = await postCursor(config, {
2855+
model: "cursortest/composer-2",
2856+
input: [
2857+
{ role: "user", content: "first" },
2858+
{ role: "assistant", content: "cursor ok" },
2859+
{ role: "user", content: "second" },
2860+
{ role: "assistant", content: "cursor ok" },
2861+
{ role: "user", content: "third" },
2862+
],
2863+
}, threadId, "cursor-token-b");
2864+
expect(third.status).toBe(200);
2865+
2866+
const fourth = await postCursor(config, {
2867+
model: "cursortest/composer-2",
2868+
input: [
2869+
{ role: "user", content: "first" },
2870+
{ role: "assistant", content: "cursor ok" },
2871+
{ role: "user", content: "second" },
2872+
{ role: "assistant", content: "cursor ok" },
2873+
{ role: "user", content: "third" },
2874+
{ role: "assistant", content: "cursor ok" },
2875+
{ role: "user", content: "fourth" },
2876+
],
2877+
}, threadId, "cursor-token-b");
2878+
expect(fourth.status).toBe(200);
2879+
2880+
expect(seen).toHaveLength(4);
2881+
expect(seen[1]).not.toBe(seen[0]);
2882+
expect(seen[2]).not.toBe(seen[1]);
2883+
expect(seen[3]).toBe(seen[2]);
2884+
});
2885+
27212886
test("external-model toolResult continuation preserves and persists the same id", async () => {
27222887
const seen: string[] = [];
27232888
customCursorTransportFactory = fakeCursorTransportFactory(seen);

0 commit comments

Comments
 (0)