fix(agents,app): read handoff after lock, forward startup edits, and surface queued switch errors

This commit is contained in:
Mohamed Boudra
2026-11-26 02:49:20 +01:00
parent ed37f6f5a4
commit 774110243e
8 changed files with 521 additions and 77 deletions
+62 -36
View File
@@ -11,9 +11,12 @@ import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import {
beginStagedProviderSwitch,
clearStagedProviderSwitch,
endStagedProviderSwitch,
getStagedProviderSwitch,
settleStagedProviderSwitch,
isStagedProviderSwitchInFlight,
settleCommittedProviderSwitch,
useStagedProviderSwitch,
} from "@/composer/provider-switch";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
@@ -1395,7 +1398,8 @@ function ComposerContentImpl({
if (
rawStagedSwitch &&
agentState.provider &&
rawStagedSwitch.provider === agentState.provider
rawStagedSwitch.provider === agentState.provider &&
!isStagedProviderSwitchInFlight(serverId, agentId)
) {
clearStagedProviderSwitch(serverId, agentId);
}
@@ -1404,11 +1408,15 @@ function ComposerContentImpl({
const handleCancelStagedSwitch = useCallback(() => {
clearStagedProviderSwitch(serverId, agentId);
setSendError(null);
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
}, [agentId, serverId]);
const queuedMessagesRaw = useSessionStore((state) =>
state.sessions[serverId]?.queuedMessages?.get(agentId),
);
const queuedSendError = useSessionStore(
(state) => state.sessions[serverId]?.queuedSendErrors?.get(agentId) ?? null,
);
const queuedMessages = queuedMessagesRaw ?? EMPTY_ARRAY;
const setQueuedMessages = useSessionStore((state) => state.setQueuedMessages);
@@ -1769,37 +1777,53 @@ function ComposerContentImpl({
const pendingSwitch = canSwitch ? getStagedProviderSwitch(serverId, targetAgentId) : null;
const stagedProviderSwitch =
pendingSwitch && pendingSwitch.provider !== liveProvider ? pendingSwitch : null;
await dispatchComposerAgentMessage({
client,
agentId: targetAgentId,
text,
attachments: sendAttachments,
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
supportsForgeAttachments: supportsForgeSearch,
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
stagedProviderSwitch,
onProviderSwitchCommitted: (agent) => {
if (stagedProviderSwitch) {
settleStagedProviderSwitch(serverId, targetAgentId, stagedProviderSwitch);
}
if (agent) {
getHostRuntimeStore().tryAcceptAgentSnapshot(
serverId,
normalizeAgentSnapshot(agent, serverId),
);
}
},
activeTurnBehavior,
activeTurnId:
activeTurnBehavior === "steer"
? (selectAgentTurnPresentation(
useSessionStore.getState().sessions[serverId],
targetAgentId,
).turnId ?? undefined)
: undefined,
});
useSessionStore.getState().setQueuedSendError(serverId, targetAgentId, null);
if (stagedProviderSwitch) {
beginStagedProviderSwitch(serverId, targetAgentId);
}
try {
await dispatchComposerAgentMessage({
client,
agentId: targetAgentId,
text,
attachments: sendAttachments,
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
supportsForgeAttachments: supportsForgeSearch,
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
stagedProviderSwitch,
onProviderSwitchCommitted: (agent) => {
if (stagedProviderSwitch) {
settleCommittedProviderSwitch({
serverId,
agentId: targetAgentId,
sentDraft: stagedProviderSwitch,
committedProvider: agent?.provider ?? null,
client,
});
}
if (agent) {
getHostRuntimeStore().tryAcceptAgentSnapshot(
serverId,
normalizeAgentSnapshot(agent, serverId),
);
}
},
activeTurnBehavior,
activeTurnId:
activeTurnBehavior === "steer"
? (selectAgentTurnPresentation(
useSessionStore.getState().sessions[serverId],
targetAgentId,
).turnId ?? undefined)
: undefined,
});
} finally {
if (stagedProviderSwitch) {
endStagedProviderSwitch(serverId, targetAgentId);
}
}
onAttentionPromptSend?.();
};
}, [appSettings.sendBehavior, client, onAttentionPromptSend, serverId, supportsForgeSearch, t]);
@@ -2152,15 +2176,17 @@ function ComposerContentImpl({
queue: queueWriter,
});
if (!result) return;
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
replaceUserInput(result.text);
setSelectedAttachments(result.attachments);
},
[agentId, queueWriter, replaceUserInput, setSelectedAttachments],
[agentId, queueWriter, replaceUserInput, serverId, setSelectedAttachments],
);
const handleSendQueuedNow = useCallback(
async (id: string) => {
if (!sendAgentMessageRef.current && !onSubmitMessageRef.current) return;
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
// Reuse the regular send path; server-side send atomically interrupts any active run.
const result = await sendQueuedComposerMessageNow({
agentId,
@@ -2174,7 +2200,7 @@ function ComposerContentImpl({
setSendError(result.errorMessage);
}
},
[agentId, queueWriter, submitMessage, t],
[agentId, queueWriter, serverId, submitMessage, t],
);
const handleQueue = useCallback(
@@ -2627,7 +2653,7 @@ function ComposerContentImpl({
// Focusing the composer on a touch screen raises the on-screen keyboard over the conversation.
const messageInputAutoFocus = autoFocus && isDesktopWebBreakpoint && hasFinePointer;
const submitLoadingPressHandler = isAgentRunning ? handleCancelAgent : undefined;
const displayError = externalError || sendError;
const displayError = externalError || sendError || queuedSendError;
const sendErrorNode = useMemo(
() =>
displayError ? (
@@ -1,8 +1,13 @@
export {
beginStagedProviderSwitch,
clearStagedProviderSwitch,
endStagedProviderSwitch,
getStagedProviderSwitch,
isStagedProviderSwitchInFlight,
settleCommittedProviderSwitch,
settleStagedProviderSwitch,
useStagedProviderSwitch,
useStagedProviderSwitchStore,
type LiveAgentSettingsWriter,
type StagedProviderSwitch,
} from "./store";
@@ -756,4 +756,127 @@ describe("app provider switching integration", () => {
expect(getStagedProviderSwitch(serverId, "agent-1")).toBeNull();
sessionStore.clearSession(serverId);
});
it("forwards target provider setting edits made during switch startup to the live agent and surfaces failed automatic drain errors", async () => {
const serverId = "srv-edited-and-failed-queue";
let resolveSwitch!: (value: { agent?: AgentSnapshotPayload }) => void;
const setAgentModel = vi.fn().mockResolvedValue(undefined);
const setAgentMode = vi.fn().mockResolvedValue(null);
const setAgentThinkingOption = vi.fn().mockResolvedValue(undefined);
const setAgentOptions = vi.fn().mockResolvedValue(undefined);
let failNextSwitch = false;
const fakeClient = {
switchAgentProvider: vi.fn((_agentId: string, _opts: { provider: string; text: string }) => {
if (failNextSwitch) {
return Promise.reject(new Error("Codex CLI is not available"));
}
return new Promise<{ agent?: AgentSnapshotPayload }>((resolve) => {
resolveSwitch = resolve;
});
}),
sendAgentMessage: vi.fn(),
setAgentModel,
setAgentMode,
setAgentThinkingOption,
setAgentOptions,
uploadFile: vi.fn(),
} as unknown as DaemonClient;
const runtime = new HostRuntimeStore({
deps: {
createClient: () => fakeClient,
connectToDaemon: async () => ({ client: fakeClient, serverId, hostname: null }),
getClientId: async () => "cid_edited_and_failed_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: "Switch with startup edit", attachments: [] }]]]),
);
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
provider: "codex",
model: "gpt-5.3",
thinkingOptionId: "low",
modeId: "auto",
providerOptions: { fast_mode: false },
});
// 1. Pre-commit automatic drain failure restores queue item and exposes error in session store.
failNextSwitch = true;
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(useSessionStore.getState().sessions[serverId]?.queuedSendErrors.get("agent-1")).toBe(
"Codex CLI is not available",
);
});
expect(useSessionStore.getState().sessions[serverId]?.queuedMessages.get("agent-1")).toEqual([
{ id: "m1", text: "Switch with startup edit", attachments: [] },
]);
// 2. Retry succeeds: while switch reply is pending, user edits Codex model/thinking/mode/options.
failNextSwitch = false;
runtime.drainQueuedAgentMessage(serverId, "agent-1");
await vi.waitFor(() => {
expect(fakeClient.switchAgentProvider).toHaveBeenCalledTimes(2);
});
expect(useSessionStore.getState().sessions[serverId]?.queuedSendErrors.get("agent-1")).toBe(
undefined,
);
useStagedProviderSwitchStore.getState().patch(serverId, "agent-1", (current) => ({
...current,
model: "gpt-5.4",
modeId: "full-auto",
thinkingOptionId: "high",
providerOptions: { fast_mode: true },
}));
resolveSwitch({ agent: { ...agentSnapshot("codex"), status: "running" } });
await vi.waitFor(() => {
expect(getStagedProviderSwitch(serverId, "agent-1")).toBeNull();
expect(setAgentModel).toHaveBeenCalledWith("agent-1", "gpt-5.4");
expect(setAgentMode).toHaveBeenCalledWith("agent-1", "full-auto");
expect(setAgentThinkingOption).toHaveBeenCalledWith("agent-1", "high");
expect(setAgentOptions).toHaveBeenCalledWith("agent-1", { fast_mode: true });
});
sessionStore.clearSession(serverId);
});
});
@@ -13,14 +13,24 @@ function stagedKey(serverId: string, agentId: string): string {
return `${serverId}:${agentId}`;
}
export interface LiveAgentSettingsWriter {
setAgentModel?: (agentId: string, modelId: string | null) => Promise<unknown>;
setAgentMode?: (agentId: string, modeId: string) => Promise<unknown>;
setAgentThinkingOption?: (agentId: string, thinkingOptionId: string) => Promise<unknown>;
setAgentOptions?: (agentId: string, options: ProviderOptions) => Promise<unknown>;
}
interface StagedProviderSwitchState {
stagedByKey: Map<string, StagedProviderSwitch>;
inFlightByKey: Map<string, number>;
stage: (serverId: string, agentId: string, draft: StagedProviderSwitch) => void;
patch: (
serverId: string,
agentId: string,
updater: (current: StagedProviderSwitch) => StagedProviderSwitch,
) => void;
beginSwitch: (serverId: string, agentId: string) => void;
endSwitch: (serverId: string, agentId: string) => void;
settle: (serverId: string, agentId: string, sentDraft: StagedProviderSwitch) => void;
clear: (serverId: string, agentId: string) => void;
clearForServer: (serverId: string) => void;
@@ -28,6 +38,7 @@ interface StagedProviderSwitchState {
export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((set) => ({
stagedByKey: new Map(),
inFlightByKey: new Map(),
stage: (serverId, agentId, draft) =>
set((state) => {
@@ -48,6 +59,28 @@ export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((s
return { stagedByKey: next };
}),
beginSwitch: (serverId, agentId) =>
set((state) => {
const key = stagedKey(serverId, agentId);
const next = new Map(state.inFlightByKey);
next.set(key, (next.get(key) ?? 0) + 1);
return { inFlightByKey: next };
}),
endSwitch: (serverId, agentId) =>
set((state) => {
const key = stagedKey(serverId, agentId);
const count = state.inFlightByKey.get(key) ?? 0;
if (count <= 0) return state;
const next = new Map(state.inFlightByKey);
if (count === 1) {
next.delete(key);
} else {
next.set(key, count - 1);
}
return { inFlightByKey: next };
}),
settle: (serverId, agentId, sentDraft) =>
set((state) => {
const key = stagedKey(serverId, agentId);
@@ -78,7 +111,14 @@ export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((s
changed = true;
}
}
return changed ? { stagedByKey: next } : state;
const nextInFlight = new Map(state.inFlightByKey);
for (const key of nextInFlight.keys()) {
if (key.startsWith(prefix)) {
nextInFlight.delete(key);
changed = true;
}
}
return changed ? { stagedByKey: next, inFlightByKey: nextInFlight } : state;
}),
}));
@@ -91,6 +131,21 @@ export function getStagedProviderSwitch(
);
}
export function beginStagedProviderSwitch(serverId: string, agentId: string): void {
useStagedProviderSwitchStore.getState().beginSwitch(serverId, agentId);
}
export function endStagedProviderSwitch(serverId: string, agentId: string): void {
useStagedProviderSwitchStore.getState().endSwitch(serverId, agentId);
}
export function isStagedProviderSwitchInFlight(serverId: string, agentId: string): boolean {
return (
(useStagedProviderSwitchStore.getState().inFlightByKey.get(stagedKey(serverId, agentId)) ?? 0) >
0
);
}
export function settleStagedProviderSwitch(
serverId: string,
agentId: string,
@@ -99,6 +154,89 @@ export function settleStagedProviderSwitch(
useStagedProviderSwitchStore.getState().settle(serverId, agentId, sentDraft);
}
function diffProviderOptions(
sent: ProviderOptions,
edited: ProviderOptions,
): ProviderOptions | null {
const patch: ProviderOptions = {};
let hasDiff = false;
for (const [key, value] of Object.entries(edited)) {
if (sent[key] !== value) {
patch[key] = value;
hasDiff = true;
}
}
return hasDiff ? patch : null;
}
async function applyEditedDraftSettingsToLiveAgent(
agentId: string,
sentDraft: StagedProviderSwitch,
editedDraft: StagedProviderSwitch,
client: LiveAgentSettingsWriter,
): Promise<void> {
if (editedDraft.model !== sentDraft.model && client.setAgentModel) {
await client.setAgentModel(agentId, editedDraft.model).catch((error) => {
console.warn("[ProviderSwitch] failed to forward edited model after switch", error);
});
}
if (
editedDraft.modeId !== sentDraft.modeId &&
editedDraft.modeId !== null &&
client.setAgentMode
) {
await client.setAgentMode(agentId, editedDraft.modeId).catch((error) => {
console.warn("[ProviderSwitch] failed to forward edited mode after switch", error);
});
}
if (
editedDraft.thinkingOptionId !== sentDraft.thinkingOptionId &&
editedDraft.thinkingOptionId !== null &&
client.setAgentThinkingOption
) {
await client.setAgentThinkingOption(agentId, editedDraft.thinkingOptionId).catch((error) => {
console.warn("[ProviderSwitch] failed to forward edited thinking option after switch", error);
});
}
const optionsPatch = diffProviderOptions(sentDraft.providerOptions, editedDraft.providerOptions);
if (optionsPatch && client.setAgentOptions) {
await client.setAgentOptions(agentId, optionsPatch).catch((error) => {
console.warn(
"[ProviderSwitch] failed to forward edited provider options after switch",
error,
);
});
}
}
/**
* Settles the staged draft captured by a committed switch.
* - Untouched draft: cleared.
* - Newer draft targeting a different provider: preserved for the next switch.
* - Newer draft editing settings of the provider that just became live: settled and forwarded
* to the live agent so the next prompt uses the edited settings.
*/
export function settleCommittedProviderSwitch(input: {
serverId: string;
agentId: string;
sentDraft: StagedProviderSwitch;
committedProvider?: AgentProvider | null;
client?: LiveAgentSettingsWriter | null;
}): void {
const { serverId, agentId, sentDraft, committedProvider, client } = input;
const store = useStagedProviderSwitchStore.getState();
store.settle(serverId, agentId, sentDraft);
const remaining = getStagedProviderSwitch(serverId, agentId);
const liveProvider = committedProvider ?? sentDraft.provider;
if (!remaining || remaining.provider !== liveProvider) {
return;
}
store.settle(serverId, agentId, remaining);
if (client) {
void applyEditedDraftSettingsToLiveAgent(agentId, sentDraft, remaining, client);
}
}
export function clearStagedProviderSwitch(serverId: string, agentId: string): void {
useStagedProviderSwitchStore.getState().clear(serverId, agentId);
}
+49 -26
View File
@@ -83,7 +83,12 @@ import {
} from "@/desktop/browser/automation/handler";
import { schedulesQueryBaseKey } from "@/schedules/aggregated-schedules";
import { dispatchComposerAgentMessage, sendQueuedComposerMessageNow } from "@/composer/actions";
import { getStagedProviderSwitch, settleStagedProviderSwitch } from "@/composer/provider-switch";
import {
beginStagedProviderSwitch,
endStagedProviderSwitch,
getStagedProviderSwitch,
settleCommittedProviderSwitch,
} from "@/composer/provider-switch";
import { createMessageSubmissionWriter } from "@/composer/submission/writer";
import { resolveComposerAttachmentSubmitFormat } from "@/composer/attachments/submit";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
@@ -2900,6 +2905,7 @@ export class HostRuntimeStore {
}
this.queuedAgentDrainInFlight.add(drainKey);
this.queuedAgentDrainPending.delete(drainKey);
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
const next = queue[0];
let drainSent = false;
void sendQueuedComposerMessageNow({
@@ -2921,37 +2927,54 @@ export class HostRuntimeStore {
: null;
const stagedProviderSwitch =
rawStagedSwitch && rawStagedSwitch.provider !== liveProvider ? rawStagedSwitch : null;
await dispatchComposerAgentMessage({
client,
agentId,
text,
attachments,
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
supportsForgeAttachments,
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
stagedProviderSwitch,
onProviderSwitchCommitted: (agent) => {
if (stagedProviderSwitch) {
settleStagedProviderSwitch(serverId, agentId, stagedProviderSwitch);
}
if (agent) {
this.tryAcceptAgentSnapshot(serverId, normalizeAgentSnapshot(agent, serverId));
}
},
// The queue drains when the agent goes idle, but the agent can start a turn of its own
// in that same moment (a wake-up after background work). Steering folds the message
// into that turn instead of interrupting it; with no turn running, the daemon starts
// a normal one.
activeTurnBehavior: "steer",
});
if (stagedProviderSwitch) {
beginStagedProviderSwitch(serverId, agentId);
}
try {
await dispatchComposerAgentMessage({
client,
agentId,
text,
attachments,
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
supportsForgeAttachments,
}),
encodeImages,
submission: createMessageSubmissionWriter(serverId),
stagedProviderSwitch,
onProviderSwitchCommitted: (agent) => {
if (stagedProviderSwitch) {
settleCommittedProviderSwitch({
serverId,
agentId,
sentDraft: stagedProviderSwitch,
committedProvider: agent?.provider ?? null,
client,
});
}
if (agent) {
this.tryAcceptAgentSnapshot(serverId, normalizeAgentSnapshot(agent, serverId));
}
},
// The queue drains when the agent goes idle, but the agent can start a turn of its own
// in that same moment (a wake-up after background work). Steering folds the message
// into that turn instead of interrupting it; with no turn running, the daemon starts
// a normal one.
activeTurnBehavior: "steer",
});
} finally {
if (stagedProviderSwitch) {
endStagedProviderSwitch(serverId, agentId);
}
}
},
})
.then((result) => {
if (result.status === "submitted") {
drainSent = true;
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
} else if (result.status === "failed") {
useSessionStore.getState().setQueuedSendError(serverId, agentId, result.errorMessage);
console.error("[HostRuntime] failed to drain queued agent message", {
serverId,
agentId,
+29
View File
@@ -536,6 +536,7 @@ export interface SessionState {
string,
Array<{ id: string; text: string; attachments: ComposerAttachment[] }>
>;
queuedSendErrors: Map<string, string>;
}
// Global store state
@@ -727,6 +728,7 @@ interface SessionStoreActions {
prev: Map<string, Array<{ id: string; text: string; attachments: ComposerAttachment[] }>>,
) => Map<string, Array<{ id: string; text: string; attachments: ComposerAttachment[] }>>),
) => void;
setQueuedSendError: (serverId: string, agentId: string, error: string | null) => void;
// Hydration
setHasHydratedAgents: (serverId: string, hydrated: boolean) => void;
@@ -782,6 +784,7 @@ function createInitialSessionState(
pendingPermissions: new Map(),
fileExplorer: new Map(),
queuedMessages: new Map(),
queuedSendErrors: new Map(),
};
}
@@ -1977,6 +1980,32 @@ export const useSessionStore = create<SessionStore>()(
});
},
setQueuedSendError: (serverId, agentId, error) => {
set((prev) => {
const session = prev.sessions[serverId];
if (!session) {
return prev;
}
const existing = session.queuedSendErrors.get(agentId) ?? null;
if (existing === error) {
return prev;
}
const next = new Map(session.queuedSendErrors);
if (error === null) {
next.delete(agentId);
} else {
next.set(agentId, error);
}
return {
...prev,
sessions: {
...prev.sessions,
[serverId]: { ...session, queuedSendErrors: next },
},
};
});
},
// Hydration
setHasHydratedAgents: (serverId, hydrated) => {
set((prev) => {
@@ -2616,6 +2616,30 @@ export class AgentManager {
return commitResult.row.seq;
}
private async buildActiveSwitchHandoff(
scope: TimelineScope,
existingLive: ActiveManagedAgent | null,
source: { fromProvider: AgentProvider; persistedTitle: string | null; cwd: string },
toProvider: AgentProvider,
) {
if (existingLive) {
await this.settleOpenRewind(existingLive, { judge: false });
}
const tail = await this.timeline.fetch(scope, {
direction: "tail",
limit: HANDOFF_TAIL_LIMIT,
wholeTurns: true,
});
return buildProviderSwitchHandoff({
rows: tail.rows,
hasOlder: tail.hasOlder,
fromProvider: source.fromProvider,
toProvider,
agentTitle: source.persistedTitle,
cwd: source.cwd,
});
}
private async switchAgentProviderUnlocked(
agentId: string,
input: SwitchAgentProviderInput,
@@ -2644,19 +2668,6 @@ export class AgentManager {
this.requireEnabledProvider(input.toProvider);
const targetClient = await this.requireAvailableClient({ provider: input.toProvider });
const tail = await this.timeline.fetch(scope, {
direction: "tail",
limit: HANDOFF_TAIL_LIMIT,
wholeTurns: true,
});
const handoff = buildProviderSwitchHandoff({
rows: tail.rows,
hasOlder: tail.hasOlder,
fromProvider: source.fromProvider,
toProvider: input.toProvider,
agentTitle: source.persistedTitle,
cwd: source.cwd,
});
const targetConfig = buildSwitchTargetSessionConfig(input, source);
const hadPreviousPaseoToolPolicy = this.paseoToolPolicies.has(agentId);
@@ -2712,10 +2723,19 @@ export class AgentManager {
);
// Re-verify idle right before committing/closing the source session, then immediately
// reserve the foreground run slot without yielding so no turn can sneak in.
// reserve the foreground run slot without yielding so no turn or rewind can sneak in.
this.assertSourceAgentIdleForSwitch(agentId, existingLive);
switchRunLock = this.runs.createPendingRun(agentId);
// Read handoff AFTER reserving the foreground turn slot and settling any open rewind so
// the marker context and first prompt reflect the exact active history.
const handoff = await this.buildActiveSwitchHandoff(
scope,
existingLive,
source,
input.toProvider,
);
intent = await this.timeline.beginProviderSwitch(scope, {
messageId: input.messageId,
fromProvider: source.fromProvider,
@@ -128,6 +128,9 @@ class E2EFakeSession implements AgentSession {
async close(): Promise<void> {
this.closed = true;
}
async revertConversation(): Promise<{ kind: "at_target" }> {
return { kind: "at_target" };
}
}
class E2EFakeClient implements AgentClient {
@@ -573,4 +576,81 @@ describe("Provider switching WebSocket RPC, receipts, and capability gating", ()
),
).toBe(true);
});
it("excludes turns rewound during target session startup from the switch handoff", async () => {
const cwd = mkdtempSync(join(tmpdir(), "paseo-provider-switch-rewind-race-e2e-"));
onTestFinished(() => rmSync(cwd, { recursive: true, force: true }));
const claude = new E2EFakeClient("claude");
const codex = new E2EFakeClient("codex", true);
daemon = await createTestPaseoDaemon({
agentClients: { claude, codex },
});
const url = `ws://127.0.0.1:${daemon.port}/ws`;
const client1 = await connectClient(url);
const client2 = await connectClient(url);
const agent = await client1.client.createAgent({ provider: "claude", cwd });
await client1.client.sendMessage(agent.id, "Keep this requirement", undefined, {
messageId: "msg-rw-1",
});
await new Promise((resolve) => setTimeout(resolve, 100));
await client1.client.sendMessage(agent.id, "Discard this requirement", undefined, {
messageId: "msg-rw-2",
});
await new Promise((resolve) => setTimeout(resolve, 100));
const beforeRewind = await client1.client.fetchAgentTimeline(agent.id, {
direction: "tail",
limit: 50,
});
const discardRow = beforeRewind.entries.find(
(e) => e.item.type === "user_message" && e.item.text === "Discard this requirement",
);
expect(discardRow?.item.type).toBe("user_message");
const discardMessageId =
discardRow?.item.type === "user_message" ? discardRow.item.messageId : undefined;
expect(discardMessageId).toBeTruthy();
let resolveCodexCreate!: () => void;
codex.createSessionGate = new Promise<void>((resolve) => {
resolveCodexCreate = resolve;
});
let resolveCodexCreateStarted!: () => void;
const codexCreateStarted = new Promise<void>((resolve) => {
resolveCodexCreateStarted = resolve;
});
codex.onCreateSessionStarted = resolveCodexCreateStarted;
// Client 1 begins switching to Codex; target startup pauses.
const switchPromise = client1.client.switchAgentProvider(agent.id, {
provider: "codex",
text: "Continue on Codex",
messageId: "msg-rw-sw",
});
await codexCreateStarted;
try {
// Client 2 rewinds the second Claude turn while Codex is still opening.
const rewindResp = await client2.client.rewindAgent(
agent.id,
discardMessageId!,
"conversation",
);
expect(rewindResp.ok).toBe(true);
} finally {
// Always release Codex session startup so daemon teardown never hangs on failure.
resolveCodexCreate();
}
const switched = await switchPromise;
expect(switched.agent?.provider).toBe("codex");
await new Promise((resolve) => setTimeout(resolve, 100));
// Codex's first prompt handoff MUST contain the kept turn and MUST NOT contain the rewound turn.
expect(codex.sessions).toHaveLength(1);
const firstCodexPrompt = renderProviderPromptText(codex.sessions[0].receivedPrompts[0]);
expect(firstCodexPrompt).toContain("Keep this requirement");
expect(firstCodexPrompt).not.toContain("Discard this requirement");
});
});