fix(web): keep a usable agent selected when the executor changes (#3388)

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
This commit is contained in:
Jonathan Marbutt
2026-09-05 17:42:06 +00:00
committed by GitHub
parent 241650f271
commit 97140168d8
31 changed files with 2114 additions and 79 deletions
@@ -25,11 +25,15 @@ const workflowAutopickDebug = createDebugLogger("executor-compat:workflow-autopi
* compatible. Every candidate is filtered against `compatibleAgentProfiles`
* so a previously-used profile that's not wired for the chosen executor
* isn't restored, then immediately fails the executor-compat gate.
*
* A pick carries `replaces` when it supersedes a selection that fell out of
* the compatible list (the executor changed after the agent was chosen). A
* workflow-locked selection is never replaced.
*/
export type AutopickDecision =
| { kind: "skip"; reason: string }
| { kind: "defer"; reason: string }
| { kind: "pick"; source: "lastId" | "defId" | "first"; id: string };
| { kind: "pick"; source: "lastId" | "defId" | "first"; id: string; replaces?: string };
export type AgentProfileAutopickInput = {
open: boolean;
@@ -46,11 +50,25 @@ export type AgentProfileAutopickInput = {
defaultAgentProfileId: string | null;
};
/**
* A set selection is re-evaluated only once the executor and the auth catalog
* are known and at least one compatible profile exists; an empty list during
* a profile refresh must not clear a valid selection.
*/
function selectionNeedsReplacement(input: AgentProfileAutopickInput): boolean {
if (!input.agentProfileId) return false;
if (!input.authLoaded || !input.executorProfileId) return false;
if (input.compatibleAgentProfiles.length === 0) return false;
return !input.compatibleAgentProfiles.some((p) => p.id === input.agentProfileId);
}
function getAgentAutopickGate(input: AgentProfileAutopickInput): AutopickDecision | null {
if (!input.open) return { kind: "skip", reason: "closed" };
if (input.agentProfileId) return { kind: "skip", reason: "already-set" };
if (input.workflowAgentProfileId) return { kind: "skip", reason: "workflow-locked" };
if (input.workflowHasAgent) return { kind: "skip", reason: "workflow-has-agent" };
if (input.agentProfileId && !selectionNeedsReplacement(input)) {
return { kind: "skip", reason: "already-set" };
}
if (input.agentProfiles.length === 0) return { kind: "skip", reason: "no-profiles" };
if (!input.authLoaded) return { kind: "defer", reason: "auth-not-loaded" };
// Defer until the executor profile is selected too - useExecutorProfileCompat
@@ -73,15 +91,18 @@ function getAgentAutopickGate(input: AgentProfileAutopickInput): AutopickDecisio
export function decideAgentProfileAutopick(input: AgentProfileAutopickInput): AutopickDecision {
const gate = getAgentAutopickGate(input);
if (gate) return gate;
const replaces = input.agentProfileId || undefined;
const pick = (source: "lastId" | "defId" | "first", id: string): AutopickDecision =>
replaces ? { kind: "pick", source, id, replaces } : { kind: "pick", source, id };
const lastId = input.lastAgentProfileId;
if (lastId && input.compatibleAgentProfiles.some((p) => p.id === lastId)) {
return { kind: "pick", source: "lastId", id: lastId };
return pick("lastId", lastId);
}
const defId = input.defaultAgentProfileId;
if (defId && input.compatibleAgentProfiles.some((p) => p.id === defId)) {
return { kind: "pick", source: "defId", id: defId };
return pick("defId", defId);
}
return { kind: "pick", source: "first", id: input.compatibleAgentProfiles[0].id };
return pick("first", input.compatibleAgentProfiles[0].id);
}
function buildAgentAutopickDebugFields(input: {
@@ -101,6 +122,7 @@ function buildAgentAutopickDebugFields(input: {
return {
reason: input.decision.kind === "pick" ? input.decision.source : input.decision.reason,
pick: input.decision.kind === "pick" ? input.decision.id : "-",
replaces: input.decision.kind === "pick" ? (input.decision.replaces ?? "-") : "-",
current: input.agentProfileId || "-",
workflow_id: input.selectedWorkflowId ?? "-",
executor_profile_id: input.executorProfileId || "-",
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import type { ExecutorProfile } from "@/lib/types/http";
import {
computeAgentCompatState,
computeHasRepositorySelection,
computeSelectedRepoCount,
filterCompatibleAgentProfiles,
@@ -227,3 +228,117 @@ describe("filterCompatibleAgentProfiles", () => {
).toEqual(["enabled"]);
});
});
describe("computeAgentCompatState", () => {
const sprites = {
id: "exec-sprites",
executor_type: "sprites",
config: {},
} as unknown as ExecutorProfile;
function profile(id: string, enabled = true): AgentProfileOption {
return {
id,
label: id,
agent_id: `agent-${id}`,
agent_name: id,
cli_passthrough: false,
enabled,
};
}
const claude = profile("claude");
const cursor = profile("cursor");
function state(
overrides: Partial<Parameters<typeof computeAgentCompatState>[0]> = {},
): ReturnType<typeof computeAgentCompatState> {
return computeAgentCompatState({
selectedExecutorProfile: sprites,
compatibleAgentProfiles: [cursor],
selectedAgentProfileId: claude.id,
selectedAgentProfile: claude,
workflowAgentLocked: false,
dynamicRoutingEnabled: true,
...overrides,
});
}
it("is compatible while no executor profile is selected", () => {
expect(state({ selectedExecutorProfile: null, compatibleAgentProfiles: [] })).toBe(
"compatible",
);
});
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.4
it("is none-compatible when the compatible list is empty and nothing locks the agent", () => {
expect(state({ compatibleAgentProfiles: [] })).toBe("none-compatible");
expect(
state({
compatibleAgentProfiles: [],
selectedAgentProfileId: "",
selectedAgentProfile: null,
}),
).toBe("none-compatible");
});
it("is compatible while nothing is selected and a compatible profile exists", () => {
expect(state({ selectedAgentProfileId: "", selectedAgentProfile: null })).toBe("compatible");
});
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.6
it("is selected-incompatible, never none-compatible, when the selection is absent from a non-empty list", () => {
expect(state()).toBe("selected-incompatible");
});
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.3
it("is compatible when the selection is in the list", () => {
expect(state({ compatibleAgentProfiles: [claude, cursor] })).toBe("compatible");
});
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.5
it("keeps the workflow-locked state even when nothing else is compatible", () => {
expect(state({ compatibleAgentProfiles: [], workflowAgentLocked: true })).toBe(
"selected-incompatible",
);
});
it("treats a disabled locked profile as no compatible agent, not a credential problem", () => {
const disabled = profile("disabled", false);
expect(
state({
selectedAgentProfileId: disabled.id,
selectedAgentProfile: disabled,
workflowAgentLocked: true,
}),
).toBe("none-compatible");
});
it("keeps an unlocked disabled selection distinct when an alternative exists", () => {
const disabled = profile("disabled", false);
expect(
state({
selectedAgentProfileId: disabled.id,
selectedAgentProfile: disabled,
workflowAgentLocked: false,
compatibleAgentProfiles: [cursor],
}),
).toBe("selected-unavailable");
});
it("keeps an unlocked dynamic selection distinct when routing is disabled", () => {
const dynamic = { ...profile("dynamic"), kind: "dynamic" } satisfies AgentProfileOption;
expect(
state({
selectedAgentProfileId: dynamic.id,
selectedAgentProfile: dynamic,
workflowAgentLocked: false,
dynamicRoutingEnabled: false,
compatibleAgentProfiles: [cursor],
}),
).toBe("selected-unavailable");
});
it("treats an unknown selected id as a credential problem when a compatible profile exists", () => {
expect(state({ selectedAgentProfileId: "gone", selectedAgentProfile: null })).toBe(
"selected-incompatible",
);
});
});
@@ -6,6 +6,7 @@ import type {
DialogComputedArgs,
DialogComputedValues,
DialogFormState,
AgentCompatState,
} from "@/components/task-create-dialog-types";
import {
useRepositoryOptions,
@@ -142,13 +143,65 @@ export function filterCompatibleAgentProfiles(
);
}
export type AgentCompatInput = {
selectedExecutorProfile: ExecutorProfile | null;
compatibleAgentProfiles: AgentProfileOption[];
/** Effective selection: the user's pick or the workflow override. */
selectedAgentProfileId: string;
/** The selected profile's store row, or null when the id is unknown. */
selectedAgentProfile: AgentProfileOption | null;
workflowAgentLocked: boolean;
dynamicRoutingEnabled: boolean;
};
/**
* Compatibility of the effective agent selection with the selected
* executor profile. Pure so the dialog's empty state, note, and footer reason
* can be tested without rendering.
*
* A workflow-locked profile that fails only the credential check keeps the
* `selected-incompatible` state even when nothing else is compatible: the
* user cannot change the agent, so the note has to name the workflow and the
* agent rather than the generic empty state. A locked profile that is not
* selectable at all (disabled) is not a credential problem and stays on the
* empty state when locked. An unlocked unavailable selection is distinct while
* an enabled alternative exists, so the dialog does not claim that no profile
* is compatible during automatic replacement.
*/
export function computeAgentCompatState(input: AgentCompatInput): AgentCompatState {
const { selectedExecutorProfile, compatibleAgentProfiles, selectedAgentProfileId } = input;
if (!selectedExecutorProfile) return "compatible";
if (!selectedAgentProfileId) {
return compatibleAgentProfiles.length === 0 ? "none-compatible" : "compatible";
}
if (compatibleAgentProfiles.some((ap) => ap.id === selectedAgentProfileId)) return "compatible";
const selectable = input.selectedAgentProfile
? isSelectableAgentProfile(input.selectedAgentProfile, input.dynamicRoutingEnabled)
: true;
if (!selectable) {
if (input.workflowAgentLocked || compatibleAgentProfiles.length === 0) {
return "none-compatible";
}
return "selected-unavailable";
}
if (input.workflowAgentLocked) return "selected-incompatible";
return compatibleAgentProfiles.length === 0 ? "none-compatible" : "selected-incompatible";
}
type AgentSelectionInput = {
/** Effective selection: the user's pick or the workflow override. */
agentProfileId: string;
agentProfiles: DialogComputedArgs["agentProfiles"];
workflowAgentLocked: boolean;
};
function useExecutorProfileCompat(
allExecutorProfiles: ExecutorProfile[],
selectedProfileId: string,
selectedAgentProfileId: string,
agentProfiles: DialogComputedArgs["agentProfiles"],
selection: AgentSelectionInput,
disabledReasonFor?: (profile: ExecutorProfile) => string | null,
) {
const { agentProfileId: selectedAgentProfileId, agentProfiles, workflowAgentLocked } = selection;
const executorProfileOptions = useExecutorProfileOptions(allExecutorProfiles, {
disabledReasonFor,
});
@@ -167,24 +220,42 @@ function useExecutorProfileCompat(
dynamicRoutingEnabled,
);
}, [agentProfiles, selectedExecutorProfile, authSpecs, authLoaded, dynamicRoutingEnabled]);
// `noCompatibleAgent` gates the submit button. It must catch BOTH cases:
// 1. The selected executor has no compatible agents at all.
// 2. The user picked an agent that isn't compatible with the executor
// (e.g. switched executor after the agent was chosen).
// Previously this only checked case 1, so case 2 silently let the user
// submit with a known-incompatible combination.
const noCompatibleAgent = useMemo(() => {
if (!selectedExecutorProfile) return false;
if (compatibleAgentProfiles.length === 0) return true;
if (!selectedAgentProfileId) return false;
return !compatibleAgentProfiles.some((ap) => ap.id === selectedAgentProfileId);
}, [selectedExecutorProfile, compatibleAgentProfiles, selectedAgentProfileId]);
// The agent column renders per state and the submit gate reads the derived
// boolean, so both "no compatible agent at all" and "selected agent is not
// compatible" block submission while only the former hides the selector.
const selectedAgentProfile = useMemo(
() => agentProfiles.find((ap) => ap.id === selectedAgentProfileId) ?? null,
[agentProfiles, selectedAgentProfileId],
);
const agentCompatState = useMemo(
() =>
computeAgentCompatState({
selectedExecutorProfile,
compatibleAgentProfiles,
selectedAgentProfileId,
selectedAgentProfile,
workflowAgentLocked,
dynamicRoutingEnabled,
}),
[
selectedExecutorProfile,
compatibleAgentProfiles,
selectedAgentProfileId,
selectedAgentProfile,
workflowAgentLocked,
dynamicRoutingEnabled,
],
);
const noCompatibleAgent = agentCompatState !== "compatible";
const selectedAgentProfileName = selectedAgentProfile?.label ?? null;
return {
selectedExecutorProfile,
compatibleAgentProfiles,
authLoaded,
executorProfileOptions,
noCompatibleAgent,
agentCompatState,
selectedAgentProfileName,
};
}
@@ -262,8 +333,7 @@ export function useDialogComputed({
const exec = useExecutorProfileCompat(
allExecutorProfiles,
fs.executorProfileId,
effectiveAgentProfileId,
agentProfiles,
{ agentProfileId: effectiveAgentProfileId, agentProfiles, workflowAgentLocked },
pickExecutorDisabledReason(fs.noRepository, isMultiRepoSelection),
);
const agentProfileOptions = useAgentProfileOptions(
@@ -302,5 +372,7 @@ export function useDialogComputed({
compatibleAgentProfiles: exec.compatibleAgentProfiles,
authLoaded: exec.authLoaded,
noCompatibleAgent: exec.noCompatibleAgent,
agentCompatState: exec.agentCompatState,
selectedAgentProfileName: exec.selectedAgentProfileName,
};
}
@@ -1,7 +1,7 @@
"use client";
import type { AgentProfileOption } from "@/lib/state/slices";
import type { DialogFormState } from "@/components/task-create-dialog-types";
import type { AgentCompatState, DialogFormState } from "@/components/task-create-dialog-types";
import { CreateEditSelectors } from "@/components/task-create-dialog-form-body";
import { AgentSelector, ExecutorProfileSelector } from "@/components/task-create-dialog-selectors";
import { useAgentProfileOptions } from "@/components/task-create-dialog-options";
@@ -22,7 +22,9 @@ type CreateModeSelectorsProps = {
onAgentProfileChange: (v: string) => void;
onExecutorProfileChange: (v: string) => void;
workflowAgentLocked: boolean;
noCompatibleAgent: boolean;
agentCompatState: AgentCompatState;
selectedAgentProfileName: string | null;
effectiveWorkflowName: string | null;
executorProfileName: string | null;
};
@@ -46,7 +48,9 @@ export function CreateModeSelectors(props: CreateModeSelectorsProps) {
onExecutorProfileChange={props.onExecutorProfileChange}
executorsLoading={props.executorsLoading}
workflowAgentLocked={props.workflowAgentLocked}
noCompatibleAgent={props.noCompatibleAgent}
agentCompatState={props.agentCompatState}
selectedAgentProfileName={props.selectedAgentProfileName}
effectiveWorkflowName={props.effectiveWorkflowName}
executorProfileName={props.executorProfileName}
AgentSelectorComponent={AgentSelector}
ExecutorProfileSelectorComponent={ExecutorProfileSelector}
@@ -10,6 +10,7 @@ import {
type AgentProfileAutopickInput,
} from "./task-create-dialog-autopick";
import type { DialogFormState, StoreSelections } from "@/components/task-create-dialog-types";
import { readQueuedTaskCreateLastUsedState } from "./task-create-dialog-handlers";
import type { AgentProfileOption } from "@/lib/state/slices";
import type { Workspace } from "@/lib/types/http";
const STORAGE_KEYS = { LAST_AGENT_PROFILE_ID: "kandev.dialog.lastAgentProfileId" } as const;
@@ -543,21 +544,6 @@ describe("useDefaultSelectionsEffect — executor-aware agent restoration", () =
await new Promise((resolve) => setTimeout(resolve, 10));
expect(fs.setAgentProfileId).not.toHaveBeenCalled();
});
it("does nothing when agentProfileId is already set (user has explicitly picked)", async () => {
const claude = makeProfile("claude");
const cursor = makeProfile("cursor");
const fs = makeDefaultSelFs({ agentProfileId: claude.id });
const sel = makeSel({
agentProfiles: [claude, cursor],
compatibleAgentProfiles: [cursor],
});
renderHook(() => useDefaultSelectionsEffect(fs, true, sel, []));
await new Promise((resolve) => setTimeout(resolve, 10));
expect(fs.setAgentProfileId).not.toHaveBeenCalled();
});
});
describe("useDefaultSelectionsEffect — auth-spec load race", () => {
@@ -641,3 +627,116 @@ describe("useDefaultSelectionsEffect — auth-spec load race", () => {
expect(fs.setAgentProfileId).not.toHaveBeenCalledWith(claude.id);
});
});
const SPRITES_PROFILE_ID = "profile-sprites";
const ALREADY_SET = { kind: "skip", reason: "already-set" } as const;
describe("decideAgentProfileAutopick — replacing an incompatible selection", () => {
const claude = makeProfile("claude");
const cursor = makeProfile("cursor");
const codex = makeProfile("codex");
const selectedOnExecutor = {
agentProfileId: claude.id,
executorProfileId: SPRITES_PROFILE_ID,
hasExecutors: true,
};
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.2
it("replaces a selection that is absent from a non-empty compatible list", () => {
expect(decideAutopick([claude, cursor, codex], [cursor, codex], selectedOnExecutor)).toEqual({
kind: "pick",
source: "first",
id: cursor.id,
replaces: claude.id,
});
});
it("prefers the last-used profile, then the workspace default, for the replacement", () => {
expect(
decideAutopick([claude, cursor, codex], [cursor, codex], {
...selectedOnExecutor,
lastAgentProfileId: codex.id,
defaultAgentProfileId: cursor.id,
}),
).toEqual({ kind: "pick", source: "lastId", id: codex.id, replaces: claude.id });
expect(
decideAutopick([claude, cursor, codex], [cursor, codex], {
...selectedOnExecutor,
defaultAgentProfileId: codex.id,
}),
).toEqual({ kind: "pick", source: "defId", id: codex.id, replaces: claude.id });
});
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.3
it("keeps a selection that is still compatible", () => {
expect(decideAutopick([claude, cursor], [claude, cursor], selectedOnExecutor)).toEqual(
ALREADY_SET,
);
});
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.5
it("never replaces a workflow-locked selection", () => {
expect(
decideAutopick([claude, cursor], [cursor], {
...selectedOnExecutor,
workflowAgentProfileId: claude.id,
}),
).toEqual({ kind: "skip", reason: "workflow-locked" });
expect(
decideAutopick([claude, cursor], [cursor], { ...selectedOnExecutor, workflowHasAgent: true }),
).toEqual({ kind: "skip", reason: "workflow-has-agent" });
});
it("leaves the selection alone while the catalog, executor, or compatible list is not ready", () => {
expect(
decideAutopick([claude, cursor], [cursor], { ...selectedOnExecutor, authLoaded: false }),
).toEqual(ALREADY_SET);
expect(
decideAutopick([claude, cursor], [cursor], { ...selectedOnExecutor, executorProfileId: "" }),
).toEqual(ALREADY_SET);
expect(decideAutopick([claude, cursor], [], selectedOnExecutor)).toEqual(ALREADY_SET);
});
});
describe("useDefaultSelectionsEffect — executor switch after an agent was chosen", () => {
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.2
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.8
it("replaces an incompatible selection without touching the queued last-used preference", async () => {
const claude = makeProfile("claude");
const cursor = makeProfile("cursor");
const codex = makeProfile("codex");
const fs = makeDefaultSelFs({
agentProfileId: claude.id,
executorProfileId: SPRITES_PROFILE_ID,
});
const sel = makeSel({
agentProfiles: [claude, cursor, codex],
compatibleAgentProfiles: [cursor, codex],
});
const queuedBefore = readQueuedTaskCreateLastUsedState();
renderHook(() => useDefaultSelectionsEffect(fs, true, sel, []));
await waitFor(() => expect(fs.setAgentProfileId).toHaveBeenCalledWith(cursor.id));
expect(readQueuedTaskCreateLastUsedState()).toEqual(queuedBefore);
});
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.3
it("keeps a selection that stays compatible with the new executor", async () => {
const claude = makeProfile("claude");
const cursor = makeProfile("cursor");
const fs = makeDefaultSelFs({
agentProfileId: cursor.id,
executorProfileId: SPRITES_PROFILE_ID,
});
const sel = makeSel({
agentProfiles: [claude, cursor],
compatibleAgentProfiles: [cursor],
});
renderHook(() => useDefaultSelectionsEffect(fs, true, sel, []));
await new Promise((resolve) => setTimeout(resolve, 10));
expect(fs.setAgentProfileId).not.toHaveBeenCalled();
});
});
@@ -4,6 +4,7 @@ import {
isNativeSubmitDisabled,
resolveDisabledReason,
REASON_NO_COMPATIBLE_AGENT,
REASON_SELECTED_AGENT_INCOMPATIBLE,
REASON_TITLE,
REASON_REPO,
REASON_BRANCH,
@@ -40,6 +41,8 @@ function makeProps(
effectiveWorkflowId: "wf-1",
executorHint: null,
noCompatibleAgent: false,
agentCompatState: "compatible",
selectedAgentProfileName: null,
executorProfileName: null,
onCancel: () => {},
onUpdateWithoutAgent: () => {},
@@ -294,3 +297,39 @@ describe("computeDisabledReason (submitBlockedReason)", () => {
expect(computeDisabledReason(makeProps({ submitBlockedReason: "" }), KIND_START)).toBeNull();
});
});
describe("computeDisabledReason — agent compatibility states", () => {
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.7
it("names the selected agent, not a missing executor, when a compatible agent exists", () => {
const props = makeProps({
noCompatibleAgent: true,
agentCompatState: "selected-incompatible",
selectedAgentProfileName: "OpenCode",
executorProfileName: "Fly",
});
expect(computeDisabledReason(props, KIND_START)).toBe(REASON_SELECTED_AGENT_INCOMPATIBLE);
expect(computeDisabledReason({ ...props, isSessionMode: true }, KIND_DEFAULT)).toBe(
REASON_SELECTED_AGENT_INCOMPATIBLE,
);
});
it("resolves the selected-agent key with the agent and executor names", () => {
const text = resolveDisabledReason(t, REASON_SELECTED_AGENT_INCOMPATIBLE, "Fly", "OpenCode");
expect(text).toContain("OpenCode");
expect(text).toContain("Fly");
expect(text).toContain("credentials");
});
it("uses an unavailable-agent reason while an unlocked selection is replaced", () => {
expect(
computeDisabledReason(
makeProps({
noCompatibleAgent: true,
agentCompatState: "selected-unavailable" as never,
selectedAgentProfileName: "Disabled agent",
}),
KIND_START,
),
).toBe("task:selectedAgentProfileUnavailable");
});
});
@@ -1,6 +1,7 @@
"use client";
import { memo } from "react";
import type { AgentCompatState } from "@/components/task-create-dialog-types";
import {
IconLoader2,
IconFileInvoice,
@@ -233,6 +234,8 @@ export type TaskCreateDialogFooterProps = {
effectiveWorkflowId: string | null;
executorHint: string | null;
noCompatibleAgent: boolean;
agentCompatState: AgentCompatState;
selectedAgentProfileName: string | null;
executorProfileName: string | null;
onCancel: () => void;
onUpdateWithoutAgent: () => void;
@@ -290,6 +293,8 @@ export const REASON_WORKFLOW = "task:reasonSelectWorkflow";
export const REASON_AGENT = "task:reasonSelectAgent";
export const REASON_DESCRIPTION = "task:reasonAddSessionDescription";
export const REASON_NO_COMPATIBLE_AGENT = "task:noCompatibleAgentProfileFor";
export const REASON_SELECTED_AGENT_INCOMPATIBLE = "task:selectedAgentNotConfiguredFor";
export const REASON_SELECTED_AGENT_UNAVAILABLE = "task:selectedAgentProfileUnavailable";
export const REASON_LOADING_DEPENDENCIES = "task:loadingDependencies";
/**
@@ -301,14 +306,28 @@ export function resolveDisabledReason(
t: (key: string, options?: Record<string, unknown>) => string,
reason: string | null | undefined,
executorProfileName: string | null,
agentProfileName: string | null = null,
): string | undefined {
if (!reason) return undefined;
if (!reason.startsWith("task:")) return reason;
return t(reason, {
target: executorProfileName ? `“${executorProfileName}”` : t("task:thisExecutor"),
agent: agentProfileName ?? t("task:selectedAgentProfileFallback"),
});
}
/** The compatibility reason must name what the agent column shows. */
function compatReason(props: TaskCreateDialogFooterProps): string | null {
if (props.agentCompatState === "selected-incompatible") {
return REASON_SELECTED_AGENT_INCOMPATIBLE;
}
if (props.agentCompatState === "selected-unavailable") {
return REASON_SELECTED_AGENT_UNAVAILABLE;
}
if (props.noCompatibleAgent) return REASON_NO_COMPATIBLE_AGENT;
return null;
}
function baseReason(props: TaskCreateDialogFooterProps): string | null {
if (props.autoTitle && !props.hasDescription) return REASON_PROMPT;
if (!props.autoTitle && !props.hasTitle) return REASON_TITLE;
@@ -316,7 +335,8 @@ function baseReason(props: TaskCreateDialogFooterProps): string | null {
if (!props.hasAllBranches) return REASON_BRANCH;
if (props.isCreateMode && !props.workspaceId) return REASON_WORKSPACE;
if (props.isCreateMode && !props.effectiveWorkflowId) return REASON_WORKFLOW;
if (props.noCompatibleAgent) return REASON_NO_COMPATIBLE_AGENT;
const compat = compatReason(props);
if (compat) return compat;
if (props.isEditMode && props.editDependenciesReady === false) {
return REASON_LOADING_DEPENDENCIES;
}
@@ -324,7 +344,8 @@ function baseReason(props: TaskCreateDialogFooterProps): string | null {
}
function sessionDefaultReason(props: TaskCreateDialogFooterProps): string | null {
if (props.noCompatibleAgent) return REASON_NO_COMPATIBLE_AGENT;
const compat = compatReason(props);
if (compat) return compat;
if (!props.agentProfileId) return REASON_AGENT;
if (!props.hasDescription) return REASON_DESCRIPTION;
return null;
@@ -429,7 +450,12 @@ export const TaskCreateDialogFooter = memo(function TaskCreateDialogFooter(
</DialogClose>
<KeyboardShortcutTooltip
shortcut={SHORTCUTS.SUBMIT}
description={resolveDisabledReason(t, disabledReason, props.executorProfileName)}
description={resolveDisabledReason(
t,
disabledReason,
props.executorProfileName,
props.selectedAgentProfileName,
)}
>
<span className="inline-flex w-full sm:w-auto" data-testid="submit-start-agent-wrapper">
{(() => {
@@ -1,4 +1,4 @@
import { createRef } from "react";
import { createRef, type ComponentProps } from "react";
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
@@ -295,30 +295,110 @@ describe("DialogPromptSection (CLI-mode parity)", () => {
});
describe("CreateEditSelectors", () => {
it("links credential setup to the selected executor profile", () => {
const EmptySelector = () => <button type="button">selector</button>;
const WORKFLOW_NAME = "Development";
const EXECUTOR_NAME = "Fly";
const EMPTY_STATE_TEST_ID = "agent-profile-empty-state";
const SELECTOR_TEST_ID = "agent-selector-stub";
const AgentSelectorStub = () => (
<button type="button" data-testid="agent-selector-stub">
selector
</button>
);
const ExecutorSelectorStub = () => <button type="button">executor</button>;
const baseProps: Omit<ComponentProps<typeof CreateEditSelectors>, "agentCompatState"> = {
isTaskStarted: false,
agentProfiles: [{ id: "agent-1", label: "Codex", agent_name: "codex" } as never],
agentProfilesLoading: false,
agentProfileOptions: [],
agentProfileId: "",
onAgentProfileChange: () => {},
isCreatingSession: false,
executorProfileOptions: [],
executorProfileId: "exec-profile-1",
onExecutorProfileChange: () => {},
executorsLoading: false,
AgentSelectorComponent: AgentSelectorStub,
ExecutorProfileSelectorComponent: ExecutorSelectorStub,
workflowAgentLocked: false,
executorProfileName: "Docker",
selectedAgentProfileName: null,
effectiveWorkflowName: null,
};
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.4
it("links credential setup to the selected executor profile", () => {
render(<CreateEditSelectors {...baseProps} agentCompatState="none-compatible" />);
expect(screen.getByTestId(EMPTY_STATE_TEST_ID).textContent).toContain(
"No compatible agent profiles",
);
expect(screen.getByRole("link", { name: /configure credentials/i }).getAttribute("href")).toBe(
"/settings/executors/exec-profile-1",
);
expect(screen.queryByTestId(SELECTOR_TEST_ID)).toBeNull();
});
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.1
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.6
it("keeps the selector and names the incompatible agent when another agent is compatible", () => {
render(
<CreateEditSelectors
isTaskStarted={false}
agentProfiles={[{ id: "agent-1", label: "Codex", agent_name: "codex" } as never]}
agentProfilesLoading={false}
agentProfileOptions={[]}
agentProfileId=""
onAgentProfileChange={() => {}}
isCreatingSession={false}
executorProfileOptions={[]}
executorProfileId="exec-profile-1"
onExecutorProfileChange={() => {}}
executorsLoading={false}
AgentSelectorComponent={EmptySelector}
ExecutorProfileSelectorComponent={EmptySelector}
workflowAgentLocked={false}
noCompatibleAgent={true}
executorProfileName="Docker"
{...baseProps}
agentProfileId="agent-1"
agentCompatState="selected-incompatible"
selectedAgentProfileName="OpenCode"
executorProfileName={EXECUTOR_NAME}
/>,
);
expect(screen.getByTestId(SELECTOR_TEST_ID)).toBeTruthy();
expect(screen.queryByTestId(EMPTY_STATE_TEST_ID)).toBeNull();
const note = screen.getByTestId("agent-profile-incompatible-note").textContent ?? "";
expect(note).toContain("OpenCode");
expect(note).toContain(EXECUTOR_NAME);
expect(screen.getByRole("link", { name: /configure credentials/i }).getAttribute("href")).toBe(
"/settings/executors/exec-profile-1",
);
});
it("keeps the selector and shows an unavailable note while replacement is pending", () => {
render(
<CreateEditSelectors
{...baseProps}
agentProfileId="agent-1"
agentCompatState={"selected-unavailable" as never}
selectedAgentProfileName="Disabled agent"
executorProfileName={EXECUTOR_NAME}
/>,
);
expect(screen.getByTestId(SELECTOR_TEST_ID)).toBeTruthy();
expect(screen.queryByTestId(EMPTY_STATE_TEST_ID)).toBeNull();
expect(screen.getByTestId("agent-profile-unavailable-note").textContent).toContain(
"Disabled agent",
);
});
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.5
it("names the workflow, agent, and executor when the workflow locks an incompatible agent", () => {
render(
<CreateEditSelectors
{...baseProps}
agentProfileId="agent-1"
agentCompatState="selected-incompatible"
workflowAgentLocked={true}
selectedAgentProfileName="OpenCode"
effectiveWorkflowName={WORKFLOW_NAME}
executorProfileName={EXECUTOR_NAME}
/>,
);
const note = screen.getByTestId("agent-profile-incompatible-note").textContent ?? "";
expect(note).toContain(WORKFLOW_NAME);
expect(note).toContain("OpenCode");
expect(note).toContain(EXECUTOR_NAME);
expect(screen.queryByTestId(SELECTOR_TEST_ID)).toBeNull();
expect(screen.queryByTestId(EMPTY_STATE_TEST_ID)).toBeNull();
expect(screen.getByRole("link", { name: /configure credentials/i }).getAttribute("href")).toBe(
"/settings/executors/exec-profile-1",
);
@@ -6,8 +6,11 @@ import type { AgentProfileOption } from "@/lib/state/slices";
import type { WorkflowSnapshotData } from "@/lib/state/slices/kanban/types";
import { WorkflowSelectorRow } from "@/components/workflow-selector-row";
import { AgentLogo } from "@/components/agent-logo";
import type { DialogFormState } from "@/components/task-create-dialog-types";
import type { DialogPromptEnhance } from "@/components/task-create-dialog-types";
import type {
AgentCompatState,
DialogFormState,
DialogPromptEnhance,
} from "@/components/task-create-dialog-types";
import type { useKeyboardShortcutHandler } from "@/hooks/use-keyboard-shortcut";
import { TaskFormInputs } from "@/components/task-create-dialog-selectors";
import { PromptResultRecovery } from "@/components/prompt-result-recovery";
@@ -56,7 +59,9 @@ type CreateEditSelectorsProps = {
popoverPortal?: boolean;
}>;
workflowAgentLocked: boolean;
noCompatibleAgent: boolean;
agentCompatState: AgentCompatState;
selectedAgentProfileName: string | null;
effectiveWorkflowName: string | null;
executorProfileName: string | null;
};
@@ -70,11 +75,22 @@ type AgentColumnProps = Pick<
| "isCreatingSession"
| "AgentSelectorComponent"
| "workflowAgentLocked"
| "noCompatibleAgent"
| "agentCompatState"
| "selectedAgentProfileName"
| "effectiveWorkflowName"
| "executorProfileName"
| "executorProfileId"
>;
function credentialsHref(executorProfileId: string): string {
return executorProfileId ? `/settings/executors/${executorProfileId}` : "/settings/executors";
}
function useExecutorTarget(executorProfileName: string | null): string {
const { t } = useTranslation();
return executorProfileName ? `“${executorProfileName}”` : t("task:thisExecutor");
}
function NoCompatibleAgentState({
executorProfileName,
executorProfileId,
@@ -83,23 +99,93 @@ function NoCompatibleAgentState({
executorProfileId: string;
}) {
const { t } = useTranslation();
const target = executorProfileName ? `“${executorProfileName}”` : "this executor";
const href = executorProfileId
? `/settings/executors/${executorProfileId}`
: "/settings/executors";
const target = useExecutorTarget(executorProfileName);
return (
<div
className="flex h-auto min-h-7 items-center justify-between gap-3 rounded-sm border border-input px-3 py-1.5 text-xs text-muted-foreground"
data-testid="agent-profile-empty-state"
>
<span>{t("task:noCompatibleAgentProfilesFor", { target })}</span>
<Link href={href} className="shrink-0 cursor-pointer text-primary hover:underline">
<Link
href={credentialsHref(executorProfileId)}
className="shrink-0 cursor-pointer text-primary hover:underline"
>
{t("task:configureCredentials")}
</Link>
</div>
);
}
/**
* The selected agent is not configured on the executor while another agent
* is. Under a workflow lock the note replaces the selector, because the
* locked profile is not among the compatible options; otherwise it sits under
* the selector until the automatic replacement lands.
*/
function IncompatibleAgentNote({
workflowName,
agentName,
executorProfileName,
executorProfileId,
}: {
workflowName: string | null;
agentName: string | null;
executorProfileName: string | null;
executorProfileId: string;
}) {
const { t } = useTranslation();
const target = useExecutorTarget(executorProfileName);
const agent =
agentName ??
t(
workflowName
? "task:selectedAgentProfileFallbackInline"
: "task:selectedAgentProfileFallback",
);
const copy = workflowName
? t("task:workflowAgentNotConfiguredOnExecutor", { workflow: workflowName, agent, target })
: t("task:agentNotConfiguredOnExecutor", { agent, target });
const boxed = workflowName !== null;
return (
<div
className={
boxed
? "flex h-auto min-h-7 flex-wrap items-center justify-between gap-x-3 gap-y-1 rounded-sm border border-input px-3 py-1.5 text-xs text-muted-foreground"
: "mt-1 flex flex-wrap items-center justify-between gap-x-3 gap-y-1 text-[11px] text-muted-foreground"
}
data-testid="agent-profile-incompatible-note"
>
<span>{copy}</span>
<Link
href={credentialsHref(executorProfileId)}
className="shrink-0 cursor-pointer text-primary hover:underline"
>
{t("task:configureCredentials")}
</Link>
</div>
);
}
function UnavailableAgentNote({
agentName,
visible,
}: {
agentName: string | null;
visible: boolean;
}) {
const { t } = useTranslation();
if (!visible) return null;
const agent = agentName ?? t("task:selectedAgentProfileFallback");
return (
<div
className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-muted-foreground"
data-testid="agent-profile-unavailable-note"
>
<span>{t("task:selectedAgentProfileUnavailable", { agent })}</span>
</div>
);
}
function AgentColumn({
agentProfiles,
agentProfilesLoading,
@@ -109,7 +195,9 @@ function AgentColumn({
isCreatingSession,
AgentSelectorComponent,
workflowAgentLocked,
noCompatibleAgent,
agentCompatState,
selectedAgentProfileName,
effectiveWorkflowName,
executorProfileName,
executorProfileId,
}: AgentColumnProps) {
@@ -127,7 +215,8 @@ function AgentColumn({
</div>
);
}
if (noCompatibleAgent && !agentProfilesLoading) {
const settled = !agentProfilesLoading;
if (settled && agentCompatState === "none-compatible") {
return (
<NoCompatibleAgentState
executorProfileName={executorProfileName}
@@ -135,6 +224,18 @@ function AgentColumn({
/>
);
}
const selectedIncompatible = settled && agentCompatState === "selected-incompatible";
const selectedUnavailable = settled && agentCompatState === "selected-unavailable";
if (selectedIncompatible && workflowAgentLocked) {
return (
<IncompatibleAgentNote
workflowName={effectiveWorkflowName ?? ""}
agentName={selectedAgentProfileName}
executorProfileName={executorProfileName}
executorProfileId={executorProfileId}
/>
);
}
const placeholder = agentProfilesLoading ? t("task:loadingAgents") : t("task:selectAgent");
return (
<>
@@ -146,6 +247,15 @@ function AgentColumn({
disabled={agentProfilesLoading || isCreatingSession || workflowAgentLocked}
popoverPortal
/>
{selectedIncompatible && (
<IncompatibleAgentNote
workflowName={null}
agentName={selectedAgentProfileName}
executorProfileName={executorProfileName}
executorProfileId={executorProfileId}
/>
)}
<UnavailableAgentNote agentName={selectedAgentProfileName} visible={selectedUnavailable} />
{workflowAgentLocked && (
<p className="text-[11px] text-muted-foreground mt-1">{t("task:agentSetByWorkflow")}</p>
)}
@@ -3,6 +3,7 @@ import type { DialogFormState } from "./task-create-dialog-types";
import {
computeHasAllBranches,
localRepositoryCreationEnabled,
resolveWorkflowName,
} from "./task-create-dialog-prop-builders";
function formState(overrides: Partial<DialogFormState>): DialogFormState {
@@ -85,3 +86,19 @@ describe("localRepositoryCreationEnabled", () => {
expect(localRepositoryCreationEnabled(true, true)).toBe(false);
});
});
describe("resolveWorkflowName", () => {
const workflows = [
{ id: "wf-dev", name: "Development" },
{ id: "wf-ops", name: "Operations" },
];
it("returns the name of the effective workflow", () => {
expect(resolveWorkflowName(workflows, "wf-dev")).toBe("Development");
});
it("returns null when no workflow is effective or the id is unknown", () => {
expect(resolveWorkflowName(workflows, null)).toBeNull();
expect(resolveWorkflowName(workflows, "wf-missing")).toBeNull();
});
});
@@ -83,7 +83,9 @@ export function buildDialogFormBodyProps(
// applying a set writes fs.repositories just as they would.
repositorySets: repoLocked ? undefined : setup.repositorySets,
isLocalExecutor: computed.isLocalExecutor,
noCompatibleAgent: computed.noCompatibleAgent,
agentCompatState: computed.agentCompatState,
selectedAgentProfileName: computed.selectedAgentProfileName,
effectiveWorkflowName: resolveWorkflowName(setup.workflows, computed.effectiveWorkflowId),
executorProfileName: computed.selectedExecutorProfileName,
extraFormSlot: props.extraFormSlot,
aboveDescriptionSlot: props.aboveDescriptionSlot,
@@ -93,6 +95,15 @@ export function buildDialogFormBodyProps(
};
}
/** Name of the effective workflow, for copy that has to name it. */
export function resolveWorkflowName(
workflows: ReadonlyArray<{ id: string; name: string }>,
effectiveWorkflowId: string | null | undefined,
): string | null {
if (!effectiveWorkflowId) return null;
return workflows.find((workflow) => workflow.id === effectiveWorkflowId)?.name ?? null;
}
export function buildDialogFooterProps(
setup: ReturnType<typeof useTaskCreateDialogSetup>,
props: TaskCreateDialogProps,
@@ -116,6 +127,8 @@ export function buildDialogFooterProps(
effectiveWorkflowId: computed.effectiveWorkflowId ?? null,
executorHint: computed.executorHint,
noCompatibleAgent: computed.noCompatibleAgent,
agentCompatState: computed.agentCompatState,
selectedAgentProfileName: computed.selectedAgentProfileName,
executorProfileName: computed.selectedExecutorProfileName,
onCancel: submitHandlers.handleCancel,
onUpdateWithoutAgent: submitHandlers.handleUpdateWithoutAgent,
@@ -1,17 +1,28 @@
import { renderHook } from "@testing-library/react";
import type { FormEvent } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { TaskCreateDialogProps } from "./task-create-dialog";
const mocks = vi.hoisted(() => ({
agentGeneratedTaskTitles: false,
submit: vi.fn(),
compatibilityBlocked: false,
agentCompatState: "compatible" as
| "compatible"
| "selected-incompatible"
| "selected-unavailable"
| "none-compatible",
shortcutHandler: null as ((event: unknown) => void) | null,
submitDeps: {} as Record<string, unknown>,
}));
vi.mock("@/lib/keyboard/constants", () => ({ SHORTCUTS: { SUBMIT: "submit" } }));
vi.mock("@/hooks/use-is-utility-configured", () => ({ useIsUtilityConfigured: () => false }));
vi.mock("@/hooks/use-keyboard-shortcut", () => ({
useKeyboardShortcutHandler: () => vi.fn(),
useKeyboardShortcutHandler: (_shortcut: string, handler: (event: unknown) => void) => {
mocks.shortcutHandler = handler;
return vi.fn();
},
}));
vi.mock("@/hooks/use-utility-agent-generator", () => ({
useUtilityAgentGenerator: () => ({ enhancePrompt: vi.fn(), isEnhancingPrompt: false }),
@@ -122,7 +133,8 @@ vi.mock("@/components/task-create-dialog-state", () => ({
agentProfilesLoading: false,
executorsLoading: false,
workflowAgentLocked: false,
noCompatibleAgent: false,
noCompatibleAgent: mocks.compatibilityBlocked,
agentCompatState: mocks.agentCompatState,
selectedExecutorProfileName: "",
executorHint: "",
hasRepositorySelection: false,
@@ -148,6 +160,9 @@ const props: TaskCreateDialogProps = {
describe("useTaskCreateDialogSetup auto-title mode", () => {
beforeEach(() => {
mocks.agentGeneratedTaskTitles = false;
mocks.compatibilityBlocked = false;
mocks.agentCompatState = "compatible";
mocks.shortcutHandler = null;
mocks.submit.mockReset();
});
@@ -172,3 +187,23 @@ it("forwards the selected dependencies to the submit handlers", () => {
renderHook(() => useTaskCreateDialogSetup({ ...props, mode: "create" }));
expect(mocks.submitDeps.blockedBy).toEqual(["dep-1"]);
});
describe("compatibility submit guard", () => {
it.each(["selected-incompatible", "none-compatible"] as const)(
"blocks the form and keyboard submit for %s",
(agentCompatState) => {
mocks.compatibilityBlocked = true;
mocks.agentCompatState = agentCompatState;
const { result } = renderHook(() => useTaskCreateDialogSetup({ ...props, mode: "create" }));
const event = { preventDefault: vi.fn() } as unknown as FormEvent;
const shortcutEvent = { preventDefault: vi.fn() } as unknown as FormEvent;
result.current.guardedHandleSubmit(event);
mocks.shortcutHandler?.(shortcutEvent);
expect(event.preventDefault).toHaveBeenCalledTimes(1);
expect(shortcutEvent.preventDefault).toHaveBeenCalledTimes(1);
expect(mocks.submit).not.toHaveBeenCalled();
},
);
});
@@ -378,6 +378,7 @@ export function useTaskCreateDialogSetup(
const guardedHandleSubmit = useGuardedSubmit(
submitHandlers.handleSubmit,
resolvedProps.submitBlockedReason,
!isTaskStarted && computed.noCompatibleAgent,
);
const handleKeyDown = useKeyboardShortcutHandler(SHORTCUTS.SUBMIT, (event) => {
guardedHandleSubmit(event as unknown as FormEvent);
@@ -468,8 +469,9 @@ function useRepositorySetsForDialog({
function useGuardedSubmit(
handleSubmit: (e: FormEvent) => void,
blockedReason: string | null | undefined,
compatibilityBlocked: boolean,
) {
const blocked = Boolean(blockedReason);
const blocked = Boolean(blockedReason) || compatibilityBlocked;
return useCallback(
(e: FormEvent) => {
if (blocked) e.preventDefault();
@@ -224,6 +224,25 @@ export type StoreSelections = {
effectiveWorkflowId?: string | null;
};
/**
* Agent-profile compatibility with the selected executor profile.
* compatible: no executor selected, nothing selected yet, or the
* selection passes the executor's credential check.
* selected-incompatible: a compatible profile exists but the selected one
* fails the executor credential check (e.g. executor
* switched after the agent was chosen, or a workflow
* pins it).
* selected-unavailable: a compatible profile exists, but the current
* selection is disabled or unavailable because dynamic
* routing is off.
* none-compatible: an executor is selected and no profile passes.
*/
export type AgentCompatState =
| "compatible"
| "selected-incompatible"
| "selected-unavailable"
| "none-compatible";
export type DialogComputedValues = {
isPassthroughProfile: boolean;
effectiveWorkflowId: string | null;
@@ -246,8 +265,12 @@ export type DialogComputedValues = {
effectiveAgentProfileId: string;
/** Display name of the currently selected executor profile (null if none). */
selectedExecutorProfileName: string | null;
/** True when an executor profile is selected and no agent profile is compatible with it. */
/** True whenever `agentCompatState` is not `compatible`; gates submission. */
noCompatibleAgent: boolean;
/** Compatibility state of the effective agent profile with the selected executor profile. */
agentCompatState: AgentCompatState;
/** Label of the effective agent profile (null when none is selected or it is unknown). */
selectedAgentProfileName: string | null;
/** Subset of agent profiles that pass the executor's auth-credential check. See `StoreSelections.compatibleAgentProfiles`. */
compatibleAgentProfiles: AgentProfileOption[];
/** True once the remote-auth catalog has been fetched. See `StoreSelections.authLoaded`. */
@@ -624,7 +647,11 @@ export type DialogFormBodyProps = {
* branch for local execution; fresh-branch mode unlocks it).
*/
isLocalExecutor: boolean;
noCompatibleAgent: boolean;
agentCompatState: AgentCompatState;
/** Label of the effective agent profile, for the incompatible-agent note. */
selectedAgentProfileName: string | null;
/** Name of the effective workflow, for the workflow-locked incompatible note. */
effectiveWorkflowName: string | null;
executorProfileName: string | null;
/** Optional render slot above the description editor. */
aboveDescriptionSlot?: React.ReactNode;
+3 -1
View File
@@ -137,7 +137,9 @@ function CreateModeAgentSelectors(props: DialogFormBodyProps) {
onAgentProfileChange={props.onAgentProfileChange}
onExecutorProfileChange={props.onExecutorProfileChange}
workflowAgentLocked={props.workflowAgentLocked}
noCompatibleAgent={props.noCompatibleAgent}
agentCompatState={props.agentCompatState}
selectedAgentProfileName={props.selectedAgentProfileName}
effectiveWorkflowName={props.effectiveWorkflowName}
executorProfileName={props.executorProfileName}
/>
);
@@ -0,0 +1,113 @@
import type { Page } from "@playwright/test";
import type { ApiClient } from "../../helpers/api-client";
/**
* Stand up the one situation the compatibility gate has to distinguish: an
* executor profile on which the seeded agent has no credentials while a
* second agent type is compatible. The E2E backend registers only the mock
* agent, so callers first restart it with `KANDEV_MOCK_PROVIDERS: "codex-acp"`
* to get that second type; the remote-credentials catalog is then mocked so
* the seeded agent needs an env secret the Docker profile does not carry and
* the Codex alias needs nothing.
*/
export const SECOND_AGENT_ID = "codex-acp";
const SECOND_AGENT_DISPLAY_NAME = "Mock Codex";
type Scenario = {
seedProfileName: string;
compatibleProfileName: string;
/** Display name shared by every profile of the second agent type. */
secondAgentDisplayName: string;
dockerProfileId: string;
cleanup: () => Promise<void>;
};
export async function seedIncompatibleAgentScenario(
apiClient: ApiClient,
page: Page,
seedAgentProfileId: string,
names: { executor: string; dockerProfile: string; compatibleProfile: string },
): Promise<Scenario> {
const seedProfile = await apiClient.getAgentProfile(seedAgentProfileId);
const { agents } = await apiClient.listAgents();
const seedAgent = agents.find((item) => item.profiles?.some((p) => p.id === seedProfile.id));
if (!seedAgent) throw new Error(`agent for profile ${seedProfile.id} not found`);
const secondAgent = agents.find((item) => item.name === SECOND_AGENT_ID);
if (!secondAgent) {
throw new Error(`${SECOND_AGENT_ID} is not registered; restart with KANDEV_MOCK_PROVIDERS`);
}
const compatibleProfile = await apiClient.createAgentProfile(
secondAgent.id,
names.compatibleProfile,
{ model: "mock-fast" },
);
const dockerExec = await apiClient.createExecutor(names.executor, "local_docker");
const dockerProfile = await apiClient.createExecutorProfile(dockerExec.id, {
name: names.dockerProfile,
config: {
image_tag: "kandev-mock-agent:test",
dockerfile: "FROM busybox\nWORKDIR /workspace\n",
},
});
await page.route("**/api/v1/remote-credentials", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
auth_specs: [
{
id: seedAgent.name,
display_name: seedProfile.agentDisplayName,
methods: [{ method_id: "test-token", type: "env", env_var: "TEST_TOKEN" }],
},
{ id: SECOND_AGENT_ID, display_name: SECOND_AGENT_DISPLAY_NAME, methods: [] },
],
}),
});
});
return {
seedProfileName: seedProfile.name,
compatibleProfileName: compatibleProfile.name,
secondAgentDisplayName: SECOND_AGENT_DISPLAY_NAME,
dockerProfileId: dockerProfile.id,
cleanup: async () => {
await apiClient.deleteExecutor(dockerExec.id).catch(() => {});
await apiClient.deleteAgentProfile(compatibleProfile.id, true).catch(() => {});
},
};
}
/** Pin `agentProfileId` on a fresh workflow and make it the dialog's remembered workflow. */
export async function seedLockedWorkflow(
apiClient: ApiClient,
workspaceId: string,
boardWorkflowId: string,
name: string,
agentProfileId: string,
): Promise<{ id: string; cleanup: () => Promise<void> }> {
const workflow = await apiClient.createWorkflow(workspaceId, name, "simple");
await apiClient.updateWorkflow(workflow.id, { agent_profile_id: agentProfileId });
const steps = await apiClient.listWorkflowSteps(workflow.id);
const startStep = steps.steps.find((step) => step.is_start_step) ?? steps.steps[0];
if (!startStep) throw new Error(`${name} workflow has no start step`);
// The dialog restores the last-used workflow per workspace, so a task in
// the locked workflow makes it the dialog's effective workflow.
await apiClient.createTask(workspaceId, `Remembered ${name} task`, {
workflow_id: workflow.id,
workflow_step_id: startStep.id,
});
await apiClient.saveUserSettings({
workspace_id: workspaceId,
workflow_filter_id: boardWorkflowId,
});
return {
id: workflow.id,
cleanup: async () => {
await apiClient.deleteWorkflow(workflow.id).catch(() => {});
await apiClient.saveUserSettings({
workspace_id: workspaceId,
workflow_filter_id: boardWorkflowId,
});
},
};
}
+127
View File
@@ -2,6 +2,7 @@ import { test, expect } from "../../fixtures/test-base";
import { useRegularMode } from "../../helpers/regular-mode";
import { KanbanPage } from "../../pages/kanban-page";
import { SessionPage } from "../../pages/session-page";
import { seedIncompatibleAgentScenario, seedLockedWorkflow } from "./agent-compatibility-helpers";
// Exercises the regular task-create dialog (New Task in the sidebar), so run
// with the office feature disabled.
@@ -704,3 +705,129 @@ async function getTaskIdFromPage(page: import("@playwright/test").Page): Promise
if (!match) throw new Error(`Cannot extract task ID from URL: ${url}`);
return match[1];
}
test.describe("Task creation agent compatibility", () => {
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.1
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.2
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.6
test("replaces the selected agent with a compatible one when the executor changes", async ({
testPage,
apiClient,
backend,
seedData,
}) => {
await backend.restart({ KANDEV_MOCK_PROVIDERS: "codex-acp" });
const scenario = await seedIncompatibleAgentScenario(
apiClient,
testPage,
seedData.agentProfileId,
{
executor: "E2E Docker Replace Agent",
dockerProfile: "Docker Codex Only",
compatibleProfile: "Codex Compatible",
},
);
try {
const kanban = new KanbanPage(testPage);
await kanban.goto();
await kanban.createTaskButton.first().click();
const dialog = testPage.getByTestId("create-task-dialog");
await expect(dialog).toBeVisible();
await dialog.getByTestId("task-title-input").fill("Replace incompatible agent");
await dialog.getByTestId("task-description-input").fill("executor switch after agent pick");
// Make sure the seeded agent is the selection while the default executor
// still accepts it. The dialog usually restores it on its own; clicking
// an already-selected option would toggle it off, so only pick it when
// something else is selected.
const agentSelector = dialog.getByTestId("agent-profile-selector");
if (!(await agentSelector.textContent())?.includes(scenario.seedProfileName)) {
await agentSelector.click();
await testPage
.getByRole("listbox")
.getByRole("option")
.filter({ hasText: scenario.seedProfileName })
.filter({ hasNotText: scenario.secondAgentDisplayName })
.first()
.click();
}
await expect(agentSelector).toContainText(scenario.seedProfileName);
await expect(agentSelector).not.toContainText(scenario.secondAgentDisplayName);
await testPage.getByTestId("executor-profile-selector").click();
await testPage.getByRole("option", { name: /Docker Codex Only/i }).click();
// The mocked alias also ships a default profile, so the replacement can
// be either Codex profile; what matters is that it is no longer the seed.
await expect(agentSelector).toContainText(scenario.secondAgentDisplayName);
await expect(agentSelector).not.toContainText(scenario.seedProfileName);
await expect(dialog.getByTestId("agent-profile-empty-state")).toHaveCount(0);
await expect(dialog.getByTestId("agent-profile-incompatible-note")).toHaveCount(0);
await expect(dialog.getByTestId(START_AGENT_TEST_ID)).toBeEnabled({
timeout: START_ENABLED_TIMEOUT,
});
} finally {
await scenario.cleanup();
await backend.restart();
}
});
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.5
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.6
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.7
test("names the workflow-locked agent when the executor lacks its credentials", async ({
testPage,
apiClient,
backend,
seedData,
}) => {
await backend.restart({ KANDEV_MOCK_PROVIDERS: "codex-acp" });
const scenario = await seedIncompatibleAgentScenario(
apiClient,
testPage,
seedData.agentProfileId,
{
executor: "E2E Docker Locked Agent",
dockerProfile: "Docker Locked Auth",
compatibleProfile: "Codex Unlocked",
},
);
const workflow = await seedLockedWorkflow(
apiClient,
seedData.workspaceId,
seedData.workflowId,
"Locked Agent",
seedData.agentProfileId,
);
try {
const kanban = new KanbanPage(testPage);
await kanban.goto();
await kanban.createTaskButton.first().click();
const dialog = testPage.getByTestId("create-task-dialog");
await expect(dialog).toBeVisible();
await expect(dialog.getByTestId("workflow-selector-trigger")).toContainText("Locked Agent");
await dialog.getByTestId("task-title-input").fill("Locked agent task");
await dialog.getByTestId("task-description-input").fill("workflow-locked incompatible agent");
await testPage.getByTestId("executor-profile-selector").click();
await testPage.getByRole("option", { name: /Docker Locked Auth/i }).click();
const note = dialog.getByTestId("agent-profile-incompatible-note");
await expect(note).toContainText("Locked Agent");
await expect(note).toContainText(scenario.seedProfileName);
await expect(note).toContainText("Docker Locked Auth");
await expect(dialog.getByRole("link", { name: "Configure credentials" })).toHaveAttribute(
"href",
`/settings/executors/${scenario.dockerProfileId}`,
);
await expect(dialog.getByTestId("agent-profile-empty-state")).toHaveCount(0);
await expect(dialog.getByTestId(START_AGENT_TEST_ID)).toBeDisabled();
} finally {
await workflow.cleanup();
await scenario.cleanup();
await backend.restart();
}
});
});
@@ -0,0 +1,153 @@
import { expect, test } from "../../fixtures/test-base";
import { useRegularMode } from "../../helpers/regular-mode";
import { MobileKanbanPage } from "../../pages/mobile-kanban-page";
import { seedIncompatibleAgentScenario, seedLockedWorkflow } from "./agent-compatibility-helpers";
useRegularMode();
const MOBILE_WIDTH = 390;
test.describe("Task creation agent compatibility on mobile", () => {
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.5
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.9
test("shows the workflow-locked note and keeps the credentials link reachable", async ({
testPage,
apiClient,
backend,
seedData,
}) => {
await backend.restart({ KANDEV_MOCK_PROVIDERS: "codex-acp" });
const scenario = await seedIncompatibleAgentScenario(
apiClient,
testPage,
seedData.agentProfileId,
{
executor: "E2E Mobile Docker Locked Agent",
dockerProfile: "Mobile Docker Locked Auth",
compatibleProfile: "Mobile Codex Unlocked",
},
);
const workflow = await seedLockedWorkflow(
apiClient,
seedData.workspaceId,
seedData.workflowId,
"Mobile Locked Agent",
seedData.agentProfileId,
);
try {
await testPage.setViewportSize({ width: MOBILE_WIDTH, height: 844 });
const mobile = new MobileKanbanPage(testPage);
await mobile.goto();
await mobile.mobileFab.tap();
const dialog = testPage.getByTestId("create-task-dialog");
await expect(dialog).toBeVisible();
await expect(dialog.getByTestId("workflow-selector-trigger")).toContainText(
"Mobile Locked Agent",
);
await dialog.getByTestId("task-title-input").fill("Mobile locked agent task");
await dialog.getByTestId("task-description-input").fill("workflow-locked on a phone");
const executorSelector = dialog.getByTestId("executor-profile-selector");
await expect(executorSelector).toBeVisible();
await expect(executorSelector).toBeEnabled();
await executorSelector.tap();
const executorOption = testPage.getByRole("option", {
name: /Mobile Docker Locked Auth/i,
});
await expect(executorOption).toBeVisible();
await executorOption.tap();
await expect(executorSelector).toContainText("Mobile Docker Locked Auth");
const note = dialog.getByTestId("agent-profile-incompatible-note");
await expect(note).toBeVisible();
await expect(note).toContainText("Mobile Locked Agent");
await expect(note).toContainText(scenario.seedProfileName);
await expect(note).toContainText("Mobile Docker Locked Auth");
const link = dialog.getByRole("link", { name: "Configure credentials" });
await expect(link).toBeVisible();
await expect(link).toHaveAttribute("href", `/settings/executors/${scenario.dockerProfileId}`);
await expect(dialog.getByTestId("agent-profile-empty-state")).toHaveCount(0);
await expect(dialog.getByTestId("submit-start-agent")).toBeDisabled();
expect(
await testPage.evaluate(() => document.documentElement.scrollWidth),
).toBeLessThanOrEqual(MOBILE_WIDTH);
await link.tap();
await expect(testPage).toHaveURL(
new RegExp(`/settings/executors/${scenario.dockerProfileId}(?:\\?.*)?$`),
);
} finally {
await workflow.cleanup();
await scenario.cleanup();
await backend.restart();
}
});
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.1
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.2
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.6
// @covers AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.9
test("replaces an incompatible selection on a phone", async ({
testPage,
apiClient,
backend,
seedData,
}) => {
await backend.restart({ KANDEV_MOCK_PROVIDERS: "codex-acp" });
const scenario = await seedIncompatibleAgentScenario(
apiClient,
testPage,
seedData.agentProfileId,
{
executor: "E2E Mobile Docker Replace Agent",
dockerProfile: "Mobile Docker Codex Only",
compatibleProfile: "Mobile Codex Compatible",
},
);
try {
await testPage.setViewportSize({ width: MOBILE_WIDTH, height: 844 });
const mobile = new MobileKanbanPage(testPage);
await mobile.goto();
await mobile.mobileFab.tap();
const dialog = testPage.getByTestId("create-task-dialog");
await expect(dialog).toBeVisible();
await dialog.getByTestId("task-title-input").fill("Mobile replacement task");
await dialog.getByTestId("task-description-input").fill("executor switch on a phone");
const agentSelector = dialog.getByTestId("agent-profile-selector");
if (!(await agentSelector.textContent())?.includes(scenario.seedProfileName)) {
await agentSelector.tap();
const seedOption = testPage
.getByRole("option", { name: new RegExp(scenario.seedProfileName) })
.first();
await expect(seedOption).toBeVisible();
await seedOption.tap();
}
await expect(agentSelector).toContainText(scenario.seedProfileName);
const executorSelector = dialog.getByTestId("executor-profile-selector");
await expect(executorSelector).toBeVisible();
await expect(executorSelector).toBeEnabled();
await executorSelector.tap();
const executorOption = testPage.getByRole("option", {
name: /Mobile Docker Codex Only/i,
});
await expect(executorOption).toBeVisible();
await executorOption.tap();
await expect(executorSelector).toContainText("Mobile Docker Codex Only");
await expect(agentSelector).toContainText(scenario.secondAgentDisplayName);
await expect(agentSelector).not.toContainText(scenario.seedProfileName);
await expect(dialog.getByTestId("agent-profile-empty-state")).toHaveCount(0);
await expect(dialog.getByTestId("agent-profile-incompatible-note")).toHaveCount(0);
await expect(dialog.getByTestId("submit-start-agent")).toBeEnabled();
expect(
await testPage.evaluate(() => document.documentElement.scrollWidth),
).toBeLessThanOrEqual(MOBILE_WIDTH);
} finally {
await scenario.cleanup();
await backend.restart();
}
});
});
+6
View File
@@ -892,6 +892,12 @@
"noCommentsYet": "No comments yet",
"noCompatibleAgentProfileFor": "No compatible agent profile is configured for {{target}}. Configure agent credentials in Settings → Executors.",
"noCompatibleAgentProfilesFor": "No compatible agent profiles for {{target}}.",
"agentNotConfiguredOnExecutor": "{{agent}} is not configured on {{target}}.",
"workflowAgentNotConfiguredOnExecutor": "The {{workflow}} workflow uses {{agent}}, which is not configured on {{target}}.",
"selectedAgentNotConfiguredFor": "{{agent}} is not configured on {{target}}. Configure agent credentials in Settings → Executors.",
"selectedAgentProfileFallback": "The selected agent profile",
"selectedAgentProfileFallbackInline": "the selected agent profile",
"selectedAgentProfileUnavailable": "{{agent}} is unavailable. Select a compatible agent profile.",
"noContent": "No content",
"noDecisionYet": "No decision yet",
"noDependency": "No dependency",
+6
View File
@@ -892,6 +892,12 @@
"noCommentsYet": "Ńō ćōḿḿēńţś ŷēţ",
"noCompatibleAgentProfileFor": "Ńō ćōḿƥàţĩƀĺē àĝēńţ ƥŕōƒĩĺē ĩś ćōńƒĩĝũŕēď ƒōŕ {{target}}. Ćōńƒĩĝũŕē àĝēńţ ćŕēďēńţĩàĺś ĩń Śēţţĩńĝś → Ēxēćũţōŕś.",
"noCompatibleAgentProfilesFor": "Ńō ćōḿƥàţĩƀĺē àĝēńţ ƥŕōƒĩĺēś ƒōŕ {{target}}.",
"agentNotConfiguredOnExecutor": "{{agent}} ĩś ńōţ ćōńƒĩĝũŕēď ōń {{target}}.",
"workflowAgentNotConfiguredOnExecutor": "Ţĥē {{workflow}} ŵōŕķƒĺōŵ ũśēś {{agent}}, ŵĥĩćĥ ĩś ńōţ ćōńƒĩĝũŕēď ōń {{target}}.",
"selectedAgentNotConfiguredFor": "{{agent}} ĩś ńōţ ćōńƒĩĝũŕēď ōń {{target}}. Ćōńƒĩĝũŕē àĝēńţ ćŕēďēńţĩàĺś ĩń Śēţţĩńĝś → Ēxēćũţōŕś.",
"selectedAgentProfileFallback": "Ţĥē śēĺēćţēď àĝēńţ ƥŕōƒĩĺē",
"selectedAgentProfileFallbackInline": "ţĥē śēĺēćţēď àĝēńţ ƥŕōƒĩĺē",
"selectedAgentProfileUnavailable": "{{agent}} ĩś ũńàvàĩĺàƀĺē. Śēĺēćţ à ćōḿƥàţĩƀĺē àĝēńţ ƥŕōƒĩĺē.",
"noContent": "Ńō ćōńţēńţ",
"noDecisionYet": "Ńō ďēćĩśĩōń ŷēţ",
"noDependency": "Ńō ďēƥēńďēńćŷ",
+6
View File
@@ -846,6 +846,12 @@
"noCommentsYet": "Ainda não há comentários",
"noCompatibleAgentProfileFor": "Não há nenhum perfil de agente compatível configurado para {{target}}. Configure as credenciais dos agentes em Definições → Executores.",
"noCompatibleAgentProfilesFor": "Não há perfis de agente compatíveis com {{target}}.",
"agentNotConfiguredOnExecutor": "{{agent}} não está configurado em {{target}}.",
"workflowAgentNotConfiguredOnExecutor": "O fluxo de trabalho {{workflow}} usa {{agent}}, que não está configurado em {{target}}.",
"selectedAgentNotConfiguredFor": "{{agent}} não está configurado em {{target}}. Configure as credenciais dos agentes em Definições → Executores.",
"selectedAgentProfileFallback": "O perfil de agente selecionado",
"selectedAgentProfileFallbackInline": "o perfil de agente selecionado",
"selectedAgentProfileUnavailable": "{{agent}} não está disponível. Selecione um perfil de agente compatível.",
"noContent": "Sem conteúdo",
"noDecisionYet": "Ainda não há decisão",
"noDocumentsFound": "Nenhum documento encontrado.",
+6
View File
@@ -845,6 +845,12 @@
"noCommentsYet": "暂无评论",
"noCompatibleAgentProfileFor": "未为 {{target}} 配置兼容的智能体配置。请在“设置 → 执行器”中配置智能体凭据。",
"noCompatibleAgentProfilesFor": "没有适用于 {{target}} 的兼容智能体配置。",
"agentNotConfiguredOnExecutor": "{{agent}} 未在 {{target}} 上配置。",
"workflowAgentNotConfiguredOnExecutor": "{{workflow}} 工作流使用 {{agent}},但其未在 {{target}} 上配置。",
"selectedAgentNotConfiguredFor": "{{agent}} 未在 {{target}} 上配置。请在“设置 → 执行器”中配置智能体凭据。",
"selectedAgentProfileFallback": "所选智能体配置",
"selectedAgentProfileFallbackInline": "所选智能体配置",
"selectedAgentProfileUnavailable": "{{agent}} 不可用。请选择兼容的智能体配置。",
"noContent": "无内容",
"noDecisionYet": "尚未决定",
"noDocumentsFound": "未找到文档。",
+6
View File
@@ -845,6 +845,12 @@
"noCommentsYet": "暫無評論",
"noCompatibleAgentProfileFor": "未為 {{target}} 設定兼容的代理程式設定檔。請在「設定 → 執行器」中設定代理程式認證資料。",
"noCompatibleAgentProfilesFor": "沒有適用於 {{target}} 的兼容代理程式設定檔。",
"agentNotConfiguredOnExecutor": "{{agent}} 未在 {{target}} 上設定。",
"workflowAgentNotConfiguredOnExecutor": "{{workflow}} 工作流程使用 {{agent}},但其未在 {{target}} 上設定。",
"selectedAgentNotConfiguredFor": "{{agent}} 未在 {{target}} 上設定。請在「設定 → 執行器」中設定代理程式認證資料。",
"selectedAgentProfileFallback": "所選代理程式設定檔",
"selectedAgentProfileFallbackInline": "所選代理程式設定檔",
"selectedAgentProfileUnavailable": "{{agent}} 不可用。請選擇相容的代理程式設定檔。",
"noContent": "無內容",
"noDecisionYet": "尚未決定",
"noDocumentsFound": "未找到文檔。",
+6
View File
@@ -845,6 +845,12 @@
"noCommentsYet": "暫無評論",
"noCompatibleAgentProfileFor": "未為 {{target}} 設定相容的代理程式設定檔。請在「設定 → 執行器」中設定代理程式認證資訊。",
"noCompatibleAgentProfilesFor": "沒有適用於 {{target}} 的相容代理程式設定檔。",
"agentNotConfiguredOnExecutor": "{{agent}} 未在 {{target}} 上設定。",
"workflowAgentNotConfiguredOnExecutor": "{{workflow}} 工作流程使用 {{agent}},但其未在 {{target}} 上設定。",
"selectedAgentNotConfiguredFor": "{{agent}} 未在 {{target}} 上設定。請在「設定 → 執行器」中設定代理程式認證資訊。",
"selectedAgentProfileFallback": "所選代理程式設定檔",
"selectedAgentProfileFallbackInline": "所選代理程式設定檔",
"selectedAgentProfileUnavailable": "{{agent}} 無法使用。請選擇相容的代理程式設定檔。",
"noContent": "無內容",
"noDecisionYet": "尚未決定",
"noDocumentsFound": "未找到檔案。",
@@ -0,0 +1,234 @@
---
created: 2026-09-04
status: implemented
requirements:
- REQ-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001
system_design:
- ../../specs/tasks/system-design/task-create-agent-executor-compatibility.md
legacy_specs: []
---
# Implementation Plan: Task Create Agent Compatibility Recovery
## Overview
Fix [issue #3387](https://github.com/kdlbs/kandev/issues/3387): the task-create
dialog shows "No compatible agent profiles for X" and hides the agent selector
whenever the selected agent is incompatible with the executor, even when other
agents are compatible. The result is a dialog that replaces an incompatible
selection automatically, keeps the selector visible whenever a compatible
profile exists, and names the workflow, agent, and executor when a workflow
lock prevents recovery.
Order: derive the state and the automatic replacement first (pure logic with
unit tests), then the presentation and copy that depend on that state, then the
end-to-end evidence. Each step is independently verifiable.
## Confirmed root cause
- `useExecutorProfileCompat` in `apps/web/components/task-create-dialog-computed.ts`
folds two conditions into one boolean, `noCompatibleAgent`: the compatible
list is empty, or the selected agent is absent from it.
- `AgentColumn` in `apps/web/components/task-create-dialog-form-body.tsx`
renders the same "No compatible agent profiles" empty state for both
conditions and drops the selector, so the second condition has no recovery
path in the UI.
- `handleExecutorProfileChange` in
`apps/web/components/task-create-dialog-handlers.ts` only stores the executor
id, and `decideAgentProfileAutopick` in
`apps/web/components/task-create-dialog-autopick.ts` skips with
`already-set` whenever an agent id is present, so nothing re-validates the
agent after an executor switch.
- The compatibility rule in `apps/web/lib/agent-executor-compat.ts` is correct.
The user's Sprites profile had Claude configured, but the pre-selected agent
was a different agent type.
Reproduction without a browser: the existing
`useDefaultSelectionsEffect` tests in
`apps/web/components/task-create-dialog-effects.test.ts` only cover an empty
`agentProfileId`. A new case with `agentProfileId` set to an incompatible
profile and a non-empty compatible list fails before the fix because
`setAgentProfileId` is never called.
## Scope
### In scope
- A compatibility state derived in the dialog's computed hook, including a
truthful pending state for an unavailable selection.
- Automatic replacement of an incompatible, non-locked selection using the
existing preference order.
- Selector kept visible whenever a compatible profile exists.
- A workflow-locked message naming workflow, agent, and executor.
- Canonical submit preflight for the form, Ctrl/Cmd+Enter shortcut, and
programmatic composer path.
- Footer disabled reasons that match the shown state.
- Translated copy in all five locales plus the regenerated pseudo locale,
including sentence-start and inline fallback forms.
- Desktop and mobile Playwright evidence for the user-visible states.
### Out of scope
- Marking incompatible executors in the executor selector.
- Changing the credential compatibility rule.
- The additional-session, handoff, and quick-chat dialogs.
- Persisting the automatic replacement as the last-used agent.
## Technical approach
### Compatibility state and replacement (`task-create-dialog-computed.ts`, `task-create-dialog-autopick.ts`, `task-create-dialog-types.ts`)
- Add `AgentCompatState` and the pure `computeAgentCompatState` helper next to
`filterCompatibleAgentProfiles`. `useExecutorProfileCompat` returns
`agentCompatState`, keeps `noCompatibleAgent` as
`agentCompatState !== "compatible"`, and returns the effective agent
profile's label as `selectedAgentProfileName`.
- Extend `AutopickDecision`'s `pick` variant with `replaces?: string`. In
`getAgentAutopickGate`, evaluate the replacement gate before the `already-set`
skip. `decideAgentProfileAutopick` reuses the last-used, workspace-default,
first-compatible candidate chain for the replacement.
- `buildAgentAutopickDebugFields` logs `replaces`.
- `DialogComputedValues` gains `agentCompatState` and
`selectedAgentProfileName`.
### Presentation and copy (`task-create-dialog-form-body.tsx`, `task-create-dialog-prop-builders.ts`, `task-create-dialog-footer.tsx`, locales)
- `AgentColumn` branches on `agentCompatState` and `workflowAgentLocked` per
the presentation table in the system design. The incompatible note carries
`data-testid="agent-profile-incompatible-note"`; an unavailable selection
uses a separate truthful note and keeps the selector visible.
- `buildFormBodyProps` forwards `agentCompatState`, `selectedAgentProfileName`,
and `effectiveWorkflowName` (looked up from `setup.workflows` by
`computed.effectiveWorkflowId`).
- `computeDisabledReason` returns state-specific keys for
`selected-incompatible` and `selected-unavailable`; `resolveDisabledReason`
accepts the agent name.
- Add `agentNotConfiguredOnExecutor`, `workflowAgentNotConfiguredOnExecutor`,
`selectedAgentNotConfiguredFor`, `selectedAgentProfileFallback`,
`selectedAgentProfileFallbackInline`, and `selectedAgentProfileUnavailable`
to every `task.json` catalog.
### Submit preflight (`task-create-dialog-setup.ts`, setup tests)
- Pass the derived compatibility block into the canonical guarded submit
handler, so the form, Ctrl/Cmd+Enter shortcut, and programmatic submit cannot
bypass the footer's disabled state.
### End-to-end evidence (`apps/web/e2e/tests/task/`)
- The E2E backend registers the mock agent as its only agent type, so every
profile shares one compatibility result until the backend is restarted with
`KANDEV_MOCK_PROVIDERS: "codex-acp"`, which registers a mocked second agent
type (the pattern `executor-agent-config.spec.ts` already uses). A shared
helper, `agent-compatibility-helpers.ts`, performs that setup: a Codex-alias
profile, a Docker executor profile without credentials, and a
`/api/v1/remote-credentials` route mock that requires an env secret for the
seeded agent and nothing for the alias.
- Desktop: extend `create-task.spec.ts` with two cases: the seeded agent is
picked on the default executor and replaced by the Codex profile after
switching to Docker; and a workflow that pins the seeded profile shows the
workflow-locked note on Docker.
- Mobile: cover both the workflow-locked flow and the unlocked automatic
replacement at a phone viewport. Assert the note, the tappable credentials
link, the disabled or enabled start action, and no horizontal document
overflow.
## Tests
| Acceptance criterion | Evidence |
| --- | --- |
| 001.1, 001.6 | `task-create-dialog-computed.test.ts`: `computeAgentCompatState` returns `selected-incompatible` or `selected-unavailable`, not a false `none-compatible`, when a compatible profile exists. `task-create-dialog-form-body.test.tsx`: `CreateEditSelectors` renders the selector and a truthful note, never the empty state, in those states. |
| 001.2, 001.8 | `task-create-dialog-effects.test.ts`: `decideAgentProfileAutopick` returns a pick with `replaces` for an incompatible non-locked selection and honors last-used, default, and first order; `useDefaultSelectionsEffect` calls `setAgentProfileId` with the replacement and never calls `syncTaskCreateLastUsed`. |
| 001.3 | `task-create-dialog-effects.test.ts`: `decideAgentProfileAutopick` skips with `already-set` when the selection is compatible. |
| 001.4 | Existing `CreateEditSelectors` empty-state test in `task-create-dialog-form-body.test.tsx` and the existing Docker E2E case. |
| 001.5 | `task-create-dialog-form-body.test.tsx`: workflow-locked note names workflow, agent, and executor, with the credentials link. `task-create-dialog-effects.test.ts`: no replacement when the workflow locks the agent. |
| 001.7 | `task-create-dialog-footer.test.ts`: `computeDisabledReason` and `resolveDisabledReason` for both states. |
| Submit guard | `task-create-dialog-setup.test.ts`: form and keyboard submission are prevented for `selected-incompatible` and `none-compatible`. |
| 001.9 | Mobile Playwright spec below. |
## E2E tests
| Flow | AC | File and project |
| --- | --- | --- |
| Docker executor without credentials shows the empty state and disables start (existing). | 001.4 | `tests/task/create-task.spec.ts`, `chromium` |
| Seeded agent picked on the default executor is replaced by the compatible Codex profile after switching to Docker; no empty state or note; start enabled. | 001.1, 001.2, 001.6 | `tests/task/create-task.spec.ts`, `chromium` |
| Workflow-locked agent on a Docker executor without credentials shows the workflow note, keeps the link, disables start. | 001.5, 001.6, 001.7 | `tests/task/create-task.spec.ts`, `chromium` |
| Same workflow-locked flow on a phone viewport, note wraps, link is tapped, no horizontal overflow. | 001.9 | `tests/task/mobile-create-task-agent-compatibility.spec.ts`, `mobile-chrome` |
| Unlocked incompatible selection is replaced on a phone and start becomes enabled. | 001.1, 001.2, 001.6, 001.9 | `tests/task/mobile-create-task-agent-compatibility.spec.ts`, `mobile-chrome` |
## Work orders
- [x] [Task 01: Derive compatibility state and replace incompatible selections](task-01-compat-state-and-replacement.md)
- [x] [Task 02: Present compatibility states with translated copy](task-02-agent-column-presentation.md)
- [x] [Task 03: End-to-end evidence on desktop and mobile](task-03-e2e-evidence.md)
## Dependency order
```text
Task 01 -> Task 02 -> Task 03
```
Task 02 consumes the state contract from Task 01. Task 03 exercises the
rendered result of Task 02 against the production build.
## Verification results
- Task 01: `pnpm exec vitest run` on the computed, effects, workflow-agent
effect, and effects-executor files: 4 files, 66 tests passed. Typecheck and
eslint clean.
- Task 02: `pnpm exec vitest run` on form-body, footer, prop-builders plus the
Task 01 files, dialog, and setup tests: 7 files, 116 tests passed.
`pnpm run i18n:check`, `pnpm run typecheck`, and eslint on every changed
production and test file: clean.
- Task 03: `pnpm e2e:raw tests/task/create-task.spec.ts`: 17 passed.
`pnpm e2e:raw --project=mobile-chrome
tests/task/mobile-create-task-agent-compatibility.spec.ts`: 1 passed.
- Package gates: `pnpm run i18n:ratchet`, `node scripts/check-new-e2e-sleeps.mjs`,
`check-no-em-dash-ui.mjs`, prettier, `python3.13 scripts/lint-spec-files.py --all`,
and `python3.13 scripts/lint-architecture.py --all`: clean.
## Risks
- The replacement effect must not fight the workflow lock effect. The gate
checks both `workflowAgentProfileId` and the synchronous
`workflowHasAgent` lookup, matching the existing autopick guard.
- A profile-list refresh could momentarily drop the selected profile. The gate
requires a non-empty compatible list, so an empty refresh cannot clear a
selection; a non-empty list that lacks the selection is a real incompatibility
or a deleted profile, and replacing it is correct.
- The `selected-incompatible` unlocked state is visible for one render before
the replacement applies. The note is honest for that render and is the only
recovery path if the effect cannot run.
- The `AgentColumn` function is near the 100-line lint cap once it branches on
the new state. Extract the note into its own component.
- Copy changes gate the build: `check-i18n-keys.mjs` fails on a missing key or
an untranslated value in any locale.
### Review remediation results
- Merged the advanced base into the branch; the only conflict was the footer's
reason table, resolved by keeping both new reason keys and evaluating the
compatibility reason before the upstream dependencies-loading reason.
- Codex review (P2): a workflow-locked incompatible agent with no other
compatible profile fell through to the generic empty state. The state helper
now takes the workflow lock and the selected row, keeps
`selected-incompatible` for an enabled locked profile even when the
compatible list is empty, and keeps a disabled locked profile on the empty
state. AC 001.5 and the design derivation record the precedence.
- Reverified: the nine dialog test files (137 tests), typecheck, eslint, i18n
ratchet, prettier, and the specification linter.
### Follow-up remediation
- The guarded submit handler now applies the compatibility block to form,
Ctrl/Cmd+Enter, and programmatic submissions. A focused setup test covers
both selected-incompatible and none-compatible states.
- The compatibility model now distinguishes `selected-unavailable` for an
unlocked disabled or dynamic-off selection with a compatible alternative.
The selector stays visible, submit stays disabled, and the autopick can
replace the selection without showing a false empty state.
- Added sentence-start and inline fallback locale keys, unavailable-state
copy in all catalogs, and updated the requirements and system design.
- Focused Vitest: 8 files, 136 tests passed. Typecheck, ESLint, i18n check and
ratchet, E2E sleep ratchet, specification lint, architecture lint, and the
production-build mobile E2E spec (2 tests) passed.
@@ -0,0 +1,130 @@
---
id: "01-compat-state-and-replacement"
title: "Derive compatibility state and replace incompatible selections"
status: done
wave: 1
depends_on: []
plan: "plan.md"
requirements:
- REQ-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001
acceptance_criteria:
- AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.2
- AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.3
- AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.6
- AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.8
system_design:
- ../../specs/tasks/system-design/task-create-agent-executor-compatibility.md
---
# Task 01: Derive compatibility state and replace incompatible selections
## Summary
Replace the single `noCompatibleAgent` boolean with a derived compatibility
`AgentCompatState` and teach the agent autopick to replace a selection that
became incompatible after an executor switch. Both changes are pure logic with
unit tests and do not touch rendering.
## In scope
- Add `AgentCompatState` and `computeAgentCompatState` to
`task-create-dialog-computed.ts`; return `agentCompatState` and
`selectedAgentProfileName` from `useExecutorProfileCompat` and
`useDialogComputed`; keep `noCompatibleAgent` derived from the state.
- Keep an unlocked disabled or dynamic-off selection in a distinct
`selected-unavailable` state while a compatible alternative exists. Preserve
the `none-compatible` behavior for a locked disabled profile.
- Add the replacement gate to `getAgentAutopickGate` and the `replaces` field
to the `pick` decision in `task-create-dialog-autopick.ts`; log `replaces`
in the autopick debug fields.
- Extend `DialogComputedValues` in `task-create-dialog-types.ts`.
- Regression tests listed under Verification.
## Out of scope
- Any change to `AgentColumn`, the footer, prop builders, or locale files.
- Any change to `isAgentConfiguredOnExecutor` or the remote-auth catalog.
- Writing the replacement to the last-used preference.
## Acceptance
- `computeAgentCompatState` returns `selected-incompatible` when the effective
agent fails the executor credential check, `selected-unavailable` for an
unlocked disabled or dynamic-off selection when another compatible profile
exists, `none-compatible` when no profile passes (including a locked disabled
profile), and `compatible` otherwise.
- With an executor selected, auth loaded, no workflow lock, and a non-empty
compatible list that lacks the current selection,
`decideAgentProfileAutopick` returns a `pick` whose `replaces` is the current
id, chosen in last-used, workspace-default, first-compatible order; with a
workflow lock or a compatible selection it returns the existing skip.
- `useDefaultSelectionsEffect` applies the replacement through
`setAgentProfileId` and never calls `syncTaskCreateLastUsed`.
## Verification
Write the failing hook test first: `agentProfileId` set to an incompatible
profile, two compatible profiles, expect `setAgentProfileId` to be called with
the first compatible one. Confirm it fails before the production change, then
run:
```bash
# Fresh worktree only, once:
cd apps && pnpm install --frozen-lockfile
# From apps/web:
pnpm exec vitest run components/task-create-dialog-computed.test.ts components/task-create-dialog-effects.test.ts components/task-create-dialog-workflow-agent-effect.test.ts components/task-create-dialog-effects-executor.test.ts
pnpm run typecheck
pnpm exec eslint --max-warnings 0 components/task-create-dialog-computed.ts components/task-create-dialog-autopick.ts components/task-create-dialog-types.ts
```
## Files likely touched
- `apps/web/components/task-create-dialog-computed.ts`
- `apps/web/components/task-create-dialog-computed.test.ts`
- `apps/web/components/task-create-dialog-autopick.ts`
- `apps/web/components/task-create-dialog-effects.test.ts`
- `apps/web/components/task-create-dialog-types.ts`
## Dependencies
None.
## Risks
- The replacement gate must run before the `already-set` skip but after the
`closed`, `workflow-locked`, and `workflow-has-agent` skips, or a locked
selection could be replaced.
- `useWorkflowAgentProfileEffect` also writes `agentProfileId`. Keep the
replacement gated on the same lock inputs so the two effects never alternate.
## Parallelism
`sequential`
## Inputs
- System design sections "Data and contracts" and "Control flow".
- Existing `decideAgentProfileAutopick` tests and the
`useDefaultSelectionsEffect` harness in `task-create-dialog-effects.test.ts`.
## Results
- Added `AgentCompatState` (`task-create-dialog-types.ts`) and the pure
`computeAgentCompatState` helper; `useExecutorProfileCompat` now returns
`agentCompatState` and `selectedAgentProfileName`, with `noCompatibleAgent`
derived from the state.
- `decideAgentProfileAutopick` evaluates `selectionNeedsReplacement` before the
`already-set` skip and returns a `pick` carrying `replaces`; the debug fields
log it.
- RED: 9 new tests failed (helper missing, decision returned `already-set`,
hook never called `setAgentProfileId`). GREEN: all pass. One legacy test that
asserted an incompatible pre-set selection is left alone was removed because
AC 001.2 supersedes it; the compatible-selection half is covered by the new
"keeps a selection that stays compatible" test.
- `pnpm exec vitest run` on the four named files: 4 files, 66 tests passed.
`pnpm run typecheck`: clean. `pnpm exec eslint --max-warnings 0` on the three
production files: clean.
Follow-up verification added the `selected-unavailable` state for unlocked
disabled or dynamic-off selections with an alternative, plus submit-guard
coverage in `task-create-dialog-setup.test.ts`.
@@ -0,0 +1,140 @@
---
id: "02-agent-column-presentation"
title: "Present compatibility states with translated copy"
status: done
wave: 2
depends_on: ["01-compat-state-and-replacement"]
plan: "plan.md"
requirements:
- REQ-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001
acceptance_criteria:
- AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.1
- AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.4
- AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.5
- AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.6
- AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.7
system_design:
- ../../specs/tasks/system-design/task-create-agent-executor-compatibility.md
---
# Task 02: Present compatibility states with translated copy
## Summary
Render the agent column and the footer's disabled reason from
`agentCompatState`. Keep the selector visible whenever a compatible profile
exists, add truthful notes for unavailable and incompatible selections, and add
the copy in every locale.
## In scope
- `AgentColumn` in `task-create-dialog-form-body.tsx` branches per the
presentation table; extract an `IncompatibleAgentNote` component carrying
`data-testid="agent-profile-incompatible-note"` and the credentials link,
plus an unavailable-selection note.
- `buildFormBodyProps` in `task-create-dialog-prop-builders.ts` forwards
`agentCompatState`, `selectedAgentProfileName`, and `effectiveWorkflowName`;
extend `DialogFormBodyProps` and `CreateEditSelectorsProps`.
- `task-create-dialog-footer.tsx`: add `REASON_SELECTED_AGENT_INCOMPATIBLE`,
add `REASON_SELECTED_AGENT_UNAVAILABLE`, and resolve both state-specific
reasons with the agent name.
- Locale keys `agentNotConfiguredOnExecutor`,
`workflowAgentNotConfiguredOnExecutor`, `selectedAgentNotConfiguredFor`,
`selectedAgentProfileFallback`, `selectedAgentProfileFallbackInline`, and
`selectedAgentProfileUnavailable` in every locale.
- Component and footer tests listed under Verification.
## Out of scope
- State derivation and the autopick (Task 01).
- Playwright coverage (Task 03).
- The new-session dialog's own empty state.
## Acceptance
- In the `selected-incompatible` state without a workflow lock,
`CreateEditSelectors` renders the agent selector and the note, and does not
render `agent-profile-empty-state`.
- In the `selected-incompatible` state with a workflow lock, the note names
the workflow, the agent profile, and the executor profile, links to
`/settings/executors/<id>`, and no selector is rendered.
- `computeDisabledReason` returns `REASON_SELECTED_AGENT_INCOMPATIBLE` for
`selected-incompatible`, `REASON_SELECTED_AGENT_UNAVAILABLE` for
`selected-unavailable`, and `REASON_NO_COMPATIBLE_AGENT` for
`none-compatible`; `pnpm run i18n:check` passes with the new keys.
## Verification
Write the failing component test first (selector plus note in the unlocked
incompatible state). Confirm it fails before the production change, then run:
```bash
# From apps/web:
pnpm exec vitest run components/task-create-dialog-form-body.test.tsx components/task-create-dialog-footer.test.ts components/task-create-dialog-prop-builders.test.ts
pnpm run i18n:check
pnpm run typecheck
pnpm exec eslint --max-warnings 0 components/task-create-dialog-form-body.tsx components/task-create-dialog-footer.tsx components/task-create-dialog-prop-builders.ts components/task-create-dialog-types.ts
```
## Files likely touched
- `apps/web/components/task-create-dialog-form-body.tsx`
- `apps/web/components/task-create-dialog-form-body.test.tsx`
- `apps/web/components/task-create-dialog-prop-builders.ts`
- `apps/web/components/task-create-dialog-prop-builders.test.ts`
- `apps/web/components/task-create-dialog-footer.tsx`
- `apps/web/components/task-create-dialog-footer.test.ts`
- `apps/web/components/task-create-dialog-types.ts`
- `apps/web/src/locales/{en,pt-pt,zh-cn,zh-hk,zh-tw,pseudo}/task.json`
## Dependencies
Task 01.
## Risks
- `AgentColumn` is close to the 100-line function cap. Extract the note and
the state switch into small components rather than growing the function.
- The i18n ratchet rejects any literal string on a changed line. Route every
new string, including the note's link label, through `t()`.
- Do not use the Unicode em dash in the new copy; the existing footer key uses
an arrow, which the check allows.
## Parallelism
`sequential`
## Inputs
- System design section "Presentation" and "Mobile composition".
- Existing `NoCompatibleAgentState` markup and the `CreateEditSelectors` test.
- `docs/i18n.md` for the locale workflow.
## Results
- `AgentColumn` branches on `agentCompatState`; the new `IncompatibleAgentNote`
(`agent-profile-incompatible-note`) renders under the selector in the
unlocked case and replaces it in the workflow-locked case, naming workflow,
agent, and executor. The hardcoded "this executor" fallback now resolves
through `task:thisExecutor`.
- `DialogFormBodyProps`, `CreateEditSelectorsProps`, and
`CreateModeSelectorsProps` carry `agentCompatState`,
`selectedAgentProfileName`, and `effectiveWorkflowName`; `buildFormBodyProps`
resolves the workflow name through the new `resolveWorkflowName` helper.
- Footer: `REASON_SELECTED_AGENT_INCOMPATIBLE` (`task:selectedAgentNotConfiguredFor`)
for the selected-incompatible state in both start-task and session-default
paths; `resolveDisabledReason` takes the agent name.
- Locale keys `agentNotConfiguredOnExecutor`,
`workflowAgentNotConfiguredOnExecutor`, `selectedAgentNotConfiguredFor`, and
`selectedAgentProfileFallback` added to en, pt-pt, zh-cn; zh-hk and zh-tw
values taken from `pnpm run i18n:zh-hant` output (the converter also rewrote
unrelated keys in 21 files, which were reverted); pseudo regenerated.
- RED: 7 tests failed (missing helper, footer key, component states). GREEN:
`pnpm exec vitest run` on form-body, footer, prop-builders plus the Task 01
files, dialog and setup tests: 7 files, 116 tests passed. `pnpm run
i18n:check`: all checks pass. `pnpm run typecheck`: clean. `pnpm exec eslint
--max-warnings 0` on the six production files and five test files: clean.
Follow-up verification added the unavailable-selection note, state-specific
footer reason, and separate inline fallback copy. All six locale catalogs pass
the i18n checks.
@@ -0,0 +1,128 @@
---
id: "03-e2e-evidence"
title: "End-to-end evidence on desktop and mobile"
status: done
wave: 3
depends_on: ["02-agent-column-presentation"]
plan: "plan.md"
requirements:
- REQ-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001
acceptance_criteria:
- AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.2
- AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.4
- AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.5
- AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.7
- AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.9
system_design:
- ../../specs/tasks/system-design/task-create-agent-executor-compatibility.md
---
# Task 03: End-to-end evidence on desktop and mobile
## Summary
Prove the rendered states against the production build on desktop and on a
phone viewport. The E2E backend runs the mock agent as its only agent type, so
each case first restarts it with `KANDEV_MOCK_PROVIDERS: "codex-acp"` to get a
second, compatible agent type, then restarts it back to the baseline.
## In scope
- Add `apps/web/e2e/tests/task/agent-compatibility-helpers.ts`: create a
Codex-alias profile, a Docker executor profile without credentials, the
`/api/v1/remote-credentials` route mock (env secret required for the seeded
agent, no methods for the alias), and a workflow that pins a profile and is
remembered as the dialog's last-used workflow.
- Extend `apps/web/e2e/tests/task/create-task.spec.ts` with two cases: pick
the seeded agent on the default executor, switch to the Docker profile, and
assert the selector now shows the Codex profile with no empty state or note
and an enabled start action; and a workflow that pins the seeded profile,
asserting the `agent-profile-incompatible-note` names the workflow, the agent
profile, and the executor profile, that the credentials link targets the
executor profile, that `agent-profile-empty-state` is absent, and that the
start action is disabled.
- Keep the existing empty-state case green.
- Add `apps/web/e2e/tests/task/mobile-create-task-agent-compatibility.spec.ts`
driving both the workflow-locked and unlocked replacement flows through
`MobileKanbanPage` at the configured phone device. Assert the note is visible,
the credentials link is tappable, the start action is disabled or enabled as
expected, and `document.documentElement.scrollWidth` does not exceed the
viewport width.
## Out of scope
- Container-backed executor projects. The Docker profile is never launched;
only the dialog's gate is exercised.
## Acceptance
- The desktop workflow-locked case passes and the existing Docker empty-state
case still passes.
- The mobile spec passes under the `mobile-chrome` project with no document
horizontal overflow, and the replacement scenario proves the compatible
profile is selected after the executor change.
## Verification
```bash
# From the repository root, after Task 02. The harness runs the built backend
# binary, the E2E web bundle, and the E2E plugin package, so all three must be
# current:
make build-backend build-web-e2e build-e2e-plugin-package
# From apps/web:
pnpm e2e:raw tests/task/create-task.spec.ts
pnpm e2e:raw --project=mobile-chrome tests/task/mobile-create-task-agent-compatibility.spec.ts
```
## Files likely touched
- `apps/web/e2e/tests/task/agent-compatibility-helpers.ts`
- `apps/web/e2e/tests/task/create-task.spec.ts`
- `apps/web/e2e/tests/task/mobile-create-task-agent-compatibility.spec.ts`
## Dependencies
Task 02.
## Risks
- Workflow creation with a pinned agent profile needs the API client helper
used by `workflow-agent-profile.spec.ts`; reuse it rather than posting raw
requests.
- The note copy is asserted through `toContainText` on the workflow, agent,
and executor names, not on the full sentence, so translations and wording
edits do not break the spec.
## Parallelism
`sequential`
## Inputs
- Plan section "E2E tests".
- Existing "explains when a Docker executor has no compatible agent
credentials" case in `create-task.spec.ts`.
- `apps/web/e2e/tests/task/mobile-create-task-branch-policy.spec.ts` as the
mobile exemplar.
## Results
- Added `agent-compatibility-helpers.ts` (second agent type through
`backend.restart({ KANDEV_MOCK_PROVIDERS: "codex-acp" })`, Codex-alias
profile, Docker profile without credentials, catalog route mock, remembered
locked workflow) and two desktop cases plus the mobile spec.
- Two false starts recorded for the next reader: the first scenario locked the
only agent type and therefore produced the empty state, not the locked note;
and clicking the already-selected seed option toggled it off, so the
replacement test now selects the seed only when something else is selected
and asserts the replacement is a Codex profile (the alias also ships a
default profile) rather than one specific name.
- Prerequisites in a fresh worktree: `make build-backend build-web-e2e
build-e2e-plugin-package` and `pnpm exec playwright install chromium`.
- `pnpm e2e:raw tests/task/create-task.spec.ts`: 17 passed (2.8 m).
`pnpm e2e:raw --project=mobile-chrome
tests/task/mobile-create-task-agent-compatibility.spec.ts`: 1 passed.
Follow-up verification: the updated mobile spec ran against a fresh production
build with 2 tests passed. The executor mutations use one touch selection each,
and the locked flow taps the credentials link and verifies the settings route.
+2
View File
@@ -86,6 +86,7 @@ signals, and task-scoped scheduling contracts.
- [Subtask re-parenting by drag and drop](requirements/subtask-reparenting-drag-drop.md)
- [Task Subtree Controls](requirements/subtree-controls.md)
- [Create Task Escape Dismissal](requirements/task-create-escape-dismissal.md)
- [Task Create Agent Compatibility Recovery](requirements/task-create-agent-executor-compatibility.md)
- [Task Create Executor Default](requirements/task-create-executor-default.md)
- [Task Create Workflow Memory](requirements/task-create-workflow-memory.md)
- [Task-create advanced settings disclosure](requirements/task-dependencies-create-dialog-advanced-settings.md)
@@ -158,6 +159,7 @@ signals, and task-scoped scheduling contracts.
- [Workflow Step Fixed-Profile Routing](system-design/workflow-step-fixed-profile-routing.md)
- [Workflow Profile Session Lifecycle](system-design/workflow-profile-session-lifecycle.md)
- [Workflow task-step transition ledger](system-design/workflow-task-step-transition-ledger.md)
- [Task Create Agent Compatibility Recovery](system-design/task-create-agent-executor-compatibility.md)
## Migration record
@@ -0,0 +1,101 @@
---
status: active
system: tasks
created: 2026-09-04
owners:
- kandev
---
# Task Create Agent Compatibility Recovery Requirements
## Overview
The task-create dialog offers an agent profile and an executor profile. A
remote executor profile (Docker, Sprites, Kubernetes) can run only the agents
whose credentials are configured on that executor profile. When the user
changes the executor after an agent is already selected, the dialog must keep
the user able to start the task with a compatible agent, and it must describe
the real obstacle when it cannot.
The task system owns this contract because it owns task creation and launch
behavior. The credential rule that decides which agent is usable on which
executor belongs to the executor and agent systems; this requirement covers
only how the task-create dialog reacts to that rule.
## Terminology
- **Compatible agent profile:** An enabled agent profile whose agent needs no
executor credentials, or whose agent has credentials configured on the
selected executor profile.
- **Workflow-locked agent:** The agent profile that the selected workflow pins
for new tasks. The user cannot change it inside the dialog.
- **Unavailable selection:** A selected profile that is disabled or blocked
because dynamic agent routing is off, while another compatible profile exists.
- **Preference order:** The existing pre-selection order for the agent profile:
the last-used profile, then the workspace default, then the first compatible
profile.
## Requirements
### REQ-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001: Agent selection recovery when the executor changes
**Intent:** A user who switches the executor keeps a usable agent selected
whenever one exists, and otherwise sees which agent, workflow, and executor
combination blocks the launch. The dialog never claims that no compatible agent
exists while one does.
**User story:** As a user creating a task, I want the dialog to keep a usable
agent selected when I switch to a remote executor, so that I can start the task
without reopening the dialog or guessing which credential is missing.
#### Acceptance criteria
- **AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.1:** When an executor profile
is selected and at least one agent profile is compatible with it, the dialog
shall show the agent selector with the compatible profiles as its options.
- **AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.2:** When the selected agent
profile is not compatible with the selected executor profile, the workflow
does not lock the agent, and at least one compatible profile exists, the
dialog shall replace the selection with a compatible profile chosen by the
preference order. Until the replacement applies, an unavailable selection
shall show a truthful pending state and keep the start action disabled.
- **AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.3:** When the selected agent
profile is compatible with a newly selected executor profile, the dialog
shall keep that selection.
- **AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.4:** When no agent profile is
compatible with the selected executor profile, the dialog shall show a
message stating that no compatible agent profile exists for that executor
profile, with a link to that executor profile's credential settings, and
shall keep the start action disabled.
- **AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.5:** When the workflow locks an
enabled agent profile that is not compatible with the selected executor
profile, the dialog shall show a message that names the workflow, the agent
profile, and the executor profile, with the same credential link, and shall
keep the start action disabled. This message takes precedence over the
message in 001.4 when no other profile is compatible either, because the
user cannot change the locked agent. A workflow that locks a disabled
profile keeps the behavior in
[Disable an Agent Profile](../../agents/requirements/profile-disable.md).
- **AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.6:** Except for the disabled
workflow-locked profile behavior in 001.5, the dialog shall not state that no
compatible agent profile exists while at least one compatible profile exists.
- **AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.7:** When the start action is
disabled because of agent compatibility, its explanation shall match the
shown state: the no-compatible message for the state in 001.4, a message
naming the agent profile and executor profile for the state in 001.5, or an
unavailable-selection message while an automatic replacement is pending.
- **AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.8:** An automatic replacement
under 001.2 shall not change the user's stored last-used agent profile. Only a
manual selection or a successful task creation records that preference.
- **AC-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001.9:** Desktop and phone
viewports shall show the same messages, link, and recovery behavior, and the
message shall wrap inside the dialog without horizontal document overflow.
## Out of scope
- Changing which agents count as compatible with an executor profile. The
credential rule stays with the executor and agent systems.
- Marking incompatible executor profiles inside the executor selector.
- The additional-session, handoff, and quick-chat dialogs, which have their own
selection contracts.
- Changing the executor default policy in
[Task Create Executor Default](task-create-executor-default.md).
@@ -0,0 +1,208 @@
---
status: current
system: tasks
requirements:
- REQ-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001
---
# Task Create Agent Compatibility Recovery System Design
## Purpose and boundaries
The task-create dialog (`apps/web/components/task-create-dialog*.ts` and
`.tsx`) owns agent and executor selection for new tasks. This design covers how
the dialog derives an agent compatibility state, replaces an incompatible
selection, and presents each state on desktop and phone.
The design uses, and does not own, two adjacent contracts:
- The compatibility rule `isAgentConfiguredOnExecutor` in
`apps/web/lib/agent-executor-compat.ts`, which reads the executor profile's
`remote_credentials` and `remote_auth_secrets` configuration.
- The remote-auth catalog served by `GET /api/v1/remote-credentials` and cached
by `useRemoteAuthSpecs` in
`apps/web/hooks/domains/settings/use-remote-auth-specs.ts`.
## Requirement mapping
| Requirement | Design section |
| --- | --- |
| `REQ-TASKS-TASK-CREATE-AGENT-COMPATIBILITY-001` | [Data and contracts](#data-and-contracts), [Control flow](#control-flow), [Presentation](#presentation) |
## Components and responsibilities
- `apps/web/components/task-create-dialog-computed.ts`:
`useExecutorProfileCompat` keeps filtering `agentProfiles` into
`compatibleAgentProfiles` and derives `agentCompatState` through a pure
`computeAgentCompatState` helper. `noCompatibleAgent` remains the derived
boolean that gates submission.
- `apps/web/components/task-create-dialog-autopick.ts`:
`decideAgentProfileAutopick` gains a replacement path for a selected profile
that is no longer compatible. `useAgentProfileAutopickEffect` applies it.
- `apps/web/components/task-create-dialog-form-body.tsx`: `AgentColumn` renders
the selector, the empty state, the unavailable note, or the incompatible note
per state.
- `apps/web/components/task-create-dialog-prop-builders.ts`: forwards the
state, the selected agent profile label, and the effective workflow name.
- `apps/web/components/task-create-dialog-footer.tsx`: `computeDisabledReason`
returns a state-specific reason key, and `resolveDisabledReason` fills the
agent and executor names.
- `apps/web/components/task-create-dialog-setup.ts`: the guarded submit handler
applies the compatibility block to form, keyboard shortcut, and programmatic
submissions.
- Locale catalogs `apps/web/src/locales/<locale>/task.json` own the copy.
## Data and contracts
```ts
export type AgentCompatState =
| "compatible"
| "selected-incompatible"
| "selected-unavailable"
| "none-compatible";
```
`computeAgentCompatState` derives the state from the selected executor profile,
`compatibleAgentProfiles`, the effective agent profile id (the user value or the
workflow override) and its store row, the workflow lock, and the dynamic
routing feature flag:
1. No executor profile selected: `compatible`.
2. No effective agent id: `none-compatible` when `compatibleAgentProfiles` is
empty, otherwise `compatible`.
3. The effective agent id is in `compatibleAgentProfiles`: `compatible`.
4. The selected row exists but is not selectable (disabled, or a dynamic
profile while routing is off): `selected-unavailable` when another
compatible profile exists. A locked disabled profile, or an unavailable
selection with no alternative, is `none-compatible`. A locked disabled
profile is a profile-disable outcome, not a credential problem.
5. The workflow locks the agent: `selected-incompatible`, even when
`compatibleAgentProfiles` is empty, so the locked note names the workflow
and agent instead of the generic empty state.
6. `compatibleAgentProfiles` is empty: `none-compatible`.
7. Otherwise: `selected-incompatible`.
`noCompatibleAgent` equals `agentCompatState !== "compatible"`, so the footer
and submit gates keep their existing input.
`DialogComputedValues` adds `agentCompatState` and
`selectedAgentProfileName: string | null` (the label of the effective agent
profile). `DialogFormBodyProps` and `CreateEditSelectorsProps` add
`agentCompatState`, `selectedAgentProfileName`, and
`effectiveWorkflowName: string | null`.
The autopick decision keeps its shape and adds an optional `replaces` field:
```ts
{ kind: "pick"; source: "lastId" | "defId" | "first"; id: string; replaces?: string }
```
The replacement gate runs before the existing `already-set` skip. It yields a
pick with `replaces` set to the current id when all of these hold: the dialog is
open, an agent id is set, no workflow lock applies (`workflowAgentProfileId` is
empty and the workflow has no agent), the auth catalog is loaded, an executor
profile is selected, `compatibleAgentProfiles` is non-empty, and the current id
is absent from `compatibleAgentProfiles`. The candidate order is unchanged:
last-used, workspace default, first compatible.
### Presentation
| State | Workflow lock | Agent column |
| --- | --- | --- |
| `compatible` | any | Existing selector (`agent-profile-selector`). |
| `none-compatible` | any | `agent-profile-empty-state` with `task:noCompatibleAgentProfilesFor` and the credentials link. |
| `selected-incompatible` | no | Selector with the compatible options plus `agent-profile-incompatible-note` with `task:agentNotConfiguredOnExecutor` and the credentials link. This state is transient until the replacement applies. |
| `selected-incompatible` | yes | `agent-profile-incompatible-note` with `task:workflowAgentNotConfiguredOnExecutor` (workflow, agent, executor) and the credentials link. No selector. |
| `selected-unavailable` | no | Selector with the compatible options plus `agent-profile-unavailable-note` with `task:selectedAgentProfileUnavailable`. This state is transient until the replacement applies. |
The credentials link keeps its existing target
`/settings/executors/<executor-profile-id>`.
Footer reason keys:
- `none-compatible`: existing `REASON_NO_COMPATIBLE_AGENT`
(`task:noCompatibleAgentProfileFor`).
- `selected-incompatible`: new `REASON_SELECTED_AGENT_INCOMPATIBLE`
(`task:selectedAgentNotConfiguredFor`, with `agent` and `target`).
- `selected-unavailable`: new `REASON_SELECTED_AGENT_UNAVAILABLE`
(`task:selectedAgentProfileUnavailable`, with `agent`).
New `task` namespace keys, added in `en`, `pt-pt`, `zh-cn`, `zh-hk`, `zh-tw`,
and regenerated `pseudo`:
- `agentNotConfiguredOnExecutor`: "{{agent}} is not configured on {{target}}."
- `workflowAgentNotConfiguredOnExecutor`: "The {{workflow}} workflow uses
{{agent}}, which is not configured on {{target}}."
- `selectedAgentNotConfiguredFor`: "{{agent}} is not configured on {{target}}.
Configure agent credentials in Settings → Executors."
- `selectedAgentProfileFallback`: capitalized fallback for a sentence start.
- `selectedAgentProfileFallbackInline`: lowercase fallback for the workflow
sentence where the agent name is not at the start.
- `selectedAgentProfileUnavailable`: "{{agent}} is unavailable. Select a
compatible agent profile."
### Mobile composition
The dialog renders one component tree for both viewports. The agent and
executor selectors sit in a grid that collapses to one column below the `sm`
breakpoint, so the note renders under the selector at full dialog width and
wraps. No drawer, new surface, or touch control is added. The nearest shipped
mobile exemplar is the create-task dialog flow in
`apps/web/e2e/tests/task/mobile-create-task-branch-policy.spec.ts`, which
already drives the executor profile selector on a phone viewport.
## Control flow
1. The user picks an executor profile. `handleExecutorProfileChange` sets
`fs.executorProfileId` and queues the last-used executor. This handler is
unchanged.
2. `useExecutorProfileCompat` recomputes `compatibleAgentProfiles` and
`agentCompatState` in the same render.
3. `useAgentProfileAutopickEffect` evaluates the replacement gate. A pick is
applied through `setAgentProfileId` on the next microtask, the same deferral
the existing autopick uses. The effect does not call
`syncTaskCreateLastUsed`, so the stored last-used agent stays untouched. The
submit gate stays closed while an unavailable selection is visible.
4. `AgentColumn` renders per the presentation table, and the footer resolves
the disabled reason.
When the workflow locks the agent, `useWorkflowAgentProfileEffect` keeps
setting the locked id, the replacement gate is skipped, and the locked note is
shown until the user changes the workflow or configures the credentials.
## Failure and recovery
- Auth catalog not loaded: `compatibleAgentProfiles` equals the selectable list
and the state resolves to `compatible`. No replacement runs. This matches the
existing deferral in the autopick gate.
- Catalog request failure: the cached specs are empty, every agent on a remote
executor is blocked, and the state is `none-compatible`. The empty state and
credentials link remain the recovery path. This behavior is unchanged.
- Agent profiles transiently empty during a refresh: `compatibleAgentProfiles`
is empty, so the replacement gate does not fire and a valid selection is not
cleared. The existing `agentProfilesLoading` guard keeps the empty state
hidden while profiles load.
- An unlocked disabled or dynamic-off selection with a compatible alternative:
the dialog shows the unavailable note, blocks submit, and waits for the
autopick replacement. It does not show the no-compatible empty state.
## Persistence
None. The replacement is dialog state only.
`users.settings.task_create_last_used.agent_profile_id` changes only through
the manual selection handler and successful task creation, as recorded in
[ADR 0028](../../../decisions/0028-task-create-last-used-source-of-truth.md)
and [ADR 0041](../../../decisions/0041-backend-owned-portable-user-settings.md).
## Observability
The `executor-compat:autopick` debug logger records the `replaces` id and the
source of a replacement decision. The existing `[executor-compat]` per-agent
check logs (`ok`, `reason`) remain the diagnostic for why a profile is
incompatible.
## Related decisions
- [ADR 0028](../../../decisions/0028-task-create-last-used-source-of-truth.md)
- [ADR 0041](../../../decisions/0041-backend-owned-portable-user-settings.md)
- [Resolve Task Executor Policy Before Last-Used Profile](../../../decisions/2026-08-01-repository-task-executor-defaults.md)