Skip to content

Commit b18fefd

Browse files
fix(web): switching a cold Claude thread to Codex no longer compacts first (#25986)
1 parent 42d645a commit b18fefd

3 files changed

Lines changed: 190 additions & 31 deletions

File tree

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
import { createMemoryHistory } from "@tanstack/react-router";
2+
import {
3+
ProviderDriverKind,
4+
ProviderInstanceId,
5+
ProviderThreadId,
6+
type OrchestrationV2ProviderThread,
7+
} from "@t3tools/contracts";
8+
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
9+
import type * as Context from "effect/Context";
10+
import * as DateTime from "effect/DateTime";
11+
import { expect, it, vi } from "vite-plus/test";
12+
import { page, userEvent } from "vite-plus/test/browser";
13+
14+
import { AppRoot } from "~/AppRoot";
15+
// The route loads ChatView lazily, and its first transform (React Compiler over ~4k lines)
16+
// takes 6-11s; importing it here keeps that out of the test's timeout.
17+
import "~/components/ChatView";
18+
import { __setClientSettingsForTests } from "~/hooks/useSettings";
19+
import { getRouter } from "~/router";
20+
import {
21+
CLAUDE_PROVIDER,
22+
CODEX_PROVIDER,
23+
ENVIRONMENT_ID,
24+
dispatchedCommands,
25+
installFakeEnvironment,
26+
threadWithHistory,
27+
type FakeDriver,
28+
} from "../../test/fakeEnvironment";
29+
import { render } from "../../test/render";
30+
31+
// The socket is the only fake layer; see test/appScenarios.renders.tsx.
32+
vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => {
33+
const [actual, { fakeDriver }, Layer] = await Promise.all([
34+
importOriginal<{ readonly ConnectionDriver: Context.Key<unknown, FakeDriver> }>(),
35+
import("../../test/fakeEnvironment"),
36+
import("effect/Layer"),
37+
]);
38+
return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) };
39+
});
40+
41+
vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({
42+
...(await original()),
43+
trackRpcRequestSent: () => {},
44+
}));
45+
46+
const CLAUDE = ProviderInstanceId.make("claudeAgent");
47+
const CLAUDE_DRIVER = ProviderDriverKind.make("claudeAgent");
48+
49+
/** A Claude thread whose 250k-token context went cold long ago, with its native thread kept for handoff. */
50+
function coldClaudeThread() {
51+
const thread = threadWithHistory("thread-claude", 3, {
52+
instanceId: CLAUDE,
53+
model: "claude-opus-4-6",
54+
});
55+
const at = DateTime.makeUnsafe("2026-03-17T19:12:28.000Z");
56+
const providerThread: OrchestrationV2ProviderThread = {
57+
id: ProviderThreadId.make("provider-thread-claude"),
58+
driver: CLAUDE_DRIVER,
59+
providerInstanceId: CLAUDE,
60+
providerSessionId: null,
61+
appThreadId: thread.id,
62+
ownerNodeId: null,
63+
nativeThreadRef: { driver: CLAUDE_DRIVER, nativeId: "native-claude", strength: "strong" },
64+
nativeConversationHeadRef: null,
65+
status: "idle",
66+
firstRunOrdinal: 1,
67+
lastRunOrdinal: 3,
68+
handoffIds: [],
69+
forkedFrom: null,
70+
pendingBackgroundTasks: [],
71+
contextUsage: { usedTokens: 250_000, maxTokens: 1_000_000 },
72+
nativeMetadata: null,
73+
goal: null,
74+
createdAt: at,
75+
updatedAt: at,
76+
};
77+
return { ...thread, providerThreads: [providerThread] };
78+
}
79+
80+
it("sends a Codex follow-up on a cold Claude thread without compacting first", async () => {
81+
const thread = coldClaudeThread();
82+
using _environment = installFakeEnvironment([thread], {
83+
acceptCommands: true,
84+
providers: [CLAUDE_PROVIDER, CODEX_PROVIDER],
85+
});
86+
__setClientSettingsForTests({
87+
...DEFAULT_CLIENT_SETTINGS,
88+
onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
89+
});
90+
const router = getRouter(
91+
createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
92+
);
93+
await router.load();
94+
await using _app = await render(<AppRoot router={router} />, {
95+
// AppRoot brings its own router.
96+
router: false,
97+
});
98+
await expect.element(page.getByText(`Answer 2 for ${thread.id}.`)).toBeVisible();
99+
const compactAndSend = page.getByRole("button", { name: "Compact and send" });
100+
await expect.element(compactAndSend).toBeVisible();
101+
102+
await page.getByRole("button", { name: "Claude Opus 4.6", exact: true }).click();
103+
// The picker lists only the active provider's models until you search.
104+
await userEvent.type(page.getByPlaceholder("Search models..."), "GPT-5.4");
105+
await page.getByRole("option", { name: "GPT-5.4", exact: false }).click();
106+
await expect.element(page.getByRole("button", { name: "GPT-5.4", exact: true })).toBeVisible();
107+
await expect.element(compactAndSend).not.toBeInTheDocument();
108+
// Picking a model leaves the composer's settings menu open.
109+
await userEvent.keyboard("{Escape}");
110+
111+
const editor = page.getByTestId("composer-editor");
112+
await userEvent.click(editor);
113+
await userEvent.type(editor, "keep going");
114+
await userEvent.keyboard("{Enter}");
115+
116+
const messages = () =>
117+
dispatchedCommands().flatMap((command) =>
118+
command.type === "message.dispatch"
119+
? [{ text: command.text, instanceId: command.modelSelection?.instanceId }]
120+
: [],
121+
);
122+
const sent = { text: "keep going", instanceId: CODEX_PROVIDER.instanceId };
123+
await vi.waitFor(() => expect(messages()).toContainEqual(sent));
124+
expect(messages()).toEqual([sent]);
125+
});

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2462,8 +2462,10 @@ export default function ChatView(props: ChatViewProps) {
24622462
pendingApprovals.length > 0 ||
24632463
pendingUserInputs.length > 0;
24642464
const compactDisabled = compactThreadUnavailable;
2465+
// The context window is the current conversation's, so a handoff destination never inherits it.
24652466
const resumeCompactionTokens =
24662467
activeContextWindow &&
2468+
pendingHandoff === null &&
24672469
resolveIdleCompaction(
24682470
settings,
24692471
activeProviderInstanceId ?? ProviderInstanceId.make("claudeAgent"),

‎apps/web/test/fakeEnvironment.ts‎

Lines changed: 63 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,11 @@ import {
1818
WS_METHODS,
1919
WsRpcGroup,
2020
type VcsStatusStreamEvent,
21+
type ModelSelection,
2122
type OrchestrationProjectShell,
2223
type OrchestrationV2Command,
2324
type OrchestrationV2ProjectedTurnItem,
25+
type OrchestrationV2ProviderThread,
2426
type OrchestrationV2Run,
2527
type OrchestrationV2ShellStreamItem,
2628
type OrchestrationV2ThreadProjection,
@@ -68,30 +70,42 @@ const auth = {
6870
sessionCookieName: "t3_session",
6971
};
7072

71-
const baseServerConfig: ServerConfig = {
72-
...Schema.decodeUnknownSync(ServerConfig)({
73+
const readyProvider = (
74+
instanceId: string,
75+
driver: string,
76+
models: ReadonlyArray<{ readonly slug: string; readonly name: string }>,
77+
) => ({
78+
instanceId,
79+
driver,
80+
enabled: true,
81+
installed: true,
82+
version: "1.0.0",
83+
status: "ready",
84+
auth: { status: "authenticated" },
85+
checkedAt: "2026-03-17T19:12:28.000Z",
86+
models: models.map((model) => ({ ...model, isCustom: false, capabilities: null })),
87+
});
88+
export const CODEX_PROVIDER = readyProvider(CODEX, "codex", [
89+
{ slug: "gpt-5.4", name: "GPT-5.4" },
90+
{ slug: "gpt-5.5", name: "GPT-5.5" },
91+
]);
92+
export const CLAUDE_PROVIDER = {
93+
...readyProvider("claudeAgent", "claudeAgent", [
94+
{ slug: "claude-opus-4-6", name: "Claude Opus 4.6" },
95+
]),
96+
slashCommands: [{ name: "compact" }],
97+
};
98+
99+
const decodeServerConfig = Schema.decodeUnknownSync(ServerConfig);
100+
const makeServerConfig = (providers: ReadonlyArray<unknown>): ServerConfig => ({
101+
...decodeServerConfig({
73102
environment: descriptor,
74103
auth,
75104
cwd: "/workspace/render",
76105
keybindingsConfigPath: "/workspace/.t3/keybindings.json",
77106
keybindings: [],
78107
issues: [],
79-
providers: [
80-
{
81-
instanceId: CODEX,
82-
driver: "codex",
83-
enabled: true,
84-
installed: true,
85-
version: "1.0.0",
86-
status: "ready",
87-
auth: { status: "authenticated" },
88-
checkedAt: "2026-03-17T19:12:28.000Z",
89-
models: [
90-
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: null },
91-
{ slug: "gpt-5.5", name: "GPT-5.5", isCustom: false, capabilities: null },
92-
],
93-
},
94-
],
108+
providers,
95109
availableEditors: [],
96110
observability: {
97111
logsDirectoryPath: "/workspace/.t3/logs",
@@ -105,7 +119,8 @@ const baseServerConfig: ServerConfig = {
105119
shellResumeCompletionMarker: true,
106120
}),
107121
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
108-
};
122+
});
123+
let baseServerConfig = makeServerConfig([CODEX_PROVIDER]);
109124
// A server only leaves threads out of the shell when it serves their families.
110125
const serverConfig = (): ServerConfig =>
111126
threads.some((thread) => thread.olderSettled)
@@ -171,13 +186,19 @@ export function assistantItem(
171186
} satisfies OrchestrationV2TurnItem;
172187
}
173188

174-
function run(threadId: ThreadId, id: RunId, ordinal: number, userMessageId: string) {
189+
function run(
190+
threadId: ThreadId,
191+
id: RunId,
192+
ordinal: number,
193+
userMessageId: string,
194+
modelSelection: ModelSelection = MODEL,
195+
) {
175196
return {
176197
id,
177198
threadId,
178199
ordinal,
179-
providerInstanceId: CODEX,
180-
modelSelection: MODEL,
200+
providerInstanceId: modelSelection.instanceId,
201+
modelSelection,
181202
providerThreadId: null,
182203
userMessageId: MessageId.make(userMessageId),
183204
rootNodeId: null,
@@ -198,18 +219,26 @@ export interface FakeThread {
198219
readonly olderSettled?: true;
199220
readonly id: ThreadId;
200221
readonly title: string;
222+
/** Defaults to GPT-5.4 on Codex. */
223+
readonly modelSelection?: ModelSelection;
224+
/** The first is the thread's active provider thread. */
225+
readonly providerThreads?: ReadonlyArray<OrchestrationV2ProviderThread>;
201226
readonly runs: ReadonlyArray<OrchestrationV2Run>;
202227
readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
203228
}
204229

205230
/** A thread of `turns` user prompts, each answered in markdown with a list and inline code. */
206-
export function threadWithHistory(name: string, turns: number): FakeThread {
231+
export function threadWithHistory(
232+
name: string,
233+
turns: number,
234+
modelSelection: ModelSelection = MODEL,
235+
): FakeThread {
207236
const id = ThreadId.make(name);
208237
const runs: OrchestrationV2Run[] = [];
209238
const items: OrchestrationV2TurnItem[] = [];
210239
for (let turn = 0; turn < turns; turn++) {
211240
const runId = RunId.make(`${name}-run-${turn}`);
212-
runs.push(run(id, runId, turn + 1, `${name}-user-${turn}`));
241+
runs.push(run(id, runId, turn + 1, `${name}-user-${turn}`, modelSelection));
213242
items.push(
214243
userItem(id, runId, `${name}-user-${turn}`, turn * 2, `${name}: question ${turn}`),
215244
assistantItem(
@@ -222,22 +251,23 @@ export function threadWithHistory(name: string, turns: number): FakeThread {
222251
),
223252
);
224253
}
225-
return { id, title: `Thread ${name}`, runs, items };
254+
return { id, title: `Thread ${name}`, modelSelection, runs, items };
226255
}
227256

228257
function shellOf(thread: FakeThread): OrchestrationV2ThreadShell {
229258
const latest = thread.runs.at(-1);
259+
const modelSelection = thread.modelSelection ?? MODEL;
230260
return {
231261
id: thread.id,
232262
projectId: PROJECT_ID,
233263
title: thread.title,
234-
providerInstanceId: CODEX,
235-
modelSelection: MODEL,
264+
providerInstanceId: modelSelection.instanceId,
265+
modelSelection,
236266
runtimeMode: "full-access",
237267
interactionMode: "default",
238268
branch: "main",
239269
worktreePath: null,
240-
activeProviderThreadId: null,
270+
activeProviderThreadId: thread.providerThreads?.[0]?.id ?? null,
241271
lineage: {
242272
rootThreadId: thread.sideChatOf ?? thread.id,
243273
parentThreadId: thread.sideChatOf ?? null,
@@ -289,7 +319,7 @@ function projectionOf(thread: FakeThread): OrchestrationV2ThreadProjection {
289319
interactionMode: shell.interactionMode,
290320
branch: shell.branch,
291321
worktreePath: shell.worktreePath,
292-
activeProviderThreadId: null,
322+
activeProviderThreadId: shell.activeProviderThreadId,
293323
lineage: shell.lineage,
294324
forkedFrom: null,
295325
createdBy: "user",
@@ -307,7 +337,7 @@ function projectionOf(thread: FakeThread): OrchestrationV2ThreadProjection {
307337
nodes: [],
308338
subagents: [],
309339
providerSessions: [],
310-
providerThreads: [],
340+
providerThreads: [...(thread.providerThreads ?? [])],
311341
providerTurns: [],
312342
runtimeRequests: [],
313343
messages: [],
@@ -465,9 +495,10 @@ const encodedDescriptor = Schema.encodeSync(ExecutionEnvironmentDescriptor)(
465495
/** Serves the environment's HTTP API and these threads until disposed. */
466496
export function installFakeEnvironment(
467497
fixtures: ReadonlyArray<FakeThread>,
468-
options?: { readonly acceptCommands?: boolean },
498+
options?: { readonly acceptCommands?: boolean; readonly providers?: ReadonlyArray<unknown> },
469499
): Disposable {
470500
threads = fixtures;
501+
baseServerConfig = makeServerConfig(options?.providers ?? [CODEX_PROVIDER]);
471502
dispatched = [];
472503
acceptCommands = options?.acceptCommands === true;
473504
globalThis.fetch = async (input, init) => {
@@ -491,6 +522,7 @@ export function installFakeEnvironment(
491522
[Symbol.dispose]: () => {
492523
globalThis.fetch = realFetch;
493524
threads = [];
525+
baseServerConfig = makeServerConfig([CODEX_PROVIDER]);
494526
dispatched = [];
495527
acceptCommands = false;
496528
},

0 commit comments

Comments
 (0)