@devries-cameron20 / t3code Mirror · read-only / commits / b18fefde72
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 21:00 UTC

fix(web): switching a cold Claude thread to Codex no longer compacts first (#25986)

Julius Marminge committed Nov 11, 2026 at 16:21 UTC b18fefde725c1fec715f2771586a0df94d75d749
3 files changed +190 -31
apps/web/src/components/ChatView.handoffCompaction.browser.test.tsx new
+125
@@ -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
+2
@@ -2462,8 +2462,10 @@ export default function ChatView(props: ChatViewProps) {
2462 pendingApprovals.length > 0 ||
2463 pendingUserInputs.length > 0;
2464 const compactDisabled = compactThreadUnavailable;
2465 + // The context window is the current conversation's, so a handoff destination never inherits it.
2466 const resumeCompactionTokens =
2467 activeContextWindow &&
2468 + pendingHandoff === null &&
2469 resolveIdleCompaction(
2470 settings,
2471 activeProviderInstanceId ?? ProviderInstanceId.make("claudeAgent"),
apps/web/test/fakeEnvironment.ts
+63 -31
@@ -18,9 +18,11 @@ import {
18 WS_METHODS,
19 WsRpcGroup,
20 type VcsStatusStreamEvent,
21 + type ModelSelection,
22 type OrchestrationProjectShell,
23 type OrchestrationV2Command,
24 type OrchestrationV2ProjectedTurnItem,
25 + type OrchestrationV2ProviderThread,
26 type OrchestrationV2Run,
27 type OrchestrationV2ShellStreamItem,
28 type OrchestrationV2ThreadProjection,
@@ -68,30 +70,42 @@ const auth = {
70 sessionCookieName: "t3_session",
71 };
72
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({
102 environment: descriptor,
103 auth,
104 cwd: "/workspace/render",
105 keybindingsConfigPath: "/workspace/.t3/keybindings.json",
106 keybindings: [],
107 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,
109 availableEditors: [],
110 observability: {
111 logsDirectoryPath: "/workspace/.t3/logs",
@@ -105,7 +119,8 @@ const baseServerConfig: ServerConfig = {
119 shellResumeCompletionMarker: true,
120 }),
121 keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
108 -};
122 +});
123 +let baseServerConfig = makeServerConfig([CODEX_PROVIDER]);
124 // A server only leaves threads out of the shell when it serves their families.
125 const serverConfig = (): ServerConfig =>
126 threads.some((thread) => thread.olderSettled)
@@ -171,13 +186,19 @@ export function assistantItem(
186 } satisfies OrchestrationV2TurnItem;
187 }
188
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 +) {
196 return {
197 id,
198 threadId,
199 ordinal,
179 - providerInstanceId: CODEX,
180 - modelSelection: MODEL,
200 + providerInstanceId: modelSelection.instanceId,
201 + modelSelection,
202 providerThreadId: null,
203 userMessageId: MessageId.make(userMessageId),
204 rootNodeId: null,
@@ -198,18 +219,26 @@ export interface FakeThread {
219 readonly olderSettled?: true;
220 readonly id: ThreadId;
221 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>;
226 readonly runs: ReadonlyArray<OrchestrationV2Run>;
227 readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
228 }
229
230 /** 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 {
236 const id = ThreadId.make(name);
237 const runs: OrchestrationV2Run[] = [];
238 const items: OrchestrationV2TurnItem[] = [];
239 for (let turn = 0; turn < turns; turn++) {
240 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));
242 items.push(
243 userItem(id, runId, `${name}-user-${turn}`, turn * 2, `${name}: question ${turn}`),
244 assistantItem(
@@ -222,22 +251,23 @@ export function threadWithHistory(name: string, turns: number): FakeThread {
251 ),
252 );
253 }
225 - return { id, title: `Thread ${name}`, runs, items };
254 + return { id, title: `Thread ${name}`, modelSelection, runs, items };
255 }
256
257 function shellOf(thread: FakeThread): OrchestrationV2ThreadShell {
258 const latest = thread.runs.at(-1);
259 + const modelSelection = thread.modelSelection ?? MODEL;
260 return {
261 id: thread.id,
262 projectId: PROJECT_ID,
263 title: thread.title,
234 - providerInstanceId: CODEX,
235 - modelSelection: MODEL,
264 + providerInstanceId: modelSelection.instanceId,
265 + modelSelection,
266 runtimeMode: "full-access",
267 interactionMode: "default",
268 branch: "main",
269 worktreePath: null,
240 - activeProviderThreadId: null,
270 + activeProviderThreadId: thread.providerThreads?.[0]?.id ?? null,
271 lineage: {
272 rootThreadId: thread.sideChatOf ?? thread.id,
273 parentThreadId: thread.sideChatOf ?? null,
@@ -289,7 +319,7 @@ function projectionOf(thread: FakeThread): OrchestrationV2ThreadProjection {
319 interactionMode: shell.interactionMode,
320 branch: shell.branch,
321 worktreePath: shell.worktreePath,
292 - activeProviderThreadId: null,
322 + activeProviderThreadId: shell.activeProviderThreadId,
323 lineage: shell.lineage,
324 forkedFrom: null,
325 createdBy: "user",
@@ -307,7 +337,7 @@ function projectionOf(thread: FakeThread): OrchestrationV2ThreadProjection {
337 nodes: [],
338 subagents: [],
339 providerSessions: [],
310 - providerThreads: [],
340 + providerThreads: [...(thread.providerThreads ?? [])],
341 providerTurns: [],
342 runtimeRequests: [],
343 messages: [],
@@ -465,9 +495,10 @@ const encodedDescriptor = Schema.encodeSync(ExecutionEnvironmentDescriptor)(
495 /** Serves the environment's HTTP API and these threads until disposed. */
496 export function installFakeEnvironment(
497 fixtures: ReadonlyArray<FakeThread>,
468 - options?: { readonly acceptCommands?: boolean },
498 + options?: { readonly acceptCommands?: boolean; readonly providers?: ReadonlyArray<unknown> },
499 ): Disposable {
500 threads = fixtures;
501 + baseServerConfig = makeServerConfig(options?.providers ?? [CODEX_PROVIDER]);
502 dispatched = [];
503 acceptCommands = options?.acceptCommands === true;
504 globalThis.fetch = async (input, init) => {
@@ -491,6 +522,7 @@ export function installFakeEnvironment(
522 [Symbol.dispose]: () => {
523 globalThis.fetch = realFetch;
524 threads = [];
525 + baseServerConfig = makeServerConfig([CODEX_PROVIDER]);
526 dispatched = [];
527 acceptCommands = false;
528 },