Compare commits

...

4 Commits

Author SHA1 Message Date
Ivan Ortega
5d99be253f Merge remote-tracking branch 'origin/main' into dashboarding-assistant-poc
# Conflicts:
#	packages/grafana-runtime/src/index.ts
2026-01-14 18:10:40 +01:00
Andrew Hackmann
5e68b07cac Elasticsearch: Make code editor look more like prometheus (#115461)
* Make code editor look more prometheus

* add warning when switching builders

* address adam's feedback

* yarn
2026-01-14 09:50:35 -07:00
Adela Almasan
99acd3766d Suggestions: Update empty state (#116172) 2026-01-14 10:37:42 -06:00
Dominik Prokop
bc140b2d13 Dashboarding/assistant POC 2026-01-09 12:26:03 +01:00
18 changed files with 3146 additions and 47 deletions

View File

@@ -77,5 +77,14 @@ export {
getCorrelationsService,
setCorrelationsService,
} from './services/CorrelationsService';
export {
getDashboardMutationAPI,
setDashboardMutationAPI,
type DashboardMutationAPI,
type MutationResult,
type MutationChange,
type MutationRequest,
type MCPToolDefinition,
} from './services/dashboardMutationAPI';
export { getAppPluginVersion, isAppPluginInstalled } from './services/pluginMeta/apps';
export { useAppPluginInstalled, useAppPluginVersion } from './services/pluginMeta/hooks';

View File

@@ -0,0 +1,160 @@
/**
* Dashboard Mutation API Service
*
* Provides a stable interface for programmatic dashboard modifications.
*
* The API is registered by DashboardScene when a dashboard is loaded and
* cleared when the dashboard is deactivated.
*/
/**
* MCP Tool Definition - describes a tool that can be invoked
* @see https://spec.modelcontextprotocol.io/specification/server/tools/
*/
export interface MCPToolDefinition {
name: string;
description: string;
inputSchema: {
type: 'object';
properties: Record<string, unknown>;
required?: string[];
};
annotations?: {
title?: string;
readOnlyHint?: boolean;
destructiveHint?: boolean;
idempotentHint?: boolean;
confirmationHint?: boolean;
};
}
export interface MutationResult {
success: boolean;
/** ID of the affected panel (for panel operations) */
panelId?: string;
/** Error message if success is false */
error?: string;
/** List of changes made by the mutation */
changes?: MutationChange[];
/** Warnings (non-fatal issues) */
warnings?: string[];
/** Data returned by read-only operations (e.g., GET_DASHBOARD_INFO) */
data?: unknown;
}
export interface MutationChange {
/** JSON path to the changed value */
path: string;
/** Value before the change */
previousValue: unknown;
/** Value after the change */
newValue: unknown;
}
export interface MutationRequest {
/** Type of mutation (e.g., 'ADD_PANEL', 'REMOVE_PANEL', 'UPDATE_PANEL') */
type: string;
/** Payload specific to the mutation type */
payload: unknown;
}
/**
* Dashboard info returned by getDashboardMutationAPI().getDashboardInfo()
*/
export interface DashboardMutationInfo {
available: boolean;
uid?: string;
title?: string;
canEdit: boolean;
isEditing: boolean;
availableTools: string[];
}
export interface DashboardMutationAPI {
/**
* Execute a mutation on the dashboard
*/
execute(mutation: MutationRequest): Promise<MutationResult>;
/**
* Check if the current user can edit the dashboard
*/
canEdit(): boolean;
/**
* Get the UID of the currently loaded dashboard
*/
getDashboardUID(): string | undefined;
/**
* Get the title of the currently loaded dashboard
*/
getDashboardTitle(): string | undefined;
/**
* Check if the dashboard is in edit mode
*/
isEditing(): boolean;
/**
* Enter edit mode if not already editing
*/
enterEditMode(): void;
/**
* Get the available MCP tool definitions for this dashboard
*/
getTools(): MCPToolDefinition[];
/**
* Get comprehensive dashboard info in a single call
*/
getDashboardInfo(): DashboardMutationInfo;
}
// Singleton instance
let _dashboardMutationAPI: DashboardMutationAPI | null = null;
// Expose on window for cross-bundle access (plugins use different bundle)
declare global {
interface Window {
__grafanaDashboardMutationAPI?: DashboardMutationAPI | null;
}
}
/**
* Set the dashboard mutation API instance.
* Called by DashboardScene when a dashboard is activated.
*
* @param api - The mutation API instance, or null to clear
* @internal
*/
export function setDashboardMutationAPI(api: DashboardMutationAPI | null): void {
_dashboardMutationAPI = api;
// Also expose on window for plugins that use a different @grafana/runtime bundle
if (typeof window !== 'undefined') {
window.__grafanaDashboardMutationAPI = api;
}
}
/**
* Get the dashboard mutation API for the currently loaded dashboard.
*
* @returns The mutation API, or null if no dashboard is loaded
*
* @example
* ```typescript
* import { getDashboardMutationAPI } from '@grafana/runtime';
*
* const api = getDashboardMutationAPI();
* if (api && api.canEdit()) {
* await api.execute({
* type: 'ADD_PANEL',
* payload: { ... }
* });
* }
* ```
*/
export function getDashboardMutationAPI(): DashboardMutationAPI | null {
return _dashboardMutationAPI;
}

View File

@@ -42,3 +42,13 @@ export {
export { setCurrentUser } from './user';
export { RuntimeDataSource } from './RuntimeDataSource';
export { ScopesContext, type ScopesContextValueState, type ScopesContextValue, useScopes } from './ScopesContext';
export {
getDashboardMutationAPI,
setDashboardMutationAPI,
type DashboardMutationAPI,
type DashboardMutationInfo,
type MutationResult,
type MutationChange,
type MutationRequest,
type MCPToolDefinition,
} from './dashboardMutationAPI';

View File

@@ -0,0 +1,288 @@
/**
* Mutation Executor
*
* Executes dashboard mutations with transaction support and event emission.
*/
import { v4 as uuidv4 } from 'uuid';
import type { DashboardScene } from '../scene/DashboardScene';
import {
handleAddPanel,
handleRemovePanel,
handleUpdatePanel,
handleMovePanel,
handleAddVariable,
handleRemoveVariable,
handleAddRow,
handleUpdateTimeSettings,
handleUpdateDashboardMeta,
handleGetDashboardInfo,
type MutationContext,
type MutationTransactionInternal,
type MutationHandler,
} from './handlers';
import {
type Mutation,
type MutationType,
type MutationResult,
type MutationEvent,
type MutationPayloadMap,
} from './types';
// ============================================================================
// Event Bus
// ============================================================================
type MutationEventListener = (event: MutationEvent) => void;
class MutationEventBus {
private listeners: Set<MutationEventListener> = new Set();
subscribe(listener: MutationEventListener): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
emit(event: MutationEvent): void {
this.listeners.forEach((listener) => {
try {
listener(event);
} catch (error) {
console.error('Event listener error:', error);
}
});
}
}
// ============================================================================
// Mutation Executor
// ============================================================================
export class MutationExecutor {
private scene!: DashboardScene;
private handlers: Map<MutationType, MutationHandler> = new Map();
private eventBus = new MutationEventBus();
private _currentTransaction: MutationTransactionInternal | null = null;
constructor() {
this.registerDefaultHandlers();
}
/**
* Set the dashboard scene to operate on
*/
setScene(scene: DashboardScene): void {
this.scene = scene;
}
/**
* Subscribe to mutation events
*/
onMutation(listener: MutationEventListener): () => void {
return this.eventBus.subscribe(listener);
}
/**
* Execute a single mutation
*/
async execute(mutation: Mutation): Promise<MutationResult> {
const results = await this.executeBatch([mutation]);
return results[0];
}
/**
* Execute multiple mutations atomically
*/
async executeBatch(mutations: Mutation[]): Promise<MutationResult[]> {
if (!this.scene) {
throw new Error('No scene set. Call setScene() first.');
}
// Create transaction
const transaction: MutationTransactionInternal = {
id: uuidv4(),
mutations,
status: 'pending',
startedAt: Date.now(),
changes: [],
};
this._currentTransaction = transaction;
const results: MutationResult[] = [];
const context: MutationContext = { scene: this.scene, transaction };
try {
// Execute each mutation
for (const mutation of mutations) {
const handler = this.handlers.get(mutation.type);
if (!handler) {
throw new Error(`No handler registered for mutation type: ${mutation.type}`);
}
const result = await handler(mutation.payload, context);
results.push(result);
if (!result.success) {
throw new Error(result.error || `Mutation ${mutation.type} failed`);
}
// Emit success event
this.eventBus.emit({
type: 'mutation_applied',
mutation,
result,
transaction,
timestamp: Date.now(),
source: 'assistant',
});
}
// Commit transaction
transaction.status = 'committed';
transaction.completedAt = Date.now();
// Trigger scene refresh
this.scene.forceRender();
return results;
} catch (error) {
// Probably need a rollback mechanism here... but skipping this for POC
console.error('Mutation batch failed:', error);
transaction.status = 'rolled_back';
transaction.completedAt = Date.now();
// Emit failure event
this.eventBus.emit({
type: 'mutation_rolled_back',
mutation: mutations[0],
result: { success: false, error: String(error), changes: [] },
transaction,
timestamp: Date.now(),
source: 'assistant',
});
// Return error results for remaining mutations
const errorMessage = error instanceof Error ? error.message : String(error);
while (results.length < mutations.length) {
results.push({
success: false,
error: errorMessage,
changes: [],
});
}
return results;
} finally {
this._currentTransaction = null;
}
}
/**
* Get current transaction (for debugging)
*/
get currentTransaction(): MutationTransactionInternal | null {
return this._currentTransaction;
}
// ==========================================================================
// Handler Registration
// ==========================================================================
private registerDefaultHandlers(): void {
// Panel operations
this.registerHandler('ADD_PANEL', handleAddPanel);
this.registerHandler('REMOVE_PANEL', handleRemovePanel);
this.registerHandler('UPDATE_PANEL', handleUpdatePanel);
this.registerHandler('MOVE_PANEL', handleMovePanel);
this.registerHandler('DUPLICATE_PANEL', this.notImplemented('DUPLICATE_PANEL'));
// Variable operations
this.registerHandler('ADD_VARIABLE', handleAddVariable);
this.registerHandler('REMOVE_VARIABLE', handleRemoveVariable);
this.registerHandler('UPDATE_VARIABLE', this.notImplemented('UPDATE_VARIABLE'));
// Row operations
this.registerHandler('ADD_ROW', handleAddRow);
this.registerHandler('REMOVE_ROW', this.notImplemented('REMOVE_ROW'));
this.registerHandler('COLLAPSE_ROW', this.notImplemented('COLLAPSE_ROW'));
// Tab operations
this.registerHandler('ADD_TAB', this.notImplemented('ADD_TAB'));
this.registerHandler('REMOVE_TAB', this.notImplemented('REMOVE_TAB'));
// Library panel operations
this.registerHandler('ADD_LIBRARY_PANEL', this.notImplemented('ADD_LIBRARY_PANEL'));
this.registerHandler('UNLINK_LIBRARY_PANEL', this.notImplemented('UNLINK_LIBRARY_PANEL'));
this.registerHandler('SAVE_AS_LIBRARY_PANEL', this.notImplemented('SAVE_AS_LIBRARY_PANEL'));
// Repeat configuration
this.registerHandler('CONFIGURE_PANEL_REPEAT', this.notImplemented('CONFIGURE_PANEL_REPEAT'));
this.registerHandler('CONFIGURE_ROW_REPEAT', this.notImplemented('CONFIGURE_ROW_REPEAT'));
// Conditional rendering
this.registerHandler('SET_CONDITIONAL_RENDERING', this.notImplemented('SET_CONDITIONAL_RENDERING'));
// Layout
this.registerHandler('CHANGE_LAYOUT_TYPE', this.notImplemented('CHANGE_LAYOUT_TYPE'));
// Annotation operations
this.registerHandler('ADD_ANNOTATION', this.notImplemented('ADD_ANNOTATION'));
this.registerHandler('UPDATE_ANNOTATION', this.notImplemented('UPDATE_ANNOTATION'));
this.registerHandler('REMOVE_ANNOTATION', this.notImplemented('REMOVE_ANNOTATION'));
// Link operations
this.registerHandler('ADD_DASHBOARD_LINK', this.notImplemented('ADD_DASHBOARD_LINK'));
this.registerHandler('REMOVE_DASHBOARD_LINK', this.notImplemented('REMOVE_DASHBOARD_LINK'));
this.registerHandler('ADD_PANEL_LINK', this.notImplemented('ADD_PANEL_LINK'));
this.registerHandler('ADD_DATA_LINK', this.notImplemented('ADD_DATA_LINK'));
// Field configuration
this.registerHandler('ADD_FIELD_OVERRIDE', this.notImplemented('ADD_FIELD_OVERRIDE'));
this.registerHandler('ADD_VALUE_MAPPING', this.notImplemented('ADD_VALUE_MAPPING'));
this.registerHandler('ADD_TRANSFORMATION', this.notImplemented('ADD_TRANSFORMATION'));
// Dashboard settings
this.registerHandler('UPDATE_TIME_SETTINGS', handleUpdateTimeSettings);
this.registerHandler('UPDATE_DASHBOARD_META', handleUpdateDashboardMeta);
// Dashboard management (backend operations)
this.registerHandler('MOVE_TO_FOLDER', this.notImplemented('MOVE_TO_FOLDER'));
this.registerHandler('TOGGLE_FAVORITE', this.notImplemented('TOGGLE_FAVORITE'));
// Version management (backend operations)
this.registerHandler('LIST_VERSIONS', this.notImplemented('LIST_VERSIONS'));
this.registerHandler('COMPARE_VERSIONS', this.notImplemented('COMPARE_VERSIONS'));
this.registerHandler('RESTORE_VERSION', this.notImplemented('RESTORE_VERSION'));
// Read-only operations
this.registerHandler('GET_DASHBOARD_INFO', handleGetDashboardInfo);
}
/**
* Create a stub handler for not-yet-implemented mutations
*/
private notImplemented(mutationType: string): MutationHandler {
return async (): Promise<MutationResult> => {
return {
success: false,
changes: [],
error: `${mutationType} is not fully implemented in POC`,
};
};
}
/**
* Register a mutation handler
*/
private registerHandler<T extends MutationType>(
type: T,
handler: (payload: MutationPayloadMap[T], context: MutationContext) => Promise<MutationResult>
): void {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
this.handlers.set(type, handler as MutationHandler);
}
}

View File

@@ -0,0 +1,159 @@
/**
* Dashboard settings mutation handlers
*/
import type { TimeSettingsSpec } from '@grafana/schema/src/schema/dashboard/v2beta1/types.spec.gen';
import { DASHBOARD_MCP_TOOLS } from '../mcpTools';
import type { MutationResult, MutationChange, UpdateDashboardMetaPayload, AddRowPayload } from '../types';
import type { MutationContext } from './types';
/**
* Add a row (stub - not fully implemented)
*/
export async function handleAddRow(_payload: AddRowPayload, _context: MutationContext): Promise<MutationResult> {
return {
success: true,
changes: [],
warnings: ['Add row is not fully implemented in POC - requires RowsLayout'],
};
}
/**
* Update dashboard time settings
*/
export async function handleUpdateTimeSettings(
payload: Partial<TimeSettingsSpec>,
context: MutationContext
): Promise<MutationResult> {
const { scene, transaction } = context;
const { from, to, timezone, autoRefresh } = payload;
try {
const timeRange = scene.state.$timeRange;
if (!timeRange) {
throw new Error('Dashboard has no time range');
}
const previousState = { ...timeRange.state };
// Apply updates based on TimeSettingsSpec fields
const updates: Record<string, unknown> = {};
if (from !== undefined) {
updates.from = from;
}
if (to !== undefined) {
updates.to = to;
}
if (timezone !== undefined) {
updates.timeZone = timezone;
}
if (autoRefresh !== undefined) {
// autoRefresh would be applied to the dashboard refresh interval
updates.refreshInterval = autoRefresh;
}
timeRange.setState(updates);
const changes: MutationChange[] = [{ path: '/timeSettings', previousValue: previousState, newValue: updates }];
transaction.changes.push(...changes);
return {
success: true,
inverseMutation: {
type: 'UPDATE_TIME_SETTINGS',
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
payload: previousState as Partial<TimeSettingsSpec>,
},
changes,
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error),
changes: [],
};
}
}
/**
* Update dashboard metadata (title, description, tags, etc.)
*/
export async function handleUpdateDashboardMeta(
payload: UpdateDashboardMetaPayload,
context: MutationContext
): Promise<MutationResult> {
const { scene, transaction } = context;
const { title, description, tags, editable } = payload;
try {
const previousState = {
title: scene.state.title,
description: scene.state.description,
tags: scene.state.tags,
editable: scene.state.editable,
};
// Apply updates
const updates: Partial<UpdateDashboardMetaPayload> = {};
if (title !== undefined) {
updates.title = title;
}
if (description !== undefined) {
updates.description = description;
}
if (tags !== undefined) {
updates.tags = tags;
}
if (editable !== undefined) {
updates.editable = editable;
}
scene.setState(updates);
const changes: MutationChange[] = [{ path: '/meta', previousValue: previousState, newValue: updates }];
transaction.changes.push(...changes);
return {
success: true,
inverseMutation: {
type: 'UPDATE_DASHBOARD_META',
payload: previousState,
},
changes,
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error),
changes: [],
};
}
}
/**
* Get dashboard info (read-only operation)
*/
export async function handleGetDashboardInfo(
_payload: Record<string, never>,
context: MutationContext
): Promise<MutationResult> {
const { scene } = context;
// Return dashboard info in the result's data field
const info = {
available: true,
uid: scene.state.uid,
title: scene.state.title,
canEdit: scene.canEditDashboard(),
isEditing: scene.state.isEditing ?? false,
availableTools: DASHBOARD_MCP_TOOLS.map((t) => t.name),
};
return {
success: true,
changes: [],
data: info,
};
}

View File

@@ -0,0 +1,27 @@
/**
* Mutation Handlers
*
* Pure functions that implement dashboard mutations.
* Each handler receives a payload and context, and returns a MutationResult.
*/
// Types
// eslint-disable-next-line no-barrel-files/no-barrel-files
export type { MutationContext, MutationTransactionInternal, MutationHandler } from './types';
// Panel handlers
// eslint-disable-next-line no-barrel-files/no-barrel-files
export { handleAddPanel, handleRemovePanel, handleUpdatePanel, handleMovePanel } from './panelHandlers';
// Variable handlers
// eslint-disable-next-line no-barrel-files/no-barrel-files
export { handleAddVariable, handleRemoveVariable } from './variableHandlers';
// Dashboard handlers
// eslint-disable-next-line no-barrel-files/no-barrel-files
export {
handleAddRow,
handleUpdateTimeSettings,
handleUpdateDashboardMeta,
handleGetDashboardInfo,
} from './dashboardHandlers';

View File

@@ -0,0 +1,224 @@
/**
* Panel mutation handlers
*/
import type { MutationResult, MutationChange, AddPanelPayload, RemovePanelPayload, UpdatePanelPayload } from '../types';
import type { MutationContext } from './types';
/**
* Add a new panel to the dashboard
*/
export async function handleAddPanel(payload: AddPanelPayload, context: MutationContext): Promise<MutationResult> {
const { scene, transaction } = context;
try {
// Extract values with defaults
// Top-level fields take precedence, then spec fields, then defaults
const title = payload.title ?? payload.spec?.title ?? 'New Panel';
// VizConfigKind.group contains the plugin ID
const vizType = payload.vizType ?? payload.spec?.vizConfig?.group ?? 'timeseries';
const description = payload.description ?? payload.spec?.description ?? '';
// Position is for future layout placement (not yet implemented)
const _position = payload.position;
void _position; // Suppress unused variable warning until layout positioning is implemented
// Generate unique element name
const elementName = `panel-${title.toLowerCase().replace(/[^a-z0-9]/g, '-')}-${Date.now()}`;
// Use scene's addPanel method (simplified for POC)
const body = scene.state.body;
if (!body) {
throw new Error('Dashboard has no body');
}
// For POC: Create a basic panel using VizPanel directly
// Real implementation would use proper panel building utilities
const { VizPanel } = await import('@grafana/scenes');
const vizPanel = new VizPanel({
title,
pluginId: vizType,
description,
options: {},
fieldConfig: { defaults: {}, overrides: [] },
key: elementName,
});
// Add panel to scene
scene.addPanel(vizPanel);
const changes: MutationChange[] = [
{ path: `/elements/${elementName}`, previousValue: undefined, newValue: { title, vizType } },
];
transaction.changes.push(...changes);
return {
success: true,
inverseMutation: {
type: 'REMOVE_PANEL',
payload: { elementName },
},
changes,
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error),
changes: [],
};
}
}
/**
* Remove a panel from the dashboard
*/
export async function handleRemovePanel(
payload: RemovePanelPayload,
context: MutationContext
): Promise<MutationResult> {
const { scene, transaction } = context;
const { elementName, panelId } = payload;
try {
// Find the panel
const body = scene.state.body;
if (!body) {
throw new Error('Dashboard has no body');
}
// Find panel by element name or ID
const { VizPanel } = await import('@grafana/scenes');
let panelToRemove: InstanceType<typeof VizPanel> | null = null;
let panelState: Record<string, unknown> = {};
// Search through the scene's panels
const panels = body.getVizPanels?.() || [];
for (const panel of panels) {
const state = panel.state;
if (elementName && state.key === elementName) {
panelToRemove = panel;
panelState = { ...state };
break;
}
// panelId is stored internally, use key for matching
if (panelId !== undefined && state.key && String(state.key).includes(String(panelId))) {
panelToRemove = panel;
panelState = { ...state };
break;
}
}
if (!panelToRemove) {
throw new Error(`Panel not found: ${elementName || panelId}`);
}
// Remove the panel
scene.removePanel(panelToRemove);
const changes: MutationChange[] = [
{ path: `/elements/${elementName || panelId}`, previousValue: panelState, newValue: undefined },
];
transaction.changes.push(...changes);
return {
success: true,
inverseMutation: {
type: 'REMOVE_PANEL',
payload: { elementName: String(panelState.key) },
},
changes,
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error),
changes: [],
};
}
}
/**
* Update an existing panel
*/
export async function handleUpdatePanel(
payload: UpdatePanelPayload,
context: MutationContext
): Promise<MutationResult> {
const { scene, transaction } = context;
const { elementName, panelId, updates } = payload;
try {
// Find the panel
const body = scene.state.body;
if (!body) {
throw new Error('Dashboard has no body');
}
const { VizPanel } = await import('@grafana/scenes');
const panels = body.getVizPanels?.() || [];
let panelToUpdate: InstanceType<typeof VizPanel> | null = null;
for (const panel of panels) {
const state = panel.state;
if (elementName && state.key === elementName) {
panelToUpdate = panel;
break;
}
// panelId is stored internally, use key for matching
if (panelId !== undefined && state.key && String(state.key).includes(String(panelId))) {
panelToUpdate = panel;
break;
}
}
if (!panelToUpdate) {
throw new Error(`Panel not found: ${elementName || panelId}`);
}
// Store previous state for rollback
const previousState = { ...panelToUpdate.state };
// Apply updates from PanelSpec
if (updates.title !== undefined) {
panelToUpdate.setState({ title: updates.title });
}
if (updates.description !== undefined) {
panelToUpdate.setState({ description: updates.description });
}
// More updates would be handled here based on PanelSpec fields
const changes: MutationChange[] = [
{ path: `/elements/${elementName || panelId}`, previousValue: previousState, newValue: updates },
];
transaction.changes.push(...changes);
return {
success: true,
inverseMutation: {
type: 'UPDATE_PANEL',
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
payload: { elementName, panelId, updates: previousState as UpdatePanelPayload['updates'] },
},
changes,
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error),
changes: [],
};
}
}
/**
* Move a panel (stub - not fully implemented)
*/
export async function handleMovePanel(): Promise<MutationResult> {
return {
success: true,
changes: [],
warnings: ['Move panel is not fully implemented in POC'],
};
}

