import { useEffect, useCallback, useState, useMemo } from "react";
import { useConfigStore } from "@/store/configStore";
import { useSwipeBack } from "@/hooks/useSwipeBack";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Plus, X, Bot } from "lucide-react";
import {
  EditorPanel,
  EditorPanelEmptyState,
  FieldGroup,
  CheckboxListField,
  CheckboxListItem,
  HistoryContextSection,
} from "@/components/shared";
import { useForm, useWatch, Controller } from "react-hook-form";
import {
  Agent,
  AgentPrivateConfig,
  AgentPrivateKnowledgeConfig,
  MemoryBackend,
  getDefaultPrivateConfig,
  resolveEffectiveDefaultTools,
  SHARED_CONTEXT_FILE_PLACEHOLDER,
} from "@/types/config";
import { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { useTools } from "@/hooks/useTools";
import { useSkills } from "@/hooks/useSkills";
import { useScopedConfigValidation } from "@/hooks/useScopedConfigValidation";
import { ToolConfigPanel } from "./ToolConfigPanel";
import { ToolSelectionRow } from "./ToolSelectionRow";

const TOOL_VALIDATION_UNAVAILABLE_MESSAGE =
  "Tool availability preview is unavailable while agent policy preview is unavailable. Save or refresh to validate tool assignments.";

export function AgentEditor() {
  const {
    agents,
    rooms,
    selectedAgentId,
    updateAgent,
    setAgentPrivateEnabled,
    deleteAgent,
    saveConfig,
    config,
    agentPoliciesByAgent,
    isDirty,
    isLoading,
    selectAgent,
    getAgentToolOverrides,
  } = useConfigStore();

  const [activeToolName, setActiveToolName] = useState<string | null>(null);
  const selectedAgent = agents.find((a) => a.id === selectedAgentId);
  const defaultLearning = config?.defaults.learning ?? true;
  const defaultLearningMode = config?.defaults.learning_mode ?? "always";
  const defaultShowToolCalls = config?.defaults.show_tool_calls ?? true;
  const defaultMarkdown = config?.defaults.markdown ?? true;
  const defaultCompressToolResults =
    config?.defaults.compress_tool_results ?? false;
  const globalMemoryBackend = config?.memory?.backend ?? "mem0";
  const knowledgeBaseNames = useMemo(
    () => Object.keys(config?.knowledge_bases || {}).sort(),
    [config?.knowledge_bases],
  );

  // Fetch tools and skills from backend
  const selectedAgentPolicy = selectedAgent
    ? (agentPoliciesByAgent[selectedAgent.id] ?? null)
    : null;
  const selectedExecutionScope = useMemo(
    () => selectedAgentPolicy?.effective_execution_scope ?? null,
    [selectedAgentPolicy],
  );
  const policyPreviewAvailable =
    selectedAgent == null || selectedAgentPolicy != null;
  const {
    tools: backendTools,
    loading: toolsLoading,
    statusAuthoritative,
  } = useTools(
    policyPreviewAvailable ? selectedAgentId : null,
    policyPreviewAvailable ? selectedExecutionScope : undefined,
  );
  const { skills: availableSkills, loading: skillsLoading } = useSkills();

  // Enable swipe back on mobile
  useSwipeBack({
    onSwipeBack: () => selectAgent(null),
    enabled: !!selectedAgentId && window.innerWidth < 1024, // Only on mobile when agent is selected
  });

  const { control, reset, setValue, getValues } = useForm<Agent>({
    defaultValues: selectedAgent || {
      id: "",
      display_name: "",
      role: "",
      tools: [],
      skills: [],
      instructions: [],
      rooms: [],
      knowledge_bases: [],
      delegate_to: [],
      context_files: [],
      private: undefined,
      compaction: undefined,
      learning: defaultLearning,
      learning_mode: defaultLearningMode,
      memory_backend: undefined,
    },
  });
  const learningEnabled = useWatch({ name: "learning", control });
  const effectiveLearningEnabled = learningEnabled ?? defaultLearning;
  const agentTools = useWatch({ name: "tools", control });
  const includeDefaultTools = useWatch({
    name: "include_default_tools",
    control,
  });
  const privateConfig = useWatch({ name: "private", control });
  const privateKnowledge = privateConfig?.knowledge;
  const policyAwareBackendTools = policyPreviewAvailable ? backendTools : [];
  const toolInfoByName = useMemo(
    () => new Map(policyAwareBackendTools.map((tool) => [tool.name, tool])),
    [policyAwareBackendTools],
  );
  const validationPrefix = useMemo<Array<string | number> | null>(
    () => (selectedAgentId == null ? null : ["agents", selectedAgentId]),
    [selectedAgentId],
  );
  const validationErrorForPath = useScopedConfigValidation(validationPrefix);
  const agentRootError = validationErrorForPath([], true);
  const numHistoryRunsError = validationErrorForPath(
    ["num_history_runs"],
    true,
  );
  const numHistoryMessagesError = validationErrorForPath(
    ["num_history_messages"],
    true,
  );
  const maxToolCallsFromHistoryError = validationErrorForPath(
    ["max_tool_calls_from_history"],
    true,
  );
  const compactionError = validationErrorForPath(["compaction"], true);
  const privateScopeError = validationErrorForPath(["private", "per"], true);
  const privateRootError = validationErrorForPath(["private", "root"], true);
  const privateTemplateDirError = validationErrorForPath(
    ["private", "template_dir"],
    true,
  );
  const privateContextFilesError = validationErrorForPath([
    "private",
    "context_files",
  ]);
  const privateKnowledgeError = validationErrorForPath(
    ["private", "knowledge"],
    true,
  );
  const privateKnowledgePathError = validationErrorForPath(
    ["private", "knowledge", "path"],
    true,
  );
  // Split tools into configured, default, and setup-required categories.
  const {
    configuredTools,
    defaultTools,
    setupRequiredTools,
    selectedUnavailableTools,
  } = useMemo(() => {
    const configured: typeof policyAwareBackendTools = [];
    const defaults: typeof policyAwareBackendTools = [];
    const setupRequired: typeof policyAwareBackendTools = [];
    const selectedUnavailable: Array<{
      name: string;
      display_name: string;
      reason: string;
    }> = [];
    const selectedToolNames = agentTools ?? [];
    const backendToolNames = new Set<string>();

    policyAwareBackendTools.forEach((tool) => {
      backendToolNames.add(tool.name);
      // delegate is managed via delegate_to, not the tools picker
      if (tool.name === "delegate") return;
      if (tool.execution_scope_supported === false) {
        if (selectedToolNames.includes(tool.name)) {
          selectedUnavailable.push({
            name: tool.name,
            display_name: tool.display_name,
            reason:
              "Not supported for this execution scope. Uncheck it to remove it.",
          });
        }
        return;
      }
      // Tools that do not require configuration are default tools.
      if (tool.setup_type === "none") {
        defaults.push(tool);
      } else if (tool.status === "available") {
        configured.push(tool);
      } else {
        setupRequired.push(tool);
      }
    });

    if (policyPreviewAvailable) {
      for (const toolName of selectedToolNames) {
        if (toolName === "delegate" || backendToolNames.has(toolName)) {
          continue;
        }
        selectedUnavailable.push({
          name: toolName,
          display_name: toolName,
          reason:
            "This tool is no longer available in the current registry. Uncheck it to remove it.",
        });
      }
    }

    return {
      configuredTools: configured.sort((a, b) =>
        a.display_name.localeCompare(b.display_name),
      ),
      defaultTools: defaults.sort((a, b) =>
        a.display_name.localeCompare(b.display_name),
      ),
      setupRequiredTools: setupRequired.sort((a, b) =>
        a.display_name.localeCompare(b.display_name),
      ),
      selectedUnavailableTools: selectedUnavailable.sort((a, b) =>
        a.display_name.localeCompare(b.display_name),
      ),
    };
  }, [agentTools, policyAwareBackendTools, policyPreviewAvailable]);
  // Compute effective tools: agent tools + defaults.tools (when include_default_tools is enabled)
  const effectiveTools = useMemo(() => {
    const tools = new Set(agentTools);
    if (includeDefaultTools ?? true) {
      for (const t of resolveEffectiveDefaultTools(config?.defaults)) {
        tools.add(t);
      }
    }
    return [...tools];
  }, [agentTools, includeDefaultTools, config?.defaults]);

  // Prepare checkbox items for skills (includes orphaned selected skills)
  const skillItems: CheckboxListItem[] = useMemo(() => {
    const selected = selectedAgent?.skills ?? [];
    const availableByName = new Map(availableSkills.map((s) => [s.name, s]));
    const allNames = [
      ...availableSkills.map((s) => s.name),
      ...selected.filter((name) => !availableByName.has(name)),
    ];
    return allNames.map((name) => ({
      value: name,
      label: name,
      description:
        availableByName.get(name)?.description ||
        "Skill not available; uncheck to remove",
    }));
  }, [availableSkills, selectedAgent?.skills]);

  // Prepare checkbox items for rooms
  const roomItems: CheckboxListItem[] = useMemo(
    () =>
      rooms.map((room) => ({
        value: room.id,
        label: room.display_name,
        description: room.description,
      })),
    [rooms],
  );
  const knowledgeBaseItems: CheckboxListItem[] = useMemo(
    () =>
      knowledgeBaseNames.map((baseName) => ({
        value: baseName,
        label: baseName,
      })),
    [knowledgeBaseNames],
  );

  // Prepare checkbox items for delegation targets (all agents except current)
  const delegateItems: CheckboxListItem[] = useMemo(
    () =>
      agents
        .filter((a) => a.id !== selectedAgentId)
        .map((a) => ({
          value: a.id,
          label: a.display_name,
          description: a.role,
        })),
    [agents, selectedAgentId],
  );

  // Reset form when selected agent changes
  useEffect(() => {
    if (selectedAgent) {
      reset({
        ...selectedAgent,
        knowledge_bases: selectedAgent.knowledge_bases ?? [],
        delegate_to: selectedAgent.delegate_to ?? [],
        context_files: selectedAgent.context_files ?? [],
        private: selectedAgent.private ?? undefined,
        compaction: selectedAgent.compaction ?? undefined,
        learning: selectedAgent.learning ?? defaultLearning,
        learning_mode: selectedAgent.learning_mode ?? defaultLearningMode,
      });
    }
  }, [defaultLearning, defaultLearningMode, selectedAgent, reset]);

  useEffect(() => {
    const selectedToolNames = agentTools ?? [];
    if (selectedToolNames.length === 0) {
      setActiveToolName(null);
      return;
    }
    setActiveToolName((currentActiveToolName) => {
      if (
        currentActiveToolName != null &&
        selectedToolNames.includes(currentActiveToolName)
      ) {
        return currentActiveToolName;
      }
      return null;
    });
  }, [agentTools, selectedAgentId, toolInfoByName]);

  // Let the store normalize against current state so sequential UI updates do not
  // reuse stale render-time agent data.
  const handleFieldChange = useCallback(
    (fieldName: keyof Agent, value: any) => {
      if (selectedAgentId) {
        updateAgent(selectedAgentId, { [fieldName]: value });
      }
    },
    [selectedAgentId, updateAgent],
  );

  const updateSelectedTools = useCallback(
    (currentTools: string[], toolName: string, checked: boolean) => {
      const nextTools = checked
        ? [...new Set([...currentTools, toolName])]
        : currentTools.filter((tool) => tool !== toolName);
      handleFieldChange("tools", nextTools);
      setActiveToolName((currentActiveToolName) => {
        if (checked) {
          return toolName;
        }
        if (
          currentActiveToolName != null &&
          nextTools.includes(currentActiveToolName)
        ) {
          return currentActiveToolName;
        }
        return null;
      });
      return nextTools;
    },
    [handleFieldChange, toolInfoByName],
  );

  const handleDelete = () => {
    if (
      selectedAgentId &&
      confirm("Are you sure you want to delete this agent?")
    ) {
      deleteAgent(selectedAgentId);
    }
  };

  const handleSave = async () => {
    return saveConfig();
  };

  const handleAddInstruction = () => {
    const current = getValues("instructions");
    const updated = [...current, ""];
    setValue("instructions", updated);
    handleFieldChange("instructions", updated);
  };

  const handleRemoveInstruction = (index: number) => {
    const current = getValues("instructions");
    const updated = current.filter((_, i) => i !== index);
    setValue("instructions", updated);
    handleFieldChange("instructions", updated);
  };

  const handleAddContextFile = () => {
    const current = getValues("context_files") ?? [];
    const updated = [...current, ""];
    setValue("context_files", updated);
    handleFieldChange("context_files", updated);
  };

  const handleRemoveContextFile = (index: number) => {
    const current = getValues("context_files") ?? [];
    const updated = current.filter((_, i) => i !== index);
    setValue("context_files", updated);
    handleFieldChange("context_files", updated);
  };

  const updatePrivate = useCallback(
    (nextPrivate: Agent["private"]) => {
      setValue("private", nextPrivate);
      handleFieldChange("private", nextPrivate);
    },
    [handleFieldChange, setValue],
  );

  const mutatePrivate = useCallback(
    (mutator: (current: Agent["private"]) => Agent["private"]) => {
      updatePrivate(mutator(getValues("private")));
    },
    [getValues, updatePrivate],
  );

  const ensurePrivateConfig = (value: Agent["private"]): AgentPrivateConfig =>
    value ?? getDefaultPrivateConfig(selectedAgent ?? { private: undefined });

  const handleEnablePrivate = (enabled: boolean) => {
    if (selectedAgentId) {
      setAgentPrivateEnabled(selectedAgentId, enabled);
    }
  };

  const updateCompaction = useCallback(
    (nextCompaction: Agent["compaction"]) => {
      setValue("compaction", nextCompaction);
      handleFieldChange("compaction", nextCompaction);
    },
    [handleFieldChange, setValue],
  );

  const mutateCompaction = useCallback(
    (mutator: (current: Agent["compaction"]) => Agent["compaction"]) => {
      updateCompaction(mutator(getValues("compaction")));
    },
    [getValues, updateCompaction],
  );

  const handlePrivateScopeChange = (per: AgentPrivateConfig["per"]) => {
    mutatePrivate((current) => ({
      ...ensurePrivateConfig(current),
      per,
    }));
  };

  const handlePrivateRootChange = (root: string) => {
    mutatePrivate((current) => ({
      ...ensurePrivateConfig(current),
      root: root.trim() === "" ? undefined : root,
    }));
  };

  const handlePrivateTemplateDirChange = (templateDir: string) => {
    mutatePrivate((current) => ({
      ...ensurePrivateConfig(current),
      template_dir: templateDir.trim() === "" ? undefined : templateDir,
    }));
  };

  const handleAddPrivateContextFile = () => {
    mutatePrivate((current) => {
      const privateState = ensurePrivateConfig(current);
      return {
        ...privateState,
        context_files: [...(privateState.context_files ?? []), ""],
      };
    });
  };

  const handleRemovePrivateContextFile = (index: number) => {
    mutatePrivate((current) => {
      const privateState = ensurePrivateConfig(current);
      return {
        ...privateState,
        context_files: (privateState.context_files ?? []).filter(
          (_, i) => i !== index,
        ),
      };
    });
  };

  const handleEnablePrivateKnowledge = (enabled: boolean) => {
    mutatePrivate((current) => {
      const privateState = ensurePrivateConfig(current);
      const currentKnowledge = privateState.knowledge;
      const nextKnowledge: AgentPrivateKnowledgeConfig | undefined = enabled
        ? {
            ...(currentKnowledge ?? {}),
            enabled: true,
            watch: currentKnowledge?.watch ?? true,
          }
        : currentKnowledge == null
          ? { enabled: false }
          : { ...currentKnowledge, enabled: false };
      return {
        ...privateState,
        knowledge: nextKnowledge,
      };
    });
  };

  const mutatePrivateKnowledge = (
    mutator: (
      current: AgentPrivateKnowledgeConfig | undefined,
    ) => AgentPrivateKnowledgeConfig,
  ) => {
    mutatePrivate((current) => {
      const privateState = ensurePrivateConfig(current);
      return {
        ...privateState,
        knowledge: mutator(privateState.knowledge ?? undefined),
      };
    });
  };

  const handlePrivateKnowledgePathChange = (path: string) => {
    mutatePrivateKnowledge((current) => ({
      ...(current ?? { enabled: true, watch: true }),
      path: path.trim() === "" ? undefined : path,
    }));
  };

  const handlePrivateKnowledgeDescriptionChange = (description: string) => {
    mutatePrivateKnowledge((current) => ({
      ...(current ?? { enabled: true, watch: true }),
      description,
    }));
  };

  const handlePrivateKnowledgeWatchChange = (watch: boolean) => {
    mutatePrivateKnowledge((current) => ({
      ...(current ?? { enabled: true }),
      watch,
    }));
  };
  const toolHasOverrides = (toolName: string): boolean => {
    if (selectedAgentId == null) {
      return false;
    }
    const overrides = getAgentToolOverrides(selectedAgentId, toolName);
    return overrides != null && Object.keys(overrides).length > 0;
  };

  if (!selectedAgent) {
    return (
      <EditorPanelEmptyState icon={Bot} message="Select an agent to edit" />
    );
  }

  return (
    <EditorPanel
      icon={Bot}
      title="Agent Details"
      isDirty={isDirty}
      onSave={handleSave}
      onDelete={handleDelete}
      disableSave={isLoading}
      onBack={() => selectAgent(null)}
    >
      {agentRootError && (
        <div className="rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
          {agentRootError}
        </div>
      )}

      {/* Display Name */}
      <FieldGroup
        label="Display Name"
        helperText="Human-readable name for the agent"
        htmlFor="display_name"
      >
        <Controller
          name="display_name"
          control={control}
          render={({ field }) => (
            <Input
              {...field}
              id="display_name"
              placeholder="Agent display name"
              onChange={(e) => {
                field.onChange(e);
                handleFieldChange("display_name", e.target.value);
              }}
            />
          )}
        />
      </FieldGroup>

      {/* Role */}
      <FieldGroup
        label="Role Description"
        helperText="Description of the agent's purpose and capabilities"
        htmlFor="role"
      >
        <Controller
          name="role"
          control={control}
          render={({ field }) => (
            <Textarea
              {...field}
              id="role"
              placeholder="What this agent does..."
              rows={2}
              onChange={(e) => {
                field.onChange(e);
                handleFieldChange("role", e.target.value);
              }}
            />
          )}
        />
      </FieldGroup>

      {/* Model Selection */}
      <FieldGroup
        label="Model"
        helperText="AI model to use (defaults to 'default' model if not specified)"
        htmlFor="model"
      >
        <Controller
          name="model"
          control={control}
          render={({ field }) => (
            <Select
              value={field.value || "default"}
              onValueChange={(value) => {
                field.onChange(value);
                handleFieldChange("model", value);
              }}
            >
              <SelectTrigger id="model">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {config &&
                  Object.keys(config.models).map((modelId) => (
                    <SelectItem key={modelId} value={modelId}>
                      {modelId}
                    </SelectItem>
                  ))}
              </SelectContent>
            </Select>
          )}
        />
      </FieldGroup>

      {/* Memory Backend */}
      <FieldGroup
        label="Memory Backend"
        helperText={`Inherit global backend (${globalMemoryBackend}) or override for this agent.`}
        htmlFor="memory_backend"
      >
        <Controller
          name="memory_backend"
          control={control}
          render={({ field }) => (
            <Select
              value={field.value ?? "inherit"}
              onValueChange={(value) => {
                const resolved =
                  value === "inherit" ? undefined : (value as MemoryBackend);
                field.onChange(resolved);
                handleFieldChange("memory_backend", resolved);
              }}
            >
              <SelectTrigger id="memory_backend">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="inherit">
                  Inherit global ({globalMemoryBackend})
                </SelectItem>
                <SelectItem value="mem0">Mem0 (vector memory)</SelectItem>
                <SelectItem value="file">File (markdown memory)</SelectItem>
                <SelectItem value="none">Disabled (stateless)</SelectItem>
              </SelectContent>
            </Select>
          )}
        />
      </FieldGroup>

      {/* Thread Mode */}
      <FieldGroup
        label="Thread Mode"
        helperText="'thread' creates Matrix threads per conversation; 'room' uses a single continuous conversation per room (ideal for bridges/mobile)"
        htmlFor="thread_mode"
      >
        <Controller
          name="thread_mode"
          control={control}
          render={({ field }) => (
            <Select
              value={field.value ?? "thread"}
              onValueChange={(value) => {
                field.onChange(value);
                handleFieldChange("thread_mode", value);
              }}
            >
              <SelectTrigger id="thread_mode">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="thread">Thread (default)</SelectItem>
                <SelectItem value="room">Room (continuous)</SelectItem>
              </SelectContent>
            </Select>
          )}
        />
      </FieldGroup>

      {/* Knowledge Bases */}
      <FieldGroup
        label="Knowledge Bases"
        helperText="Assign one or more knowledge bases for this agent to search"
      >
        <CheckboxListField
          name="knowledge_bases"
          control={control}
          items={knowledgeBaseItems}
          fieldName="knowledge_bases"
          onFieldChange={handleFieldChange}
          idPrefix="knowledge-base"
          emptyMessage="No knowledge bases available. Add one in the Knowledge tab."
          className="space-y-2 max-h-48 overflow-y-auto border rounded-lg p-2"
        />
      </FieldGroup>

      {/* Delegate To */}
      <FieldGroup
        label="Delegate To"
        helperText="Allow this agent to delegate tasks to other agents via tool calls"
      >
        <CheckboxListField
          name="delegate_to"
          control={control}
          items={delegateItems}
          fieldName="delegate_to"
          onFieldChange={handleFieldChange}
          idPrefix="delegate"
          emptyMessage="No other agents available to delegate to."
          className="space-y-2 max-h-48 overflow-y-auto border rounded-lg p-2"
        />
      </FieldGroup>

      {/* Context Files */}
      <FieldGroup
        label="Context Files"
        helperText={
          privateConfig != null
            ? "Shared workspace-relative files loaded into each agent instance. Use Private Context Files below for requester-local files."
            : "Workspace-relative files loaded into each freshly built agent instance and prepended to its role context."
        }
        actions={
          <Button
            variant="outline"
            size="sm"
            onClick={handleAddContextFile}
            className="h-9 px-3"
            data-testid="add-context-file-button"
          >
            <Plus className="h-4 w-4 sm:mr-1" />
            <span className="hidden sm:inline">Add</span>
          </Button>
        }
      >
        <Controller
          name="context_files"
          control={control}
          render={({ field }) => (
            <div className="space-y-2">
              {(field.value ?? []).map((filePath, index) => (
                <div key={index} className="flex gap-2">
                  <Input
                    value={filePath}
                    onChange={(e) => {
                      const updated = [...(field.value ?? [])];
                      updated[index] = e.target.value;
                      field.onChange(updated);
                      handleFieldChange("context_files", updated);
                    }}
                    placeholder={SHARED_CONTEXT_FILE_PLACEHOLDER}
                    className="min-h-[40px]"
                  />
                  <Button
                    variant="ghost"
                    size="icon"
                    onClick={() => handleRemoveContextFile(index)}
                    className="h-10 w-10 flex-shrink-0"
                  >
                    <X className="h-4 w-4" />
                  </Button>
                </div>
              ))}
            </div>
          )}
        />
      </FieldGroup>

      <div className="border-t border-gray-200 dark:border-gray-700 pt-4 mt-2">
        <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-4">
          Private Instance
        </h3>

        <FieldGroup
          label="Requester-Private State"
          helperText="Enable requester-local state for one shared agent definition. Private agents cannot join configured teams or transitive delegation, but explicitly tagged ad hoc teams can include them for that requester."
          htmlFor="private_enabled"
        >
          <div className="flex items-center gap-2">
            <Checkbox
              id="private_enabled"
              checked={privateConfig != null}
              onCheckedChange={(checked) =>
                handleEnablePrivate(checked === true)
              }
            />
            <label
              htmlFor="private_enabled"
              className="text-sm font-medium cursor-pointer select-none"
            >
              Enable requester-private state
            </label>
          </div>
        </FieldGroup>

        {privateConfig != null && (
          <>
            <FieldGroup
              label="Private Scope"
              helperText="Requester boundary that gets its own private instance. Private agents derive their execution scope from this boundary."
              htmlFor="private_per"
              error={privateScopeError}
            >
              <Select
                value={privateConfig.per}
                onValueChange={(value) =>
                  handlePrivateScopeChange(value as AgentPrivateConfig["per"])
                }
              >
                <SelectTrigger id="private_per">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="user">user</SelectItem>
                  <SelectItem value="user_agent">user_agent</SelectItem>
                </SelectContent>
              </Select>
            </FieldGroup>

            <FieldGroup
              label="Private Root"
              helperText="Optional requester-local root name under the canonical private-instance state root."
              htmlFor="private_root"
              error={privateRootError}
            >
              <Input
                id="private_root"
                value={privateConfig.root ?? ""}
                placeholder="mind_data"
                onChange={(e) => handlePrivateRootChange(e.target.value)}
              />
            </FieldGroup>

            <FieldGroup
              label="Template Directory"
              helperText="Optional local directory copied into each requester root without overwriting existing files."
              htmlFor="private_template_dir"
              error={privateTemplateDirError}
            >
              <Input
                id="private_template_dir"
                value={privateConfig.template_dir ?? ""}
                placeholder="./mind_template"
                onChange={(e) => handlePrivateTemplateDirChange(e.target.value)}
              />
            </FieldGroup>

            <FieldGroup
              label="Private Context Files"
              helperText="Private-root-relative files loaded into role context for each requester-private instance."
              error={privateContextFilesError}
              actions={
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleAddPrivateContextFile}
                  className="h-9 px-3"
                >
                  <Plus className="h-4 w-4 sm:mr-1" />
                  <span className="hidden sm:inline">Add</span>
                </Button>
              }
            >
              <div className="space-y-2">
                {(privateConfig.context_files ?? []).map((filePath, index) => (
                  <div key={index} className="flex gap-2">
                    <Input
                      value={filePath}
                      onChange={(e) => {
                        const updated = [
                          ...(privateConfig.context_files ?? []),
                        ];
                        updated[index] = e.target.value;
                        mutatePrivate((current) => ({
                          ...ensurePrivateConfig(current),
                          context_files: updated,
                        }));
                      }}
                      placeholder="SOUL.md"
                      className="min-h-[40px]"
                    />
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => handleRemovePrivateContextFile(index)}
                      className="h-10 w-10 flex-shrink-0"
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  </div>
                ))}
              </div>
            </FieldGroup>

            <FieldGroup
              label="Private Knowledge"
              helperText="Requester-local knowledge indexed from inside the private root."
              htmlFor="private_knowledge_enabled"
              error={privateKnowledgeError}
            >
              <div className="flex items-center gap-2">
                <Checkbox
                  id="private_knowledge_enabled"
                  checked={privateKnowledge?.enabled ?? false}
                  onCheckedChange={(checked) =>
                    handleEnablePrivateKnowledge(checked === true)
                  }
                />
                <label
                  htmlFor="private_knowledge_enabled"
                  className="text-sm font-medium cursor-pointer select-none"
                >
                  Enable private knowledge
                </label>
              </div>
            </FieldGroup>

            {privateKnowledge?.enabled === true && (
              <>
                <FieldGroup
                  label="Private Knowledge Description"
                  helperText="Shown in the knowledge search tool metadata for this requester-private source."
                  htmlFor="private_knowledge_description"
                >
                  <Textarea
                    id="private_knowledge_description"
                    value={privateKnowledge.description ?? ""}
                    placeholder="Requester-private notes, preferences, and working memory"
                    onChange={(e) =>
                      handlePrivateKnowledgeDescriptionChange(e.target.value)
                    }
                  />
                </FieldGroup>

                <FieldGroup
                  label="Private Knowledge Path"
                  helperText="Private-root-relative path to index as private agent knowledge."
                  htmlFor="private_knowledge_path"
                  error={privateKnowledgePathError}
                >
                  <Input
                    id="private_knowledge_path"
                    value={privateKnowledge.path ?? ""}
                    placeholder="memory"
                    onChange={(e) =>
                      handlePrivateKnowledgePathChange(e.target.value)
                    }
                  />
                </FieldGroup>

                <FieldGroup
                  label="Refresh Private Knowledge"
                  helperText="Schedule refresh on access for private agent knowledge."
                  htmlFor="private_knowledge_watch"
                >
                  <div className="flex items-center gap-2">
                    <Checkbox
                      id="private_knowledge_watch"
                      checked={privateKnowledge.watch ?? true}
                      onCheckedChange={(checked) =>
                        handlePrivateKnowledgeWatchChange(checked === true)
                      }
                    />
                    <label
                      htmlFor="private_knowledge_watch"
                      className="text-sm font-medium cursor-pointer select-none"
                    >
                      Refresh on access
                    </label>
                  </div>
                </FieldGroup>
              </>
            )}
          </>
        )}
      </div>

      {/* Include Default Tools */}
      <FieldGroup
        label="Include Default Tools"
        helperText="Whether to merge the global default tools into this agent's tools"
        htmlFor="include_default_tools"
      >
        <Controller
          name="include_default_tools"
          control={control}
          render={({ field }) => (
            <div className="flex items-center gap-2">
              <Checkbox
                id="include_default_tools"
                checked={field.value ?? true}
                onCheckedChange={(checked) => {
                  const value = checked === true;
                  field.onChange(value);
                  handleFieldChange("include_default_tools", value);
                }}
              />
              <label
                htmlFor="include_default_tools"
                className="text-sm font-medium cursor-pointer select-none"
              >
                Include default tools
              </label>
            </div>
          )}
        />
      </FieldGroup>

      {/* Tools */}
      <FieldGroup label="Tools" helperText="Select tools this agent can use">
        <div className="space-y-4">
          {selectedAgent != null && selectedAgentPolicy == null && (
            <Alert>
              <AlertDescription>
                Agent policy preview is unavailable. Save or refresh to
                re-validate tool scope support for this draft.
              </AlertDescription>
            </Alert>
          )}
          {selectedExecutionScope != null && statusAuthoritative === false && (
            <Alert>
              <AlertDescription>
                Requester-scoped tool status is preview only. The dashboard can
                show scope support rules and shared env-backed availability, but
                it cannot inspect live requester-owned scoped credentials.
              </AlertDescription>
            </Alert>
          )}
          {!policyPreviewAvailable ? (
            <div className="text-sm text-muted-foreground text-center py-4">
              {TOOL_VALIDATION_UNAVAILABLE_MESSAGE}
            </div>
          ) : toolsLoading ? (
            <div className="text-sm text-muted-foreground text-center py-4">
              Loading available tools...
            </div>
          ) : configuredTools.length === 0 &&
            defaultTools.length === 0 &&
            setupRequiredTools.length === 0 &&
            selectedUnavailableTools.length === 0 ? (
            <div className="text-sm text-muted-foreground text-center py-4">
              No tools are available. Please configure tools in the Tools tab
              first.
            </div>
          ) : (
            <>
              {selectedUnavailableTools.length > 0 && (
                <div className="space-y-2">
                  <div className="flex items-center gap-2 mb-2">
                    <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300">
                      Selected But Unavailable
                    </h4>
                    <Badge variant="destructive" className="text-xs">
                      {selectedUnavailableTools.length}
                    </Badge>
                    <span className="text-xs text-muted-foreground">
                      (uncheck to remove invalid tool assignments)
                    </span>
                  </div>
                  <div className="pl-2 space-y-1">
                    {selectedUnavailableTools.map((tool) => (
                      <Controller
                        key={tool.name}
                        name="tools"
                        control={control}
                        render={({ field }) => (
                          <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-2">
                            <div className="flex items-center justify-between">
                              <div className="flex items-center space-x-3 sm:space-x-2">
                                <Checkbox
                                  id={`unavailable-${tool.name}`}
                                  checked={field.value.includes(tool.name)}
                                  onCheckedChange={(checked) => {
                                    field.onChange(
                                      updateSelectedTools(
                                        field.value,
                                        tool.name,
                                        checked === true,
                                      ),
                                    );
                                  }}
                                  className="h-5 w-5 sm:h-4 sm:w-4"
                                />
                                <label
                                  htmlFor={`unavailable-${tool.name}`}
                                  className="text-sm font-medium leading-none cursor-pointer select-none"
                                >
                                  {tool.display_name}
                                </label>
                              </div>
                              <Badge variant="destructive" className="text-xs">
                                Remove
                              </Badge>
                            </div>
                            <p className="pl-8 pt-1 text-xs text-muted-foreground">
                              {tool.reason}
                            </p>
                          </div>
                        )}
                      />
                    ))}
                  </div>
                </div>
              )}

              {selectedUnavailableTools.length > 0 &&
                (configuredTools.length > 0 ||
                  defaultTools.length > 0 ||
                  setupRequiredTools.length > 0) && (
                  <div className="border-t border-gray-200 dark:border-gray-700" />
                )}

              {/* Configured Tools Section */}
              {configuredTools.length > 0 && (
                <div className="space-y-2">
                  <div className="flex items-center gap-2 mb-2">
                    <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300">
                      Configured Tools
                    </h4>
                    <Badge
                      variant="default"
                      className="text-xs bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"
                    >
                      {configuredTools.length}
                    </Badge>
                  </div>
                  <div className="pl-2 space-y-1">
                    {configuredTools.map((tool) => (
                      <Controller
                        key={tool.name}
                        name="tools"
                        control={control}
                        render={({ field }) => {
                          const isChecked = field.value.includes(tool.name);
                          const hasOverrides = toolHasOverrides(tool.name);
                          const isActive = activeToolName === tool.name;
                          const hasSettings =
                            (tool.agent_override_fields?.length ?? 0) > 0 ||
                            (tool.config_fields?.length ?? 0) > 0;
                          const showSettings = hasSettings || hasOverrides;

                          return (
                            <>
                              <ToolSelectionRow
                                tool={tool}
                                sectionKind="configured"
                                checkboxId={`configured-${tool.name}`}
                                isChecked={isChecked}
                                isActive={isActive}
                                hasOverrides={hasOverrides}
                                showSettings={showSettings}
                                onCheckedChange={(checked) => {
                                  field.onChange(
                                    updateSelectedTools(
                                      field.value,
                                      tool.name,
                                      checked,
                                    ),
                                  );
                                }}
                                onToggleSettings={() =>
                                  setActiveToolName((prev) =>
                                    prev === tool.name ? null : tool.name,
                                  )
                                }
                              />
                              {isChecked && isActive && showSettings && (
                                <ToolConfigPanel
                                  agentId={selectedAgent.id}
                                  toolName={tool.name}
                                  toolDisplayName={tool.display_name}
                                  overrideFields={
                                    tool.agent_override_fields ?? null
                                  }
                                  configFields={tool.config_fields ?? null}
                                />
                              )}
                            </>
                          );
                        }}
                      />
                    ))}
                  </div>
                </div>
              )}

              {/* Divider if both sections have content */}
              {configuredTools.length > 0 &&
                (defaultTools.length > 0 || setupRequiredTools.length > 0) && (
                  <div className="border-t border-gray-200 dark:border-gray-700" />
                )}

              {/* Default Tools Section */}
              {defaultTools.length > 0 && (
                <div className="space-y-2">
                  <div className="flex items-center gap-2 mb-2">
                    <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300">
                      Default Tools
                    </h4>
                    <Badge variant="secondary" className="text-xs">
                      {defaultTools.length}
                    </Badge>
                    <span className="text-xs text-muted-foreground">
                      (work without configuration)
                    </span>
                  </div>
                  <div className="pl-2 space-y-1">
                    {defaultTools.map((tool) => (
                      <Controller
                        key={tool.name}
                        name="tools"
                        control={control}
                        render={({ field }) => {
                          const isChecked = field.value.includes(tool.name);
                          const hasOverrides = toolHasOverrides(tool.name);
                          const isActive = activeToolName === tool.name;
                          const hasSettings =
                            (tool.agent_override_fields?.length ?? 0) > 0 ||
                            (tool.config_fields?.length ?? 0) > 0;
                          const showSettings = hasSettings || hasOverrides;

                          return (
                            <>
                              <ToolSelectionRow
                                tool={tool}
                                sectionKind="default"
                                checkboxId={`default-${tool.name}`}
                                isChecked={isChecked}
                                isActive={isActive}
                                hasOverrides={hasOverrides}
                                showSettings={showSettings}
                                onCheckedChange={(checked) => {
                                  field.onChange(
                                    updateSelectedTools(
                                      field.value,
                                      tool.name,
                                      checked,
                                    ),
                                  );
                                }}
                                onToggleSettings={() =>
                                  setActiveToolName((prev) =>
                                    prev === tool.name ? null : tool.name,
                                  )
                                }
                              />
                              {isChecked && isActive && showSettings && (
                                <ToolConfigPanel
                                  agentId={selectedAgent.id}
                                  toolName={tool.name}
                                  toolDisplayName={tool.display_name}
                                  overrideFields={
                                    tool.agent_override_fields ?? null
                                  }
                                  configFields={tool.config_fields ?? null}
                                />
                              )}
                            </>
                          );
                        }}
                      />
                    ))}
                  </div>
                </div>
              )}

              {/* Divider if a setup-required section follows */}
              {(configuredTools.length > 0 || defaultTools.length > 0) &&
                setupRequiredTools.length > 0 && (
                  <div className="border-t border-gray-200 dark:border-gray-700" />
                )}

              {/* Setup Required Tools Section */}
              {setupRequiredTools.length > 0 && (
                <div className="space-y-2">
                  <div className="flex items-center gap-2 mb-2">
                    <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300">
                      Setup Required
                    </h4>
                    <Badge variant="outline" className="text-xs">
                      {setupRequiredTools.length}
                    </Badge>
                    <span className="text-xs text-muted-foreground">
                      (selectable after credentials are configured)
                    </span>
                  </div>
                  <div className="pl-2 space-y-1">
                    {setupRequiredTools.map((tool) => (
                      <Controller
                        key={tool.name}
                        name="tools"
                        control={control}
                        render={({ field }) => {
                          const isChecked = field.value.includes(tool.name);
                          const setupBlocked =
                            tool.dashboard_configuration_supported === false;
                          const hasOverrides = toolHasOverrides(tool.name);
                          const isActive = activeToolName === tool.name;
                          const hasSettings =
                            (tool.agent_override_fields?.length ?? 0) > 0 ||
                            (tool.config_fields?.length ?? 0) > 0;
                          const showSettings = hasSettings || hasOverrides;

                          return (
                            <>
                              <ToolSelectionRow
                                tool={tool}
                                sectionKind="setupRequired"
                                checkboxId={`setup-${tool.name}`}
                                isChecked={isChecked}
                                isActive={isActive}
                                hasOverrides={hasOverrides}
                                showSettings={showSettings}
                                setupBlocked={setupBlocked}
                                onCheckedChange={(checked) => {
                                  field.onChange(
                                    updateSelectedTools(
                                      field.value,
                                      tool.name,
                                      checked,
                                    ),
                                  );
                                }}
                                onToggleSettings={() =>
                                  setActiveToolName((prev) =>
                                    prev === tool.name ? null : tool.name,
                                  )
                                }
                              />
                              {isChecked && isActive && showSettings && (
                                <ToolConfigPanel
                                  agentId={selectedAgent.id}
                                  toolName={tool.name}
                                  toolDisplayName={tool.display_name}
                                  overrideFields={
                                    tool.agent_override_fields ?? null
                                  }
                                  configFields={tool.config_fields ?? null}
                                />
                              )}
                            </>
                          );
                        }}
                      />
                    ))}
                  </div>
                </div>
              )}
            </>
          )}
        </div>
      </FieldGroup>

      {/* Skills */}
      <FieldGroup
        label="Skills"
        helperText="Select skills this agent can invoke"
      >
        {skillsLoading ? (
          <div className="text-sm text-muted-foreground text-center py-2">
            Loading skills...
          </div>
        ) : (
          <CheckboxListField
            name="skills"
            control={control}
            items={skillItems}
            fieldName="skills"
            onFieldChange={handleFieldChange}
            idPrefix="skill"
            emptyMessage="No skills available. Create skills in the Skills tab first."
          />
        )}
      </FieldGroup>

      {/* Instructions */}
      <FieldGroup
        label="Instructions"
        helperText="Custom instructions for this agent"
        actions={
          <Button
            variant="outline"
            size="sm"
            onClick={handleAddInstruction}
            data-testid="add-instruction-button"
            className="h-9 px-3"
          >
            <Plus className="h-4 w-4 sm:mr-1" />
            <span className="hidden sm:inline">Add</span>
          </Button>
        }
      >
        <Controller
          name="instructions"
          control={control}
          render={({ field }) => (
            <div className="space-y-2">
              {field.value.map((instruction, index) => (
                <div key={index} className="flex gap-2">
                  <Input
                    value={instruction}
                    onChange={(e) => {
                      const updated = [...field.value];
                      updated[index] = e.target.value;
                      field.onChange(updated);
                      handleFieldChange("instructions", updated);
                    }}
                    placeholder="Instruction..."
                    className="min-h-[40px]"
                  />
                  <Button
                    variant="ghost"
                    size="icon"
                    onClick={() => handleRemoveInstruction(index)}
                    className="h-10 w-10 flex-shrink-0"
                  >
                    <X className="h-4 w-4" />
                  </Button>
                </div>
              ))}
            </div>
          )}
        />
      </FieldGroup>

      {/* Rooms */}
      <FieldGroup
        label="Agent Rooms"
        helperText="Select rooms where this agent can operate"
      >
        <CheckboxListField
          name="rooms"
          control={control}
          items={roomItems}
          fieldName="rooms"
          onFieldChange={handleFieldChange}
          idPrefix="room"
          emptyMessage="No rooms available. Create rooms in the Rooms tab."
          className="space-y-2 max-h-48 overflow-y-auto border rounded-lg p-2"
        />
      </FieldGroup>

      {/* Markdown */}
      <FieldGroup
        label="Markdown"
        helperText={`Use markdown formatting in responses (global default: ${
          defaultMarkdown ? "on" : "off"
        })`}
        htmlFor="markdown"
      >
        <Controller
          name="markdown"
          control={control}
          render={({ field }) => (
            <div className="flex items-center gap-2">
              <Checkbox
                id="markdown"
                checked={field.value ?? defaultMarkdown}
                onCheckedChange={(checked) => {
                  const value = checked === true;
                  field.onChange(value);
                  handleFieldChange("markdown", value);
                }}
              />
              <label
                htmlFor="markdown"
                className="text-sm font-medium cursor-pointer select-none"
              >
                Enable markdown
              </label>
            </div>
          )}
        />
      </FieldGroup>

      {/* Learning */}
      <FieldGroup
        label="Learning"
        helperText="Enable Agno Learning so this agent can learn from conversations"
        htmlFor="learning"
      >
        <Controller
          name="learning"
          control={control}
          render={({ field }) => (
            <div className="flex items-center gap-2">
              <Checkbox
                id="learning"
                checked={field.value ?? defaultLearning}
                onCheckedChange={(checked) => {
                  const value = checked === true;
                  field.onChange(value);
                  handleFieldChange("learning", value);
                }}
              />
              <label
                htmlFor="learning"
                className="text-sm font-medium cursor-pointer select-none"
              >
                Enable learning
              </label>
            </div>
          )}
        />
      </FieldGroup>

      <FieldGroup
        label="Learning Mode"
        helperText="Always: automatic extraction. Agentic: agent decides via tools."
        htmlFor="learning_mode"
      >
        <Controller
          name="learning_mode"
          control={control}
          render={({ field }) => (
            <Select
              value={field.value ?? defaultLearningMode}
              onValueChange={(value) => {
                field.onChange(value);
                handleFieldChange("learning_mode", value);
              }}
              disabled={effectiveLearningEnabled === false}
            >
              <SelectTrigger id="learning_mode">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="always">Always (automatic)</SelectItem>
                <SelectItem value="agentic">Agentic (tool-driven)</SelectItem>
              </SelectContent>
            </Select>
          )}
        />
      </FieldGroup>

      {/* Show Tool Calls */}
      <FieldGroup
        label="Show Tool Calls"
        helperText="Display tool call details inline in agent responses"
        htmlFor="show_tool_calls"
      >
        <Controller
          name="show_tool_calls"
          control={control}
          render={({ field }) => (
            <div className="flex items-center gap-2">
              <Checkbox
                id="show_tool_calls"
                checked={field.value ?? defaultShowToolCalls}
                onCheckedChange={(checked) => {
                  const value = checked === true;
                  field.onChange(value);
                  handleFieldChange("show_tool_calls", value);
                }}
              />
              <label
                htmlFor="show_tool_calls"
                className="text-sm font-medium cursor-pointer select-none"
              >
                Show tool calls inline
              </label>
            </div>
          )}
        />
      </FieldGroup>

      {/* Worker Tools */}
      {effectiveTools.length > 0 && (
        <FieldGroup
          label="Worker Tools"
          helperText={`Select which of this agent's tools to route through worker-scoped execution via the sandbox proxy${
            config?.defaults.worker_tools != null
              ? ` (default: ${
                  config.defaults.worker_tools.length > 0
                    ? config.defaults.worker_tools.join(", ")
                    : "none"
                })`
              : ""
          }`}
        >
          <Controller
            name="worker_tools"
            control={control}
            render={({ field }) => (
              <div className="space-y-1 max-h-48 overflow-y-auto border rounded-lg p-2">
                {effectiveTools.map((toolName) => {
                  const effective =
                    field.value ?? config?.defaults.worker_tools ?? [];
                  const isChecked = effective.includes(toolName);
                  const isInherited =
                    field.value == null &&
                    config?.defaults.worker_tools != null;
                  const toggle = () => {
                    // On first interaction when inheriting, seed from defaults
                    const current =
                      field.value ?? config?.defaults.worker_tools ?? [];
                    const updated = isChecked
                      ? current.filter((t) => t !== toolName)
                      : [...current, toolName];
                    field.onChange(updated);
                    handleFieldChange("worker_tools", updated);
                  };
                  return (
                    <div
                      key={toolName}
                      className="flex items-center space-x-3 sm:space-x-2 p-2 rounded-lg hover:bg-gray-50 dark:hover:bg-white/5 transition-colors"
                    >
                      <Checkbox
                        aria-label={`worker ${toolName}`}
                        checked={isChecked}
                        onCheckedChange={toggle}
                        className="h-5 w-5 sm:h-4 sm:w-4"
                      />
                      <span
                        role="none"
                        onClick={toggle}
                        className={`text-sm font-medium leading-none cursor-pointer select-none${
                          isInherited && isChecked
                            ? " text-gray-400 dark:text-gray-500 italic"
                            : ""
                        }`}
                      >
                        {toolName}
                        {isInherited && isChecked ? " (default)" : ""}
                      </span>
                    </div>
                  );
                })}
              </div>
            )}
          />
        </FieldGroup>
      )}

      {/* Allow Self Config */}
      <FieldGroup
        label="Allow Self Config"
        helperText="Let this agent read and modify its own configuration at runtime"
        htmlFor="allow_self_config"
      >
        <Controller
          name="allow_self_config"
          control={control}
          render={({ field }) => (
            <div className="flex items-center gap-2">
              <Checkbox
                id="allow_self_config"
                checked={
                  field.value ?? config?.defaults.allow_self_config ?? false
                }
                onCheckedChange={(checked) => {
                  const value = checked === true;
                  field.onChange(value);
                  handleFieldChange("allow_self_config", value);
                }}
              />
              <label
                htmlFor="allow_self_config"
                className="text-sm font-medium cursor-pointer select-none"
              >
                Enable self-configuration
              </label>
            </div>
          )}
        />
      </FieldGroup>

      <HistoryContextSection
        control={control}
        resetKey={selectedAgentId}
        defaults={config?.defaults}
        onFieldChange={(fieldName, value) =>
          handleFieldChange(
            fieldName as keyof Agent,
            value as Agent[keyof Agent],
          )
        }
        updateCompaction={updateCompaction}
        mutateCompaction={mutateCompaction}
        historyRunsHelperText={`Number of prior conversation runs to include as history context. Leave empty to use default${
          config?.defaults.num_history_runs != null
            ? ` (${config.defaults.num_history_runs})`
            : " (all)"
        }.`}
        historyMessagesHelperText={`Max messages from history (mutually exclusive with History Runs). Leave empty to use default${
          config?.defaults.num_history_messages != null
            ? ` (${config.defaults.num_history_messages})`
            : " (all)"
        }.`}
        maxToolCallsHelperText={`Max tool call messages replayed from history. Leave empty to use default${
          config?.defaults.max_tool_calls_from_history != null
            ? ` (${config.defaults.max_tool_calls_from_history})`
            : " (no limit)"
        }.`}
        autoCompactionHelperText="Automatically compact older session history before a run when raw replay exceeds the hard context budget."
        thresholdTokensHelperText="Soft replay budget in tokens. Crossing it records planning metadata; destructive compaction waits for the hard budget."
        compactionModelPlaceholder={
          config?.defaults.compaction?.model ?? "Default: agent model"
        }
        numHistoryRunsError={numHistoryRunsError}
        numHistoryMessagesError={numHistoryMessagesError}
        maxToolCallsFromHistoryError={maxToolCallsFromHistoryError}
        compactionError={compactionError}
        compressToolResults={{
          defaultValue: defaultCompressToolResults,
          helperText: `Compress tool results in history to save context (global default: ${
            defaultCompressToolResults ? "on" : "off"
          }). On Anthropic/Vertex Claude, enabling this can invalidate prompt-cache prefixes.`,
          onChange: (value) =>
            handleFieldChange("compress_tool_results", value),
        }}
      />
    </EditorPanel>
  );
}
