@checkstack/dashboards-backend 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,269 @@
1
+ import { z } from "zod";
2
+ import { qualifyAccessRuleId } from "@checkstack/common";
3
+ import type { RpcClient } from "@checkstack/backend-api";
4
+ import {
5
+ CreateDashboardInputSchema,
6
+ DashboardsApi,
7
+ UpdateDashboardInputSchema,
8
+ dashboardsAccess,
9
+ pluginMetadata,
10
+ type Dashboard,
11
+ type Panel,
12
+ } from "@checkstack/dashboards-common";
13
+ import type { AiFieldDiff, AiProposalPreview } from "@checkstack/ai-common";
14
+ import { ToolValidationError, type RegisteredAiTool } from "@checkstack/ai-backend";
15
+ import type { BuildingBlocksRegistry } from "../building-blocks";
16
+ import {
17
+ renderLayoutPreview,
18
+ validateDashboardDraft,
19
+ type DraftIssue,
20
+ } from "./draft-validation";
21
+ import {
22
+ VISUAL_INSPECTION_STEPS,
23
+ appBaseUrl,
24
+ dashboardViewLinks,
25
+ type DashboardViewLinks,
26
+ } from "./view-links";
27
+
28
+ /**
29
+ * Input of `dashboards.propose`: a whole dashboard draft. With `dashboardId`
30
+ * it edits that dashboard (fields left out keep their value; `panels` replaces
31
+ * the whole panel list); without it, it creates one.
32
+ */
33
+ export const DashboardsProposeInputSchema = UpdateDashboardInputSchema.omit({
34
+ id: true,
35
+ }).extend({
36
+ dashboardId: z
37
+ .string()
38
+ .min(1)
39
+ .optional()
40
+ .describe(
41
+ "Edit this dashboard (read the current dashboard first and send the full new panel list). Omit to create a new dashboard.",
42
+ ),
43
+ systemId: CreateDashboardInputSchema.shape.systemId,
44
+ teamId: z
45
+ .string()
46
+ .optional()
47
+ .describe("Owning team of a NEW dashboard; required when you hold no global dashboard manage rule."),
48
+ });
49
+ export type DashboardsProposeInput = z.infer<typeof DashboardsProposeInputSchema>;
50
+
51
+ export interface DashboardsProposeResult {
52
+ dashboard: Dashboard;
53
+ /** Where to open it in a browser tool to check it visually. */
54
+ links: DashboardViewLinks;
55
+ layoutPreview: string;
56
+ visualInspection: string;
57
+ }
58
+
59
+ /** Feedback the chat loop and MCP server hand back to the model to fix. */
60
+ function draftError(issues: DraftIssue[]): ToolValidationError {
61
+ return new ToolValidationError(
62
+ `The dashboard draft is invalid. Fix these and propose again:\n${issues
63
+ .map((issue) => `- ${issue.path}: ${issue.message}`)
64
+ .join("\n")}`,
65
+ issues.map((issue) => ({ path: [issue.path], message: issue.message })),
66
+ );
67
+ }
68
+
69
+ function plural({ count, word }: { count: number; word: string }): string {
70
+ return `${count} ${word}${count === 1 ? "" : "s"}`;
71
+ }
72
+
73
+ /** A per-panel diff summary of an update. */
74
+ export function diffPanels({
75
+ before,
76
+ after,
77
+ }: {
78
+ before: Panel[];
79
+ after: Panel[];
80
+ }): { added: string[]; removed: string[]; changed: string[] } {
81
+ const old = new Map(before.map((p) => [p.id, JSON.stringify(p)]));
82
+ const next = new Set(after.map((p) => p.id));
83
+ return {
84
+ added: after.filter((p) => !old.has(p.id)).map((p) => p.id),
85
+ removed: before.filter((p) => !next.has(p.id)).map((p) => p.id),
86
+ changed: after
87
+ .filter((p) => old.has(p.id) && old.get(p.id) !== JSON.stringify(p))
88
+ .map((p) => p.id),
89
+ };
90
+ }
91
+
92
+ const DIFF_FIELDS = [
93
+ "title",
94
+ "description",
95
+ "tags",
96
+ "settings",
97
+ "visibility",
98
+ "visibleRoleIds",
99
+ ] as const;
100
+
101
+ /** Before -> after of the top-level fields an update touches. */
102
+ export function diffDashboardFields({
103
+ current,
104
+ input,
105
+ }: {
106
+ current: Dashboard;
107
+ input: DashboardsProposeInput;
108
+ }): AiFieldDiff[] {
109
+ const diff: AiFieldDiff[] = [];
110
+ for (const field of DIFF_FIELDS) {
111
+ const after = input[field];
112
+ if (after === undefined) continue;
113
+ const before = current[field];
114
+ if (JSON.stringify(before) !== JSON.stringify(after)) {
115
+ diff.push({ path: field, before, after });
116
+ }
117
+ }
118
+ return diff;
119
+ }
120
+
121
+ async function loadDashboard({
122
+ rpcClient,
123
+ id,
124
+ }: {
125
+ rpcClient: RpcClient;
126
+ id: string;
127
+ }): Promise<Dashboard> {
128
+ const current = await rpcClient.forPlugin(DashboardsApi).getDashboard({ id });
129
+ if (!current) {
130
+ throw new Error(
131
+ `Dashboard ${id} was not found or you cannot view it. Find ids with dashboards_listDashboards.`,
132
+ );
133
+ }
134
+ return current;
135
+ }
136
+
137
+ /** The apply result: the dashboard plus where and how to look at it. */
138
+ function appliedResult({
139
+ dashboard,
140
+ baseUrl,
141
+ }: {
142
+ dashboard: Dashboard;
143
+ baseUrl: string;
144
+ }): DashboardsProposeResult {
145
+ return {
146
+ dashboard,
147
+ links: dashboardViewLinks({ baseUrl, dashboard }),
148
+ layoutPreview: renderLayoutPreview({ panels: dashboard.panels }),
149
+ visualInspection: VISUAL_INSPECTION_STEPS,
150
+ };
151
+ }
152
+
153
+ /**
154
+ * `dashboards.propose` - create or edit a dashboard from a drafted panel list.
155
+ * The dry run validates every panel against the registered data sources,
156
+ * visualizations and widgets and the grid, and renders a text picture of the
157
+ * layout for review. Apply runs `createDashboard` / `updateDashboard` as the
158
+ * user, so the contract's team/system authorization applies unchanged.
159
+ */
160
+ export function createDashboardsProposeTool({
161
+ registry,
162
+ baseUrl = appBaseUrl,
163
+ }: {
164
+ registry: BuildingBlocksRegistry;
165
+ /** The app's public origin, read at call time. */
166
+ baseUrl?: () => string;
167
+ }): RegisteredAiTool<DashboardsProposeInput, DashboardsProposeResult> {
168
+ return {
169
+ name: "dashboards.propose",
170
+ description:
171
+ "Create a dashboard, or edit one (pass dashboardId), from a drafted list of panels. First call {{tool:dashboards.getBuildingBlocks}} for the panel types, data sources and their query fields, and use the discovery tools it names to find real ids (never invent ids). For an edit, read the dashboard with {{tool:dashboards.getDashboard}} and send the complete new panel list. The draft is validated (known panel types and data sources, valid queries and options, panels inside the 24-column grid without overlaps) and an invalid draft is rejected with every problem listed. A system dashboard sets systemId (from {{tool:catalog.listSystems}}); a global or home dashboard omits it and sets systemId on each query instead. Once applied, the result has the URL to open it in a browser tool and check it visually ({{tool:dashboards.inspect}} gives the same for any dashboard).",
172
+ effect: "mutate",
173
+ input: DashboardsProposeInputSchema,
174
+ requiredAccessRules: [
175
+ qualifyAccessRuleId(pluginMetadata, dashboardsAccess.dashboard.manage),
176
+ ],
177
+ async dryRun({
178
+ input,
179
+ rpcClient,
180
+ }): Promise<AiProposalPreview<DashboardsProposeInput>> {
181
+ const current = input.dashboardId
182
+ ? await loadDashboard({ rpcClient, id: input.dashboardId })
183
+ : undefined;
184
+ if (!current && !input.title) {
185
+ throw draftError([
186
+ { path: "title", message: "A new dashboard needs a title." },
187
+ ]);
188
+ }
189
+ if (current && input.systemId !== undefined && input.systemId !== current.systemId) {
190
+ throw draftError([
191
+ { path: "systemId", message: "A dashboard's system cannot be changed; create a new dashboard instead." },
192
+ ]);
193
+ }
194
+ const panels = input.panels ?? current?.panels ?? [];
195
+ const dashboardSystemId = current ? current.systemId : (input.systemId ?? null);
196
+ const { errors, warnings } = validateDashboardDraft({
197
+ panels,
198
+ dashboardSystemId,
199
+ registry,
200
+ });
201
+ if (errors.length > 0) throw draftError(errors);
202
+
203
+ const layoutPreview = renderLayoutPreview({ panels });
204
+ const warningText =
205
+ warnings.length > 0
206
+ ? ` Warnings: ${warnings.map((w) => `${w.path}: ${w.message}`).join(" ")}`
207
+ : "";
208
+ const payload = {
209
+ ...input,
210
+ layoutPreview,
211
+ warnings: warnings.map((w) => `${w.path}: ${w.message}`),
212
+ };
213
+
214
+ if (!current) {
215
+ const scope = input.systemId ? "for its system" : "as a global dashboard";
216
+ return {
217
+ summary: `Create dashboard "${input.title}" ${scope} with ${plural({ count: panels.length, word: "panel" })}.${warningText}`,
218
+ payload,
219
+ };
220
+ }
221
+
222
+ const changes = input.panels
223
+ ? diffPanels({ before: current.panels, after: input.panels })
224
+ : { added: [], removed: [], changed: [] };
225
+ const parts = [
226
+ changes.added.length > 0 && `add ${plural({ count: changes.added.length, word: "panel" })}`,
227
+ changes.removed.length > 0 && `remove ${plural({ count: changes.removed.length, word: "panel" })}`,
228
+ changes.changed.length > 0 && `change ${plural({ count: changes.changed.length, word: "panel" })}`,
229
+ ].filter(Boolean);
230
+ const fieldDiff = diffDashboardFields({ current, input });
231
+ const diff: AiFieldDiff[] = [
232
+ ...fieldDiff,
233
+ ...changes.added.map((id) => ({ path: `panels.${id}`, before: undefined, after: "added" })),
234
+ ...changes.removed.map((id) => ({ path: `panels.${id}`, before: "present", after: undefined })),
235
+ ...changes.changed.map((id) => ({ path: `panels.${id}`, before: "previous", after: "changed" })),
236
+ ];
237
+ const what = [
238
+ ...parts,
239
+ ...fieldDiff.map((d) => `set ${d.path}`),
240
+ ].join(", ");
241
+ return {
242
+ summary: `Update dashboard "${current.title}": ${what || "no changes"}.${warningText}`,
243
+ payload,
244
+ diff,
245
+ };
246
+ },
247
+ async execute({ input, rpcClient }) {
248
+ // Only reached via apply. The contract procedures re-validate the input
249
+ // and authorize the caller (system manage / team grants) as usual.
250
+ const client = rpcClient.forPlugin(DashboardsApi);
251
+ const { dashboardId, systemId, teamId, ...fields } = input;
252
+ const url = baseUrl();
253
+ if (dashboardId) {
254
+ return appliedResult({
255
+ dashboard: await client.updateDashboard({ id: dashboardId, ...fields }),
256
+ baseUrl: url,
257
+ });
258
+ }
259
+ const dashboard = await client.createDashboard({
260
+ ...fields,
261
+ title: fields.title ?? "Untitled dashboard",
262
+ description: fields.description ?? undefined,
263
+ systemId,
264
+ teamId,
265
+ });
266
+ return appliedResult({ dashboard, baseUrl: url });
267
+ },
268
+ };
269
+ }
@@ -0,0 +1,66 @@
1
+ import { z } from "zod";
2
+ import {
3
+ defineDashboardDataSourceSpec,
4
+ type DataSourceQuery,
5
+ type Panel,
6
+ } from "@checkstack/dashboards-common";
7
+ import {
8
+ CORE_HOME_WIDGETS,
9
+ createBuildingBlocksRegistry,
10
+ type BuildingBlocksRegistry,
11
+ } from "../building-blocks";
12
+
13
+ const MetricQuerySchema = z.object({
14
+ streamId: z.string().default(""),
15
+ metricName: z.string().default(""),
16
+ aggregation: z.enum(["avg", "rate"]).default("avg"),
17
+ });
18
+
19
+ /** A registry with one metric-like data source and the core home widgets. */
20
+ export function testRegistry(): BuildingBlocksRegistry {
21
+ const registry = createBuildingBlocksRegistry();
22
+ const spec = defineDashboardDataSourceSpec({
23
+ pluginMetadata: { pluginId: "metricstream" },
24
+ id: "metric",
25
+ label: "Metrics",
26
+ description: "Metric time series",
27
+ produces: ["timeseries"],
28
+ querySchema: MetricQuerySchema,
29
+ requiredFields: ["streamId", "metricName"],
30
+ ai: {
31
+ useFor: "metrics",
32
+ howToFill: "streamId from {{tool:metricstream.listStreamsForSystem}}.",
33
+ exampleQuery: { streamId: "s1", metricName: "cpu", aggregation: "avg" },
34
+ visualizations: ["dashboards.timeseries"],
35
+ },
36
+ });
37
+ registry.registerDataSource({
38
+ ...spec,
39
+ querySchema: spec.querySchema as z.ZodType<DataSourceQuery>,
40
+ requiredFields: [...spec.requiredFields],
41
+ });
42
+ for (const widget of CORE_HOME_WIDGETS) registry.registerWidget(widget);
43
+ return registry;
44
+ }
45
+
46
+ /** A valid time-series panel at `gridPos`. */
47
+ export function metricPanel({
48
+ id,
49
+ gridPos = { x: 0, y: 0, w: 12, h: 8 },
50
+ query = { streamId: "s1", metricName: "cpu" },
51
+ }: {
52
+ id: string;
53
+ gridPos?: Panel["gridPos"];
54
+ query?: Record<string, unknown>;
55
+ }): Panel {
56
+ return {
57
+ id,
58
+ type: "dashboards.timeseries",
59
+ title: "CPU",
60
+ gridPos,
61
+ queries: [
62
+ { refId: "A", dataSourceId: "metricstream.metric", query, hidden: false },
63
+ ],
64
+ options: {},
65
+ };
66
+ }
@@ -0,0 +1,9 @@
1
+ import { replaceAiToolPlaceholders } from "@checkstack/common";
2
+
3
+ /** `{{tool:a.b}}` -> `a_b`, the name chat and MCP clients call. */
4
+ export function renderToolNames(text: string): string {
5
+ return replaceAiToolPlaceholders({
6
+ text,
7
+ replace: ({ name }) => name.replaceAll(".", "_"),
8
+ });
9
+ }
@@ -0,0 +1,215 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import type { AuthUser, RpcClient } from "@checkstack/backend-api";
3
+ import type { Dashboard } from "@checkstack/dashboards-common";
4
+ import { ToolValidationError } from "@checkstack/ai-backend";
5
+ import { createBuildingBlocksRegistry } from "../building-blocks";
6
+ import { describeBuildingBlocks } from "./building-blocks-tool";
7
+ import { createDashboardsProposeTool, type DashboardsProposeInput } from "./propose-tool";
8
+ import { buildDashboardsGuidance } from "./guidance";
9
+ import { createInspectDashboardTool } from "./inspect-tool";
10
+ import { appBaseUrl } from "./view-links";
11
+ import { metricPanel, testRegistry } from "./test-fixtures";
12
+
13
+ const principal = { type: "user", id: "u1" } as unknown as AuthUser;
14
+
15
+ function clientWith({
16
+ dashboard,
17
+ calls = [],
18
+ }: {
19
+ dashboard?: Dashboard | null;
20
+ calls?: Array<{ method: string; input: unknown }>;
21
+ }): RpcClient {
22
+ const api = {
23
+ getDashboard: async () => dashboard ?? null,
24
+ createDashboard: async (input: unknown) => {
25
+ calls.push({ method: "createDashboard", input });
26
+ return dashboard;
27
+ },
28
+ updateDashboard: async (input: unknown) => {
29
+ calls.push({ method: "updateDashboard", input });
30
+ return dashboard;
31
+ },
32
+ };
33
+ return { forPlugin: () => api } as unknown as RpcClient;
34
+ }
35
+
36
+ const existing: Dashboard = {
37
+ id: "d1",
38
+ systemId: "sys-1",
39
+ title: "API",
40
+ description: null,
41
+ tags: [],
42
+ visibility: "authenticated",
43
+ visibleRoleIds: [],
44
+ createdBy: null,
45
+ createdAt: new Date(0),
46
+ updatedAt: new Date(0),
47
+ panels: [metricPanel({ id: "a" })],
48
+ settings: { timeRange: { from: "now-6h", to: "now" }, refreshSeconds: 0 },
49
+ };
50
+
51
+ describe("describeBuildingBlocks", () => {
52
+ it("lists visualizations, data sources with JSON schemas and widgets", () => {
53
+ const blocks = describeBuildingBlocks({ registry: testRegistry() });
54
+ expect(blocks.grid?.columns).toBe(24);
55
+ const types = blocks.visualizations?.map((v) => v.type) ?? [];
56
+ expect(types).toContain("dashboards.timeseries");
57
+ expect(types).toContain("dashboards.section");
58
+ const [source] = blocks.dataSources;
59
+ expect(source.dataSourceId).toBe("metricstream.metric");
60
+ expect(source.querySchema).toMatchObject({ type: "object" });
61
+ // Placeholders render to the names chat and MCP clients call.
62
+ expect(source.howToFill).toContain("metricstream_listStreamsForSystem");
63
+ expect(source.howToFill).not.toContain("{{tool:");
64
+ expect(blocks.widgets?.available.map((w) => w.widgetId)).toContain(
65
+ "dashboard.system-health",
66
+ );
67
+ });
68
+
69
+ it("narrows to one data source", () => {
70
+ const blocks = describeBuildingBlocks({ registry: testRegistry(), dataSourceId: "metricstream.metric" });
71
+ expect(Object.keys(blocks)).toEqual(["dataSources"]);
72
+ });
73
+ });
74
+
75
+ describe("building blocks registry", () => {
76
+ it("rejects a data source whose example does not fill its required fields", () => {
77
+ const registry = createBuildingBlocksRegistry();
78
+ const [source] = testRegistry().dataSources();
79
+ expect(() =>
80
+ registry.registerDataSource({ ...source, ai: { ...source.ai, exampleQuery: {} } }),
81
+ ).toThrow(/streamId/);
82
+ });
83
+ });
84
+
85
+ describe("dashboards.propose", () => {
86
+ const tool = createDashboardsProposeTool({ registry: testRegistry() });
87
+ const dryRun = (input: DashboardsProposeInput, dashboard?: Dashboard) => {
88
+ if (!tool.dryRun) throw new Error("dryRun missing");
89
+ return tool.dryRun({ input, principal, rpcClient: clientWith({ dashboard }) });
90
+ };
91
+
92
+ it("is a mutate tool gated on the manage rule", () => {
93
+ expect(tool.effect).toBe("mutate");
94
+ expect(tool.requiredAccessRules).toEqual(["dashboards.dashboard.manage"]);
95
+ });
96
+
97
+ it("previews a new dashboard with its layout", async () => {
98
+ const preview = await dryRun({ title: "API", systemId: "sys-1", panels: [metricPanel({ id: "a" })] });
99
+ expect(preview.summary).toBe('Create dashboard "API" for its system with 1 panel.');
100
+ expect(preview.payload).toMatchObject({ layoutPreview: expect.stringContaining("A = CPU") });
101
+ });
102
+
103
+ it("rejects an invalid draft with every issue", async () => {
104
+ const promise = dryRun({
105
+ title: "API",
106
+ systemId: "sys-1",
107
+ panels: [metricPanel({ id: "a", query: {} }), metricPanel({ id: "b" })],
108
+ });
109
+ await expect(promise).rejects.toThrow(/metricName[\s\S]*overlaps/);
110
+ // A ToolValidationError, so chat and MCP hand the issues back to the model.
111
+ const error = await promise.catch((caught: unknown) => caught);
112
+ expect(error).toBeInstanceOf(ToolValidationError);
113
+ expect((error as ToolValidationError).issues.map((i) => i.path)).toEqual([
114
+ ["panels[0].queries[0].query"],
115
+ ["panels[1].gridPos"],
116
+ ]);
117
+ });
118
+
119
+ it("requires a title for a new dashboard", async () => {
120
+ await expect(dryRun({ panels: [] })).rejects.toThrow(/needs a title/);
121
+ });
122
+
123
+ it("summarizes an edit with a panel diff", async () => {
124
+ const preview = await dryRun(
125
+ {
126
+ dashboardId: "d1",
127
+ title: "API overview",
128
+ panels: [
129
+ { ...metricPanel({ id: "a" }), title: "CPU load" },
130
+ metricPanel({ id: "b", gridPos: { x: 12, y: 0, w: 12, h: 8 } }),
131
+ ],
132
+ },
133
+ existing,
134
+ );
135
+ expect(preview.summary).toBe('Update dashboard "API": add 1 panel, change 1 panel, set title.');
136
+ expect(preview.diff?.map((d) => d.path)).toEqual(["title", "panels.b", "panels.a"]);
137
+ });
138
+
139
+ it("refuses to move a dashboard to another system", async () => {
140
+ await expect(dryRun({ dashboardId: "d1", systemId: "sys-2" }, existing)).rejects.toThrow(/cannot be changed/);
141
+ });
142
+
143
+ it("applies through the contract procedures and returns where to look at it", async () => {
144
+ const calls: Array<{ method: string; input: unknown }> = [];
145
+ const rpcClient = clientWith({ dashboard: existing, calls });
146
+ const linked = createDashboardsProposeTool({
147
+ registry: testRegistry(),
148
+ baseUrl: () => "https://ops.example",
149
+ });
150
+ const result = await linked.execute({ input: { dashboardId: "d1", title: "New" }, principal, rpcClient });
151
+ expect(result.links).toEqual({
152
+ viewUrl: "https://ops.example/dashboards/d1",
153
+ signInUrl: "https://ops.example/auth/login?returnTo=%2Fdashboards%2Fd1",
154
+ });
155
+ expect(result.layoutPreview).toContain("A = CPU");
156
+ expect(result.visualInspection).toContain("never ask for");
157
+ await tool.execute({ input: { title: "Fresh", systemId: "sys-1", teamId: "t1" }, principal, rpcClient });
158
+ expect(calls).toEqual([
159
+ { method: "updateDashboard", input: { id: "d1", title: "New" } },
160
+ {
161
+ method: "createDashboard",
162
+ input: { title: "Fresh", description: undefined, systemId: "sys-1", teamId: "t1" },
163
+ },
164
+ ]);
165
+ });
166
+ });
167
+
168
+ describe("dashboards.inspect", () => {
169
+ const tool = createInspectDashboardTool({ baseUrl: () => "https://ops.example" });
170
+
171
+ it("returns links, the layout and the inspection steps", async () => {
172
+ const result = await tool.execute({
173
+ input: { dashboardId: "d1" },
174
+ principal,
175
+ rpcClient: clientWith({ dashboard: { ...existing, visibility: "public" } }),
176
+ });
177
+ expect(tool.effect).toBe("read");
178
+ expect(result.links).toEqual({
179
+ viewUrl: "https://ops.example/dashboards/d1",
180
+ signInUrl: "https://ops.example/auth/login?returnTo=%2Fdashboards%2Fd1",
181
+ publicUrl: "https://ops.example/dashboards/public/d1",
182
+ });
183
+ expect(result.layoutPreview).toContain("A = CPU");
184
+ });
185
+
186
+ it("fails for a dashboard the user cannot view", async () => {
187
+ await expect(
188
+ tool.execute({ input: { dashboardId: "nope" }, principal, rpcClient: clientWith({ dashboard: null }) }),
189
+ ).rejects.toThrow(/not found/);
190
+ });
191
+ });
192
+
193
+ describe("appBaseUrl", () => {
194
+ it("uses BASE_URL without a trailing slash", () => {
195
+ expect(appBaseUrl({ env: { BASE_URL: "https://ops.example/" } })).toBe("https://ops.example");
196
+ expect(appBaseUrl({ env: {} })).toBe("http://localhost:3000");
197
+ });
198
+ });
199
+
200
+ describe("dashboards guidance", () => {
201
+ it("is offered with the dashboard tools and names the discovery chain", () => {
202
+ const [section] = buildDashboardsGuidance();
203
+ expect(section.tools).toEqual(["dashboards.propose", "dashboards.getBuildingBlocks"]);
204
+ for (const tool of [
205
+ "dashboards.getBuildingBlocks",
206
+ "dashboards.propose",
207
+ "catalog.listSystems",
208
+ "metricstream.listMetricNames",
209
+ "dashboards.getDashboard",
210
+ "dashboards.inspect",
211
+ ]) {
212
+ expect(section.body).toContain(`{{tool:${tool}}}`);
213
+ }
214
+ });
215
+ });
@@ -0,0 +1,62 @@
1
+ import { resolveRoute } from "@checkstack/common";
2
+ import { signInPathReturningTo } from "@checkstack/auth-common";
3
+ import { dashboardsRoutes, type Dashboard } from "@checkstack/dashboards-common";
4
+
5
+ /** Links an agent can open in a browser tool to look at a dashboard. */
6
+ export interface DashboardViewLinks {
7
+ /** The dashboard in the app (needs a signed-in session in that browser). */
8
+ viewUrl: string;
9
+ /**
10
+ * The sign-in page; after the USER signs in there it opens the dashboard.
11
+ * Open it when `viewUrl` shows a sign-in page or "not found".
12
+ */
13
+ signInUrl: string;
14
+ /** Viewable without signing in; only for dashboards published as public. */
15
+ publicUrl?: string;
16
+ }
17
+
18
+ /**
19
+ * The app's public origin (`BASE_URL`, where the UI is served), without a
20
+ * trailing slash.
21
+ */
22
+ export function appBaseUrl({ env = process.env }: { env?: Record<string, string | undefined> } = {}): string {
23
+ return (env.BASE_URL || "http://localhost:3000").replace(/\/+$/, "");
24
+ }
25
+
26
+ export function dashboardViewLinks({
27
+ baseUrl,
28
+ dashboard,
29
+ }: {
30
+ baseUrl: string;
31
+ dashboard: Pick<Dashboard, "id" | "visibility">;
32
+ }): DashboardViewLinks {
33
+ const viewPath = resolveRoute(dashboardsRoutes.routes.view, {
34
+ dashboardId: dashboard.id,
35
+ });
36
+ return {
37
+ viewUrl: `${baseUrl}${viewPath}`,
38
+ signInUrl: `${baseUrl}${signInPathReturningTo({ returnPath: viewPath })}`,
39
+ ...(dashboard.visibility === "public"
40
+ ? {
41
+ publicUrl: `${baseUrl}${resolveRoute(dashboardsRoutes.routes.publicView, {
42
+ dashboardId: dashboard.id,
43
+ })}`,
44
+ }
45
+ : {}),
46
+ };
47
+ }
48
+
49
+ /**
50
+ * How to look at a dashboard with a browser tool. Returned with the links so a
51
+ * vision-capable agent can check its own work; written for the model.
52
+ */
53
+ export const VISUAL_INSPECTION_STEPS =
54
+ "If you have browser tools and can see images, check the dashboard visually: " +
55
+ "open viewUrl (publicUrl needs no sign-in). If the page shows a sign-in form or " +
56
+ "\"Dashboard not found\", the browser is not signed in: open signInUrl and ask the " +
57
+ "user to sign in in that browser themselves, then wait for them to confirm; never " +
58
+ "ask for, type or store their password or a session token. After the panels finish " +
59
+ "loading (a few seconds), take a screenshot at a desktop width (about 1440px) and " +
60
+ "check that every panel shows data instead of 'No data' or an error, titles and " +
61
+ "axis labels are readable, related panels line up in rows, and nothing is cramped or " +
62
+ "has large empty gaps. Fix problems by proposing the changed panel list again.";