View File

@@ -0,0 +1,29 @@
/**
* Shared types for mutation handlers
*/
import type { DashboardScene } from '../../scene/DashboardScene';
import type { MutationResult, MutationChange, MutationType, MutationPayloadMap, MutationTransaction } from '../types';
/**
* Context passed to all mutation handlers
*/
export interface MutationContext {
scene: DashboardScene;
transaction: MutationTransactionInternal;
}
/**
* Internal transaction type with mutable changes array
*/
export interface MutationTransactionInternal extends MutationTransaction {
changes: MutationChange[];
}
/**
* A mutation handler function
*/
export type MutationHandler<T extends MutationType = MutationType> = (
payload: MutationPayloadMap[T],
context: MutationContext
) => Promise<MutationResult>;

View File

@@ -0,0 +1,72 @@
/**
* Variable mutation handlers
*/
import type { MutationResult, MutationChange, AddVariablePayload, RemoveVariablePayload } from '../types';
import type { MutationContext } from './types';
/**
* Add a variable (stub - not fully implemented)
*/
export async function handleAddVariable(
_payload: AddVariablePayload,
_context: MutationContext
): Promise<MutationResult> {
// TODO: Variable creation requires access to internal serialization functions
// (createSceneVariableFromVariableModel) which are not currently exported.
// This needs to be addressed by exporting the function or creating a public API.
return {
success: true,
changes: [],
warnings: ['Add variable is not fully implemented in POC - requires exported variable factory'],
};
}
/**
* Remove a variable from the dashboard
*/
export async function handleRemoveVariable(
payload: RemoveVariablePayload,
context: MutationContext
): Promise<MutationResult> {
const { scene, transaction } = context;
const { name } = payload;
try {
const variables = scene.state.$variables;
if (!variables) {
throw new Error('Dashboard has no variable set');
}
const variable = variables.getByName(name);
if (!variable) {
throw new Error(`Variable '${name}' not found`);
}
const previousState = variable.state;
// Remove variable
variables.setState({
variables: variables.state.variables.filter((v: { state: { name: string } }) => v.state.name !== name),
});
const changes: MutationChange[] = [
{ path: `/variables/${name}`, previousValue: previousState, newValue: undefined },
];
transaction.changes.push(...changes);
// inverse mutation would need to reconstruct the VariableKind from SceneVariable state
// This is simplified for POC
return {
success: true,
changes,
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error),
changes: [],
};
}
}

