fix(app): settle only the sent staged provider draft on switch reply

This commit is contained in:
Mohamed Boudra
2026-11-26 02:49:20 +01:00
parent bfc2f5cb3a
commit ed37f6f5a4
6 changed files with 206 additions and 3 deletions
+4 -1
View File
@@ -13,6 +13,7 @@ import { Button } from "@/components/ui/button";
import {
clearStagedProviderSwitch,
getStagedProviderSwitch,
settleStagedProviderSwitch,
useStagedProviderSwitch,
} from "@/composer/provider-switch";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
@@ -1780,7 +1781,9 @@ function ComposerContentImpl({
submission: createMessageSubmissionWriter(serverId),
stagedProviderSwitch,
onProviderSwitchCommitted: (agent) => {
clearStagedProviderSwitch(serverId, targetAgentId);
if (stagedProviderSwitch) {
settleStagedProviderSwitch(serverId, targetAgentId, stagedProviderSwitch);
}
if (agent) {
getHostRuntimeStore().tryAcceptAgentSnapshot(
serverId,
@@ -1,6 +1,7 @@
export {
clearStagedProviderSwitch,
getStagedProviderSwitch,
settleStagedProviderSwitch,
useStagedProviderSwitch,
useStagedProviderSwitchStore,
type StagedProviderSwitch,
@@ -613,4 +613,147 @@ describe("app provider switching integration", () => {
expect(switchedCalls).toHaveLength(1);
sessionStore.clearSession(serverId);
});
it("preserves a newer staged provider choice made while an earlier queued switch reply is pending", async () => {
const serverId = "srv-newer-choice-queue";
const switchedCalls: Array<{ provider: string; text: string }> = [];
const sentCalls: string[] = [];
let resolveFirstSwitch!: (value: { agent?: AgentSnapshotPayload }) => void;
const fakeClient = {
switchAgentProvider: vi.fn((_agentId: string, opts: { provider: string; text: string }) => {
switchedCalls.push({ provider: opts.provider, text: opts.text });
if (switchedCalls.length === 1) {
return new Promise<{ agent?: AgentSnapshotPayload }>((resolve) => {
resolveFirstSwitch = resolve;
});
}
return Promise.resolve({
agent: { ...agentSnapshot(opts.provider), status: "running" },
});
}),
sendAgentMessage: vi.fn(async (_agentId: string, text: string) => {
sentCalls.push(text);
return { messageId: "unexpected-plain-send" };
}),
uploadFile: vi.fn(),
} as unknown as DaemonClient;
const runtime = new HostRuntimeStore({
deps: {
createClient: () => fakeClient,
connectToDaemon: async () => ({ client: fakeClient, serverId, hostname: null }),
getClientId: async () => "cid_newer_choice_queue",
},
});
const sessionStore = useSessionStore.getState();
sessionStore.initializeSession(serverId, fakeClient, 1);
useSessionStore.setState((state) => ({
sessions: {
...state.sessions,
[serverId]: {
...state.sessions[serverId]!,
serverInfo: {
serverId,
hostname: "localhost",
version: "0.18.0",
features: { providerSwitching: true },
},
},
},
}));
sessionStore.setAgents(
serverId,
new Map([
[
"agent-1",
{
...agentSnapshot("claude"),
serverId,
parentAgentId: null,
createdAt: new Date(TS),
updatedAt: new Date(TS),
lastUserMessageAt: null,
lastActivityAt: new Date(TS),
attentionTimestamp: null,
archivedAt: null,
status: "idle",
turn: { phase: "idle", cancellationRequestId: null },
},
],
]),
);
sessionStore.setQueuedMessages(
serverId,
new Map([
[
"agent-1",
[
{ id: "m1", text: "First switch to Codex", attachments: [] },
{ id: "m2", text: "Second switch to Copilot", attachments: [] },
],
],
]),
);
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: null,
modeId: null,
providerOptions: {},
});
// M1 begins switching to Codex.
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(switchedCalls).toEqual([{ provider: "codex", text: "First switch to Codex" }]);
});
// While Codex switch reply is still pending, user selects Copilot for the next prompt.
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
provider: "copilot",
model: "gpt-5",
thinkingOptionId: null,
modeId: null,
providerOptions: {},
});
// Codex switch reply arrives -> MUST NOT clear the newer Copilot draft!
resolveFirstSwitch({ agent: { ...agentSnapshot("codex"), status: "running" } });
await new Promise((resolve) => setTimeout(resolve, 30));
expect(getStagedProviderSwitch(serverId, "agent-1")?.provider).toBe("copilot");
// Once Codex goes idle and queue resumes, M2 MUST switch to Copilot (not send plainly to Codex).
sessionStore.setAgents(
serverId,
new Map([
[
"agent-1",
{
...agentSnapshot("codex"),
serverId,
parentAgentId: null,
createdAt: new Date(TS),
updatedAt: new Date(TS),
lastUserMessageAt: null,
lastActivityAt: new Date(TS),
attentionTimestamp: null,
archivedAt: null,
status: "idle",
turn: { phase: "idle", cancellationRequestId: null },
},
],
]),
);
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(switchedCalls).toEqual([
{ provider: "codex", text: "First switch to Codex" },
{ provider: "copilot", text: "Second switch to Copilot" },
]);
});
expect(sentCalls).toEqual([]);
expect(getStagedProviderSwitch(serverId, "agent-1")).toBeNull();
sessionStore.clearSession(serverId);
});
});
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it } from "vitest";
import {
clearStagedProviderSwitch,
getStagedProviderSwitch,
settleStagedProviderSwitch,
useStagedProviderSwitchStore,
} from "./index";
@@ -48,4 +49,38 @@ describe("staged provider switch store", () => {
store.clearForServer("srv-1");
expect(getStagedProviderSwitch("srv-1", "agent-2")).toBeNull();
});
it("settles only the draft that was sent and preserves any newer selection or edit", () => {
const store = useStagedProviderSwitchStore.getState();
store.stage("srv-1", "agent-1", {
provider: "codex",
model: "gpt-5.4",
thinkingOptionId: null,
modeId: null,
providerOptions: {},
});
const sentDraft = getStagedProviderSwitch("srv-1", "agent-1")!;
// User chooses Copilot before Codex reply returns -> settling Codex draft preserves Copilot.
store.stage("srv-1", "agent-1", {
provider: "copilot",
model: "gpt-5",
thinkingOptionId: null,
modeId: null,
providerOptions: {},
});
settleStagedProviderSwitch("srv-1", "agent-1", sentDraft);
const copilotDraft = getStagedProviderSwitch("srv-1", "agent-1")!;
expect(copilotDraft.provider).toBe("copilot");
// Patching the draft also produces a newer revision that settling the older reference preserves.
store.patch("srv-1", "agent-1", (current) => ({ ...current, thinkingOptionId: "high" }));
settleStagedProviderSwitch("srv-1", "agent-1", copilotDraft);
const patchedCopilot = getStagedProviderSwitch("srv-1", "agent-1")!;
expect(patchedCopilot.thinkingOptionId).toBe("high");
// Settling the current draft clears it cleanly.
settleStagedProviderSwitch("srv-1", "agent-1", patchedCopilot);
expect(getStagedProviderSwitch("srv-1", "agent-1")).toBeNull();
});
});
@@ -21,6 +21,7 @@ interface StagedProviderSwitchState {
agentId: string,
updater: (current: StagedProviderSwitch) => StagedProviderSwitch,
) => void;
settle: (serverId: string, agentId: string, sentDraft: StagedProviderSwitch) => void;
clear: (serverId: string, agentId: string) => void;
clearForServer: (serverId: string) => void;
}
@@ -47,6 +48,16 @@ export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((s
return { stagedByKey: next };
}),
settle: (serverId, agentId, sentDraft) =>
set((state) => {
const key = stagedKey(serverId, agentId);
const current = state.stagedByKey.get(key);
if (!current || current !== sentDraft) return state;
const next = new Map(state.stagedByKey);
next.delete(key);
return { stagedByKey: next };
}),
clear: (serverId, agentId) =>
set((state) => {
const key = stagedKey(serverId, agentId);
@@ -80,6 +91,14 @@ export function getStagedProviderSwitch(
);
}
export function settleStagedProviderSwitch(
serverId: string,
agentId: string,
sentDraft: StagedProviderSwitch,
): void {
useStagedProviderSwitchStore.getState().settle(serverId, agentId, sentDraft);
}
export function clearStagedProviderSwitch(serverId: string, agentId: string): void {
useStagedProviderSwitchStore.getState().clear(serverId, agentId);
}
+4 -2
View File
@@ -83,7 +83,7 @@ import {
} from "@/desktop/browser/automation/handler";
import { schedulesQueryBaseKey } from "@/schedules/aggregated-schedules";
import { dispatchComposerAgentMessage, sendQueuedComposerMessageNow } from "@/composer/actions";
import { clearStagedProviderSwitch, getStagedProviderSwitch } from "@/composer/provider-switch";
import { getStagedProviderSwitch, settleStagedProviderSwitch } from "@/composer/provider-switch";
import { createMessageSubmissionWriter } from "@/composer/submission/writer";
import { resolveComposerAttachmentSubmitFormat } from "@/composer/attachments/submit";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
@@ -2933,7 +2933,9 @@ export class HostRuntimeStore {
submission: createMessageSubmissionWriter(serverId),
stagedProviderSwitch,
onProviderSwitchCommitted: (agent) => {
clearStagedProviderSwitch(serverId, agentId);
if (stagedProviderSwitch) {
settleStagedProviderSwitch(serverId, agentId, stagedProviderSwitch);
}
if (agent) {
this.tryAcceptAgentSnapshot(serverId, normalizeAgentSnapshot(agent, serverId));
}