mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
fix(app): await atomic startup settings application before draining queued follow-up
This commit is contained in:
@@ -218,7 +218,7 @@ export interface DispatchComposerAgentMessageInput {
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
activeTurnId?: string;
|
||||
stagedProviderSwitch?: StagedProviderSwitch | null;
|
||||
onProviderSwitchCommitted?: (agent: AgentSnapshotPayload | undefined) => void;
|
||||
onProviderSwitchCommitted?: (agent: AgentSnapshotPayload | undefined) => void | Promise<void>;
|
||||
}
|
||||
|
||||
export async function dispatchComposerAgentMessage(
|
||||
@@ -253,8 +253,8 @@ export async function dispatchComposerAgentMessage(
|
||||
images: imagesData ?? [],
|
||||
attachments: wirePayload.attachments,
|
||||
});
|
||||
input.onProviderSwitchCommitted?.(result.agent);
|
||||
input.submission.accept(input.agentId, clientMessageId);
|
||||
await input.onProviderSwitchCommitted?.(result.agent);
|
||||
return;
|
||||
}
|
||||
await input.client.sendAgentMessage(input.agentId, input.text, {
|
||||
@@ -267,7 +267,7 @@ export async function dispatchComposerAgentMessage(
|
||||
} catch (error) {
|
||||
input.submission.reject(input.agentId, clientMessageId);
|
||||
if (error instanceof AgentProviderSwitchError && error.agent) {
|
||||
input.onProviderSwitchCommitted?.(error.agent);
|
||||
await input.onProviderSwitchCommitted?.(error.agent);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
clearStagedProviderSwitch,
|
||||
endStagedProviderSwitch,
|
||||
getStagedProviderSwitch,
|
||||
hasRetainedProviderSwitchEditFailure,
|
||||
isStagedProviderSwitchInFlight,
|
||||
settleCommittedProviderSwitch,
|
||||
useStagedProviderSwitch,
|
||||
@@ -1399,7 +1400,8 @@ function ComposerContentImpl({
|
||||
rawStagedSwitch &&
|
||||
agentState.provider &&
|
||||
rawStagedSwitch.provider === agentState.provider &&
|
||||
!isStagedProviderSwitchInFlight(serverId, agentId)
|
||||
!isStagedProviderSwitchInFlight(serverId, agentId) &&
|
||||
!hasRetainedProviderSwitchEditFailure(serverId, agentId)
|
||||
) {
|
||||
clearStagedProviderSwitch(serverId, agentId);
|
||||
}
|
||||
@@ -1793,21 +1795,24 @@ function ComposerContentImpl({
|
||||
encodeImages,
|
||||
submission: createMessageSubmissionWriter(serverId),
|
||||
stagedProviderSwitch,
|
||||
onProviderSwitchCommitted: (agent) => {
|
||||
onProviderSwitchCommitted: async (agent) => {
|
||||
if (agent) {
|
||||
getHostRuntimeStore().tryAcceptAgentSnapshot(
|
||||
serverId,
|
||||
normalizeAgentSnapshot(agent, serverId),
|
||||
);
|
||||
}
|
||||
if (stagedProviderSwitch) {
|
||||
settleCommittedProviderSwitch({
|
||||
const settled = await settleCommittedProviderSwitch({
|
||||
serverId,
|
||||
agentId: targetAgentId,
|
||||
sentDraft: stagedProviderSwitch,
|
||||
committedProvider: agent?.provider ?? null,
|
||||
client,
|
||||
});
|
||||
}
|
||||
if (agent) {
|
||||
getHostRuntimeStore().tryAcceptAgentSnapshot(
|
||||
serverId,
|
||||
normalizeAgentSnapshot(agent, serverId),
|
||||
);
|
||||
if (!settled.applied) {
|
||||
setSendError(settled.errorMessage);
|
||||
}
|
||||
}
|
||||
},
|
||||
activeTurnBehavior,
|
||||
|
||||
@@ -3,11 +3,13 @@ export {
|
||||
clearStagedProviderSwitch,
|
||||
endStagedProviderSwitch,
|
||||
getStagedProviderSwitch,
|
||||
hasRetainedProviderSwitchEditFailure,
|
||||
isStagedProviderSwitchInFlight,
|
||||
settleCommittedProviderSwitch,
|
||||
settleStagedProviderSwitch,
|
||||
useStagedProviderSwitch,
|
||||
useStagedProviderSwitchStore,
|
||||
type LiveAgentSettingsWriter,
|
||||
type SettleCommittedProviderSwitchResult,
|
||||
type StagedProviderSwitch,
|
||||
} from "./store";
|
||||
|
||||
@@ -121,7 +121,9 @@ describe("app provider switching integration", () => {
|
||||
encodeImages: async () => [],
|
||||
submission,
|
||||
stagedProviderSwitch: staged,
|
||||
onProviderSwitchCommitted: (agent) => committed.push(agent),
|
||||
onProviderSwitchCommitted: (agent) => {
|
||||
committed.push(agent);
|
||||
},
|
||||
});
|
||||
|
||||
expect(sendAgentMessage).not.toHaveBeenCalled();
|
||||
@@ -141,7 +143,9 @@ describe("app provider switching integration", () => {
|
||||
encodeImages: async () => [],
|
||||
submission,
|
||||
stagedProviderSwitch: staged,
|
||||
onProviderSwitchCommitted: (agent) => committed.push(agent),
|
||||
onProviderSwitchCommitted: (agent) => {
|
||||
committed.push(agent);
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("Codex CLI unavailable");
|
||||
expect(committed).toEqual([]);
|
||||
@@ -159,7 +163,9 @@ describe("app provider switching integration", () => {
|
||||
encodeImages: async () => [],
|
||||
submission,
|
||||
stagedProviderSwitch: staged,
|
||||
onProviderSwitchCommitted: (agent) => committed.push(agent),
|
||||
onProviderSwitchCommitted: (agent) => {
|
||||
committed.push(agent);
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("Rate limited");
|
||||
expect(committed).toEqual([expect.objectContaining({ provider: "codex" })]);
|
||||
@@ -889,4 +895,181 @@ describe("app provider switching integration", () => {
|
||||
|
||||
sessionStore.clearSession(serverId);
|
||||
});
|
||||
|
||||
it("holds queued follow-up M2 until edited startup settings (including plan_mode) finish applying, and retains the draft if an edit rejects", async () => {
|
||||
const serverId = "srv-startup-edit-ordering";
|
||||
const callOrder: string[] = [];
|
||||
let resolveSwitch!: (value: { agent?: AgentSnapshotPayload }) => void;
|
||||
let resolveApplyConfig!: () => void;
|
||||
let rejectApplyConfig: ((err: Error) => void) | null = null;
|
||||
|
||||
const fakeClient = {
|
||||
switchAgentProvider: vi.fn((_agentId: string, _opts: { provider: string; text: string }) => {
|
||||
callOrder.push("switch:codex");
|
||||
return new Promise<{ agent?: AgentSnapshotPayload }>((resolve) => {
|
||||
resolveSwitch = resolve;
|
||||
});
|
||||
}),
|
||||
applyAgentConfig: vi.fn((_agentId: string, config: unknown, opts?: unknown) => {
|
||||
callOrder.push(`applyConfig:${JSON.stringify({ config, opts })}`);
|
||||
return new Promise<null>((resolve, reject) => {
|
||||
resolveApplyConfig = () => resolve(null);
|
||||
rejectApplyConfig = reject;
|
||||
});
|
||||
}),
|
||||
sendAgentMessage: vi.fn(async (_agentId: string, text: string) => {
|
||||
callOrder.push(`send:${text}`);
|
||||
return { messageId: "m2-ack" };
|
||||
}),
|
||||
uploadFile: vi.fn(),
|
||||
} as unknown as DaemonClient;
|
||||
|
||||
const runtime = new HostRuntimeStore({
|
||||
deps: {
|
||||
createClient: () => fakeClient,
|
||||
connectToDaemon: async () => ({ client: fakeClient, serverId, hostname: null }),
|
||||
getClientId: async () => "cid_startup_edit_ordering",
|
||||
},
|
||||
});
|
||||
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 prompt", attachments: [] },
|
||||
{ id: "m2", text: "Follow-up in Plan mode", attachments: [] },
|
||||
],
|
||||
],
|
||||
]),
|
||||
);
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3",
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: { plan_mode: false },
|
||||
});
|
||||
|
||||
// M1 starts switching; while Codex opens, user changes model AND enables plan_mode.
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
await vi.waitFor(() => {
|
||||
expect(callOrder).toEqual(["switch:codex"]);
|
||||
});
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, "agent-1", (current) => ({
|
||||
...current,
|
||||
model: "gpt-5.4",
|
||||
providerOptions: { plan_mode: true },
|
||||
}));
|
||||
|
||||
// Fast turn finishes idle and triggers queue drain BEFORE switch + settings edits complete.
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
resolveSwitch({ agent: { ...agentSnapshot("codex"), status: "idle" } });
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(callOrder).toHaveLength(2);
|
||||
});
|
||||
// M2 MUST NOT have sent yet while applyAgentConfig (model + plan_mode: true) is still pending!
|
||||
expect(callOrder.some((entry) => entry.startsWith("send:"))).toBe(false);
|
||||
|
||||
// Once applyAgentConfig completes, M2 drains strictly AFTER plan_mode: true took effect!
|
||||
resolveApplyConfig();
|
||||
await vi.waitFor(() => {
|
||||
expect(callOrder).toHaveLength(3);
|
||||
});
|
||||
expect(callOrder[1]).toContain('"plan_mode":true');
|
||||
expect(callOrder[1]).toContain('"modelId":"gpt-5.4"');
|
||||
expect(callOrder[1]).toContain('"expectedProvider":"codex"');
|
||||
expect(callOrder[2]).toBe("send:Follow-up in Plan mode");
|
||||
expect(getStagedProviderSwitch(serverId, "agent-1")).toBeNull();
|
||||
|
||||
// Case 2: If daemon rejects the edited settings, draft is RETAINED, error is surfaced, and M2 is HELD.
|
||||
callOrder.length = 0;
|
||||
sessionStore.setQueuedMessages(
|
||||
serverId,
|
||||
new Map([
|
||||
[
|
||||
"agent-1",
|
||||
[
|
||||
{ id: "m3", text: "Switch with rejected edit", attachments: [] },
|
||||
{ id: "m4", text: "Must stay queued", attachments: [] },
|
||||
],
|
||||
],
|
||||
]),
|
||||
);
|
||||
useStagedProviderSwitchStore.getState().stage(serverId, "agent-1", {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3",
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: { plan_mode: false },
|
||||
});
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
await vi.waitFor(() => {
|
||||
expect(callOrder).toEqual(["switch:codex"]);
|
||||
});
|
||||
useStagedProviderSwitchStore.getState().patch(serverId, "agent-1", (current) => ({
|
||||
...current,
|
||||
providerOptions: { plan_mode: true },
|
||||
}));
|
||||
runtime.drainQueuedAgentMessage(serverId, "agent-1");
|
||||
resolveSwitch({ agent: { ...agentSnapshot("codex"), status: "idle" } });
|
||||
await vi.waitFor(() => {
|
||||
expect(callOrder).toHaveLength(2);
|
||||
});
|
||||
|
||||
rejectApplyConfig!(new Error("Plan mode rejected by provider"));
|
||||
await vi.waitFor(() => {
|
||||
expect(useSessionStore.getState().sessions[serverId]?.queuedSendErrors.get("agent-1")).toBe(
|
||||
"Plan mode rejected by provider",
|
||||
);
|
||||
});
|
||||
expect(getStagedProviderSwitch(serverId, "agent-1")?.providerOptions).toEqual({
|
||||
plan_mode: true,
|
||||
});
|
||||
// M4 MUST NOT have drained after settings rejection!
|
||||
expect(callOrder.some((entry) => entry.startsWith("send:"))).toBe(false);
|
||||
expect(useSessionStore.getState().sessions[serverId]?.queuedMessages.get("agent-1")).toEqual([
|
||||
{ id: "m4", text: "Must stay queued", attachments: [] },
|
||||
]);
|
||||
|
||||
sessionStore.clearSession(serverId);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { create } from "zustand";
|
||||
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentConfigApply } from "@getpaseo/protocol/messages";
|
||||
|
||||
export interface StagedProviderSwitch {
|
||||
provider: AgentProvider;
|
||||
@@ -14,6 +15,11 @@ function stagedKey(serverId: string, agentId: string): string {
|
||||
}
|
||||
|
||||
export interface LiveAgentSettingsWriter {
|
||||
applyAgentConfig?: (
|
||||
agentId: string,
|
||||
config: AgentConfigApply,
|
||||
options?: { expectedProvider?: AgentProvider },
|
||||
) => Promise<unknown>;
|
||||
setAgentModel?: (
|
||||
agentId: string,
|
||||
modelId: string | null,
|
||||
@@ -36,9 +42,14 @@ export interface LiveAgentSettingsWriter {
|
||||
) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export type SettleCommittedProviderSwitchResult =
|
||||
| { applied: true }
|
||||
| { applied: false; errorMessage: string };
|
||||
|
||||
interface StagedProviderSwitchState {
|
||||
stagedByKey: Map<string, StagedProviderSwitch>;
|
||||
inFlightByKey: Map<string, number>;
|
||||
retainedOnEditFailureByKey: Set<string>;
|
||||
stage: (serverId: string, agentId: string, draft: StagedProviderSwitch) => void;
|
||||
patch: (
|
||||
serverId: string,
|
||||
@@ -47,6 +58,7 @@ interface StagedProviderSwitchState {
|
||||
) => void;
|
||||
beginSwitch: (serverId: string, agentId: string) => void;
|
||||
endSwitch: (serverId: string, agentId: string) => void;
|
||||
markRetainedOnEditFailure: (serverId: string, agentId: string) => void;
|
||||
settle: (serverId: string, agentId: string, sentDraft: StagedProviderSwitch) => void;
|
||||
clear: (serverId: string, agentId: string) => void;
|
||||
clearForServer: (serverId: string) => void;
|
||||
@@ -55,12 +67,16 @@ interface StagedProviderSwitchState {
|
||||
export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((set) => ({
|
||||
stagedByKey: new Map(),
|
||||
inFlightByKey: new Map(),
|
||||
retainedOnEditFailureByKey: new Set(),
|
||||
|
||||
stage: (serverId, agentId, draft) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.set(stagedKey(serverId, agentId), draft);
|
||||
return { stagedByKey: next };
|
||||
next.set(key, draft);
|
||||
const nextRetained = new Set(state.retainedOnEditFailureByKey);
|
||||
nextRetained.delete(key);
|
||||
return { stagedByKey: next, retainedOnEditFailureByKey: nextRetained };
|
||||
}),
|
||||
|
||||
patch: (serverId, agentId, updater) =>
|
||||
@@ -72,7 +88,9 @@ export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((s
|
||||
if (updated === current) return state;
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.set(key, updated);
|
||||
return { stagedByKey: next };
|
||||
const nextRetained = new Set(state.retainedOnEditFailureByKey);
|
||||
nextRetained.delete(key);
|
||||
return { stagedByKey: next, retainedOnEditFailureByKey: nextRetained };
|
||||
}),
|
||||
|
||||
beginSwitch: (serverId, agentId) =>
|
||||
@@ -97,6 +115,15 @@ export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((s
|
||||
return { inFlightByKey: next };
|
||||
}),
|
||||
|
||||
markRetainedOnEditFailure: (serverId, agentId) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
if (state.retainedOnEditFailureByKey.has(key)) return state;
|
||||
const next = new Set(state.retainedOnEditFailureByKey);
|
||||
next.add(key);
|
||||
return { retainedOnEditFailureByKey: next };
|
||||
}),
|
||||
|
||||
settle: (serverId, agentId, sentDraft) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
@@ -104,16 +131,20 @@ export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((s
|
||||
if (!current || current !== sentDraft) return state;
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.delete(key);
|
||||
return { stagedByKey: next };
|
||||
const nextRetained = new Set(state.retainedOnEditFailureByKey);
|
||||
nextRetained.delete(key);
|
||||
return { stagedByKey: next, retainedOnEditFailureByKey: nextRetained };
|
||||
}),
|
||||
|
||||
clear: (serverId, agentId) =>
|
||||
set((state) => {
|
||||
const key = stagedKey(serverId, agentId);
|
||||
if (!state.stagedByKey.has(key)) return state;
|
||||
if (!state.stagedByKey.has(key) && !state.retainedOnEditFailureByKey.has(key)) return state;
|
||||
const next = new Map(state.stagedByKey);
|
||||
next.delete(key);
|
||||
return { stagedByKey: next };
|
||||
const nextRetained = new Set(state.retainedOnEditFailureByKey);
|
||||
nextRetained.delete(key);
|
||||
return { stagedByKey: next, retainedOnEditFailureByKey: nextRetained };
|
||||
}),
|
||||
|
||||
clearForServer: (serverId) =>
|
||||
@@ -134,7 +165,20 @@ export const useStagedProviderSwitchStore = create<StagedProviderSwitchState>((s
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed ? { stagedByKey: next, inFlightByKey: nextInFlight } : state;
|
||||
const nextRetained = new Set(state.retainedOnEditFailureByKey);
|
||||
for (const key of nextRetained) {
|
||||
if (key.startsWith(prefix)) {
|
||||
nextRetained.delete(key);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed
|
||||
? {
|
||||
stagedByKey: next,
|
||||
inFlightByKey: nextInFlight,
|
||||
retainedOnEditFailureByKey: nextRetained,
|
||||
}
|
||||
: state;
|
||||
}),
|
||||
}));
|
||||
|
||||
@@ -162,6 +206,12 @@ export function isStagedProviderSwitchInFlight(serverId: string, agentId: string
|
||||
);
|
||||
}
|
||||
|
||||
export function hasRetainedProviderSwitchEditFailure(serverId: string, agentId: string): boolean {
|
||||
return useStagedProviderSwitchStore
|
||||
.getState()
|
||||
.retainedOnEditFailureByKey.has(stagedKey(serverId, agentId));
|
||||
}
|
||||
|
||||
export function settleStagedProviderSwitch(
|
||||
serverId: string,
|
||||
agentId: string,
|
||||
@@ -185,78 +235,103 @@ function diffProviderOptions(
|
||||
return hasDiff ? patch : null;
|
||||
}
|
||||
|
||||
async function applyEditedDraftSettingsToLiveAgent(
|
||||
agentId: string,
|
||||
function buildEditedSettingsBundle(
|
||||
sentDraft: StagedProviderSwitch,
|
||||
editedDraft: StagedProviderSwitch,
|
||||
): AgentConfigApply | null {
|
||||
const config: AgentConfigApply = {};
|
||||
let hasChanges = false;
|
||||
if (editedDraft.model !== sentDraft.model) {
|
||||
config.modelId = editedDraft.model;
|
||||
hasChanges = true;
|
||||
}
|
||||
if (editedDraft.modeId !== sentDraft.modeId && editedDraft.modeId !== null) {
|
||||
config.modeId = editedDraft.modeId;
|
||||
hasChanges = true;
|
||||
}
|
||||
if (
|
||||
editedDraft.thinkingOptionId !== sentDraft.thinkingOptionId &&
|
||||
editedDraft.thinkingOptionId !== null
|
||||
) {
|
||||
config.thinkingOptionId = editedDraft.thinkingOptionId;
|
||||
hasChanges = true;
|
||||
}
|
||||
const optionsPatch = diffProviderOptions(sentDraft.providerOptions, editedDraft.providerOptions);
|
||||
if (optionsPatch) {
|
||||
config.options = optionsPatch;
|
||||
hasChanges = true;
|
||||
}
|
||||
return hasChanges ? config : null;
|
||||
}
|
||||
|
||||
async function applyEditedDraftSettingsToLiveAgent(
|
||||
agentId: string,
|
||||
bundle: AgentConfigApply,
|
||||
expectedProvider: AgentProvider,
|
||||
client: LiveAgentSettingsWriter,
|
||||
): Promise<void> {
|
||||
const providerGuard = { expectedProvider };
|
||||
if (editedDraft.model !== sentDraft.model && client.setAgentModel) {
|
||||
await client.setAgentModel(agentId, editedDraft.model, providerGuard).catch((error) => {
|
||||
console.warn("[ProviderSwitch] failed to forward edited model after switch", error);
|
||||
});
|
||||
if (client.applyAgentConfig) {
|
||||
await client.applyAgentConfig(agentId, bundle, providerGuard);
|
||||
return;
|
||||
}
|
||||
if (bundle.modelId !== undefined && client.setAgentModel) {
|
||||
await client.setAgentModel(agentId, bundle.modelId, providerGuard);
|
||||
}
|
||||
if (bundle.modeId !== undefined && client.setAgentMode) {
|
||||
await client.setAgentMode(agentId, bundle.modeId, providerGuard);
|
||||
}
|
||||
if (
|
||||
editedDraft.modeId !== sentDraft.modeId &&
|
||||
editedDraft.modeId !== null &&
|
||||
client.setAgentMode
|
||||
) {
|
||||
await client.setAgentMode(agentId, editedDraft.modeId, providerGuard).catch((error) => {
|
||||
console.warn("[ProviderSwitch] failed to forward edited mode after switch", error);
|
||||
});
|
||||
}
|
||||
if (
|
||||
editedDraft.thinkingOptionId !== sentDraft.thinkingOptionId &&
|
||||
editedDraft.thinkingOptionId !== null &&
|
||||
bundle.thinkingOptionId !== undefined &&
|
||||
bundle.thinkingOptionId !== null &&
|
||||
client.setAgentThinkingOption
|
||||
) {
|
||||
await client
|
||||
.setAgentThinkingOption(agentId, editedDraft.thinkingOptionId, providerGuard)
|
||||
.catch((error) => {
|
||||
console.warn(
|
||||
"[ProviderSwitch] failed to forward edited thinking option after switch",
|
||||
error,
|
||||
);
|
||||
});
|
||||
await client.setAgentThinkingOption(agentId, bundle.thinkingOptionId, providerGuard);
|
||||
}
|
||||
const optionsPatch = diffProviderOptions(sentDraft.providerOptions, editedDraft.providerOptions);
|
||||
if (optionsPatch && client.setAgentOptions) {
|
||||
await client.setAgentOptions(agentId, optionsPatch, providerGuard).catch((error) => {
|
||||
console.warn(
|
||||
"[ProviderSwitch] failed to forward edited provider options after switch",
|
||||
error,
|
||||
);
|
||||
});
|
||||
if (bundle.options && client.setAgentOptions) {
|
||||
await client.setAgentOptions(agentId, bundle.options, providerGuard);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Settles the staged draft captured by a committed switch.
|
||||
* Settles the staged draft captured by a committed switch and awaits any edited settings
|
||||
* for the provider that just became live before callers release queued follow-up prompts.
|
||||
* - 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.
|
||||
* - Newer draft editing settings of the provider that just became live: applied atomically
|
||||
* (via `applyAgentConfig` when available, else sequential setters) before settling the draft.
|
||||
* If the daemon rejects an edit, the draft is kept intact and `{ applied: false, errorMessage }`
|
||||
* is returned so callers surface the error and hold any queued follow-up prompt.
|
||||
*/
|
||||
export function settleCommittedProviderSwitch(input: {
|
||||
export async function settleCommittedProviderSwitch(input: {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
sentDraft: StagedProviderSwitch;
|
||||
committedProvider?: AgentProvider | null;
|
||||
client?: LiveAgentSettingsWriter | null;
|
||||
}): void {
|
||||
}): Promise<SettleCommittedProviderSwitchResult> {
|
||||
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;
|
||||
return { applied: true };
|
||||
}
|
||||
store.settle(serverId, agentId, remaining);
|
||||
if (client) {
|
||||
void applyEditedDraftSettingsToLiveAgent(agentId, sentDraft, remaining, liveProvider, client);
|
||||
const bundle = buildEditedSettingsBundle(sentDraft, remaining);
|
||||
if (!bundle || !client) {
|
||||
store.settle(serverId, agentId, remaining);
|
||||
return { applied: true };
|
||||
}
|
||||
try {
|
||||
await applyEditedDraftSettingsToLiveAgent(agentId, bundle, liveProvider, client);
|
||||
store.settle(serverId, agentId, remaining);
|
||||
return { applied: true };
|
||||
} catch (error) {
|
||||
store.markRetainedOnEditFailure(serverId, agentId);
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
console.warn("[ProviderSwitch] failed to forward edited settings after switch", error);
|
||||
return { applied: false, errorMessage };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2908,6 +2908,7 @@ export class HostRuntimeStore {
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
|
||||
const next = queue[0];
|
||||
let drainSent = false;
|
||||
let drainBlockedBySettingsError: string | null = null;
|
||||
void sendQueuedComposerMessageNow({
|
||||
agentId,
|
||||
messageId: next.id,
|
||||
@@ -2942,18 +2943,21 @@ export class HostRuntimeStore {
|
||||
encodeImages,
|
||||
submission: createMessageSubmissionWriter(serverId),
|
||||
stagedProviderSwitch,
|
||||
onProviderSwitchCommitted: (agent) => {
|
||||
onProviderSwitchCommitted: async (agent) => {
|
||||
if (agent) {
|
||||
this.tryAcceptAgentSnapshot(serverId, normalizeAgentSnapshot(agent, serverId));
|
||||
}
|
||||
if (stagedProviderSwitch) {
|
||||
settleCommittedProviderSwitch({
|
||||
const settled = await settleCommittedProviderSwitch({
|
||||
serverId,
|
||||
agentId,
|
||||
sentDraft: stagedProviderSwitch,
|
||||
committedProvider: agent?.provider ?? null,
|
||||
client,
|
||||
});
|
||||
}
|
||||
if (agent) {
|
||||
this.tryAcceptAgentSnapshot(serverId, normalizeAgentSnapshot(agent, serverId));
|
||||
if (!settled.applied) {
|
||||
drainBlockedBySettingsError = settled.errorMessage;
|
||||
}
|
||||
}
|
||||
},
|
||||
// The queue drains when the agent goes idle, but the agent can start a turn of its own
|
||||
@@ -2971,8 +2975,10 @@ export class HostRuntimeStore {
|
||||
})
|
||||
.then((result) => {
|
||||
if (result.status === "submitted") {
|
||||
drainSent = true;
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, null);
|
||||
drainSent = drainBlockedBySettingsError === null;
|
||||
useSessionStore
|
||||
.getState()
|
||||
.setQueuedSendError(serverId, agentId, drainBlockedBySettingsError);
|
||||
} else if (result.status === "failed") {
|
||||
useSessionStore.getState().setQueuedSendError(serverId, agentId, result.errorMessage);
|
||||
console.error("[HostRuntime] failed to drain queued agent message", {
|
||||
|
||||
Reference in New Issue
Block a user