View File

@@ -0,0 +1,76 @@
/**
* Dashboard Mutation API
*
* This module provides a stable API for programmatic dashboard modifications.
* It is designed for use by Grafana Assistant and other tools that need to modify dashboards.
*
* @example
* ```typescript
* import { getDashboardMutationAPI } from '@grafana/runtime';
*
* const api = getDashboardMutationAPI();
* if (api && api.canEdit()) {
* // Simple: just title and vizType
* const result = await api.execute({
* type: 'ADD_PANEL',
* payload: { title: 'CPU Usage', vizType: 'timeseries' },
* });
*
* // Advanced: with full spec
* const result2 = await api.execute({
* type: 'ADD_PANEL',
* payload: {
* title: 'Memory Usage',
* spec: {
* vizConfig: { kind: 'VizConfig', spec: { pluginId: 'stat' } },
* data: { kind: 'QueryGroup', spec: { queries: [] } },
* },
* },
* });
* }
* ```
*/
// Types - intentionally re-exported as public API surface
// eslint-disable-next-line no-barrel-files/no-barrel-files
export type {
// Mutation types
MutationType,
Mutation,
MutationPayloadMap,
MutationResult,
MutationChange,
MutationTransaction,
MutationEvent,
// Payload types (use schema types directly where possible)
AddPanelPayload,
RemovePanelPayload,
UpdatePanelPayload,
MovePanelPayload,
DuplicatePanelPayload,
AddVariablePayload,
RemoveVariablePayload,
UpdateVariablePayload,
AddRowPayload,
RemoveRowPayload,
CollapseRowPayload,
UpdateTimeSettingsPayload,
UpdateDashboardMetaPayload,
// Supporting types
LayoutPosition,
// MCP types
MCPToolDefinition,
MCPResourceDefinition,
MCPPromptDefinition,
} from './types';
// Mutation Executor
// eslint-disable-next-line no-barrel-files/no-barrel-files
export { MutationExecutor } from './MutationExecutor';
// MCP Tool Definitions
// eslint-disable-next-line no-barrel-files/no-barrel-files
export { DASHBOARD_MCP_TOOLS, DASHBOARD_MCP_RESOURCES, DASHBOARD_MCP_PROMPTS } from './mcpTools';

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,420 @@
/**
* Dashboard Mutation API - Core Types
*
* This module defines the types for the MCP-based dashboard mutation API.
* It provides a standardized interface for programmatic dashboard modifications.
*/
/**
* Import v2 schema types - these are the source of truth.
*
* The mutation API uses these types directly to ensure compatibility with the dashboard schema.
* No custom payload types are created - we use schema types with Omit for auto-generated fields.
*/
import type {
// Panel types
PanelSpec,
DataLink,
// Variable types
VariableKind,
// Layout types
GridLayoutItemSpec,
RowsLayoutRowSpec,
TabsLayoutTabSpec,
AutoGridLayoutSpec,
RepeatOptions,
ConditionalRenderingGroupSpec,
// Annotation types
AnnotationQuerySpec,
// Dashboard types
DashboardLink,
TimeSettingsSpec,
// Field config types
DynamicConfigValue,
MatcherConfig,
ValueMapping,
DataTransformerConfig,
} from '@grafana/schema/src/schema/dashboard/v2beta1/types.spec.gen';
// ============================================================================
// Mutation Types
// ============================================================================
export type MutationType =
// Panel operations
| 'ADD_PANEL'
| 'REMOVE_PANEL'
| 'UPDATE_PANEL'
| 'MOVE_PANEL'
| 'DUPLICATE_PANEL'
// Variable operations
| 'ADD_VARIABLE'
| 'REMOVE_VARIABLE'
| 'UPDATE_VARIABLE'
// Row operations
| 'ADD_ROW'
| 'REMOVE_ROW'
| 'COLLAPSE_ROW'
// Tab operations
| 'ADD_TAB'
| 'REMOVE_TAB'
// Library panel operations
| 'ADD_LIBRARY_PANEL'
| 'UNLINK_LIBRARY_PANEL'
| 'SAVE_AS_LIBRARY_PANEL'
// Repeat configuration
| 'CONFIGURE_PANEL_REPEAT'
| 'CONFIGURE_ROW_REPEAT'
// Conditional rendering
| 'SET_CONDITIONAL_RENDERING'
// Layout
| 'CHANGE_LAYOUT_TYPE'
// Annotation operations
| 'ADD_ANNOTATION'
| 'UPDATE_ANNOTATION'
| 'REMOVE_ANNOTATION'
// Link operations
| 'ADD_DASHBOARD_LINK'
| 'REMOVE_DASHBOARD_LINK'
| 'ADD_PANEL_LINK'
| 'ADD_DATA_LINK'
// Field configuration
| 'ADD_FIELD_OVERRIDE'
| 'ADD_VALUE_MAPPING'
| 'ADD_TRANSFORMATION'
// Dashboard settings
| 'UPDATE_TIME_SETTINGS'
| 'UPDATE_DASHBOARD_META'
// Dashboard management (backend)
| 'MOVE_TO_FOLDER'
| 'TOGGLE_FAVORITE'
// Version management (backend)
| 'LIST_VERSIONS'
| 'COMPARE_VERSIONS'
| 'RESTORE_VERSION'
// Read-only operations
| 'GET_DASHBOARD_INFO';
// ============================================================================
// Mutation Payloads
// ============================================================================
/**
* Payload for adding a panel.
*
* Uses Partial<PanelSpec> so callers can provide just the fields they care about.
* Missing fields are filled with sensible defaults (title defaults to "New Panel", etc.)
* The `id` field is always auto-generated by the system.
*
* Minimal example: { title: "My Panel" }
* Full example: { title: "My Panel", description: "...", vizConfig: {...}, data: {...} }
*/
export interface AddPanelPayload {
/** Panel title (required for meaningful panels) */
title?: string;
/** Visualization type shorthand (e.g., "timeseries", "stat", "table") */
vizType?: string;
/** Panel description */
description?: string;
/** Full panel spec - for advanced use cases. Fields here override top-level fields. */
spec?: Partial<Omit<PanelSpec, 'id'>>;
/** Position in the layout */
position?: LayoutPosition;
}
export interface RemovePanelPayload {
/** Element name in the elements map */
elementName?: string;
/** Alternative: Panel ID */
panelId?: number;
}
export interface UpdatePanelPayload {
/** Element name or panel ID to update */
elementName?: string;
panelId?: number;
/** Updates to apply - partial PanelSpec (id cannot be changed) */
updates: Partial<Omit<PanelSpec, 'id'>>;
}
export interface MovePanelPayload {
/** Element name to move */
elementName: string;
/** Target position */
targetPosition: LayoutPosition;
}
export interface DuplicatePanelPayload {
/** Element name to duplicate */
elementName: string;
/** New title (optional, defaults to "Copy of {original}") */
newTitle?: string;
}
/**
* Payload for adding a variable.
* Uses VariableKind from schema directly - the union of all variable types.
*/
export interface AddVariablePayload {
/** The complete variable definition from v2 schema */
variable: VariableKind;
/** Position in the variables array (optional, appends if not specified) */
position?: number;
}
export interface RemoveVariablePayload {
/** Variable name to remove */
name: string;
}
export interface UpdateVariablePayload {
/** Variable name to update */
name: string;
/** The updated variable definition - replaces the existing one */
variable: VariableKind;
}
/**
* Payload for adding a row.
* Uses RowsLayoutRowSpec from schema, but layout is optional (created empty).
*/
export interface AddRowPayload {
/** Row spec - uses schema type. Layout is created empty if not provided. */
spec: Omit<RowsLayoutRowSpec, 'layout'> & {
layout?: RowsLayoutRowSpec['layout'];
};
/** Position index (0 = first) */
position?: number;
}
export interface RemoveRowPayload {
/** Row title or index to identify the row */
rowTitle?: string;
rowIndex?: number;
/** What to do with panels in the row */
panelHandling?: 'delete' | 'moveToRoot';
}
export interface CollapseRowPayload {
/** Row title or index to identify the row */
rowTitle?: string;
rowIndex?: number;
/** Whether to collapse or expand */
collapsed: boolean;
}
/**
* Payload for updating time settings.
* Uses TimeSettingsSpec from schema.
*/
export type UpdateTimeSettingsPayload = Partial<TimeSettingsSpec>;
/**
* Payload for updating dashboard metadata.
* These are top-level DashboardV2Spec fields.
*/
export interface UpdateDashboardMetaPayload {
title?: string;
description?: string;
tags?: string[];
editable?: boolean;
preload?: boolean;
liveNow?: boolean;
}
// ============================================================================
// Supporting Types - derived from schema types
// ============================================================================
/**
* Layout position for placing elements.
* Combines GridLayoutItemSpec position fields with container targeting.
*/
export type LayoutPosition = Pick<GridLayoutItemSpec, 'x' | 'y' | 'width' | 'height' | 'repeat'> & {
/** Target row title (for RowsLayout) */
targetRow?: string;
/** Target tab title (for TabsLayout) */
targetTab?: string;
};
// ============================================================================
// Mutation Definition
// ============================================================================
export interface Mutation<T extends MutationType = MutationType> {
type: T;
payload: MutationPayloadMap[T];
}
export interface MutationPayloadMap {
// Panel operations
ADD_PANEL: AddPanelPayload;
REMOVE_PANEL: RemovePanelPayload;
UPDATE_PANEL: UpdatePanelPayload;
MOVE_PANEL: MovePanelPayload;
DUPLICATE_PANEL: DuplicatePanelPayload;
// Variable operations
ADD_VARIABLE: AddVariablePayload;
REMOVE_VARIABLE: RemoveVariablePayload;
UPDATE_VARIABLE: UpdateVariablePayload;
// Row operations
ADD_ROW: AddRowPayload;
REMOVE_ROW: RemoveRowPayload;
COLLAPSE_ROW: CollapseRowPayload;
// Tab operations - uses TabsLayoutTabSpec from schema
ADD_TAB: {
spec: Omit<TabsLayoutTabSpec, 'layout'> & { layout?: TabsLayoutTabSpec['layout'] };
position?: number;
};
REMOVE_TAB: { tabTitle?: string; tabIndex?: number; panelHandling?: 'delete' | 'moveToRoot' };
// Library panel operations
ADD_LIBRARY_PANEL: { libraryPanelUid?: string; libraryPanelName?: string; position?: LayoutPosition };
UNLINK_LIBRARY_PANEL: { elementName: string };
SAVE_AS_LIBRARY_PANEL: { elementName: string; libraryPanelName: string; folderUid?: string };
// Repeat configuration - uses RepeatOptions from schema
CONFIGURE_PANEL_REPEAT: { elementName: string; repeat: RepeatOptions | null };
CONFIGURE_ROW_REPEAT: { rowTitle?: string; rowIndex?: number; repeat: RowsLayoutRowSpec['repeat'] | null };
// Conditional rendering - uses ConditionalRenderingGroupSpec from schema
SET_CONDITIONAL_RENDERING: {
elementName: string;
conditionalRendering: ConditionalRenderingGroupSpec | null;
};
// Layout - uses AutoGridLayoutSpec for options
CHANGE_LAYOUT_TYPE: {
layoutType: 'GridLayout' | 'RowsLayout' | 'AutoGridLayout' | 'TabsLayout';
options?: Partial<AutoGridLayoutSpec>;
};
// Annotation operations - uses AnnotationQuerySpec from schema
ADD_ANNOTATION: Omit<AnnotationQuerySpec, 'query'> & { query?: AnnotationQuerySpec['query'] };
UPDATE_ANNOTATION: { name: string; updates: Partial<AnnotationQuerySpec> };
REMOVE_ANNOTATION: { name: string };
// Link operations - uses DashboardLink from schema
ADD_DASHBOARD_LINK: DashboardLink;
REMOVE_DASHBOARD_LINK: { title?: string; index?: number };
// Panel link operations - uses DataLink from schema
ADD_PANEL_LINK: { elementName: string; link: DataLink };
ADD_DATA_LINK: { elementName: string; link: DataLink };
// Field configuration - uses schema types
ADD_FIELD_OVERRIDE: {
elementName: string;
matcher: MatcherConfig;
properties: DynamicConfigValue[];
};
ADD_VALUE_MAPPING: { elementName: string; mapping: ValueMapping };
ADD_TRANSFORMATION: { elementName: string; transformation: Omit<DataTransformerConfig, 'id'> & { id: string } };
// Dashboard settings
UPDATE_TIME_SETTINGS: UpdateTimeSettingsPayload;
UPDATE_DASHBOARD_META: UpdateDashboardMetaPayload;
// Dashboard management (backend)
MOVE_TO_FOLDER: { folderUid?: string; folderTitle?: string };
TOGGLE_FAVORITE: { favorite: boolean };
// Version management (backend)
LIST_VERSIONS: { limit?: number };
COMPARE_VERSIONS: { baseVersion: number; newVersion: number };
RESTORE_VERSION: { version: number };
// Read-only operations (no payload required)
GET_DASHBOARD_INFO: Record<string, never>;
}
// ============================================================================
// Mutation Result
// ============================================================================
export interface MutationResult {
success: boolean;
/** Mutation to apply to undo this change */
inverseMutation?: Mutation;
/** Changes that were applied */
changes: MutationChange[];
/** Error message if failed */
error?: string;
/** Warnings (non-fatal issues) */
warnings?: string[];
/** Data returned by read-only operations (e.g., GET_DASHBOARD_INFO) */
data?: unknown;
}
export interface MutationChange {
path: string;
previousValue: unknown;
newValue: unknown;
}
// ============================================================================
// Transaction
// ============================================================================
export interface MutationTransaction {
id: string;
mutations: Mutation[];
status: 'pending' | 'committed' | 'rolled_back';
startedAt: number;
completedAt?: number;
}
// ============================================================================
// Event Types
// ============================================================================
export interface MutationEvent {
type: 'mutation_applied' | 'mutation_failed' | 'mutation_rolled_back';
mutation: Mutation;
result: MutationResult;
transaction?: MutationTransaction;
timestamp: number;
source: 'assistant' | 'ui' | 'api';
}
// ============================================================================
// MCP Tool Types
// ============================================================================
export interface MCPToolDefinition {
name: string;
description: string;
inputSchema: {
type: 'object';
properties: Record<string, unknown>;
required?: string[];
};
annotations?: {
title?: string;
readOnlyHint?: boolean;
destructiveHint?: boolean;
idempotentHint?: boolean;
confirmationHint?: boolean;
};
}
export interface MCPResourceDefinition {
uri: string;
uriTemplate?: boolean;
name: string;
description: string;
mimeType: string;
}
export interface MCPPromptDefinition {
name: string;
description: string;
arguments: Array<{
name: string;
description: string;
required: boolean;
}>;
}

