feat(FN-1191): hot-swap active executor sessions on model changes

- Show resolved default executor, validator, and planning models in the task Model tab
- Pass merged settings into the Model tab from TaskDetailModal so default badges reflect effective runtime resolution
- Hot-swap active single-session executor models when task overrides change, including fallback to project defaults when overrides are cleared
- Add dashboard and executor tests for default model display, hot-swap behavior, fallback logic, and failure logging
- Document hot-swap behavior and limitations in AGENTS.md and add a patch changeset for @gsxdsm/fusion
This commit is contained in:
gsxdsm
2026-04-08 01:18:01 -07:00
parent bd601959b6
commit d30419d70b
7 changed files with 428 additions and 10 deletions

View File

@@ -88,6 +88,14 @@ vi.mock("@mariozechner/pi-coding-agent", () => {
open: vi.fn().mockReturnValue(mockSessionManager),
inMemory: vi.fn().mockReturnValue(mockSessionManager),
},
ModelRegistry: vi.fn().mockImplementation(() => ({
find: vi.fn(),
refresh: vi.fn(),
})),
AuthStorage: {
create: vi.fn().mockReturnValue({}),
},
getAgentDir: vi.fn().mockReturnValue("/tmp/agent-dir"),
};
});
@@ -2812,6 +2820,196 @@ describe("TaskExecutor pause behavior", () => {
});
});
describe("TaskExecutor executor model hot-swap", () => {
const buildUpdatedTask = (overrides: Partial<Task> = {}): Task => ({
id: "FN-001",
title: "Model task",
description: "Test model updates",
column: "in-progress",
paused: false,
dependencies: [],
steps: [],
currentStep: 0,
log: [],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
...overrides,
});
const flushTaskUpdated = async () => {
await new Promise((resolve) => setTimeout(resolve, 20));
};
beforeEach(() => {
vi.clearAllMocks();
});
it("hot-swaps executor model on active session when modelProvider/modelId change", async () => {
const store = createMockStore();
const setModel = vi.fn().mockResolvedValue(undefined);
const findModel = vi.fn().mockReturnValue({
provider: { name: "openai" },
id: "gpt-4o",
name: "GPT-4o",
});
const executor = new TaskExecutor(store, "/tmp/test");
(executor as any)._modelRegistry = { find: findModel };
(executor as any).activeSessions.set("FN-001", {
session: { setModel, dispose: vi.fn() },
seenSteeringIds: new Set(),
lastModelProvider: "anthropic",
lastModelId: "claude-sonnet-4-5",
});
store._trigger("task:updated", buildUpdatedTask({
modelProvider: "openai",
modelId: "gpt-4o",
}));
await flushTaskUpdated();
expect(setModel).toHaveBeenCalledTimes(1);
expect(setModel).toHaveBeenCalledWith(expect.objectContaining({
provider: expect.objectContaining({ name: "openai" }),
id: "gpt-4o",
}));
expect(store.logEntry).toHaveBeenCalledWith("FN-001", "Model changed to openai/gpt-4o");
});
it("does not attempt hot-swap when no active session exists", async () => {
const store = createMockStore();
const setModel = vi.fn().mockResolvedValue(undefined);
new TaskExecutor(store, "/tmp/test");
store._trigger("task:updated", buildUpdatedTask({
modelProvider: "openai",
modelId: "gpt-4o",
}));
await flushTaskUpdated();
expect(setModel).not.toHaveBeenCalled();
});
it("does not hot-swap when model fields are unchanged", async () => {
const store = createMockStore();
const setModel = vi.fn().mockResolvedValue(undefined);
const findModel = vi.fn();
const executor = new TaskExecutor(store, "/tmp/test");
(executor as any)._modelRegistry = { find: findModel };
(executor as any).activeSessions.set("FN-001", {
session: { setModel, dispose: vi.fn() },
seenSteeringIds: new Set(),
lastModelProvider: "anthropic",
lastModelId: "claude-sonnet-4-5",
});
store._trigger("task:updated", buildUpdatedTask({
modelProvider: "anthropic",
modelId: "claude-sonnet-4-5",
}));
await flushTaskUpdated();
expect(findModel).not.toHaveBeenCalled();
expect(setModel).not.toHaveBeenCalled();
});
it("hot-swaps to settings default when override is cleared", async () => {
const store = createMockStore();
const setModel = vi.fn().mockResolvedValue(undefined);
const findModel = vi.fn().mockReturnValue({
provider: { name: "openai" },
id: "gpt-4o",
name: "GPT-4o",
});
store.getSettings.mockResolvedValue({
defaultProvider: "openai",
defaultModelId: "gpt-4o",
});
const executor = new TaskExecutor(store, "/tmp/test");
(executor as any)._modelRegistry = { find: findModel };
(executor as any).activeSessions.set("FN-001", {
session: { setModel, dispose: vi.fn() },
seenSteeringIds: new Set(),
lastModelProvider: "anthropic",
lastModelId: "claude-sonnet-4-5",
});
store._trigger("task:updated", buildUpdatedTask({
modelProvider: undefined,
modelId: undefined,
}));
await flushTaskUpdated();
expect(findModel).toHaveBeenCalledWith("openai", "gpt-4o");
expect(setModel).toHaveBeenCalledTimes(1);
});
it("logs error and continues when setModel fails", async () => {
const store = createMockStore();
const setModel = vi.fn().mockRejectedValue(new Error("API key not found"));
const findModel = vi.fn().mockReturnValue({
provider: { name: "openai" },
id: "gpt-4o",
name: "GPT-4o",
});
const executor = new TaskExecutor(store, "/tmp/test");
(executor as any)._modelRegistry = { find: findModel };
(executor as any).activeSessions.set("FN-001", {
session: { setModel, dispose: vi.fn() },
seenSteeringIds: new Set(),
lastModelProvider: "anthropic",
lastModelId: "claude-sonnet-4-5",
});
store._trigger("task:updated", buildUpdatedTask({
modelProvider: "openai",
modelId: "gpt-4o",
}));
await flushTaskUpdated();
expect(store.logEntry).toHaveBeenCalledWith("FN-001", "Model change failed: API key not found");
expect((executor as any).activeSessions.has("FN-001")).toBe(true);
});
it("does not attempt hot-swap on paused task", async () => {
const store = createMockStore();
const setModel = vi.fn().mockResolvedValue(undefined);
const dispose = vi.fn();
const findModel = vi.fn();
const executor = new TaskExecutor(store, "/tmp/test");
(executor as any)._modelRegistry = { find: findModel };
(executor as any).activeSessions.set("FN-001", {
session: { setModel, dispose },
seenSteeringIds: new Set(),
lastModelProvider: "anthropic",
lastModelId: "claude-sonnet-4-5",
});
store._trigger("task:updated", buildUpdatedTask({
paused: true,
modelProvider: "openai",
modelId: "gpt-4o",
}));
await flushTaskUpdated();
expect(dispose).toHaveBeenCalledTimes(1);
expect(findModel).not.toHaveBeenCalled();
expect(setModel).not.toHaveBeenCalled();
});
});
describe("TaskExecutor global pause behavior", () => {
beforeEach(() => {
vi.clearAllMocks();

View File

@@ -9,7 +9,7 @@ import { generateWorktreeName, slugify } from "./worktree-names.js";
import { Type, type Static } from "@mariozechner/pi-ai";
import { createKbAgent, describeModel, promptWithFallback, compactSessionContext } from "./pi.js";
import { reviewStep, type ReviewVerdict } from "./reviewer.js";
import { SessionManager, type ToolDefinition, type AgentSession } from "@mariozechner/pi-coding-agent";
import { AuthStorage, ModelRegistry, SessionManager, getAgentDir, type ToolDefinition, type AgentSession } from "@mariozechner/pi-coding-agent";
import { PRIORITY_EXECUTE, type AgentSemaphore } from "./concurrency.js";
import type { WorktreePool } from "./worktree-pool.js";
import { AgentLogger } from "./agent-logger.js";
@@ -241,6 +241,8 @@ export class TaskExecutor {
private activeSessions = new Map<string, {
session: AgentSession;
seenSteeringIds: Set<string>;
lastModelProvider?: string | null;
lastModelId?: string | null;
}>();
/** Active step-session executors per task (mutually exclusive with activeSessions). */
private activeStepExecutors = new Map<string, StepSessionExecutor>();
@@ -262,6 +264,16 @@ export class TaskExecutor {
private totalSpawnedCount = 0;
/** Token cap detector for proactive context compaction. */
private tokenCapDetector = new TokenCapDetector();
private _modelRegistry?: InstanceType<typeof ModelRegistry>;
private get modelRegistry(): InstanceType<typeof ModelRegistry> {
if (!this._modelRegistry) {
const authStorage = AuthStorage.create();
this._modelRegistry = new ModelRegistry(authStorage, join(getAgentDir(), "models.json"));
this._modelRegistry.refresh();
}
return this._modelRegistry;
}
/** Returns the set of task IDs currently being executed. */
getExecutingTaskIds(): Set<string> {
@@ -344,6 +356,42 @@ export class TaskExecutor {
return;
}
// Handle executor model hot-swap on active single-session executions
if (this.activeSessions.has(task.id) && !task.paused) {
const activeEntry = this.activeSessions.get(task.id)!;
const providerChanged = task.modelProvider !== activeEntry.lastModelProvider;
const modelIdChanged = task.modelId !== activeEntry.lastModelId;
if (providerChanged || modelIdChanged) {
activeEntry.lastModelProvider = task.modelProvider;
activeEntry.lastModelId = task.modelId;
const settings = await this.store.getSettings();
const newProvider = task.modelProvider && task.modelId
? task.modelProvider
: settings?.defaultProvider;
const newModelId = task.modelProvider && task.modelId
? task.modelId
: settings?.defaultModelId;
if (newProvider && newModelId) {
try {
const model = this.modelRegistry.find(newProvider, newModelId);
if (model) {
await activeEntry.session.setModel(model);
executorLog.log(`${task.id}: executor model hot-swapped to ${newProvider}/${newModelId}`);
await this.store.logEntry(task.id, `Model changed to ${newProvider}/${newModelId}`);
} else {
executorLog.log(`${task.id}: model ${newProvider}/${newModelId} not found in registry for hot-swap`);
}
} catch (err: any) {
executorLog.error(`${task.id}: failed to hot-swap model: ${err.message}`);
await this.store.logEntry(task.id, `Model change failed: ${err.message}`);
}
}
}
}
// Handle steering comments - inject new ones into the running session
// Only process if session is active (activeSessions check is sufficient
// since entries are only added when a task is in-progress)
@@ -1061,7 +1109,12 @@ export class TaskExecutor {
seenSteeringIds.add(comment.id);
}
}
this.activeSessions.set(task.id, { session, seenSteeringIds });
this.activeSessions.set(task.id, {
session,
seenSteeringIds,
lastModelProvider: detail.modelProvider,
lastModelId: detail.modelId,
});
// Register with stuck task detector for heartbeat monitoring
stuckDetector?.trackTask(task.id, session);
@@ -1232,7 +1285,12 @@ export class TaskExecutor {
// Reassign so finally{} disposes the correct session
session = retrySession;
sessionRef.current = retrySession;
this.activeSessions.set(task.id, { session: retrySession, seenSteeringIds });
this.activeSessions.set(task.id, {
session: retrySession,
seenSteeringIds,
lastModelProvider: detail.modelProvider,
lastModelId: detail.modelId,
});
stuckDetector?.trackTask(task.id, retrySession);
const retryPrompt = [