View File

@@ -2,7 +2,13 @@ import * as H from 'history';
import { CoreApp, DataQueryRequest, locationUtil, NavIndex, NavModelItem } from '@grafana/data';
import { t } from '@grafana/i18n';
import { config, locationService, RefreshEvent } from '@grafana/runtime';
import {
config,
locationService,
RefreshEvent,
setDashboardMutationAPI,
type DashboardMutationAPI,
} from '@grafana/runtime';
import {
sceneGraph,
SceneObject,
@@ -45,6 +51,9 @@ import {
} from '../../apiserver/types';
import { DashboardEditPane } from '../edit-pane/DashboardEditPane';
import { dashboardEditActions } from '../edit-pane/shared';
import { MutationExecutor } from '../mutation-api/MutationExecutor';
import { DASHBOARD_MCP_TOOLS } from '../mutation-api/mcpTools';
import type { Mutation } from '../mutation-api/types';
import { PanelEditor } from '../panel-edit/PanelEditor';
import { DashboardSceneChangeTracker } from '../saving/DashboardSceneChangeTracker';
import { SaveDashboardDrawer } from '../saving/SaveDashboardDrawer';
@@ -93,6 +102,11 @@ import { clearClipboard } from './layouts-shared/paste';
import { DashboardLayoutManager } from './types/DashboardLayoutManager';
import { LayoutParent } from './types/LayoutParent';
// Type for window with mutation API (for cross-bundle access with plugins)
interface WindowWithMutationAPI extends Window {
__grafanaDashboardMutationAPI?: DashboardMutationAPI | null;
}
export const PERSISTED_PROPS = ['title', 'description', 'tags', 'editable', 'graphTooltip', 'links', 'meta', 'preload'];
export const PANEL_SEARCH_VAR = 'systemPanelFilterVar';
export const PANELS_PER_ROW_VAR = 'systemDynamicRowSizeVar';
@@ -219,6 +233,9 @@ export class DashboardScene extends SceneObjectBase<DashboardSceneState> impleme
window.__grafanaSceneContext = this;
// Register Dashboard Mutation API for Grafana Assistant and other tools
this._registerMutationAPI();
this._initializePanelSearch();
if (this.state.isEditing) {
@@ -247,6 +264,10 @@ export class DashboardScene extends SceneObjectBase<DashboardSceneState> impleme
// Deactivation logic
return () => {
window.__grafanaSceneContext = prevSceneContext;
// Clear mutation API
setDashboardMutationAPI(null);
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
(window as WindowWithMutationAPI).__grafanaDashboardMutationAPI = null;
clearKeyBindings();
this._changeTracker.terminate();
oldDashboardWrapper.destroy();
@@ -254,6 +275,49 @@ export class DashboardScene extends SceneObjectBase<DashboardSceneState> impleme
};
}
/**
* Register the Dashboard Mutation API for use by Grafana Assistant and other tools.
* This provides a stable interface for programmatic dashboard modifications.
*
* The API is exposed on window.__grafanaDashboardMutationAPI for cross-bundle access,
* since plugins use a different @grafana/runtime bundle.
*/
private _registerMutationAPI() {
const dashboard = this;
const executor = new MutationExecutor();
executor.setScene(this);
const api: DashboardMutationAPI = {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
execute: (mutation) => executor.executeMutation(mutation as Mutation),
canEdit: () => dashboard.canEditDashboard(),
getDashboardUID: () => dashboard.state.uid,
getDashboardTitle: () => dashboard.state.title,
isEditing: () => dashboard.state.isEditing ?? false,
enterEditMode: () => {
if (!dashboard.state.isEditing) {
dashboard.onEnterEditMode();
}
},
getTools: () => DASHBOARD_MCP_TOOLS,
getDashboardInfo: () => ({
available: true,
uid: dashboard.state.uid,
title: dashboard.state.title,
canEdit: dashboard.canEditDashboard(),
isEditing: dashboard.state.isEditing ?? false,
availableTools: DASHBOARD_MCP_TOOLS.map((t) => t.name),
}),
};
// Register via @grafana/runtime for same-bundle access
setDashboardMutationAPI(api);
// Also expose on window for cross-bundle access (plugins use different bundle)
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
(window as WindowWithMutationAPI).__grafanaDashboardMutationAPI = api;
}
private _initializePanelSearch() {
const systemPanelFilter = sceneGraph.lookupVariable(PANEL_SEARCH_VAR, this)?.getValue();
if (typeof systemPanelFilter === 'string') {

View File

@@ -2,8 +2,9 @@ import { render, screen } from '@testing-library/react';
import { defaultsDeep } from 'lodash';
import { Provider } from 'react-redux';
import { FieldType, getDefaultTimeRange, LoadingState } from '@grafana/data';
import { PanelDataErrorViewProps } from '@grafana/runtime';
import { CoreApp, EventBusSrv, FieldType, getDefaultTimeRange, LoadingState } from '@grafana/data';
import { config, PanelDataErrorViewProps } from '@grafana/runtime';
import { usePanelContext } from '@grafana/ui';
import { configureStore } from 'app/store/configureStore';
import { PanelDataErrorView } from './PanelDataErrorView';
@@ -16,7 +17,24 @@ jest.mock('app/features/dashboard/services/DashboardSrv', () => ({
},
}));
jest.mock('@grafana/ui', () => ({
...jest.requireActual('@grafana/ui'),
usePanelContext: jest.fn(),
}));
const mockUsePanelContext = jest.mocked(usePanelContext);
const RUN_QUERY_MESSAGE = 'Run a query to visualize it here or go to all visualizations to add other panel types';
const panelContextRoot = {
app: CoreApp.Dashboard,
eventsScope: 'global',
eventBus: new EventBusSrv(),
};
describe('PanelDataErrorView', () => {
beforeEach(() => {
mockUsePanelContext.mockReturnValue(panelContextRoot);
});
it('show No data when there is no data', () => {
renderWithProps();
@@ -70,6 +88,45 @@ describe('PanelDataErrorView', () => {
expect(screen.getByText('Query returned nothing')).toBeInTheDocument();
});
it('should show "Run a query..." message when no query is configured and feature toggle is enabled', () => {
mockUsePanelContext.mockReturnValue(panelContextRoot);
const originalFeatureToggle = config.featureToggles.newVizSuggestions;
config.featureToggles.newVizSuggestions = true;
renderWithProps({
data: {
state: LoadingState.Done,
series: [],
timeRange: getDefaultTimeRange(),
},
});
expect(screen.getByText(RUN_QUERY_MESSAGE)).toBeInTheDocument();
config.featureToggles.newVizSuggestions = originalFeatureToggle;
});
it('should show "No data" message when feature toggle is disabled even without queries', () => {
mockUsePanelContext.mockReturnValue(panelContextRoot);
const originalFeatureToggle = config.featureToggles.newVizSuggestions;
config.featureToggles.newVizSuggestions = false;
renderWithProps({
data: {
state: LoadingState.Done,
series: [],
timeRange: getDefaultTimeRange(),
},
});
expect(screen.getByText('No data')).toBeInTheDocument();
expect(screen.queryByText(RUN_QUERY_MESSAGE)).not.toBeInTheDocument();
config.featureToggles.newVizSuggestions = originalFeatureToggle;
});
});
function renderWithProps(overrides?: Partial<PanelDataErrorViewProps>) {

View File

@@ -5,14 +5,15 @@ import {
FieldType,
getPanelDataSummary,
GrafanaTheme2,
PanelData,
PanelDataSummary,
PanelPluginVisualizationSuggestion,
} from '@grafana/data';
import { selectors } from '@grafana/e2e-selectors';
import { t, Trans } from '@grafana/i18n';
import { PanelDataErrorViewProps, locationService } from '@grafana/runtime';
import { PanelDataErrorViewProps, locationService, config } from '@grafana/runtime';
import { VizPanel } from '@grafana/scenes';
import { usePanelContext, useStyles2 } from '@grafana/ui';
import { Icon, usePanelContext, useStyles2 } from '@grafana/ui';
import { CardButton } from 'app/core/components/CardButton';
import { LS_VISUALIZATION_SELECT_TAB_KEY } from 'app/core/constants';
import store from 'app/core/store';
@@ -24,6 +25,11 @@ import { findVizPanelByKey, getVizPanelKeyForPanelId } from 'app/features/dashbo
import { useDispatch } from 'app/types/store';
import { changePanelPlugin } from '../state/actions';
import { hasData } from '../suggestions/utils';
function hasNoQueryConfigured(data: PanelData): boolean {
return !data.request?.targets || data.request.targets.length === 0;
}
export function PanelDataErrorView(props: PanelDataErrorViewProps) {
const styles = useStyles2(getStyles);
@@ -93,8 +99,14 @@ export function PanelDataErrorView(props: PanelDataErrorViewProps) {
}
};
const noData = !hasData(props.data);
const noQueryConfigured = hasNoQueryConfigured(props.data);
const showEmptyState =
config.featureToggles.newVizSuggestions && context.app === CoreApp.PanelEditor && noQueryConfigured && noData;
return (
<div className={styles.wrapper}>
{showEmptyState && <Icon name="chart-line" size="xxxl" className={styles.emptyStateIcon} />}
<div className={styles.message} data-testid={selectors.components.Panels.Panel.PanelDataErrorMessage}>
{message}
</div>
@@ -131,7 +143,17 @@ function getMessageFor(
return message;
}
if (!data.series || data.series.length === 0 || data.series.every((frame) => frame.length === 0)) {
const noData = !hasData(data);
const noQueryConfigured = hasNoQueryConfigured(data);
if (config.featureToggles.newVizSuggestions && noQueryConfigured && noData) {
return t(
'dashboard.new-panel.empty-state-message',
'Run a query to visualize it here or go to all visualizations to add other panel types'
);
}
if (noData) {
return fieldConfig?.defaults.noValue ?? t('panel.panel-data-error-view.no-value.default', 'No data');
}
@@ -176,5 +198,9 @@ const getStyles = (theme: GrafanaTheme2) => {
width: '100%',
maxWidth: '600px',
}),
emptyStateIcon: css({
color: theme.colors.text.secondary,
marginBottom: theme.spacing(2),
}),
};
};

View File

@@ -1,29 +1,26 @@
import { SelectableValue } from '@grafana/data';
import { RadioButtonGroup } from '@grafana/ui';
import { useDispatch } from '../../hooks/useStatelessReducer';
import { EditorType } from '../../types';
import { useQuery } from './ElasticsearchQueryContext';
import { changeEditorTypeAndResetQuery } from './state';
const BASE_OPTIONS: Array<SelectableValue<EditorType>> = [
{ value: 'builder', label: 'Builder' },
{ value: 'code', label: 'Code' },
];
export const EditorTypeSelector = () => {
const query = useQuery();
const dispatch = useDispatch();
// Default to 'builder' if editorType is empty
const editorType: EditorType = query.editorType === 'code' ? 'code' : 'builder';
const onChange = (newEditorType: EditorType) => {
dispatch(changeEditorTypeAndResetQuery(newEditorType));
};
interface Props {
value: EditorType;
onChange: (editorType: EditorType) => void;
}
export const EditorTypeSelector = ({ value, onChange }: Props) => {
return (
<RadioButtonGroup<EditorType> fullWidth={false} options={BASE_OPTIONS} value={editorType} onChange={onChange} />
<RadioButtonGroup<EditorType>
data-testid="elasticsearch-editor-type-toggle"
size="sm"
options={BASE_OPTIONS}
value={value}
onChange={onChange}
/>
);
};

View File

@@ -10,9 +10,13 @@ interface Props {
onRunQuery: () => void;
}
// This offset was chosen by testing to match Prometheus behavior
const EDITOR_HEIGHT_OFFSET = 2;
export function RawQueryEditor({ value, onChange, onRunQuery }: Props) {
const styles = useStyles2(getStyles);
const editorRef = useRef<monacoTypes.editor.IStandaloneCodeEditor | null>(null);
const containerRef = useRef<HTMLDivElement | null>(null);
const handleEditorDidMount = useCallback(
(editor: monacoTypes.editor.IStandaloneCodeEditor, monaco: Monaco) => {
@@ -22,6 +26,22 @@ export function RawQueryEditor({ value, onChange, onRunQuery }: Props) {
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter, () => {
onRunQuery();
});
// Make the editor resize itself so that the content fits (grows taller when necessary)
// this code comes from the Prometheus query editor.
// We may wish to consider abstracting it into the grafana/ui repo in the future
const updateElementHeight = () => {
const containerDiv = containerRef.current;
if (containerDiv !== null) {
const pixelHeight = editor.getContentHeight();
containerDiv.style.height = `${pixelHeight + EDITOR_HEIGHT_OFFSET}px`;
const pixelWidth = containerDiv.clientWidth;
editor.layout({ width: pixelWidth, height: pixelHeight });
}
};
editor.onDidContentSizeChange(updateElementHeight);
updateElementHeight();
},
[onRunQuery]
);
@@ -65,7 +85,17 @@ export function RawQueryEditor({ value, onChange, onRunQuery }: Props) {
return (
<Box>
<div className={styles.header}>
<div ref={containerRef} className={styles.editorContainer}>
<CodeEditor
value={value ?? ''}
language="json"
width="100%"
onBlur={handleQueryChange}
monacoOptions={monacoOptions}
onEditorDidMount={handleEditorDidMount}
/>
</div>
<div className={styles.footer}>
<Stack gap={1}>
<Button
size="sm"
@@ -76,20 +106,8 @@ export function RawQueryEditor({ value, onChange, onRunQuery }: Props) {
>
Format
</Button>
<Button size="sm" variant="primary" icon="play" onClick={onRunQuery} tooltip="Run query (Ctrl/Cmd+Enter)">
Run
</Button>
</Stack>
</div>
<CodeEditor
value={value ?? ''}
language="json"
height={200}
width="100%"
onBlur={handleQueryChange}
monacoOptions={monacoOptions}
onEditorDidMount={handleEditorDidMount}
/>
</Box>
);
}
@@ -100,7 +118,11 @@ const getStyles = (theme: GrafanaTheme2) => ({
flexDirection: 'column',
gap: theme.spacing(1),
}),
header: css({
editorContainer: css({
width: '100%',
overflow: 'hidden',
}),
footer: css({
display: 'flex',
justifyContent: 'flex-end',
padding: theme.spacing(0.5, 0),

View File

@@ -1,16 +1,16 @@
import { css } from '@emotion/css';
import { useEffect, useId, useState } from 'react';
import { useCallback, useEffect, useId, useState } from 'react';
import { SemVer } from 'semver';
import { getDefaultTimeRange, GrafanaTheme2, QueryEditorProps } from '@grafana/data';
import { config } from '@grafana/runtime';
import { Alert, InlineField, InlineLabel, Input, QueryField, useStyles2 } from '@grafana/ui';
import { Alert, ConfirmModal, InlineField, InlineLabel, Input, QueryField, useStyles2 } from '@grafana/ui';
import { ElasticsearchDataQuery } from '../../dataquery.gen';
import { ElasticDatasource } from '../../datasource';
import { useNextId } from '../../hooks/useNextId';
import { useDispatch } from '../../hooks/useStatelessReducer';
import { ElasticsearchOptions } from '../../types';
import { EditorType, ElasticsearchOptions } from '../../types';
import { isSupportedVersion, isTimeSeriesQuery, unsupportedVersionMessage } from '../../utils';
import { BucketAggregationsEditor } from './BucketAggregationsEditor';
@@ -20,7 +20,7 @@ import { MetricAggregationsEditor } from './MetricAggregationsEditor';
import { metricAggregationConfig } from './MetricAggregationsEditor/utils';
import { QueryTypeSelector } from './QueryTypeSelector';
import { RawQueryEditor } from './RawQueryEditor';
import { changeAliasPattern, changeQuery, changeRawDSLQuery } from './state';
import { changeAliasPattern, changeEditorTypeAndResetQuery, changeQuery, changeRawDSLQuery } from './state';
export type ElasticQueryEditorProps = QueryEditorProps<ElasticDatasource, ElasticsearchDataQuery, ElasticsearchOptions>;
@@ -97,31 +97,61 @@ const QueryEditorForm = ({ value, onRunQuery }: Props & { onRunQuery: () => void
const inputId = useId();
const styles = useStyles2(getStyles);
const [switchModalOpen, setSwitchModalOpen] = useState(false);
const [pendingEditorType, setPendingEditorType] = useState<EditorType | null>(null);
const isTimeSeries = isTimeSeriesQuery(value);
const isCodeEditor = value.editorType === 'code';
const rawDSLFeatureEnabled = config.featureToggles.elasticsearchRawDSLQuery;
// Default to 'builder' if editorType is empty
const currentEditorType: EditorType = value.editorType === 'code' ? 'code' : 'builder';
const showBucketAggregationsEditor = value.metrics?.every(
(metric) => metricAggregationConfig[metric.type].impliedQueryType === 'metrics'
);
const onEditorTypeChange = useCallback((newEditorType: EditorType) => {
// Show warning modal when switching modes
setPendingEditorType(newEditorType);
setSwitchModalOpen(true);
}, []);
const confirmEditorTypeChange = useCallback(() => {
if (pendingEditorType) {
dispatch(changeEditorTypeAndResetQuery(pendingEditorType));
}
setSwitchModalOpen(false);
setPendingEditorType(null);
}, [dispatch, pendingEditorType]);
const cancelEditorTypeChange = useCallback(() => {
setSwitchModalOpen(false);
setPendingEditorType(null);
}, []);
return (
<>
<ConfirmModal
isOpen={switchModalOpen}
title="Switch editor"
body="Switching between editors will reset your query. Are you sure you want to continue?"
confirmText="Continue"
onConfirm={confirmEditorTypeChange}
onDismiss={cancelEditorTypeChange}
/>
<div className={styles.root}>
<InlineLabel width={17}>Query type</InlineLabel>
<div className={styles.queryItem}>
<QueryTypeSelector />
</div>
</div>
{rawDSLFeatureEnabled && (
<div className={styles.root}>
<InlineLabel width={17}>Editor type</InlineLabel>
<div className={styles.queryItem}>
<EditorTypeSelector />
{rawDSLFeatureEnabled && (
<div style={{ marginLeft: 'auto' }}>
<EditorTypeSelector value={currentEditorType} onChange={onEditorTypeChange} />
</div>
</div>
)}
)}
</div>
{isCodeEditor && rawDSLFeatureEnabled && (
<RawQueryEditor