A connection can declare one authenticated probe operation that answers "is this credential still alive?". Core owns the vocabulary (HealthStatus, HealthCheckSpec, HealthCheckResult, HealthCheckCandidate) and dispatch (integrations.healthCheck.{get,candidates,set}, connections.{checkHealth, validate}); the OpenAPI plugin implements the probe against its stored operation bindings, ranking candidates non-destructive-first. The UI gets a status dot + Check now per connection, a health-check editor sheet, and a validate-the-key-first step in the Add Connection modal.
Unified · Split
| @@ -0,0 +1,573 @@ | ||
| 1 | +// Cross-target (browser): the UI side of connection health checks, the feature | |
| 2 | +// that answers "has this credential expired?" (the Google 7-day dev-token case). | |
| 3 | +// These scenarios pin the operation picker, the part that lets a user choose | |
| 4 | +// WHICH call the probe runs: | |
| 5 | +// | |
| 6 | +// 1. Add Connection: with no health check configured yet, the user picks a | |
| 7 | +// read-only operation inline, clicks "Check the key works", the probe runs, | |
| 8 | +// and the picked operation is saved as the integration's health check. | |
| 9 | +// 2. Edit sheet, large spec: typing into the operation combobox filters a | |
| 10 | +// hundreds-long candidate list down to the one match, and committing it | |
| 11 | +// stores the real operation (not the freeform text typed to find it). | |
| 12 | +// 3. Add screen, large spec: the same picker is fed by the bounded spec | |
| 13 | +// preview, so typing must reach an operation ranked well past the preview's | |
| 14 | +// top slice. | |
| 15 | +// | |
| 16 | +// The upstream API is a real node:http server on 127.0.0.1 that gates `GET /me` | |
| 17 | +// on a bearer token. The probe runs server-side, so the in-process server is | |
| 18 | +// reachable from the dev server on the same host. | |
| 19 | +// | |
| 20 | +// These scenarios skip on targets without a browser surface (selfhost today). | |
| 21 | +import { randomBytes } from "node:crypto"; | |
| 22 | +import { createServer } from "node:http"; | |
| 23 | + | |
| 24 | +import { Effect } from "effect"; | |
| 25 | +import { expect } from "@effect/vitest"; | |
| 26 | +import type { HttpApiClient } from "effect/unstable/httpapi"; | |
| 27 | +import type { Page } from "playwright"; | |
| 28 | +import { composePluginApi } from "@executor-js/api/server"; | |
| 29 | +import { openApiHttpPlugin } from "@executor-js/plugin-openapi/api"; | |
| 30 | +import { IntegrationSlug } from "@executor-js/sdk/shared"; | |
| 31 | + | |
| 32 | +import { scenario } from "../src/scenario"; | |
| 33 | +import { Api, Browser, Target } from "../src/services"; | |
| 34 | + | |
| 35 | +const api = composePluginApi([openApiHttpPlugin()] as const); | |
| 36 | +type Client = HttpApiClient.ForApi<typeof api>; | |
| 37 | + | |
| 38 | +const newSlug = (prefix: string) => | |
| 39 | + IntegrationSlug.make(`${prefix}-${randomBytes(4).toString("hex")}`); | |
| 40 | + | |
| 41 | +/** OpenAPI 3 spec with an auth-gated GET (`/me`, the obvious health check) plus a | |
| 42 | + * destructive POST so the candidate ranking has something to sort the GET ahead | |
| 43 | + * of. */ | |
| 44 | +const identitySpec = (baseUrl: string): string => | |
| 45 | + JSON.stringify({ | |
| 46 | + openapi: "3.0.3", | |
| 47 | + info: { title: "Identity API", version: "1.0.0" }, | |
| 48 | + servers: [{ url: baseUrl }], | |
| 49 | + paths: { | |
| 50 | + "/me": { | |
| 51 | + get: { | |
| 52 | + operationId: "getMe", | |
| 53 | + summary: "The current account", | |
| 54 | + responses: { | |
| 55 | + "200": { | |
| 56 | + description: "The authenticated account", | |
| 57 | + content: { | |
| 58 | + "application/json": { | |
| 59 | + schema: { | |
| 60 | + type: "object", | |
| 61 | + properties: { email: { type: "string" }, login: { type: "string" } }, | |
| 62 | + }, | |
| 63 | + }, | |
| 64 | + }, | |
| 65 | + }, | |
| 66 | + }, | |
| 67 | + }, | |
| 68 | + }, | |
| 69 | + "/messages": { | |
| 70 | + post: { | |
| 71 | + operationId: "sendMessage", | |
| 72 | + summary: "Send a message", | |
| 73 | + responses: { "201": { description: "created" } }, | |
| 74 | + }, | |
| 75 | + }, | |
| 76 | + }, | |
| 77 | + }); | |
| 78 | + | |
| 79 | +/** A real node:http API on 127.0.0.1. `GET /me` returns 200 only when the bearer | |
| 80 | + * token matches; any other token is a 401. Closed by the scope's finalizer. */ | |
| 81 | +const serveIdentityApi = (validToken: string) => | |
| 82 | + Effect.acquireRelease( | |
| 83 | + Effect.callback<{ readonly url: string; readonly close: () => void }>((resume) => { | |
| 84 | + const server = createServer((request, response) => { | |
| 85 | + const authorized = request.headers["authorization"] === `Bearer ${validToken}`; | |
| 86 | + if (request.method === "GET" && (request.url ?? "").startsWith("/me")) { | |
| 87 | + response.writeHead(authorized ? 200 : 401, { "content-type": "application/json" }); | |
| 88 | + response.end( | |
| 89 | + JSON.stringify(authorized ? { email: "alice@example.com" } : { error: "x" }), | |
| 90 | + ); | |
| 91 | + return; | |
| 92 | + } | |
| 93 | + response.writeHead(404, { "content-type": "application/json" }); | |
| 94 | + response.end(JSON.stringify({ error: "not_found" })); | |
| 95 | + }); | |
| 96 | + server.listen(0, "127.0.0.1", () => { | |
| 97 | + const address = server.address(); | |
| 98 | + const port = typeof address === "object" && address ? address.port : 0; | |
| 99 | + resume( | |
| 100 | + Effect.succeed({ | |
| 101 | + url: `http://127.0.0.1:${port}`, | |
| 102 | + close: () => { | |
| 103 | + server.close(); | |
| 104 | + server.closeAllConnections(); | |
| 105 | + }, | |
| 106 | + }), | |
| 107 | + ); | |
| 108 | + }); | |
| 109 | + }), | |
| 110 | + (server) => Effect.sync(server.close), | |
| 111 | + ); | |
| 112 | + | |
| 113 | +/** Register the identity integration against `baseUrl` with a bearer-token auth | |
| 114 | + * method (single `token` input → connection `value`). */ | |
| 115 | +const registerIdentityIntegration = (client: Client, slug: IntegrationSlug, baseUrl: string) => | |
| 116 | + client.openapi.addSpec({ | |
| 117 | + payload: { | |
| 118 | + spec: { kind: "blob", value: identitySpec(baseUrl) }, | |
| 119 | + slug, | |
| 120 | + baseUrl, | |
| 121 | + authenticationTemplate: [ | |
| 122 | + { | |
| 123 | + slug: "apiKey", | |
| 124 | + type: "apiKey", | |
| 125 | + headers: { authorization: ["Bearer ", { type: "variable", name: "token" }] }, | |
| 126 | + }, | |
| 127 | + ], | |
| 128 | + }, | |
| 129 | + }); | |
| 130 | + | |
| 131 | +/** The stored operation name for the GET probe (openapi prefixes it by tag), | |
| 132 | + * discovered the same way the editor does: from the ranked candidate list. */ | |
| 133 | +const getMeOperation = (client: Client, slug: IntegrationSlug) => | |
| 134 | + Effect.gen(function* () { | |
| 135 | + const candidates = yield* client.integrations.healthCheckCandidates({ params: { slug } }); | |
| 136 | + const getMe = candidates.find((candidate) => candidate.method === "get"); | |
| 137 | + if (!getMe) return yield* Effect.die("identity spec exposed no GET candidate"); | |
| 138 | + return getMe.operation; | |
| 139 | + }); | |
| 140 | + | |
| 141 | +/** Select a combobox option by CLICKING it (the real mouse path). The popup is | |
| 142 | + * portaled out of the modal, so this exercises both that the option is clickable | |
| 143 | + * (popup `pointer-events`) and that clicking it does not dismiss the surrounding | |
| 144 | + * modal (the dialog/sheet outside-interaction guard). */ | |
| 145 | +const clickComboboxOption = async (page: Page, inputId: string, optionText: string) => { | |
| 146 | + await page.locator(`#${inputId}`).click(); | |
| 147 | + const target = page.getByRole("option").filter({ hasText: optionText }).first(); | |
| 148 | + await target.waitFor({ timeout: 10_000 }); | |
| 149 | + await target.click(); | |
| 150 | +}; | |
| 151 | + | |
| 152 | +// A distinctive operation buried in a large spec, found by its unique summary | |
| 153 | +// (which no filler operation shares) so the filter test can search for it. | |
| 154 | +const PROBE_TOKEN = "ztarget"; | |
| 155 | +const PROBE_SUMMARY = `Health probe candidate ${PROBE_TOKEN}`; | |
| 156 | + | |
| 157 | +/** An OpenAPI 3 spec with ~250 GET operations plus one distinctive probe. The | |
| 158 | + * candidate list is far longer than the popup renders at once, so the operation | |
| 159 | + * picker only surfaces a given operation when typing actually filters the list. | |
| 160 | + * The title is parameterizable so the add screen (which mints the slug from the | |
| 161 | + * title) gets a collision-free integration per run. */ | |
| 162 | +const largeSpec = (baseUrl: string, title = "Big API"): string => { | |
| 163 | + const okJson = { | |
| 164 | + "200": { | |
| 165 | + description: "ok", | |
| 166 | + content: { | |
| 167 | + "application/json": { schema: { type: "object", properties: { id: { type: "string" } } } }, | |
| 168 | + }, | |
| 169 | + }, | |
| 170 | + }; | |
| 171 | + const paths: Record<string, unknown> = {}; | |
| 172 | + for (let index = 0; index < 250; index++) { | |
| 173 | + paths[`/things/item${index}`] = { | |
| 174 | + get: { operationId: `getThing${index}`, summary: `Thing number ${index}`, responses: okJson }, | |
| 175 | + }; | |
| 176 | + } | |
| 177 | + paths["/probe/target"] = { | |
| 178 | + get: { operationId: "probeTarget", summary: PROBE_SUMMARY, responses: okJson }, | |
| 179 | + }; | |
| 180 | + return JSON.stringify({ | |
| 181 | + openapi: "3.0.3", | |
| 182 | + info: { title, version: "1.0.0" }, | |
| 183 | + servers: [{ url: baseUrl }], | |
| 184 | + paths, | |
| 185 | + }); | |
| 186 | +}; | |
| 187 | + | |
| 188 | +// =========================================================================== | |
| 189 | +// 1. Add Connection, no check configured: pick an operation inline, check the | |
| 190 | +// key works, and the picked operation is saved as the integration's check. | |
| 191 | +// =========================================================================== | |
| 192 | + | |
| 193 | +scenario( | |
| 194 | + "Health checks (UI) · Add Connection checks the key against an inline-picked operation and saves it", | |
| 195 | + {}, | |
| 196 | + Effect.scoped( | |
| 197 | + Effect.gen(function* () { | |
| 198 | + const target = yield* Target; | |
| 199 | + const browser = yield* Browser; | |
| 200 | + const { client: makeClient } = yield* Api; | |
| 201 | + const identity = yield* target.newIdentity(); | |
| 202 | + const client = yield* makeClient(api, identity); | |
| 203 | + const goodToken = `gk_${randomBytes(8).toString("hex")}`; | |
| 204 | + const server = yield* serveIdentityApi(goodToken); | |
| 205 | + const slug = newSlug("hc-ui-connect-check"); | |
| 206 | + | |
| 207 | + yield* Effect.ensuring( | |
| 208 | + Effect.gen(function* () { | |
| 209 | + // Register the integration but deliberately configure NO health check: | |
| 210 | + // the Add Connection modal must let the user pick one inline. | |
| 211 | + yield* registerIdentityIntegration(client, slug, server.url); | |
| 212 | + expect( | |
| 213 | + yield* client.integrations.healthCheckGet({ params: { slug } }), | |
| 214 | + "no health check is configured up front", | |
| 215 | + ).toBeNull(); | |
| 216 | + const candidates = yield* client.integrations.healthCheckCandidates({ params: { slug } }); | |
| 217 | + const getMe = candidates.find((candidate) => candidate.method === "get"); | |
| 218 | + if (!getMe) return yield* Effect.die("identity spec exposed no GET candidate"); | |
| 219 | + | |
| 220 | + yield* browser.session(identity, async ({ page, step }) => { | |
| 221 | + const dialog = page.getByRole("dialog"); | |
| 222 | + | |
| 223 | + await step("Open the Add Connection modal", async () => { | |
| 224 | + await page.goto(`/integrations/${slug}`, { waitUntil: "networkidle" }); | |
| 225 | + await page.getByRole("button", { name: "Add connection", exact: true }).click(); | |
| 226 | + await page.getByRole("heading", { name: /Add connection/ }).waitFor(); | |
| 227 | + }); | |
| 228 | + | |
| 229 | + await step("Paste the key and pick an operation to test it against", async () => { | |
| 230 | + await dialog.getByPlaceholder("paste the value / token").fill(goodToken); | |
| 231 | + // No check configured ⇒ the inline operation picker is shown. CLICK | |
| 232 | + // the option (the real mouse path): the popup is portaled out of the | |
| 233 | + // dialog, so this proves clicking it neither fails nor dismisses the | |
| 234 | + // modal before the selection lands. | |
| 235 | + await clickComboboxOption(page, "connect-health-check-operation", "getMe"); | |
| 236 | + // The modal must still be open after the click. | |
| 237 | + await page.getByRole("heading", { name: /Add connection/ }).waitFor(); | |
| 238 | + }); | |
| 239 | + | |
| 240 | + await step("Check the key works: it probes healthy", async () => { | |
| 241 | + await dialog.getByRole("button", { name: "Check the key works" }).click(); | |
| 242 | + await dialog.getByText("Healthy").waitFor({ timeout: 30_000 }); | |
| 243 | + }); | |
| 244 | + }); | |
| 245 | + | |
| 246 | + // The healthy inline check was persisted as the integration's check. | |
| 247 | + const stored = yield* client.integrations.healthCheckGet({ params: { slug } }); | |
| 248 | + expect(stored?.operation, "the picked operation was saved as the health check").toBe( | |
| 249 | + getMe.operation, | |
| 250 | + ); | |
| 251 | + }), | |
| 252 | + client.openapi.removeSpec({ params: { slug } }).pipe(Effect.ignore), | |
| 253 | + ); | |
| 254 | + }), | |
| 255 | + ), | |
| 256 | +); | |
| 257 | + | |
| 258 | +// =========================================================================== | |
| 259 | +// 2. Edit sheet, large spec: typing filters the operation picker to the match. | |
| 260 | +// =========================================================================== | |
| 261 | + | |
| 262 | +scenario( | |
| 263 | + "Health checks (UI) · large spec: typing filters the operation picker down to the match", | |
| 264 | + {}, | |
| 265 | + Effect.scoped( | |
| 266 | + Effect.gen(function* () { | |
| 267 | + const target = yield* Target; | |
| 268 | + const browser = yield* Browser; | |
| 269 | + const { client: makeClient } = yield* Api; | |
| 270 | + const identity = yield* target.newIdentity(); | |
| 271 | + const client = yield* makeClient(api, identity); | |
| 272 | + const slug = newSlug("hc-ui-large"); | |
| 273 | + | |
| 274 | + yield* Effect.ensuring( | |
| 275 | + Effect.gen(function* () { | |
| 276 | + yield* client.openapi.addSpec({ | |
| 277 | + payload: { | |
| 278 | + spec: { kind: "blob", value: largeSpec("https://big.example.com") }, | |
| 279 | + slug, | |
| 280 | + baseUrl: "https://big.example.com", | |
| 281 | + authenticationTemplate: [ | |
| 282 | + { | |
| 283 | + slug: "apiKey", | |
| 284 | + type: "apiKey", | |
| 285 | + headers: { | |
| 286 | + authorization: ["Bearer ", { type: "variable", name: "token" }], | |
| 287 | + }, | |
| 288 | + }, | |
| 289 | + ], | |
| 290 | + }, | |
| 291 | + }); | |
| 292 | + // The toolPath the registration assigned the distinctive probe op, | |
| 293 | + // matched by its unique summary, so the read-back asserts exactly the | |
| 294 | + // operation the on-camera filter-then-pick selected. | |
| 295 | + const candidates = yield* client.integrations.healthCheckCandidates({ params: { slug } }); | |
| 296 | + const probe = candidates.find((candidate) => candidate.summary === PROBE_SUMMARY); | |
| 297 | + if (!probe) return yield* Effect.die("large spec is missing its probe operation"); | |
| 298 | + const probeOperation = probe.operation; | |
| 299 | + // Sanity: the spec really is large, so the picker can't just show them all. | |
| 300 | + expect(candidates.length).toBeGreaterThan(100); | |
| 301 | + | |
| 302 | + yield* browser.session(identity, async ({ page, step }) => { | |
| 303 | + const input = page.locator("#health-check-operation"); | |
| 304 | + const options = page.getByRole("option"); | |
| 305 | + | |
| 306 | + await step("Open the health-check editor over the large spec", async () => { | |
| 307 | + await page.goto(`/integrations/${slug}`, { waitUntil: "networkidle" }); | |
| 308 | + await page.getByRole("heading", { level: 3, name: "Health check" }).waitFor(); | |
| 309 | + await page.getByRole("button", { name: "Set up" }).click(); | |
| 310 | + await input.waitFor(); | |
| 311 | + }); | |
| 312 | + | |
| 313 | + await step("A broad query still surfaces many operations", async () => { | |
| 314 | + await input.click(); | |
| 315 | + // Real keystrokes (base-ui filters on the input value, not a | |
| 316 | + // programmatic set): a shared summary prefix matches the fillers. | |
| 317 | + await input.selectText(); | |
| 318 | + await input.pressSequentially("Thing number", { delay: 10 }); | |
| 319 | + await options.filter({ hasText: "Thing number" }).first().waitFor(); | |
| 320 | + // The popup caps how many it renders, but a broad match fills it. | |
| 321 | + expect(await options.count()).toBeGreaterThan(20); | |
| 322 | + }); | |
| 323 | + | |
| 324 | + await step("A distinctive query narrows the list to the one match", async () => { | |
| 325 | + await input.selectText(); | |
| 326 | + await input.pressSequentially(PROBE_TOKEN, { delay: 10 }); | |
| 327 | + const match = options.filter({ hasText: PROBE_SUMMARY }).first(); | |
| 328 | + await match.waitFor({ timeout: 10_000 }); | |
| 329 | + // Typing actually filters: the hundreds collapse to the single | |
| 330 | + // matching operation (plus the freeform echo of the typed text). | |
| 331 | + expect(await options.count()).toBeLessThanOrEqual(3); | |
| 332 | + }); | |
| 333 | + | |
| 334 | + await step("Select the filtered operation and save", async () => { | |
| 335 | + const match = options.filter({ hasText: PROBE_SUMMARY }).first(); | |
| 336 | + // base-ui pre-highlights the freeform echo; arrow onto the real op. | |
| 337 | + for (let i = 0; i < 8; i++) { | |
| 338 | + if ((await match.getAttribute("data-highlighted")) !== null) break; | |
| 339 | + await input.press("ArrowDown"); | |
| 340 | + } | |
| 341 | + await input.press("Enter"); | |
| 342 | + await page.getByRole("button", { name: "Save", exact: true }).click(); | |
| 343 | + await input.waitFor({ state: "hidden" }); | |
| 344 | + }); | |
| 345 | + }); | |
| 346 | + | |
| 347 | + // The picker committed the real operation behind the matched summary, | |
| 348 | + // not the freeform text that was typed to find it. | |
| 349 | + const stored = yield* client.integrations.healthCheckGet({ params: { slug } }); | |
| 350 | + expect(stored?.operation).toBe(probeOperation); | |
| 351 | + }), | |
| 352 | + Effect.gen(function* () { | |
| 353 | + yield* client.openapi.removeSpec({ params: { slug } }).pipe(Effect.ignore); | |
| 354 | + }), | |
| 355 | + ); | |
| 356 | + }), | |
| 357 | + ), | |
| 358 | +); | |
| 359 | + | |
| 360 | +// =========================================================================== | |
| 361 | +// 3. Add screen, large spec: the operation picker is fed by the bounded spec | |
| 362 | +// preview, so it must carry enough of a big spec that typing reaches an | |
| 363 | +// operation ranked well past the preview's top slice (the Vercel "user" | |
| 364 | +// case: searching found nothing because the op wasn't in the top few). | |
| 365 | +// =========================================================================== | |
| 366 | + | |
| 367 | +scenario( | |
| 368 | + "Health checks (UI) · add screen large spec: typing reaches an operation beyond the preview's top slice", | |
| 369 | + {}, | |
| 370 | + Effect.scoped( | |
| 371 | + Effect.gen(function* () { | |
| 372 | + const target = yield* Target; | |
| 373 | + const browser = yield* Browser; | |
| 374 | + const { client: makeClient } = yield* Api; | |
| 375 | + const identity = yield* target.newIdentity(); | |
| 376 | + const client = yield* makeClient(api, identity); | |
| 377 | + // The add screen mints the slug from the title, so make it unique. Search | |
| 378 | + // for an operation whose toolPath sorts far past the old top-10 cap. | |
| 379 | + const title = `Big API ${randomBytes(4).toString("hex")}`; | |
| 380 | + const spec = largeSpec("https://big.example.com", title); | |
| 381 | + const targetSummary = "Thing number 137"; | |
| 382 | + | |
| 383 | + let createdSlug = ""; | |
| 384 | + yield* Effect.ensuring( | |
| 385 | + Effect.gen(function* () { | |
| 386 | + yield* browser.session(identity, async ({ page, step }) => { | |
| 387 | + const input = page.locator("#add-health-check-operation"); | |
| 388 | + const options = page.getByRole("option"); | |
| 389 | + | |
| 390 | + await step("Open the Add form and paste the large spec", async () => { | |
| 391 | + await page.goto("/integrations/add/openapi", { waitUntil: "networkidle" }); | |
| 392 | + await page.getByPlaceholder("https://api.example.com/openapi.json").fill(spec); | |
| 393 | + await page | |
| 394 | + .getByRole("heading", { name: "Health check (optional)" }) | |
| 395 | + .waitFor({ timeout: 20_000 }); | |
| 396 | + }); | |
| 397 | + | |
| 398 | + await step("Type to reach an operation past the preview's top slice", async () => { | |
| 399 | + await input.click(); | |
| 400 | + // Real keystrokes; the operation isn't in the first handful, so it | |
| 401 | + // is reachable only because the preview now carries the whole spec. | |
| 402 | + await input.selectText(); | |
| 403 | + await input.pressSequentially(targetSummary, { delay: 10 }); | |
| 404 | + // The real option carries the GET label + toolPath; the freeform | |
| 405 | + // echo is just the typed text, so "GET" disambiguates them. | |
| 406 | + const match = options.filter({ hasText: targetSummary }).filter({ hasText: "GET" }); | |
| 407 | + await match.first().waitFor({ timeout: 10_000 }); | |
| 408 | + }); | |
| 409 | + | |
| 410 | + await step("Select the found operation and add the integration", async () => { | |
| 411 | + const match = options.filter({ hasText: targetSummary }).filter({ hasText: "GET" }); | |
| 412 | + for (let i = 0; i < 8; i++) { | |
| 413 | + if ((await match.first().getAttribute("data-highlighted")) !== null) break; | |
| 414 | + await input.press("ArrowDown"); | |
| 415 | + } | |
| 416 | + await input.press("Enter"); | |
| 417 | + await page.getByRole("button", { name: "Add integration" }).click(); | |
| 418 | + await page.waitForURL(/\/integrations\/[^/?#]+$/, { timeout: 30_000 }); | |
| 419 | + const url = page.url().match(/\/integrations\/([^/?#]+)/); | |
| 420 | + createdSlug = url?.[1] ?? ""; | |
| 421 | + }); | |
| 422 | + }); | |
| 423 | + | |
| 424 | + expect(createdSlug.length).toBeGreaterThan(0); | |
| 425 | + const slug = IntegrationSlug.make(createdSlug); | |
| 426 | + // The drafted check persisted the operation behind the matched summary, | |
| 427 | + // proving the add-screen search reached past the preview's top slice. | |
| 428 | + const candidates = yield* client.integrations.healthCheckCandidates({ params: { slug } }); | |
| 429 | + const expected = candidates.find((candidate) => candidate.summary === targetSummary); | |
| 430 | + if (!expected) return yield* Effect.die("created integration is missing the target op"); | |
| 431 | + const stored = yield* client.integrations.healthCheckGet({ params: { slug } }); | |
| 432 | + expect(stored?.operation).toBe(expected.operation); | |
| 433 | + }), | |
| 434 | + Effect.gen(function* () { | |
| 435 | + if (createdSlug.length > 0) { | |
| 436 | + yield* client.openapi | |
| 437 | + .removeSpec({ params: { slug: IntegrationSlug.make(createdSlug) } }) | |
| 438 | + .pipe(Effect.ignore); | |
| 439 | + } | |
| 440 | + }), | |
| 441 | + ); | |
| 442 | + }), | |
| 443 | + ), | |
| 444 | +); | |
| 445 | + | |
| 446 | +// =========================================================================== | |
| 447 | + | |
| 448 | +scenario( | |
| 449 | + "Health checks (UI) · clicking a combobox option in the sheet selects it without closing the sheet", | |
| 450 | + {}, | |
| 451 | + Effect.scoped( | |
| 452 | + Effect.gen(function* () { | |
| 453 | + const target = yield* Target; | |
| 454 | + const browser = yield* Browser; | |
| 455 | + const { client: makeClient } = yield* Api; | |
| 456 | + const identity = yield* target.newIdentity(); | |
| 457 | + const client = yield* makeClient(api, identity); | |
| 458 | + const slug = newSlug("hc-ui-click"); | |
| 459 | + | |
| 460 | + yield* Effect.ensuring( | |
| 461 | + Effect.gen(function* () { | |
| 462 | + yield* registerIdentityIntegration(client, slug, "https://identity.example.com"); | |
| 463 | + const operation = yield* getMeOperation(client, slug); | |
| 464 | + | |
| 465 | + yield* browser.session(identity, async ({ page, step }) => { | |
| 466 | + const sheet = page.getByRole("dialog"); | |
| 467 | + const operationInput = page.locator("#health-check-operation"); | |
| 468 | + | |
| 469 | + await step("Open the health-check editor", async () => { | |
| 470 | + await page.goto(`/integrations/${slug}`, { waitUntil: "networkidle" }); | |
| 471 | + await page.getByRole("heading", { level: 3, name: "Health check" }).waitFor(); | |
| 472 | + await page.getByRole("button", { name: "Set up" }).click(); | |
| 473 | + await operationInput.waitFor(); | |
| 474 | + }); | |
| 475 | + | |
| 476 | + await step( | |
| 477 | + "Click the operation option by mouse: it selects and the sheet stays open", | |
| 478 | + async () => { | |
| 479 | + await operationInput.click(); | |
| 480 | + await page.getByRole("option").filter({ hasText: "getMe" }).first().click(); | |
| 481 | + // Clicking the portaled popup option must NOT dismiss the sheet. | |
| 482 | + await sheet.waitFor(); | |
| 483 | + expect(await operationInput.inputValue()).toContain("getMe"); | |
| 484 | + await page.getByRole("button", { name: "Save", exact: true }).click(); | |
| 485 | + await operationInput.waitFor({ state: "hidden" }); | |
| 486 | + }, | |
| 487 | + ); | |
| 488 | + }); | |
| 489 | + | |
| 490 | + // The mouse-driven selection persisted: only possible if the option | |
| 491 | + // click selected without dismissing the sheet first. | |
| 492 | + const stored = yield* client.integrations.healthCheckGet({ params: { slug } }); | |
| 493 | + expect(stored).toEqual({ operation }); | |
| 494 | + }), | |
| 495 | + client.openapi.removeSpec({ params: { slug } }).pipe(Effect.ignore), | |
| 496 | + ); | |
| 497 | + }), | |
| 498 | + ), | |
| 499 | +); | |
| 500 | + | |
| 501 | +// =========================================================================== | |
| 502 | +// 7. Edit sheet, scroll: a modal dialog locks body scroll, which freezes the | |
| 503 | +// portaled combobox list. The editor sheet is non-modal so the list scrolls. | |
| 504 | +// =========================================================================== | |
| 505 | + | |
| 506 | +scenario( | |
| 507 | + "Health checks (UI) · the combobox list scrolls inside the edit sheet", | |
| 508 | + {}, | |
| 509 | + Effect.scoped( | |
| 510 | + Effect.gen(function* () { | |
| 511 | + const target = yield* Target; | |
| 512 | + const browser = yield* Browser; | |
| 513 | + const { client: makeClient } = yield* Api; | |
| 514 | + const identity = yield* target.newIdentity(); | |
| 515 | + const client = yield* makeClient(api, identity); | |
| 516 | + const slug = newSlug("hc-ui-scroll"); | |
| 517 | + | |
| 518 | + yield* Effect.ensuring( | |
| 519 | + Effect.gen(function* () { | |
| 520 | + // Many operations so the popup list overflows and must scroll. | |
| 521 | + yield* client.openapi.addSpec({ | |
| 522 | + payload: { | |
| 523 | + spec: { kind: "blob", value: largeSpec("https://big.example.com") }, | |
| 524 | + slug, | |
| 525 | + baseUrl: "https://big.example.com", | |
| 526 | + authenticationTemplate: [ | |
| 527 | + { | |
| 528 | + slug: "apiKey", | |
| 529 | + type: "apiKey", | |
| 530 | + headers: { authorization: ["Bearer ", { type: "variable", name: "token" }] }, | |
| 531 | + }, | |
| 532 | + ], | |
| 533 | + }, | |
| 534 | + }); | |
| 535 | + | |
| 536 | + yield* browser.session(identity, async ({ page, step }) => { | |
| 537 | + const operationInput = page.locator("#health-check-operation"); | |
| 538 | + const list = page.locator("[data-slot='combobox-list']").first(); | |
| 539 | + | |
| 540 | + await step("Open the operation combobox in the sheet", async () => { | |
| 541 | + await page.goto(`/integrations/${slug}`, { waitUntil: "networkidle" }); | |
| 542 | + await page.getByRole("heading", { level: 3, name: "Health check" }).waitFor(); | |
| 543 | + await page.getByRole("button", { name: "Set up" }).click(); | |
| 544 | + await operationInput.waitFor(); | |
| 545 | + await operationInput.click(); | |
| 546 | + await list.waitFor(); | |
| 547 | + }); | |
| 548 | + | |
| 549 | + await step("Wheel-scroll the list: it actually moves (not scroll-locked)", async () => { | |
| 550 | + const before = await list.evaluate((el) => el.scrollTop); | |
| 551 | + await list.hover(); | |
| 552 | + await page.mouse.wheel(0, 600); | |
| 553 | + // Poll: the wheel scroll must move the list (blocked → stays 0). | |
| 554 | + await page.waitForFunction( | |
| 555 | + (start) => { | |
| 556 | + const el = document.querySelector("[data-slot='combobox-list']"); | |
| 557 | + return el != null && el.scrollTop > start + 20; | |
| 558 | + }, | |
| 559 | + before, | |
| 560 | + { timeout: 5000 }, | |
| 561 | + ); | |
| 562 | + const after = await list.evaluate((el) => el.scrollTop); | |
| 563 | + expect(after, "the list scrolled past its starting offset").toBeGreaterThan(before); | |
| 564 | + // The sheet stayed open through the scroll interaction. | |
| 565 | + await page.getByRole("dialog").waitFor(); | |
| 566 | + }); | |
| 567 | + }); | |
| 568 | + }), | |
| 569 | + client.openapi.removeSpec({ params: { slug } }).pipe(Effect.ignore), | |
| 570 | + ); | |
| 571 | + }), | |
| 572 | + ), | |
| 573 | +); | |
| @@ -0,0 +1,315 @@ | ||
| 1 | +// Cross-target: connection health checks, the feature that answers "has this | |
| 2 | +// credential expired?" (the Google 7-day dev-token case) in one declared probe. | |
| 3 | +// Entirely through the typed client: | |
| 4 | +// | |
| 5 | +// 1. register an OpenAPI integration whose `GET /me` is auth-gated, | |
| 6 | +// 2. CONFIGURE a health check by picking that operation (the same flow the | |
| 7 | +// user drives in the editor: list candidates, ranked GET-first, then set), | |
| 8 | +// 3. CHECK a SAVED connection and watch its status flip healthy -> expired | |
| 9 | +// when the stored key stops working, | |
| 10 | +// 4. confirm a connection with no configured check reports `unknown`. | |
| 11 | +// | |
| 12 | +// The upstream API is a real node:http server started inside the scenario on | |
| 13 | +// 127.0.0.1 that gates `GET /me` on a bearer token: a generic "bring your own | |
| 14 | +// OpenAPI" integration, so the generic openapi health-check path is exercised | |
| 15 | +// rather than any one provider's quirks. | |
| 16 | +import { randomBytes } from "node:crypto"; | |
| 17 | +import { createServer } from "node:http"; | |
| 18 | + | |
| 19 | +import { expect } from "@effect/vitest"; | |
| 20 | +import { Effect } from "effect"; | |
| 21 | +import type { HttpApiClient } from "effect/unstable/httpapi"; | |
| 22 | +import { composePluginApi } from "@executor-js/api/server"; | |
| 23 | +import { openApiHttpPlugin } from "@executor-js/plugin-openapi/api"; | |
| 24 | +import { AuthTemplateSlug, ConnectionName, IntegrationSlug } from "@executor-js/sdk/shared"; | |
| 25 | + | |
| 26 | +import { scenario } from "../src/scenario"; | |
| 27 | +import { Api, Target } from "../src/services"; | |
| 28 | + | |
| 29 | +const api = composePluginApi([openApiHttpPlugin()] as const); | |
| 30 | +type Client = HttpApiClient.ForApi<typeof api>; | |
| 31 | + | |
| 32 | +const TEMPLATE = AuthTemplateSlug.make("apiKey"); | |
| 33 | +const ACCOUNT_EMAIL = "alice@example.com"; | |
| 34 | + | |
| 35 | +const newSlug = (prefix: string) => | |
| 36 | + IntegrationSlug.make(`${prefix}-${randomBytes(4).toString("hex")}`); | |
| 37 | + | |
| 38 | +/** OpenAPI 3 spec with an auth-gated GET (`/me`, the obvious health check) plus a | |
| 39 | + * destructive POST so the candidate ranking has something to sort the GET ahead | |
| 40 | + * of. */ | |
| 41 | +const identitySpec = (baseUrl: string): string => | |
| 42 | + JSON.stringify({ | |
| 43 | + openapi: "3.0.3", | |
| 44 | + info: { title: "Identity API", version: "1.0.0" }, | |
| 45 | + servers: [{ url: baseUrl }], | |
| 46 | + paths: { | |
| 47 | + "/me": { | |
| 48 | + get: { | |
| 49 | + operationId: "getMe", | |
| 50 | + summary: "The current account", | |
| 51 | + responses: { | |
| 52 | + "200": { | |
| 53 | + description: "The authenticated account", | |
| 54 | + content: { | |
| 55 | + "application/json": { | |
| 56 | + schema: { | |
| 57 | + type: "object", | |
| 58 | + properties: { email: { type: "string" }, login: { type: "string" } }, | |
| 59 | + }, | |
| 60 | + }, | |
| 61 | + }, | |
| 62 | + }, | |
| 63 | + }, | |
| 64 | + }, | |
| 65 | + }, | |
| 66 | + "/messages": { | |
| 67 | + post: { | |
| 68 | + operationId: "sendMessage", | |
| 69 | + summary: "Send a message", | |
| 70 | + responses: { "201": { description: "created" } }, | |
| 71 | + }, | |
| 72 | + }, | |
| 73 | + }, | |
| 74 | + }); | |
| 75 | + | |
| 76 | +/** A real node:http identity API on 127.0.0.1. `GET /me` returns the account | |
| 77 | + * JSON only when the bearer token matches `validToken`; any other token is a | |
| 78 | + * 401 (the "the dev token got revoked" case the health check classifies as | |
| 79 | + * expired). Closed by the scope's finalizer. */ | |
| 80 | +const serveIdentityApi = (validToken: string) => | |
| 81 | + Effect.acquireRelease( | |
| 82 | + Effect.callback<{ readonly url: string; readonly close: () => void }>((resume) => { | |
| 83 | + const server = createServer((request, response) => { | |
| 84 | + const authorized = request.headers["authorization"] === `Bearer ${validToken}`; | |
| 85 | + if (request.method === "GET" && (request.url ?? "").startsWith("/me")) { | |
| 86 | + if (!authorized) { | |
| 87 | + response.writeHead(401, { "content-type": "application/json" }); | |
| 88 | + response.end(JSON.stringify({ error: "invalid_token" })); | |
| 89 | + return; | |
| 90 | + } | |
| 91 | + response.writeHead(200, { "content-type": "application/json" }); | |
| 92 | + response.end(JSON.stringify({ email: ACCOUNT_EMAIL, login: "alice" })); | |
| 93 | + return; | |
| 94 | + } | |
| 95 | + response.writeHead(404, { "content-type": "application/json" }); | |
| 96 | + response.end(JSON.stringify({ error: "not_found" })); | |
| 97 | + }); | |
| 98 | + server.listen(0, "127.0.0.1", () => { | |
| 99 | + const address = server.address(); | |
| 100 | + const port = typeof address === "object" && address ? address.port : 0; | |
| 101 | + resume( | |
| 102 | + Effect.succeed({ | |
| 103 | + url: `http://127.0.0.1:${port}`, | |
| 104 | + close: () => { | |
| 105 | + server.close(); | |
| 106 | + server.closeAllConnections(); | |
| 107 | + }, | |
| 108 | + }), | |
| 109 | + ); | |
| 110 | + }); | |
| 111 | + }), | |
| 112 | + (server) => Effect.sync(server.close), | |
| 113 | + ); | |
| 114 | + | |
| 115 | +/** Register the identity integration against `baseUrl` with a bearer-token auth | |
| 116 | + * method (single `token` input → connection `value`). Returns the slug. */ | |
| 117 | +const registerIdentityIntegration = (client: Client, slug: IntegrationSlug, baseUrl: string) => | |
| 118 | + client.openapi.addSpec({ | |
| 119 | + payload: { | |
| 120 | + spec: { kind: "blob", value: identitySpec(baseUrl) }, | |
| 121 | + slug, | |
| 122 | + baseUrl, | |
| 123 | + authenticationTemplate: [ | |
| 124 | + { | |
| 125 | + slug: "apiKey", | |
| 126 | + type: "apiKey", | |
| 127 | + headers: { authorization: ["Bearer ", { type: "variable", name: "token" }] }, | |
| 128 | + }, | |
| 129 | + ], | |
| 130 | + }, | |
| 131 | + }); | |
| 132 | + | |
| 133 | +/** The stored operation name for the GET probe (openapi prefixes it by tag, e.g. | |
| 134 | + * `me.getMe`), discovered the same way the editor does: from the ranked | |
| 135 | + * candidate list. */ | |
| 136 | +const getMeOperation = (client: Client, slug: IntegrationSlug) => | |
| 137 | + Effect.gen(function* () { | |
| 138 | + const candidates = yield* client.integrations.healthCheckCandidates({ params: { slug } }); | |
| 139 | + const getMe = candidates.find((candidate) => candidate.method === "get"); | |
| 140 | + if (!getMe) return yield* Effect.die("identity spec exposed no GET candidate"); | |
| 141 | + return getMe.operation; | |
| 142 | + }); | |
| 143 | + | |
| 144 | +scenario( | |
| 145 | + "Health checks · the editor ranks the non-destructive GET ahead of the destructive POST", | |
| 146 | + {}, | |
| 147 | + Effect.scoped( | |
| 148 | + Effect.gen(function* () { | |
| 149 | + const target = yield* Target; | |
| 150 | + const { client: makeClient } = yield* Api; | |
| 151 | + const identity = yield* target.newIdentity(); | |
| 152 | + const client = yield* makeClient(api, identity); | |
| 153 | + const goodToken = `gk_${randomBytes(8).toString("hex")}`; | |
| 154 | + const server = yield* serveIdentityApi(goodToken); | |
| 155 | + const slug = newSlug("hc-rank"); | |
| 156 | + | |
| 157 | + yield* Effect.ensuring( | |
| 158 | + Effect.gen(function* () { | |
| 159 | + yield* registerIdentityIntegration(client, slug, server.url); | |
| 160 | + | |
| 161 | + // The editor offers the integration's operations, ranked so the | |
| 162 | + // non-destructive GET endpoint floats to the top. | |
| 163 | + const candidates = yield* client.integrations.healthCheckCandidates({ | |
| 164 | + params: { slug }, | |
| 165 | + }); | |
| 166 | + const get = candidates.find((candidate) => candidate.method === "get"); | |
| 167 | + const post = candidates.find((candidate) => candidate.method === "post"); | |
| 168 | + if (!get || !post) { | |
| 169 | + return yield* Effect.die("identity spec should expose a GET and a POST candidate"); | |
| 170 | + } | |
| 171 | + // Operations are stored tag-prefixed (e.g. `me.getMe`); match the suffix. | |
| 172 | + expect(get.operation.split(".").at(-1), "the GET is offered").toBe("getMe"); | |
| 173 | + expect(post.operation.split(".").at(-1), "the destructive POST is offered").toBe( | |
| 174 | + "sendMessage", | |
| 175 | + ); | |
| 176 | + expect( | |
| 177 | + candidates[0]?.operation, | |
| 178 | + "the non-destructive GET ranks ahead of the destructive POST", | |
| 179 | + ).toBe(get.operation); | |
| 180 | + expect(get.destructive, "the GET probe is non-destructive").toBe(false); | |
| 181 | + expect(post.destructive, "the POST is flagged destructive").toBe(true); | |
| 182 | + | |
| 183 | + // Pick it: just the operation (a pure liveness probe). | |
| 184 | + yield* client.integrations.healthCheckSet({ | |
| 185 | + params: { slug }, | |
| 186 | + payload: { spec: { operation: get.operation } }, | |
| 187 | + }); | |
| 188 | + const stored = yield* client.integrations.healthCheckGet({ params: { slug } }); | |
| 189 | + expect(stored, "the chosen health check round-trips").toEqual({ | |
| 190 | + operation: get.operation, | |
| 191 | + }); | |
| 192 | + }), | |
| 193 | + client.openapi.removeSpec({ params: { slug } }).pipe(Effect.ignore), | |
| 194 | + ); | |
| 195 | + }), | |
| 196 | + ), | |
| 197 | +); | |
| 198 | + | |
| 199 | +scenario( | |
| 200 | + "Health checks · a saved connection reports healthy, then expired when its key stops working", | |
| 201 | + {}, | |
| 202 | + Effect.scoped( | |
| 203 | + Effect.gen(function* () { | |
| 204 | + const target = yield* Target; | |
| 205 | + const { client: makeClient } = yield* Api; | |
| 206 | + const identity = yield* target.newIdentity(); | |
| 207 | + const client = yield* makeClient(api, identity); | |
| 208 | + const goodToken = `gk_${randomBytes(8).toString("hex")}`; | |
| 209 | + const server = yield* serveIdentityApi(goodToken); | |
| 210 | + const slug = newSlug("hc-saved"); | |
| 211 | + const name = ConnectionName.make("main"); | |
| 212 | + | |
| 213 | + yield* Effect.ensuring( | |
| 214 | + Effect.gen(function* () { | |
| 215 | + yield* registerIdentityIntegration(client, slug, server.url); | |
| 216 | + const operation = yield* getMeOperation(client, slug); | |
| 217 | + yield* client.integrations.healthCheckSet({ | |
| 218 | + params: { slug }, | |
| 219 | + payload: { spec: { operation } }, | |
| 220 | + }); | |
| 221 | + | |
| 222 | + // A connection holding the live key checks out healthy. | |
| 223 | + yield* client.connections.create({ | |
| 224 | + payload: { | |
| 225 | + owner: "org", | |
| 226 | + name, | |
| 227 | + integration: slug, | |
| 228 | + template: TEMPLATE, | |
| 229 | + value: goodToken, | |
| 230 | + }, | |
| 231 | + }); | |
| 232 | + const healthy = yield* client.connections.checkHealth({ | |
| 233 | + params: { owner: "org", integration: slug, name }, | |
| 234 | + }); | |
| 235 | + expect(healthy.status, "the saved connection's live key is healthy").toBe("healthy"); | |
| 236 | + expect(healthy.httpStatus, "the saved probe saw the 200").toBe(200); | |
| 237 | + | |
| 238 | + // Re-creating the same (owner, integration, name) replaces the stored | |
| 239 | + // key in place: now the connection holds a key the server rejects. | |
| 240 | + yield* client.connections.create({ | |
| 241 | + payload: { | |
| 242 | + owner: "org", | |
| 243 | + name, | |
| 244 | + integration: slug, | |
| 245 | + template: TEMPLATE, | |
| 246 | + value: "rotated-away", | |
| 247 | + }, | |
| 248 | + }); | |
| 249 | + const expired = yield* client.connections.checkHealth({ | |
| 250 | + params: { owner: "org", integration: slug, name }, | |
| 251 | + }); | |
| 252 | + expect(expired.status, "the same connection now reads as expired").toBe("expired"); | |
| 253 | + expect(expired.httpStatus, "the saved probe saw the 401").toBe(401); | |
| 254 | + }), | |
| 255 | + Effect.gen(function* () { | |
| 256 | + yield* client.connections | |
| 257 | + .remove({ params: { owner: "org", integration: slug, name } }) | |
| 258 | + .pipe(Effect.ignore); | |
| 259 | + yield* client.openapi.removeSpec({ params: { slug } }).pipe(Effect.ignore); | |
| 260 | + }), | |
| 261 | + ); | |
| 262 | + }), | |
| 263 | + ), | |
| 264 | +); | |
| 265 | + | |
| 266 | +scenario( | |
| 267 | + "Health checks · a connection with no configured check reports unknown, not a failure", | |
| 268 | + {}, | |
| 269 | + Effect.scoped( | |
| 270 | + Effect.gen(function* () { | |
| 271 | + const target = yield* Target; | |
| 272 | + const { client: makeClient } = yield* Api; | |
| 273 | + const identity = yield* target.newIdentity(); | |
| 274 | + const client = yield* makeClient(api, identity); | |
| 275 | + const goodToken = `gk_${randomBytes(8).toString("hex")}`; | |
| 276 | + const server = yield* serveIdentityApi(goodToken); | |
| 277 | + const slug = newSlug("hc-unknown"); | |
| 278 | + const name = ConnectionName.make("main"); | |
| 279 | + | |
| 280 | + yield* Effect.ensuring( | |
| 281 | + Effect.gen(function* () { | |
| 282 | + // No healthCheckSet: the integration declares no probe. | |
| 283 | + yield* registerIdentityIntegration(client, slug, server.url); | |
| 284 | + expect( | |
| 285 | + yield* client.integrations.healthCheckGet({ params: { slug } }), | |
| 286 | + "an integration with no configured check reports none", | |
| 287 | + ).toBeNull(); | |
| 288 | + | |
| 289 | + yield* client.connections.create({ | |
| 290 | + payload: { | |
| 291 | + owner: "org", | |
| 292 | + name, | |
| 293 | + integration: slug, | |
| 294 | + template: TEMPLATE, | |
| 295 | + value: goodToken, | |
| 296 | + }, | |
| 297 | + }); | |
| 298 | + const result = yield* client.connections.checkHealth({ | |
| 299 | + params: { owner: "org", integration: slug, name }, | |
| 300 | + }); | |
| 301 | + expect(result.status, "with no check configured the status is unknown").toBe("unknown"); | |
| 302 | + expect(result.detail ?? "", "the result explains why it is unknown").toContain( | |
| 303 | + "No health check configured", | |
| 304 | + ); | |
| 305 | + }), | |
| 306 | + Effect.gen(function* () { | |
| 307 | + yield* client.connections | |
| 308 | + .remove({ params: { owner: "org", integration: slug, name } }) | |
| 309 | + .pipe(Effect.ignore); | |
| 310 | + yield* client.openapi.removeSpec({ params: { slug } }).pipe(Effect.ignore); | |
| 311 | + }), | |
| 312 | + ); | |
| 313 | + }), | |
| 314 | + ), | |
| 315 | +); | |
| @@ -16,6 +16,8 @@ import { · 15 unmodified lines | ||
| 16 | 16 | ConnectionName, |
| 17 | 17 | ConnectionNotFoundError, |
| 18 | 18 | CredentialProviderNotRegisteredError, |
| 19 | + HealthCheckResult, | |
| 20 | + HealthCheckSpec, | |
| 19 | 21 | IntegrationNotFoundError, |
| 20 | 22 | IntegrationSlug, |
| 21 | 23 | InternalError, |
| @@ -108,6 +110,31 @@ const CreateConnectionPayload = Schema.Struct({ · 86 unmodified lines | ||
| 108 | 110 | ), |
| 109 | 111 | ); |
| 110 | 112 | |
| 113 | +// Validate an in-flight credential WITHOUT saving it (the key-first connect | |
| 114 | +// flow). Same origin shape as create, plus an optional `spec` override so the | |
| 115 | +// editor can preview a candidate against a live key. No `name` — the point is | |
| 116 | +// to derive one from the identity the probe returns. | |
| 117 | +const ValidateConnectionPayload = Schema.Struct({ | |
| 118 | + owner: Owner, | |
| 119 | + integration: IntegrationSlug, | |
| 120 | + template: AuthTemplateSlug, | |
| 121 | + spec: Schema.optional(HealthCheckSpec), | |
| 122 | + value: Schema.optional(Schema.String), | |
| 123 | + values: Schema.optional(Schema.Record(Schema.String, Schema.String)), | |
| 124 | + from: Schema.optional( | |
| 125 | + Schema.Struct({ | |
| 126 | + provider: ProviderKey, | |
| 127 | + id: ProviderItemId, | |
| 128 | + }), | |
| 129 | + ), | |
| 130 | +}).check( | |
| 131 | + Schema.makeFilter((payload) => | |
| 132 | + [payload.value, payload.values, payload.from].filter(Predicate.isNotUndefined).length === 1 | |
| 133 | + ? undefined | |
| 134 | + : "Expected exactly one credential origin", | |
| 135 | + ), | |
| 136 | +); | |
| 137 | + | |
| 111 | 138 | // --------------------------------------------------------------------------- |
| 112 | 139 | // Query — optional list filters. |
| 113 | 140 | // --------------------------------------------------------------------------- |
| @@ -186,4 +213,25 @@ export const ConnectionsApi = HttpApiGroup.make("connections") · 72 unmodified lines | ||
| 186 | 213 | success: Schema.Array(ToolResponse), |
| 187 | 214 | error: [InternalError, ConnectionNotFound, IntegrationNotFound], |
| 188 | 215 | }), |
| 216 | + ) | |
| 217 | + // Run the integration's declared health check against a SAVED connection: is | |
| 218 | + // this credential still alive (Google's 7-day dev-token revocation), and whose | |
| 219 | + // account is it? Returns a classified status + optional identity, never an | |
| 220 | + // error for an auth wall (that surfaces as `status: "expired"`). | |
| 221 | + .add( | |
| 222 | + HttpApiEndpoint.post("checkHealth", "/connections/:owner/:integration/:name/health", { | |
| 223 | + params: ConnectionParams, | |
| 224 | + success: HealthCheckResult, | |
| 225 | + error: [InternalError, ConnectionNotFound, IntegrationNotFound], | |
| 226 | + }), | |
| 227 | + ) | |
| 228 | + // Run the health check against an IN-FLIGHT credential without saving it (the | |
| 229 | + // key-first connect flow): confirm the pasted key works and surface the | |
| 230 | + // identity the UI derives a connection name from before anything persists. | |
| 231 | + .add( | |
| 232 | + HttpApiEndpoint.post("validate", "/connections/validate", { | |
| 233 | + payload: ValidateConnectionPayload, | |
| 234 | + success: HealthCheckResult, | |
| 235 | + error: [InternalError, IntegrationNotFound], | |
| 236 | + }), | |
| 189 | 237 | ); |
| @@ -7,7 +7,9 @@ import { · 6 unmodified lines | ||
| 7 | 7 | type Connection, |
| 8 | 8 | type ConnectionRef, |
| 9 | 9 | type CreateConnectionInput, |
| 10 | + type HealthCheckResult, | |
| 10 | 11 | type Tool, |
| 12 | + type ValidateConnectionInput, | |
| 11 | 13 | } from "@executor-js/sdk"; |
| 12 | 14 | |
| 13 | 15 | import { ExecutorApi } from "../api"; |
| @@ -38,6 +40,13 @@ const toolToResponse = (t: Tool) => ({ · 24 unmodified lines | ||
| 38 | 40 | description: t.description, |
| 39 | 41 | }); |
| 40 | 42 | |
| 43 | +const toHealthResponse = (r: HealthCheckResult) => ({ | |
| 44 | + status: r.status, | |
| 45 | + checkedAt: r.checkedAt, | |
| 46 | + ...(r.httpStatus !== undefined ? { httpStatus: r.httpStatus } : {}), | |
| 47 | + ...(r.detail !== undefined ? { detail: r.detail } : {}), | |
| 48 | +}); | |
| 49 | + | |
| 41 | 50 | export const ConnectionsHandlers = HttpApiBuilder.group(ExecutorApi, "connections", (handlers) => |
| 42 | 51 | handlers |
| 43 | 52 | .handle("list", ({ query }) => |
| @@ -130,5 +139,30 @@ export const ConnectionsHandlers = HttpApiBuilder.group(ExecutorApi, "connection · 86 unmodified lines | ||
| 130 | 139 | return tools.map(toolToResponse); |
| 131 | 140 | }), |
| 132 | 141 | ), |
| 142 | + ) | |
| 143 | + .handle("checkHealth", ({ params: path }) => | |
| 144 | + capture( | |
| 145 | + Effect.gen(function* () { | |
| 146 | + const executor = yield* ExecutorService; | |
| 147 | + const result = yield* executor.connections.checkHealth({ | |
| 148 | + owner: path.owner, | |
| 149 | + integration: path.integration, | |
| 150 | + name: path.name, | |
| 151 | + }); | |
| 152 | + return toHealthResponse(result); | |
| 153 | + }), | |
| 154 | + ), | |
| 155 | + ) | |
| 156 | + .handle("validate", ({ payload }) => | |
| 157 | + capture( | |
| 158 | + Effect.gen(function* () { | |
| 159 | + const executor = yield* ExecutorService; | |
| 160 | + // The payload mirrors `ValidateConnectionInput`: owner/integration/ | |
| 161 | + // template/spec plus a single credential origin (`value` | `values` | | |
| 162 | + // `from`). Pass it through verbatim. | |
| 163 | + const result = yield* executor.connections.validate(payload as ValidateConnectionInput); | |
| 164 | + return toHealthResponse(result); | |
| 165 | + }), | |
| 166 | + ), | |
| 133 | 167 | ), |
| 134 | 168 | ); |
| @@ -79,5 +79,30 @@ export const IntegrationsHandlers = HttpApiBuilder.group(ExecutorApi, "integrati · 78 unmodified lines | ||
| 79 | 79 | })); |
| 80 | 80 | }), |
| 81 | 81 | ), |
| 82 | + ) | |
| 83 | + .handle("healthCheckGet", ({ params: path }) => | |
| 84 | + capture( | |
| 85 | + Effect.gen(function* () { | |
| 86 | + const executor = yield* ExecutorService; | |
| 87 | + return yield* executor.integrations.healthCheck.get(path.slug); | |
| 88 | + }), | |
| 89 | + ), | |
| 90 | + ) | |
| 91 | + .handle("healthCheckCandidates", ({ params: path }) => | |
| 92 | + capture( | |
| 93 | + Effect.gen(function* () { | |
| 94 | + const executor = yield* ExecutorService; | |
| 95 | + return yield* executor.integrations.healthCheck.candidates(path.slug); | |
| 96 | + }), | |
| 97 | + ), | |
| 98 | + ) | |
| 99 | + .handle("healthCheckSet", ({ params: path, payload }) => | |
| 100 | + capture( | |
| 101 | + Effect.gen(function* () { | |
| 102 | + const executor = yield* ExecutorService; | |
| 103 | + yield* executor.integrations.healthCheck.set(path.slug, payload.spec); | |
| 104 | + return { ok: true }; | |
| 105 | + }), | |
| 106 | + ), | |
| 82 | 107 | ), |
| 83 | 108 | ); |
| @@ -11,6 +11,8 @@ · 10 unmodified lines | ||
| 11 | 11 | import { HttpApiEndpoint, HttpApiGroup } from "effect/unstable/httpapi"; |
| 12 | 12 | import { Schema } from "effect"; |
| 13 | 13 | import { |
| 14 | + HealthCheckCandidate, | |
| 15 | + HealthCheckSpec, | |
| 14 | 16 | IntegrationDetectionResult, |
| 15 | 17 | IntegrationNotFoundError, |
| 16 | 18 | IntegrationRemovalNotAllowedError, |
| @@ -90,6 +92,12 @@ const DetectRequest = Schema.Struct({ · 73 unmodified lines | ||
| 90 | 92 | url: Schema.String.check(Schema.isMaxLength(2_048)), |
| 91 | 93 | }); |
| 92 | 94 | |
| 95 | +// Set (or clear, with null) the integration's declared health check. The spec | |
| 96 | +// lives inside the owning plugin's opaque config; core only routes it. | |
| 97 | +const SetHealthCheckPayload = Schema.Struct({ | |
| 98 | + spec: Schema.NullOr(HealthCheckSpec), | |
| 99 | +}); | |
| 100 | + | |
| 93 | 101 | // --------------------------------------------------------------------------- |
| 94 | 102 | // Error schemas with HTTP status annotations |
| 95 | 103 | // --------------------------------------------------------------------------- |
| @@ -138,4 +146,30 @@ export const IntegrationsApi = HttpApiGroup.make("integrations") · 42 unmodified lines | ||
| 138 | 146 | success: Schema.Array(IntegrationDetectionResult), |
| 139 | 147 | error: InternalError, |
| 140 | 148 | }), |
| 149 | + ) | |
| 150 | + // The integration's currently declared health check (null when none is set). | |
| 151 | + .add( | |
| 152 | + HttpApiEndpoint.get("healthCheckGet", "/integrations/:slug/health-check", { | |
| 153 | + params: IntegrationParams, | |
| 154 | + success: Schema.NullOr(HealthCheckSpec), | |
| 155 | + error: InternalError, | |
| 156 | + }), | |
| 157 | + ) | |
| 158 | + // Operations the user can pick as the health check, ranked non-destructive + | |
| 159 | + // fewest-required-args first so the obvious identity endpoint floats to the top. | |
| 160 | + .add( | |
| 161 | + HttpApiEndpoint.get("healthCheckCandidates", "/integrations/:slug/health-check/candidates", { | |
| 162 | + params: IntegrationParams, | |
| 163 | + success: Schema.Array(HealthCheckCandidate), | |
| 164 | + error: [InternalError, IntegrationNotFound], | |
| 165 | + }), | |
| 166 | + ) | |
| 167 | + // Persist (or clear) the integration's health check. | |
| 168 | + .add( | |
| 169 | + HttpApiEndpoint.put("healthCheckSet", "/integrations/:slug/health-check", { | |
| 170 | + params: IntegrationParams, | |
| 171 | + payload: SetHealthCheckPayload, | |
| 172 | + success: Schema.Struct({ ok: Schema.Boolean }), | |
| 173 | + error: [InternalError, IntegrationNotFound], | |
| 174 | + }), | |
| 141 | 175 | ); |
| @@ -8,6 +8,7 @@ import type { · 7 unmodified lines | ||
| 8 | 8 | ProviderItemId, |
| 9 | 9 | ProviderKey, |
| 10 | 10 | } from "./ids"; |
| 11 | +import type { HealthCheckSpec } from "./health-check"; | |
| 11 | 12 | |
| 12 | 13 | /* A Connection is THE saved credential — secret, account, and connection are one |
| 13 | 14 | * concept — bound to exactly ONE integration (born wired; there is no unwired |
| @@ -95,6 +96,19 @@ export type CreateConnectionInput = { · 81 unmodified lines | ||
| 95 | 96 | readonly description?: string | null; |
| 96 | 97 | } & ConnectionValueInput; |
| 97 | 98 | |
| 99 | +/** Validate an in-flight credential WITHOUT saving it (the key-first connect | |
| 100 | + * flow). Resolves the pasted value(s) the same way `create` would, then runs | |
| 101 | + * the integration's declared health check so the UI can confirm the key works | |
| 102 | + * and derive a connection name from the returned identity before anything is | |
| 103 | + * persisted. `spec` overrides the integration's declared check (used by the | |
| 104 | + * editor to preview a candidate against a live key). */ | |
| 105 | +export type ValidateConnectionInput = { | |
| 106 | + readonly owner: Owner; | |
| 107 | + readonly integration: IntegrationSlug; | |
| 108 | + readonly template: AuthTemplateSlug; | |
| 109 | + readonly spec?: HealthCheckSpec; | |
| 110 | +} & ConnectionValueInput; | |
| 111 | + | |
| 98 | 112 | /** Edit a connection's user-curated metadata. Only the provided fields change; |
| 99 | 113 | * credentials and OAuth lifecycle are untouchable here (recreate or refresh |
| 100 | 114 | * instead). */ |
| @@ -25,7 +25,9 @@ import type { · 24 unmodified lines | ||
| 25 | 25 | CreateConnectionInput, |
| 26 | 26 | ConnectionValueInput, |
| 27 | 27 | UpdateConnectionInput, |
| 28 | + ValidateConnectionInput, | |
| 28 | 29 | } from "./connection"; |
| 30 | +import type { HealthCheckCandidate, HealthCheckResult, HealthCheckSpec } from "./health-check"; | |
| 29 | 31 | import { |
| 30 | 32 | coreSchema, |
| 31 | 33 | isToolPolicyAction, |
| @@ -263,6 +265,29 @@ export type Executor<TPlugins extends readonly AnyPlugin[] = readonly []> = { · 231 unmodified lines | ||
| 263 | 265 | readonly detect: ( |
| 264 | 266 | url: string, |
| 265 | 267 | ) => Effect.Effect<readonly IntegrationDetectionResult[], StorageFailure>; |
| 268 | + /** The integration's declared health check: which authenticated operation a | |
| 269 | + * connection runs to prove its credential is alive and surface whose | |
| 270 | + * account it is. Configured by the user the same way auth methods are. */ | |
| 271 | + readonly healthCheck: { | |
| 272 | + /** The currently declared check, or null when none is configured (or the | |
| 273 | + * owning plugin has no health-check capability). */ | |
| 274 | + readonly get: ( | |
| 275 | + slug: IntegrationSlug, | |
| 276 | + ) => Effect.Effect<HealthCheckSpec | null, StorageFailure>; | |
| 277 | + /** The operations a user can pick from, ranked non-destructive-first then | |
| 278 | + * fewest required arguments. Empty when the plugin has no candidates. */ | |
| 279 | + readonly candidates: ( | |
| 280 | + slug: IntegrationSlug, | |
| 281 | + ) => Effect.Effect< | |
| 282 | + readonly HealthCheckCandidate[], | |
| 283 | + IntegrationNotFoundError | StorageFailure | |
| 284 | + >; | |
| 285 | + /** Declare (or clear, with `null`) the health check for the integration. */ | |
| 286 | + readonly set: ( | |
| 287 | + slug: IntegrationSlug, | |
| 288 | + spec: HealthCheckSpec | null, | |
| 289 | + ) => Effect.Effect<void, IntegrationNotFoundError | StorageFailure>; | |
| 290 | + }; | |
| 266 | 291 | }; |
| 267 | 292 | |
| 268 | 293 | readonly connections: { |
| @@ -295,6 +320,23 @@ export type Executor<TPlugins extends readonly AnyPlugin[] = readonly []> = { · 26 unmodified lines | ||
| 295 | 320 | readonly Tool[], |
| 296 | 321 | ConnectionNotFoundError | IntegrationNotFoundError | StorageFailure |
| 297 | 322 | >; |
| 323 | + /** Run the integration's declared health check against a saved connection: | |
| 324 | + * classify the credential (healthy / expired / degraded / unknown) and | |
| 325 | + * extract its identity for display. Never throws on an auth wall or upstream | |
| 326 | + * error: those come back as a `HealthCheckResult` with the matching status. */ | |
| 327 | + readonly checkHealth: ( | |
| 328 | + ref: ConnectionRef, | |
| 329 | + ) => Effect.Effect< | |
| 330 | + HealthCheckResult, | |
| 331 | + ConnectionNotFoundError | IntegrationNotFoundError | StorageFailure | |
| 332 | + >; | |
| 333 | + /** Validate an in-flight credential WITHOUT saving it (key-first connect): | |
| 334 | + * resolve the pasted value(s), run the health check, and return the result | |
| 335 | + * so the caller can confirm the key works and derive a name from the | |
| 336 | + * identity before creating the connection. */ | |
| 337 | + readonly validate: ( | |
| 338 | + input: ValidateConnectionInput, | |
| 339 | + ) => Effect.Effect<HealthCheckResult, IntegrationNotFoundError | StorageFailure>; | |
| 298 | 340 | }; |
| 299 | 341 | |
| 300 | 342 | /** Shared OAuth service. Hosts use this through the core HTTP OAuth group; |
| @@ -1708,6 +1750,39 @@ export const createExecutor = <const TPlugins extends readonly AnyPlugin[] = rea · 1407 unmodified lines | ||
| 1708 | 1750 | } |
| 1709 | 1751 | }; |
| 1710 | 1752 | |
| 1753 | + // Project a row's declared health check via the owning plugin's | |
| 1754 | + // `describeHealthCheck` hook. Pure (no I/O); degrades a plugin throw to | |
| 1755 | + // `null` like the other catalog projectors. | |
| 1756 | + const describeHealthCheckForRow = (row: IntegrationRow): HealthCheckSpec | null => { | |
| 1757 | + const runtime = runtimes.get(row.plugin_id); | |
| 1758 | + const describe = runtime?.plugin.describeHealthCheck; | |
| 1759 | + if (!describe) return null; | |
| 1760 | + const record = rowToIntegrationRecord(row); | |
| 1761 | + // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: plugin-authored projector must never fail the catalog read | |
| 1762 | + try { | |
| 1763 | + return describe(record); | |
| 1764 | + } catch { | |
| 1765 | + return null; | |
| 1766 | + } | |
| 1767 | + }; | |
| 1768 | + | |
| 1769 | + // The health-check hooks are typed `Effect<_, unknown>` at the PluginSpec | |
| 1770 | + // boundary (each plugin owns its own error shape). Fold that channel into a | |
| 1771 | + // StorageError so the public health-check surface stays StorageFailure-typed. | |
| 1772 | + // A genuine storage failure surfaces here; an auth wall or upstream error is | |
| 1773 | + // a SUCCESSFUL `HealthCheckResult` (status expired/degraded), not a failure. | |
| 1774 | + const foldPluginFailure = <A>( | |
| 1775 | + effect: Effect.Effect<A, unknown>, | |
| 1776 | + message: string, | |
| 1777 | + ): Effect.Effect<A, StorageFailure> => | |
| 1778 | + effect.pipe( | |
| 1779 | + Effect.catch((cause: unknown) => | |
| 1780 | + isStorageFailure(cause) | |
| 1781 | + ? Effect.fail(cause) | |
| 1782 | + : Effect.fail(new StorageError({ message, cause })), | |
| 1783 | + ), | |
| 1784 | + ); | |
| 1785 | + | |
| 1711 | 1786 | const integrationsList = (): Effect.Effect<readonly Integration[], StorageFailure> => |
| 1712 | 1787 | Effect.gen(function* () { |
| 1713 | 1788 | const rows = yield* core.findMany("integration", {}); |
| @@ -1867,6 +1942,54 @@ export const createExecutor = <const TPlugins extends readonly AnyPlugin[] = rea · 153 unmodified lines | ||
| 1867 | 1942 | return results; |
| 1868 | 1943 | }); |
| 1869 | 1944 | |
| 1945 | + // ------------------------------------------------------------------ | |
| 1946 | + // Health checks — dispatch to the owning plugin's hooks. | |
| 1947 | + // ------------------------------------------------------------------ | |
| 1948 | + | |
| 1949 | + const integrationHealthCheckGet = ( | |
| 1950 | + slug: IntegrationSlug, | |
| 1951 | + ): Effect.Effect<HealthCheckSpec | null, StorageFailure> => | |
| 1952 | + findIntegrationRow(slug).pipe( | |
| 1953 | + Effect.map((row) => (row ? describeHealthCheckForRow(row) : null)), | |
| 1954 | + ); | |
| 1955 | + | |
| 1956 | + const integrationHealthCheckCandidates = ( | |
| 1957 | + slug: IntegrationSlug, | |
| 1958 | + ): Effect.Effect<readonly HealthCheckCandidate[], IntegrationNotFoundError | StorageFailure> => | |
| 1959 | + Effect.gen(function* () { | |
| 1960 | + const row = yield* findIntegrationRow(slug); | |
| 1961 | + if (!row) return yield* new IntegrationNotFoundError({ slug }); | |
| 1962 | + const runtime = runtimes.get(row.plugin_id); | |
| 1963 | + const list = runtime?.plugin.listHealthCheckCandidates; | |
| 1964 | + if (!runtime || !list) return []; | |
| 1965 | + const record = rowToIntegrationRecord(row, describeAuthMethodsForRow(row)); | |
| 1966 | + return yield* foldPluginFailure( | |
| 1967 | + list({ ctx: runtime.ctx, integration: record }), | |
| 1968 | + `Listing health-check candidates for "${slug}" failed.`, | |
| 1969 | + ); | |
| 1970 | + }); | |
| 1971 | + | |
| 1972 | + const integrationSetHealthCheck = ( | |
| 1973 | + slug: IntegrationSlug, | |
| 1974 | + spec: HealthCheckSpec | null, | |
| 1975 | + ): Effect.Effect<void, IntegrationNotFoundError | StorageFailure> => | |
| 1976 | + Effect.gen(function* () { | |
| 1977 | + const row = yield* findIntegrationRow(slug); | |
| 1978 | + if (!row) return yield* new IntegrationNotFoundError({ slug }); | |
| 1979 | + const runtime = runtimes.get(row.plugin_id); | |
| 1980 | + const set = runtime?.plugin.setHealthCheck; | |
| 1981 | + if (!runtime || !set) { | |
| 1982 | + return yield* new StorageError({ | |
| 1983 | + message: `Plugin "${row.plugin_id}" does not support health checks.`, | |
| 1984 | + cause: undefined, | |
| 1985 | + }); | |
| 1986 | + } | |
| 1987 | + yield* foldPluginFailure( | |
| 1988 | + set({ ctx: runtime.ctx, integration: slug, spec }), | |
| 1989 | + `Setting the health check for "${slug}" failed.`, | |
| 1990 | + ); | |
| 1991 | + }); | |
| 1992 | + | |
| 1870 | 1993 | // ------------------------------------------------------------------ |
| 1871 | 1994 | // Per-connection tool production |
| 1872 | 1995 | // ------------------------------------------------------------------ |
| @@ -2448,6 +2571,114 @@ export const createExecutor = <const TPlugins extends readonly AnyPlugin[] = rea · 575 unmodified lines | ||
| 2448 | 2571 | return yield* produceConnectionTools(integrationRow, ref); |
| 2449 | 2572 | }); |
| 2450 | 2573 | |
| 2574 | + // No health-check capability ⇒ "unknown" rather than an error: the caller | |
| 2575 | + // can still render the connection, just without a liveness verdict. | |
| 2576 | + const unknownHealth = (): HealthCheckResult => ({ status: "unknown", checkedAt: Date.now() }); | |
| 2577 | + | |
| 2578 | + // Resolve an in-flight credential's value map (key-first validation) without | |
| 2579 | + // saving anything. Mirrors `resolveConnectionValues` for the saved-row path: | |
| 2580 | + // pasted `value`/`values` are used directly; `from` origins resolve through | |
| 2581 | + // their provider. Single-secret sugar lands on the `token` variable. | |
| 2582 | + const resolveInFlightValues = ( | |
| 2583 | + input: ConnectionValueInput, | |
| 2584 | + ): Effect.Effect<Record<string, string | null>, StorageFailure> => | |
| 2585 | + Effect.gen(function* () { | |
| 2586 | + const out: Record<string, string | null> = {}; | |
| 2587 | + for (const { variable, origin } of normalizeConnectionInputs(input)) { | |
| 2588 | + if ("value" in origin) { | |
| 2589 | + out[variable] = origin.value; | |
| 2590 | + continue; | |
| 2591 | + } | |
| 2592 | + const provider = credentialProviders.get(String(origin.from.provider)); | |
| 2593 | + if (!provider) { | |
| 2594 | + return yield* new StorageError({ | |
| 2595 | + message: `Credential provider "${origin.from.provider}" is not registered.`, | |
| 2596 | + cause: undefined, | |
| 2597 | + }); | |
| 2598 | + } | |
| 2599 | + out[variable] = yield* provider.get(origin.from.id); | |
| 2600 | + } | |
| 2601 | + return out; | |
| 2602 | + }); | |
| 2603 | + | |
| 2604 | + const connectionCheckHealth = ( | |
| 2605 | + ref: ConnectionRef, | |
| 2606 | + ): Effect.Effect< | |
| 2607 | + HealthCheckResult, | |
| 2608 | + ConnectionNotFoundError | IntegrationNotFoundError | StorageFailure | |
| 2609 | + > => | |
| 2610 | + Effect.gen(function* () { | |
| 2611 | + const connectionRow = yield* findConnectionRow(ref); | |
| 2612 | + if (!connectionRow) { | |
| 2613 | + return yield* new ConnectionNotFoundError({ | |
| 2614 | + owner: ref.owner, | |
| 2615 | + integration: ref.integration, | |
| 2616 | + name: ref.name, | |
| 2617 | + }); | |
| 2618 | + } | |
| 2619 | + const integrationRow = yield* findIntegrationRow(ref.integration); | |
| 2620 | + if (!integrationRow) { | |
| 2621 | + return yield* new IntegrationNotFoundError({ slug: ref.integration }); | |
| 2622 | + } | |
| 2623 | + const runtime = runtimes.get(integrationRow.plugin_id); | |
| 2624 | + const check = runtime?.plugin.checkHealth; | |
| 2625 | + if (!runtime || !check) return unknownHealth(); | |
| 2626 | + | |
| 2627 | + const values = yield* foldResolutionFailure(resolveConnectionValues(connectionRow)); | |
| 2628 | + const record = rowToIntegrationRecord( | |
| 2629 | + integrationRow, | |
| 2630 | + describeAuthMethodsForRow(integrationRow), | |
| 2631 | + ); | |
| 2632 | + const credential: ToolInvocationCredential = { | |
| 2633 | + owner: connectionRow.owner as Owner, | |
| 2634 | + integration: ref.integration, | |
| 2635 | + connection: ConnectionName.make(connectionRow.name), | |
| 2636 | + template: AuthTemplateSlug.make(connectionRow.template), | |
| 2637 | + value: values[PRIMARY_INPUT_VARIABLE] ?? null, | |
| 2638 | + values, | |
| 2639 | + config: record.config, | |
| 2640 | + }; | |
| 2641 | + return yield* foldPluginFailure( | |
| 2642 | + check({ ctx: runtime.ctx, integration: record, credential }), | |
| 2643 | + `Health check for connection "${ref.name}" failed.`, | |
| 2644 | + ); | |
| 2645 | + }); | |
| 2646 | + | |
| 2647 | + const connectionValidate = ( | |
| 2648 | + input: ValidateConnectionInput, | |
| 2649 | + ): Effect.Effect<HealthCheckResult, IntegrationNotFoundError | StorageFailure> => | |
| 2650 | + Effect.gen(function* () { | |
| 2651 | + const integrationRow = yield* findIntegrationRow(input.integration); | |
| 2652 | + if (!integrationRow) { | |
| 2653 | + return yield* new IntegrationNotFoundError({ slug: input.integration }); | |
| 2654 | + } | |
| 2655 | + const runtime = runtimes.get(integrationRow.plugin_id); | |
| 2656 | + const check = runtime?.plugin.checkHealth; | |
| 2657 | + if (!runtime || !check) return unknownHealth(); | |
| 2658 | + | |
| 2659 | + const values = yield* resolveInFlightValues(input); | |
| 2660 | + const record = rowToIntegrationRecord( | |
| 2661 | + integrationRow, | |
| 2662 | + describeAuthMethodsForRow(integrationRow), | |
| 2663 | + ); | |
| 2664 | + const credential: ToolInvocationCredential = { | |
| 2665 | + owner: input.owner, | |
| 2666 | + integration: input.integration, | |
| 2667 | + // No connection exists yet (key-first); a synthetic name keeps the | |
| 2668 | + // credential shape whole. The probe authenticates on values+template, | |
| 2669 | + // not on this name (it only appears in upstream-error messages). | |
| 2670 | + connection: ConnectionName.make("(unsaved)"), | |
| 2671 | + template: input.template, | |
| 2672 | + value: values[PRIMARY_INPUT_VARIABLE] ?? null, | |
| 2673 | + values, | |
| 2674 | + config: record.config, | |
| 2675 | + }; | |
| 2676 | + return yield* foldPluginFailure( | |
| 2677 | + check({ ctx: runtime.ctx, integration: record, credential, spec: input.spec }), | |
| 2678 | + `Validating credential for "${input.integration}" failed.`, | |
| 2679 | + ); | |
| 2680 | + }); | |
| 2681 | + | |
| 2451 | 2682 | // ------------------------------------------------------------------ |
| 2452 | 2683 | // Active policy source. |
| 2453 | 2684 | // ------------------------------------------------------------------ |
| @@ -3452,6 +3683,11 @@ export const createExecutor = <const TPlugins extends readonly AnyPlugin[] = rea · 998 unmodified lines | ||
| 3452 | 3683 | update: integrationsUpdatePublic, |
| 3453 | 3684 | remove: integrationsRemove, |
| 3454 | 3685 | detect: integrationsDetect, |
| 3686 | + healthCheck: { | |
| 3687 | + get: integrationHealthCheckGet, | |
| 3688 | + candidates: integrationHealthCheckCandidates, | |
| 3689 | + set: integrationSetHealthCheck, | |
| 3690 | + }, | |
| 3455 | 3691 | }, |
| 3456 | 3692 | connections: { |
| 3457 | 3693 | create: connectionsCreate, |
| @@ -3460,6 +3696,8 @@ export const createExecutor = <const TPlugins extends readonly AnyPlugin[] = rea · 2 unmodified lines | ||
| 3460 | 3696 | update: connectionsUpdate, |
| 3461 | 3697 | remove: connectionsRemove, |
| 3462 | 3698 | refresh: connectionsRefresh, |
| 3699 | + checkHealth: connectionCheckHealth, | |
| 3700 | + validate: connectionValidate, | |
| 3463 | 3701 | }, |
| 3464 | 3702 | oauth, |
| 3465 | 3703 | tools: { |
| @@ -0,0 +1,122 @@ | ||
| 1 | +// --------------------------------------------------------------------------- | |
| 2 | +// @executor-js/sdk health-check vocabulary — browser-safe. | |
| 3 | +// | |
| 4 | +// A health check is a single declared, authenticated operation a connection can | |
| 5 | +// run to answer one question: "is this credential still alive?". The plugin owns | |
| 6 | +// WHICH operation (it lives in the plugin's opaque integration config, picked by | |
| 7 | +// the user the same way auth methods are configured); core owns the shared | |
| 8 | +// vocabulary below so every surface (API, React, plugins) speaks the same shapes. | |
| 9 | +// | |
| 10 | +// The probe runs an operation with optional pinned `args` (some liveness | |
| 11 | +// endpoints need a fixed parameter; e.g. Google's People API needs | |
| 12 | +// `resourceName=people/me`), maps the HTTP status to a `HealthStatus`, and | |
| 13 | +// reports it. Everything here is pure Effect/Schema with no server/node imports | |
| 14 | +// so it is safe to import from React. | |
| 15 | +// --------------------------------------------------------------------------- | |
| 16 | + | |
| 17 | +import { Schema } from "effect"; | |
| 18 | + | |
| 19 | +// --------------------------------------------------------------------------- | |
| 20 | +// Status — the four states a connection can be in. `expired` is the one this | |
| 21 | +// whole feature exists for (Google's 7-day dev-token revocation): the credential | |
| 22 | +// authenticated fine yesterday and now returns 401/403. `degraded` covers any | |
| 23 | +// other non-2xx (upstream 5xx, a 404 on a mis-picked operation); `unknown` is | |
| 24 | +// "never checked / no health check configured". | |
| 25 | +// --------------------------------------------------------------------------- | |
| 26 | + | |
| 27 | +export const HealthStatus = Schema.Literals(["healthy", "expired", "degraded", "unknown"]); | |
| 28 | +export type HealthStatus = typeof HealthStatus.Type; | |
| 29 | + | |
| 30 | +// --------------------------------------------------------------------------- | |
| 31 | +// HealthCheckSpec — the persisted configuration: which operation to run and any | |
| 32 | +// pinned arguments. Stored inside the owning plugin's opaque integration config; | |
| 33 | +// core never parses it (the plugin reads it back in `checkHealth`). | |
| 34 | +// --------------------------------------------------------------------------- | |
| 35 | + | |
| 36 | +export const HealthCheckSpec = Schema.Struct({ | |
| 37 | + /** The tool / operation name to invoke (the plugin maps this to its binding). */ | |
| 38 | + operation: Schema.String, | |
| 39 | + /** Pinned arguments merged into the probe call. Required for liveness | |
| 40 | + * endpoints that take a fixed parameter (e.g. People API `resourceName`). */ | |
| 41 | + args: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), | |
| 42 | +}); | |
| 43 | +export type HealthCheckSpec = typeof HealthCheckSpec.Type; | |
| 44 | + | |
| 45 | +// --------------------------------------------------------------------------- | |
| 46 | +// HealthCheckResult — the outcome of running a probe. `httpStatus` and `detail` | |
| 47 | +// are diagnostic. | |
| 48 | +// --------------------------------------------------------------------------- | |
| 49 | + | |
| 50 | +export const HealthCheckResult = Schema.Struct({ | |
| 51 | + status: HealthStatus, | |
| 52 | + /** The HTTP status the probe observed, when the check ran against HTTP. */ | |
| 53 | + httpStatus: Schema.optional(Schema.Number), | |
| 54 | + /** Epoch ms the check ran. */ | |
| 55 | + checkedAt: Schema.Number, | |
| 56 | + /** Human-readable diagnostic (error message, "no health check configured"). */ | |
| 57 | + detail: Schema.optional(Schema.String), | |
| 58 | +}); | |
| 59 | +export type HealthCheckResult = typeof HealthCheckResult.Type; | |
| 60 | + | |
| 61 | +// --------------------------------------------------------------------------- | |
| 62 | +// HealthCheckCandidate — one operation the user can pick as the health check, | |
| 63 | +// projected from the plugin's stored operations. The editor lists these ranked | |
| 64 | +// (non-destructive first, then fewest required args) so the obvious "GET /me" | |
| 65 | +// style endpoint floats to the top. | |
| 66 | +// --------------------------------------------------------------------------- | |
| 67 | + | |
| 68 | +export const HealthCheckCandidateParameter = Schema.Struct({ | |
| 69 | + name: Schema.String, | |
| 70 | + /** Where the parameter is carried (e.g. "query", "path", "header"). */ | |
| 71 | + location: Schema.String, | |
| 72 | + required: Schema.Boolean, | |
| 73 | + description: Schema.optional(Schema.String), | |
| 74 | +}); | |
| 75 | +export type HealthCheckCandidateParameter = typeof HealthCheckCandidateParameter.Type; | |
| 76 | + | |
| 77 | +export const HealthCheckCandidate = Schema.Struct({ | |
| 78 | + /** The operation / tool name to store as `HealthCheckSpec.operation`. */ | |
| 79 | + operation: Schema.String, | |
| 80 | + /** HTTP method, lower-cased ("get", "post", …), for display + ranking. */ | |
| 81 | + method: Schema.String, | |
| 82 | + /** How many parameters are required to call it (ranking key: fewer is better). */ | |
| 83 | + requiredArgCount: Schema.Number, | |
| 84 | + /** True for mutating methods (post/put/patch/delete) — ranked last and shown | |
| 85 | + * with a warning, since a health check should be safe to run repeatedly. */ | |
| 86 | + destructive: Schema.Boolean, | |
| 87 | + /** Operation summary / description for display, when known. */ | |
| 88 | + summary: Schema.optional(Schema.String), | |
| 89 | + /** The operation's parameters, so the editor can offer pinned-arg inputs. */ | |
| 90 | + parameters: Schema.optional(Schema.Array(HealthCheckCandidateParameter)), | |
| 91 | +}); | |
| 92 | +export type HealthCheckCandidate = typeof HealthCheckCandidate.Type; | |
| 93 | + | |
| 94 | +// --------------------------------------------------------------------------- | |
| 95 | +// Pure helpers — shared so classification behaves identically wherever a probe | |
| 96 | +// is interpreted. | |
| 97 | +// --------------------------------------------------------------------------- | |
| 98 | + | |
| 99 | +/** Map an HTTP status to a health state: 2xx healthy, 401/403 expired (the auth | |
| 100 | + * wall), everything else degraded. */ | |
| 101 | +export const classifyHttpStatus = (status: number): HealthStatus => { | |
| 102 | + if (status >= 200 && status < 300) return "healthy"; | |
| 103 | + if (status === 401 || status === 403) return "expired"; | |
| 104 | + return "degraded"; | |
| 105 | +}; | |
| 106 | + | |
| 107 | +/** Stable ranking for the candidate list: non-destructive before destructive, | |
| 108 | + * then fewest required args, then by method (get first), then alphabetical. | |
| 109 | + * Returns a negative/zero/positive comparator value. */ | |
| 110 | +export const compareHealthCheckCandidates = ( | |
| 111 | + a: HealthCheckCandidate, | |
| 112 | + b: HealthCheckCandidate, | |
| 113 | +): number => { | |
| 114 | + if (a.destructive !== b.destructive) return a.destructive ? 1 : -1; | |
| 115 | + if (a.requiredArgCount !== b.requiredArgCount) return a.requiredArgCount - b.requiredArgCount; | |
| 116 | + if (a.method !== b.method) { | |
| 117 | + if (a.method === "get") return -1; | |
| 118 | + if (b.method === "get") return 1; | |
| 119 | + return a.method < b.method ? -1 : 1; | |
| 120 | + } | |
| 121 | + return a.operation < b.operation ? -1 : a.operation > b.operation ? 1 : 0; | |
| 122 | +}; | |
| @@ -92,6 +92,7 @@ export type { · 91 unmodified lines | ||
| 92 | 92 | ConnectionValueInput, |
| 93 | 93 | CreateConnectionInput, |
| 94 | 94 | UpdateConnectionInput, |
| 95 | + ValidateConnectionInput, | |
| 95 | 96 | } from "./connection"; |
| 96 | 97 | export type { Tool, ToolDef, ToolListFilter, ToolAnnotations } from "./tool"; |
| 97 | 98 | |
| @@ -101,6 +102,17 @@ export type { CredentialProvider, ProviderEntry } from "./provider"; · 3 unmodified lines | ||
| 101 | 102 | // Public projections / detection. |
| 102 | 103 | export { ToolSchemaView, IntegrationDetectionResult } from "./types"; |
| 103 | 104 | |
| 105 | +// Health-check vocabulary (pure Schema + helpers). | |
| 106 | +export { | |
| 107 | + HealthStatus, | |
| 108 | + HealthCheckSpec, | |
| 109 | + HealthCheckResult, | |
| 110 | + HealthCheckCandidate, | |
| 111 | + HealthCheckCandidateParameter, | |
| 112 | + classifyHttpStatus, | |
| 113 | + compareHealthCheckCandidates, | |
| 114 | +} from "./health-check"; | |
| 115 | + | |
| 104 | 116 | // Core schema. |
| 105 | 117 | export { |
| 106 | 118 | bigintColumn, |
| @@ -297,6 +309,9 @@ export { · 190 unmodified lines | ||
| 297 | 309 | type ResolveToolsInput, |
| 298 | 310 | type ResolveToolsResult, |
| 299 | 311 | type ToolInvocationCredential, |
| 312 | + type HealthCheckInput, | |
| 313 | + type HealthCheckCandidatesInput, | |
| 314 | + type SetHealthCheckInput, | |
| 300 | 315 | type Elicit, |
| 301 | 316 | definePlugin, |
| 302 | 317 | tool, |
| @@ -19,6 +19,7 @@ import type { · 18 unmodified lines | ||
| 19 | 19 | IntegrationDisplayDescriptor, |
| 20 | 20 | RegisterIntegrationInput, |
| 21 | 21 | } from "./integration"; |
| 22 | +import type { HealthCheckCandidate, HealthCheckResult, HealthCheckSpec } from "./health-check"; | |
| 22 | 23 | import type { ToolInvocationRow } from "./core-schema"; |
| 23 | 24 | import type { |
| 24 | 25 | AuthTemplateSlug, |
| @@ -300,6 +301,42 @@ export interface ToolInvocationCredential { · 275 unmodified lines | ||
| 300 | 301 | readonly config: IntegrationConfig; |
| 301 | 302 | } |
| 302 | 303 | |
| 304 | +// --------------------------------------------------------------------------- | |
| 305 | +// Health-check hook inputs. A health check is a single declared authenticated | |
| 306 | +// operation a connection runs to prove its credential is still alive and to | |
| 307 | +// surface whose account it is. The plugin owns which operation (stored in its | |
| 308 | +// opaque config); core dispatches these hooks. | |
| 309 | +// --------------------------------------------------------------------------- | |
| 310 | + | |
| 311 | +/** Input to `checkHealth` — run the configured (or overridden) probe against a | |
| 312 | + * resolved credential. The credential may come from a saved connection OR from | |
| 313 | + * in-flight values (key-first validation, before the connection is saved). */ | |
| 314 | +export interface HealthCheckInput<TStore = unknown> { | |
| 315 | + readonly ctx: PluginCtx<TStore>; | |
| 316 | + /** The catalog record (with opaque config) whose health is being checked. */ | |
| 317 | + readonly integration: IntegrationRecord; | |
| 318 | + /** The resolved credential to authenticate the probe. */ | |
| 319 | + readonly credential: ToolInvocationCredential; | |
| 320 | + /** Optional spec override. When omitted, the plugin uses the health check | |
| 321 | + * stored in its own config; an override lets the editor test a candidate | |
| 322 | + * before saving it. */ | |
| 323 | + readonly spec?: HealthCheckSpec; | |
| 324 | +} | |
| 325 | + | |
| 326 | +/** Input to `listHealthCheckCandidates` — the operations a user can pick. */ | |
| 327 | +export interface HealthCheckCandidatesInput<TStore = unknown> { | |
| 328 | + readonly ctx: PluginCtx<TStore>; | |
| 329 | + readonly integration: IntegrationRecord; | |
| 330 | +} | |
| 331 | + | |
| 332 | +/** Input to `setHealthCheck` — persist or clear an integration's health check. */ | |
| 333 | +export interface SetHealthCheckInput<TStore = unknown> { | |
| 334 | + readonly ctx: PluginCtx<TStore>; | |
| 335 | + readonly integration: IntegrationSlug; | |
| 336 | + /** The new health check, or null to clear it. */ | |
| 337 | + readonly spec: HealthCheckSpec | null; | |
| 338 | +} | |
| 339 | + | |
| 303 | 340 | // --------------------------------------------------------------------------- |
| 304 | 341 | // Static tool / source declarations. Unchanged from v1 except the ctx shape. |
| 305 | 342 | // --------------------------------------------------------------------------- |
| @@ -572,6 +609,28 @@ export interface PluginSpec< · 266 unmodified lines | ||
| 572 | 609 | integration: IntegrationRecord, |
| 573 | 610 | ) => IntegrationDisplayDescriptor; |
| 574 | 611 | |
| 612 | + /** Project this plugin's opaque integration config into the configured health | |
| 613 | + * check, when one is set. Synchronous and pure (the config is already | |
| 614 | + * loaded); must tolerate a malformed/foreign config blob by returning null. | |
| 615 | + * Absent ⇒ core reports "no health check configured". */ | |
| 616 | + readonly describeHealthCheck?: (integration: IntegrationRecord) => HealthCheckSpec | null; | |
| 617 | + | |
| 618 | + /** List the operations a user can pick as this integration's health check, | |
| 619 | + * ranked best-first (non-destructive, fewest required args). */ | |
| 620 | + readonly listHealthCheckCandidates?: ( | |
| 621 | + input: HealthCheckCandidatesInput<TStore>, | |
| 622 | + ) => Effect.Effect<readonly HealthCheckCandidate[], unknown>; | |
| 623 | + | |
| 624 | + /** Persist (or clear, with a null spec) the integration's health check in the | |
| 625 | + * plugin's opaque config. Mirrors `integrationConfigure`'s read-modify-write. */ | |
| 626 | + readonly setHealthCheck?: (input: SetHealthCheckInput<TStore>) => Effect.Effect<void, unknown>; | |
| 627 | + | |
| 628 | + /** Run the configured (or overridden) health check against a resolved | |
| 629 | + * credential and classify the outcome into a `HealthCheckResult`. */ | |
| 630 | + readonly checkHealth?: ( | |
| 631 | + input: HealthCheckInput<TStore>, | |
| 632 | + ) => Effect.Effect<HealthCheckResult, unknown>; | |
| 633 | + | |
| 575 | 634 | /** URL autodetection hook for onboarding. */ |
| 576 | 635 | readonly detect?: (input: { |
| 577 | 636 | readonly ctx: PluginCtx<TStore>; |
| @@ -43,6 +43,7 @@ export type { · 42 unmodified lines | ||
| 43 | 43 | ConnectionValueInput, |
| 44 | 44 | CreateConnectionInput, |
| 45 | 45 | UpdateConnectionInput, |
| 46 | + ValidateConnectionInput, | |
| 46 | 47 | } from "./connection"; |
| 47 | 48 | export type { CredentialProvider, ProviderEntry } from "./provider"; |
| 48 | 49 | export type { Tool, ToolDef, ToolListFilter, ToolAnnotations } from "./tool"; |
| @@ -105,6 +106,17 @@ export { · 56 unmodified lines | ||
| 105 | 106 | type OAuthCallbackState, |
| 106 | 107 | } from "./oauth"; |
| 107 | 108 | |
| 109 | +// Health-check vocabulary (pure Schema + helpers). | |
| 110 | +export { | |
| 111 | + HealthStatus, | |
| 112 | + HealthCheckSpec, | |
| 113 | + HealthCheckResult, | |
| 114 | + HealthCheckCandidate, | |
| 115 | + HealthCheckCandidateParameter, | |
| 116 | + classifyHttpStatus, | |
| 117 | + compareHealthCheckCandidates, | |
| 118 | +} from "./health-check"; | |
| 119 | + | |
| 108 | 120 | // OAuth wire contracts (data + tagged errors; the flow impl is server-only). |
| 109 | 121 | export { |
| 110 | 122 | type OAuthGrant, |
| @@ -4,13 +4,19 @@ import * as Effect from "effect/Effect"; · 3 unmodified lines | ||
| 4 | 4 | import * as Exit from "effect/Exit"; |
| 5 | 5 | import * as Option from "effect/Option"; |
| 6 | 6 | |
| 7 | −import { IntegrationSlug } from "@executor-js/sdk/shared"; | |
| 8 | −import { integrationWriteKeys } from "@executor-js/react/api/reactivity-keys"; | |
| 7 | +import { | |
| 8 | + IntegrationSlug, | |
| 9 | + type HealthCheckCandidate, | |
| 10 | + type HealthCheckSpec, | |
| 11 | +} from "@executor-js/sdk/shared"; | |
| 12 | +import { integrationWriteKeys, healthCheckWriteKeys } from "@executor-js/react/api/reactivity-keys"; | |
| 13 | +import { setIntegrationHealthCheck } from "@executor-js/react/api/atoms"; | |
| 9 | 14 | import { |
| 10 | 15 | slugifyNamespace, |
| 11 | 16 | useIntegrationIdentity, |
| 12 | 17 | } from "@executor-js/react/plugins/integration-identity"; |
| 13 | 18 | import { Button } from "@executor-js/react/components/button"; |
| 19 | +import { HealthCheckConfigFields } from "@executor-js/react/components/health-check-editor"; | |
| 14 | 20 | import { |
| 15 | 21 | AuthMethodListEditor, |
| 16 | 22 | useAuthMethodList, |
| @@ -107,8 +113,15 @@ export default function AddOpenApiSource(props: { · 90 unmodified lines | ||
| 107 | 113 | const [adding, setAdding] = useState(false); |
| 108 | 114 | const [addError, setAddError] = useState<string | null>(null); |
| 109 | 115 | |
| 116 | + // Optional health check drafted while adding. Empty `hcOperation` means "not | |
| 117 | + // drafted": we then leave the integration's auto-detected default untouched | |
| 118 | + // rather than persisting a blank. | |
| 119 | + const [hcOperation, setHcOperation] = useState(""); | |
| 120 | + const [hcArgs, setHcArgs] = useState<Record<string, string>>({}); | |
| 121 | + | |
| 110 | 122 | const doPreview = useAtomSet(previewOpenApiSpec, { mode: "promiseExit" }); |
| 111 | 123 | const doAdd = useAtomSet(addOpenApiSpec, { mode: "promiseExit" }); |
| 124 | + const doSetHealthCheck = useAtomSet(setIntegrationHealthCheck, { mode: "promiseExit" }); | |
| 112 | 125 | |
| 113 | 126 | // Keep the latest handleAnalyze in a ref so the debounced effect doesn't need |
| 114 | 127 | // it as a dependency (it closes over fresh state). |
| @@ -204,15 +217,47 @@ export default function AddOpenApiSource(props: { · 89 unmodified lines | ||
| 204 | 217 | return templates; |
| 205 | 218 | }, [authMethodList.rows]); |
| 206 | 219 | |
| 220 | + // Health-check candidates from the bounded preview (top-ranked operations with | |
| 221 | + // their response fields). The picker is freeform, so a custom op is still | |
| 222 | + // reachable when the spec exposes none. | |
| 223 | + const healthCheckCandidates = useMemo<readonly HealthCheckCandidate[]>( | |
| 224 | + () => preview?.healthCheckCandidates ?? [], | |
| 225 | + [preview?.healthCheckCandidates], | |
| 226 | + ); | |
| 227 | + const hcSelected = useMemo( | |
| 228 | + () => healthCheckCandidates.find((c) => c.operation === hcOperation) ?? null, | |
| 229 | + [healthCheckCandidates, hcOperation], | |
| 230 | + ); | |
| 231 | + const hcRequiredParams = useMemo( | |
| 232 | + () => (hcSelected?.parameters ?? []).filter((p) => p.required), | |
| 233 | + [hcSelected], | |
| 234 | + ); | |
| 235 | + const hcMissingRequired = hcRequiredParams.some( | |
| 236 | + (p) => (hcArgs[p.name] ?? "").trim().length === 0, | |
| 237 | + ); | |
| 238 | + | |
| 239 | + const onHcOperationChange = (next: string) => { | |
| 240 | + setHcOperation(next); | |
| 241 | + // Args are operation-specific; drop them so none dangle onto a freshly | |
| 242 | + // picked operation. | |
| 243 | + setHcArgs({}); | |
| 244 | + }; | |
| 245 | + const onHcArgChange = (name: string, value: string) => | |
| 246 | + setHcArgs((prev) => ({ ...prev, [name]: value })); | |
| 247 | + | |
| 207 | 248 | // Pre-empt the API's `IntegrationAlreadyExistsError`: adding an integration |
| 208 | 249 | // whose slug already exists clobbers the existing one's connections/policies, |
| 209 | 250 | // so the API blocks it. Surface that here from the tenant-scoped catalog list. |
| 210 | 251 | const slugAlreadyExists = useSlugAlreadyExists(resolvedSourceId); |
| 211 | 252 | |
| 212 | 253 | // The base URL is optional when the spec declares servers (resolved per call); |
| 213 | − // required only when it doesn't. | |
| 254 | + // required only when it doesn't. A drafted health check must have its required | |
| 255 | + // args filled (an empty draft, `hcOperation === ""`, imposes no constraint). | |
| 214 | 256 | const canAdd = |
| 215 | − preview !== null && !slugAlreadyExists && (!previewHasNoServers || resolvedBaseUrl.length > 0); | |
| 257 | + preview !== null && | |
| 258 | + !slugAlreadyExists && | |
| 259 | + (!previewHasNoServers || resolvedBaseUrl.length > 0) && | |
| 260 | + !(hcOperation.length > 0 && hcMissingRequired); | |
| 216 | 261 | |
| 217 | 262 | // ---- Handlers ---- |
| 218 | 263 | |
| @@ -281,6 +326,32 @@ export default function AddOpenApiSource(props: { · 62 unmodified lines | ||
| 281 | 326 | return; |
| 282 | 327 | } |
| 283 | 328 | |
| 329 | + // Persist the drafted health check only when the user actively picked an | |
| 330 | + // operation; otherwise leave the integration's auto-detected default in | |
| 331 | + // place. A failure here is non-fatal: the integration is already created and | |
| 332 | + // the check stays editable from its detail page, so surface it and move on. | |
| 333 | + if (hcOperation.length > 0) { | |
| 334 | + const argEntries = Object.entries(hcArgs) | |
| 335 | + .map(([key, value]) => [key, value.trim()] as const) | |
| 336 | + .filter(([, value]) => value.length > 0); | |
| 337 | + const spec: HealthCheckSpec = { | |
| 338 | + operation: hcOperation, | |
| 339 | + ...(argEntries.length > 0 ? { args: Object.fromEntries(argEntries) } : {}), | |
| 340 | + }; | |
| 341 | + const exit = await doSetHealthCheck({ | |
| 342 | + params: { slug: integration }, | |
| 343 | + payload: { spec }, | |
| 344 | + reactivityKeys: healthCheckWriteKeys, | |
| 345 | + }); | |
| 346 | + if (Exit.isFailure(exit)) { | |
| 347 | + setAddError( | |
| 348 | + errorMessageFromExit(exit, "Integration added, but saving the health check failed"), | |
| 349 | + ); | |
| 350 | + setAdding(false); | |
| 351 | + return; | |
| 352 | + } | |
| 353 | + } | |
| 354 | + | |
| 284 | 355 | props.onComplete(String(integration)); |
| 285 | 356 | }; |
| 286 | 357 | |
| @@ -367,6 +438,28 @@ export default function AddOpenApiSource(props: { · 80 unmodified lines | ||
| 367 | 438 | /> |
| 368 | 439 | )} |
| 369 | 440 | |
| 441 | + {preview && healthCheckCandidates.length > 0 && ( | |
| 442 | + <section className="space-y-4"> | |
| 443 | + <div className="space-y-1"> | |
| 444 | + <h3 className="text-sm font-medium text-foreground">Health check (optional)</h3> | |
| 445 | + <p className="text-[11px] text-muted-foreground"> | |
| 446 | + One read-only call Executor runs to tell whether a connection's credential is still | |
| 447 | + alive. You can change this later from the integration page. | |
| 448 | + </p> | |
| 449 | + </div> | |
| 450 | + <HealthCheckConfigFields | |
| 451 | + candidates={healthCheckCandidates} | |
| 452 | + selected={hcSelected} | |
| 453 | + operation={hcOperation} | |
| 454 | + onOperationChange={onHcOperationChange} | |
| 455 | + args={hcArgs} | |
| 456 | + onArgChange={onHcArgChange} | |
| 457 | + disabled={adding} | |
| 458 | + idPrefix="add-health-check" | |
| 459 | + /> | |
| 460 | + </section> | |
| 461 | + )} | |
| 462 | + | |
| 370 | 463 | {preview && slugAlreadyExists && !adding && <SlugCollisionAlert slug={resolvedSourceId} />} |
| 371 | 464 | |
| 372 | 465 | {addError && <FormErrorAlert message={addError} />} |
| @@ -6,6 +6,7 @@ import { AuthTemplateSlug, IntegrationSlug } from "@executor-js/sdk/shared"; · 5 unmodified lines | ||
| 6 | 6 | import type { IntegrationAccountHandoff } from "@executor-js/sdk/client"; |
| 7 | 7 | |
| 8 | 8 | import { AccountsSection } from "@executor-js/react/components/accounts-section"; |
| 9 | +import { HealthCheckEditor } from "@executor-js/react/components/health-check-editor"; | |
| 9 | 10 | import { integrationWriteKeys } from "@executor-js/react/api/reactivity-keys"; |
| 10 | 11 | import type { AuthMethod, Placement } from "@executor-js/react/lib/auth-placements"; |
| 11 | 12 | import { |
| @@ -113,6 +114,7 @@ export default function OpenApiAccountsPanel(props: { · 101 unmodified lines | ||
| 113 | 114 | createCustomMethod={createCustomMethod} |
| 114 | 115 | removeCustomMethod={removeCustomMethod} |
| 115 | 116 | /> |
| 117 | + <HealthCheckEditor integration={slug} /> | |
| 116 | 118 | </div> |
| 117 | 119 | ); |
| 118 | 120 | } |
| @@ -7,6 +7,14 @@ import { · 6 unmodified lines | ||
| 7 | 7 | ToolName, |
| 8 | 8 | ToolResult, |
| 9 | 9 | authToolFailure, |
| 10 | + classifyHttpStatus, | |
| 11 | + compareHealthCheckCandidates, | |
| 12 | + type HealthCheckCandidate, | |
| 13 | + type HealthCheckResult, | |
| 14 | + type HealthCheckSpec, | |
| 15 | + type IntegrationConfig, | |
| 16 | + type IntegrationRecord, | |
| 17 | + type IntegrationSlug, | |
| 10 | 18 | type PluginCtx, |
| 11 | 19 | type ResolveToolsResult, |
| 12 | 20 | type StorageFailure, |
| @@ -28,7 +36,7 @@ import { · 15 unmodified lines | ||
| 28 | 36 | streamOperationBindingsFromStructure, |
| 29 | 37 | } from "./extract"; |
| 30 | 38 | import { compileToolDefinitions, type ToolDefinition } from "./definitions"; |
| 31 | −import { annotationsForOperation, buildRequest, invokeWithLayer } from "./invoke"; | |
| 39 | +import { annotationsForOperation, buildRequest, invokeWithLayer, REQUIRE_APPROVAL } from "./invoke"; | |
| 32 | 40 | import { parse, type ParsedDocument } from "./parse"; |
| 33 | 41 | import { parseEntry, structuralSplit, type KeepPathItem, type SpecStructure } from "./split"; |
| 34 | 42 | import { type OpenapiStore, type StoredOperation } from "./store"; |
| @@ -683,3 +691,215 @@ export const resolveOpenApiBackedAnnotations = (input: { · 648 unmodified lines | ||
| 683 | 691 | } |
| 684 | 692 | return out; |
| 685 | 693 | }); |
| 694 | + | |
| 695 | +// --------------------------------------------------------------------------- | |
| 696 | +// Health checks — the declared liveness probe for a connection. | |
| 697 | +// --------------------------------------------------------------------------- | |
| 698 | + | |
| 699 | +/** Resolve the invocation binding for a health-check operation. Unlike the tool | |
| 700 | + * invoke path we do not need `responseBody` (the probe reads the raw response), | |
| 701 | + * so the stored binding is enough; only recompile the spec when it is missing | |
| 702 | + * (e.g. an operation added to the spec but not yet persisted). */ | |
| 703 | +const resolveHealthCheckBinding = ( | |
| 704 | + ctx: PluginCtx<OpenapiStore>, | |
| 705 | + integration: string, | |
| 706 | + operation: string, | |
| 707 | + config: OpenApiIntegrationConfig | null, | |
| 708 | +): Effect.Effect<OperationBinding | undefined, StorageFailure> => | |
| 709 | + Effect.gen(function* () { | |
| 710 | + const stored = (yield* ctx.storage.getOperation(integration, operation))?.binding; | |
| 711 | + if (stored) return stored; | |
| 712 | + if (!config) return undefined; | |
| 713 | + const specText = yield* loadOpenApiSpecText(ctx.storage, config).pipe( | |
| 714 | + Effect.catch(() => Effect.succeed(null)), | |
| 715 | + ); | |
| 716 | + if (specText == null) return undefined; | |
| 717 | + const compiled = yield* compileOpenApiSpec(specText).pipe( | |
| 718 | + Effect.catch(() => Effect.succeed(null)), | |
| 719 | + ); | |
| 720 | + if (!compiled) return undefined; | |
| 721 | + return openApiStoredOperationsFromCompiled(integration, compiled).find( | |
| 722 | + (op) => op.toolName === operation, | |
| 723 | + )?.binding; | |
| 724 | + }); | |
| 725 | + | |
| 726 | +/** Run the configured (or overridden) probe against a resolved credential and | |
| 727 | + * classify the outcome. Never fails for credential/upstream reasons: a rejected | |
| 728 | + * credential is a `HealthCheckResult` with `status: "expired"`, not an error. */ | |
| 729 | +export const checkHealthOpenApi = (input: { | |
| 730 | + readonly ctx: PluginCtx<OpenapiStore>; | |
| 731 | + readonly integration: IntegrationRecord; | |
| 732 | + readonly credential: ToolInvocationCredential; | |
| 733 | + readonly spec?: HealthCheckSpec; | |
| 734 | + readonly httpClientLayer: Layer.Layer<HttpClient.HttpClient, never, never>; | |
| 735 | +}): Effect.Effect<HealthCheckResult, StorageFailure> => | |
| 736 | + Effect.gen(function* () { | |
| 737 | + const checkedAt = Date.now(); | |
| 738 | + const config = decodeOpenApiIntegrationConfig(input.integration.config); | |
| 739 | + const spec = input.spec ?? config?.healthCheck; | |
| 740 | + if (!spec) { | |
| 741 | + return { | |
| 742 | + status: "unknown", | |
| 743 | + checkedAt, | |
| 744 | + detail: "No health check configured.", | |
| 745 | + } satisfies HealthCheckResult; | |
| 746 | + } | |
| 747 | + | |
| 748 | + const integration = String(input.integration.slug); | |
| 749 | + const binding = yield* resolveHealthCheckBinding( | |
| 750 | + input.ctx, | |
| 751 | + integration, | |
| 752 | + spec.operation, | |
| 753 | + config, | |
| 754 | + ); | |
| 755 | + if (!binding) { | |
| 756 | + return { | |
| 757 | + status: "unknown", | |
| 758 | + checkedAt, | |
| 759 | + detail: `Health check operation "${spec.operation}" not found on "${integration}".`, | |
| 760 | + } satisfies HealthCheckResult; | |
| 761 | + } | |
| 762 | + | |
| 763 | + const headers: Record<string, string> = { ...(config?.headers ?? {}) }; | |
| 764 | + const queryParams: Record<string, string> = { ...(config?.queryParams ?? {}) }; | |
| 765 | + | |
| 766 | + const template = (config?.authenticationTemplate ?? []).find( | |
| 767 | + (entry) => String(entry.slug) === String(input.credential.template), | |
| 768 | + ); | |
| 769 | + if (template) { | |
| 770 | + const missing = requiredTemplateVariables(template).filter((name) => { | |
| 771 | + const value = input.credential.values[name]; | |
| 772 | + return value == null || value === ""; | |
| 773 | + }); | |
| 774 | + if (missing.length > 0) { | |
| 775 | + return { | |
| 776 | + status: "expired", | |
| 777 | + checkedAt, | |
| 778 | + detail: `Connection "${input.credential.connection}" has no resolvable credential value.`, | |
| 779 | + } satisfies HealthCheckResult; | |
| 780 | + } | |
| 781 | + const rendered = renderAuthTemplate(template, input.credential.values); | |
| 782 | + Object.assign(headers, rendered.headers); | |
| 783 | + Object.assign(queryParams, rendered.queryParams); | |
| 784 | + } | |
| 785 | + | |
| 786 | + // `invokeWithLayer` fails only with the typed `OpenApiInvocationError` | |
| 787 | + // (transport / body-read failures before an HTTP status); fold it onto the | |
| 788 | + // success channel so a dead upstream reads as `degraded`, not a thrown error. | |
| 789 | + const probe = yield* invokeWithLayer( | |
| 790 | + binding, | |
| 791 | + { ...(spec.args ?? {}) } as Record<string, unknown>, | |
| 792 | + config?.baseUrl ?? "", | |
| 793 | + headers, | |
| 794 | + queryParams, | |
| 795 | + input.httpClientLayer, | |
| 796 | + ).pipe( | |
| 797 | + Effect.map((result) => ({ ok: true as const, result })), | |
| 798 | + Effect.catch((failure) => Effect.succeed({ ok: false as const, failure })), | |
| 799 | + ); | |
| 800 | + | |
| 801 | + if (!probe.ok) { | |
| 802 | + return { | |
| 803 | + status: "degraded", | |
| 804 | + checkedAt, | |
| 805 | + detail: `Health check request failed: ${probe.failure.message}`, | |
| 806 | + } satisfies HealthCheckResult; | |
| 807 | + } | |
| 808 | + | |
| 809 | + const status = classifyHttpStatus(probe.result.status); | |
| 810 | + return { | |
| 811 | + status, | |
| 812 | + httpStatus: probe.result.status, | |
| 813 | + checkedAt, | |
| 814 | + ...(status === "healthy" | |
| 815 | + ? {} | |
| 816 | + : { detail: extractOpenApiUpstreamMessage(probe.result.error, probe.result.status) }), | |
| 817 | + } satisfies HealthCheckResult; | |
| 818 | + }); | |
| 819 | + | |
| 820 | +/** List the operations a user can pick as the health check, ranked | |
| 821 | + * non-destructive-first then fewest-required-args so the obvious "GET /me" | |
| 822 | + * style endpoint floats to the top. Recompiles the spec once (best-effort) | |
| 823 | + * to recover human summaries the stored binding does not keep. */ | |
| 824 | +export const listHealthCheckCandidatesOpenApi = (input: { | |
| 825 | + readonly ctx: PluginCtx<OpenapiStore>; | |
| 826 | + readonly integration: IntegrationRecord; | |
| 827 | +}): Effect.Effect<readonly HealthCheckCandidate[], StorageFailure> => | |
| 828 | + Effect.gen(function* () { | |
| 829 | + const integration = String(input.integration.slug); | |
| 830 | + const operations = yield* input.ctx.storage.listOperations(integration); | |
| 831 | + const config = decodeOpenApiIntegrationConfig(input.integration.config); | |
| 832 | + | |
| 833 | + const summaries = new Map<string, string>(); | |
| 834 | + if (config) { | |
| 835 | + const specText = yield* loadOpenApiSpecText(input.ctx.storage, config).pipe( | |
| 836 | + Effect.catch(() => Effect.succeed(null)), | |
| 837 | + ); | |
| 838 | + const compiled = | |
| 839 | + specText == null | |
| 840 | + ? null | |
| 841 | + : yield* compileOpenApiSpec(specText).pipe(Effect.catch(() => Effect.succeed(null))); | |
| 842 | + if (compiled) { | |
| 843 | + for (const def of compiled.definitions) { | |
| 844 | + const summary = | |
| 845 | + Option.getOrUndefined(def.operation.summary) ?? | |
| 846 | + Option.getOrUndefined(def.operation.description); | |
| 847 | + if (summary) summaries.set(def.toolPath, summary); | |
| 848 | + } | |
| 849 | + } | |
| 850 | + } | |
| 851 | + | |
| 852 | + const candidates = operations.map((op): HealthCheckCandidate => { | |
| 853 | + const method = op.binding.method.toLowerCase(); | |
| 854 | + const parameters = op.binding.parameters.map((parameter) => ({ | |
| 855 | + name: parameter.name, | |
| 856 | + location: parameter.location, | |
| 857 | + required: parameter.required, | |
| 858 | + ...(Option.isSome(parameter.description) | |
| 859 | + ? { description: parameter.description.value } | |
| 860 | + : {}), | |
| 861 | + })); | |
| 862 | + return { | |
| 863 | + operation: op.toolName, | |
| 864 | + method, | |
| 865 | + requiredArgCount: op.binding.parameters.filter((parameter) => parameter.required).length, | |
| 866 | + destructive: REQUIRE_APPROVAL.has(method), | |
| 867 | + summary: summaries.get(op.toolName) ?? `${method.toUpperCase()} ${op.binding.pathTemplate}`, | |
| 868 | + ...(parameters.length > 0 ? { parameters } : {}), | |
| 869 | + }; | |
| 870 | + }); | |
| 871 | + return [...candidates].sort(compareHealthCheckCandidates); | |
| 872 | + }); | |
| 873 | + | |
| 874 | +/** Persist (or clear, when `spec` is null) the integration's health check. | |
| 875 | + * Read-modify-write of the opaque config inside a transaction, mirroring | |
| 876 | + * `configure`. */ | |
| 877 | +export const setHealthCheckOpenApi = (input: { | |
| 878 | + readonly ctx: PluginCtx<OpenapiStore>; | |
| 879 | + readonly integration: IntegrationSlug; | |
| 880 | + readonly spec: HealthCheckSpec | null; | |
| 881 | +}): Effect.Effect<void, StorageFailure> => | |
| 882 | + input.ctx.transaction( | |
| 883 | + Effect.gen(function* () { | |
| 884 | + const record = yield* input.ctx.core.integrations.get(input.integration); | |
| 885 | + if (!record) return; | |
| 886 | + // Guard: only touch configs that decode as the openapi shape. Merge over | |
| 887 | + // the RAW config object (not the decoded one, which strips unknown keys) | |
| 888 | + // so provider supersets (Microsoft presets, Google discovery URLs) survive | |
| 889 | + // a health-check write. `healthCheck: undefined` drops the key on JSON | |
| 890 | + // serialization, clearing the stored health check. | |
| 891 | + if (decodeOpenApiIntegrationConfig(record.config) === null) return; | |
| 892 | + const raw = (record.config ?? {}) as Record<string, unknown>; | |
| 893 | + const next = input.spec | |
| 894 | + ? { ...raw, healthCheck: input.spec } | |
| 895 | + : { ...raw, healthCheck: undefined }; | |
| 896 | + yield* input.ctx.core.integrations.update(input.integration, { | |
| 897 | + config: next as IntegrationConfig, | |
| 898 | + }); | |
| 899 | + }), | |
| 900 | + ); | |
| 901 | + | |
| 902 | +/** Pure projector: the health check declared in the integration's config, or | |
| 903 | + * null when none is configured. */ | |
| 904 | +export const describeHealthCheckOpenApi = (record: IntegrationRecord): HealthCheckSpec | null => | |
| 905 | + decodeOpenApiIntegrationConfig(record.config)?.healthCheck ?? null; | |
| @@ -5,6 +5,7 @@ import { · 4 unmodified lines | ||
| 5 | 5 | renderAuthPlacements, |
| 6 | 6 | requiredPlacementVariables, |
| 7 | 7 | } from "@executor-js/sdk/http-auth"; |
| 8 | +import { HealthCheckSpec } from "@executor-js/sdk/core"; | |
| 8 | 9 | |
| 9 | 10 | import type { Authentication } from "./types"; |
| 10 | 11 | |
| @@ -53,6 +54,10 @@ export const OpenApiIntegrationConfigSchema = Schema.Struct({ · 42 unmodified lines | ||
| 53 | 54 | queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)), |
| 54 | 55 | /** The auth methods a connection's value can be applied through. */ |
| 55 | 56 | authenticationTemplate: Schema.optional(Schema.Array(AuthenticationSchema)), |
| 57 | + /** The declared health check: which operation a connection runs to prove its | |
| 58 | + * credential is alive and surface whose account it is. Picked by the user | |
| 59 | + * the same way auth methods are configured. Absent = no health check. */ | |
| 60 | + healthCheck: Schema.optional(HealthCheckSpec), | |
| 56 | 61 | }); |
| 57 | 62 | |
| 58 | 63 | export type OpenApiIntegrationConfig = Omit< |
| @@ -15,19 +15,23 @@ export { · 14 unmodified lines | ||
| 15 | 15 | export { invoke, invokeWithLayer, buildRequest, annotationsForOperation } from "./invoke"; |
| 16 | 16 | export { |
| 17 | 17 | buildDefsJsonStreaming, |
| 18 | + checkHealthOpenApi, | |
| 18 | 19 | compileAndPersistOpenApiOperations, |
| 19 | 20 | compileAndPersistOpenApiSpec, |
| 20 | 21 | compileAndPersistOpenApiSpecStreaming, |
| 21 | 22 | compileOpenApiDocument, |
| 22 | 23 | compileOpenApiSpec, |
| 24 | + describeHealthCheckOpenApi, | |
| 23 | 25 | extractOpenApiUpstreamMessage, |
| 24 | 26 | invokeOpenApiBackedTool, |
| 27 | + listHealthCheckCandidatesOpenApi, | |
| 25 | 28 | loadOpenApiSpecText, |
| 26 | 29 | normalizeOpenApiRefs, |
| 27 | 30 | openApiStoredOperationsFromCompiled, |
| 28 | 31 | openApiToolDefsFromCompiled, |
| 29 | 32 | resolveOpenApiBackedAnnotations, |
| 30 | 33 | resolveOpenApiBackedTools, |
| 34 | + setHealthCheckOpenApi, | |
| 31 | 35 | validateOpenApiBackedToolArgs, |
| 32 | 36 | type CompiledOpenApiSpec, |
| 33 | 37 | type OpenApiPersistResult, |
| @@ -959,7 +959,7 @@ export const invokeWithLayer = ( · 958 unmodified lines | ||
| 959 | 959 | // Derive annotations from HTTP method |
| 960 | 960 | // --------------------------------------------------------------------------- |
| 961 | 961 | |
| 962 | −const REQUIRE_APPROVAL = new Set(["post", "put", "patch", "delete"]); | |
| 962 | +export const REQUIRE_APPROVAL = new Set(["post", "put", "patch", "delete"]); | |
| 963 | 963 | |
| 964 | 964 | export const annotationsForOperation = ( |
| 965 | 965 | method: string, |
| @@ -39,11 +39,15 @@ import type { Authentication } from "./types"; · 38 unmodified lines | ||
| 39 | 39 | import { normalizeOpenApiAuthInputs, type AuthenticationInput } from "./types"; |
| 40 | 40 | import { ApiKeyAuthTemplate, describeApiKeyAuthMethod } from "@executor-js/sdk/http-auth"; |
| 41 | 41 | import { |
| 42 | + checkHealthOpenApi, | |
| 42 | 43 | compileOpenApiSpec, |
| 44 | + describeHealthCheckOpenApi, | |
| 43 | 45 | invokeOpenApiBackedTool, |
| 46 | + listHealthCheckCandidatesOpenApi, | |
| 44 | 47 | openApiStoredOperationsFromCompiled, |
| 45 | 48 | resolveOpenApiBackedAnnotations, |
| 46 | 49 | resolveOpenApiBackedTools, |
| 50 | + setHealthCheckOpenApi, | |
| 47 | 51 | validateOpenApiBackedToolArgs, |
| 48 | 52 | } from "./backing"; |
| 49 | 53 | import { resolveServerUrl } from "./openapi-utils"; |
| @@ -1013,6 +1017,23 @@ export const openApiPlugin = definePlugin((options?: OpenApiPluginOptions) => { · 963 unmodified lines | ||
| 1013 | 1017 | describeAuthMethods: describeOpenApiAuthMethods, |
| 1014 | 1018 | describeIntegrationDisplay: describeOpenApiIntegrationDisplay, |
| 1015 | 1019 | |
| 1020 | + // Health checks: the declared liveness/identity probe. `describeHealthCheck` | |
| 1021 | + // is a pure projector off the opaque config; the rest run operations or | |
| 1022 | + // read-modify-write the config, so they thread the plugin's http layer / ctx. | |
| 1023 | + describeHealthCheck: describeHealthCheckOpenApi, | |
| 1024 | + listHealthCheckCandidates: (input) => | |
| 1025 | + listHealthCheckCandidatesOpenApi({ ctx: input.ctx, integration: input.integration }), | |
| 1026 | + setHealthCheck: (input) => | |
| 1027 | + setHealthCheckOpenApi({ ctx: input.ctx, integration: input.integration, spec: input.spec }), | |
| 1028 | + checkHealth: (input) => | |
| 1029 | + checkHealthOpenApi({ | |
| 1030 | + ctx: input.ctx, | |
| 1031 | + integration: input.integration, | |
| 1032 | + credential: input.credential, | |
| 1033 | + spec: input.spec, | |
| 1034 | + httpClientLayer: options?.httpClientLayer ?? input.ctx.httpClientLayer, | |
| 1035 | + }), | |
| 1036 | + | |
| 1016 | 1037 | // Produce one tool per spec operation. Spec-derived, identical for every |
| 1017 | 1038 | // connection on the integration - so `getValue` is never called here. The |
| 1018 | 1039 | // operation bindings invokeTool needs are persisted at addSpec time; this |
| @@ -1,10 +1,25 @@ | ||
| 1 | 1 | import { Effect, Option, Predicate } from "effect"; |
| 2 | 2 | import { Schema } from "effect"; |
| 3 | 3 | |
| 4 | +import { HealthCheckCandidate, compareHealthCheckCandidates } from "@executor-js/sdk/core"; | |
| 5 | + | |
| 4 | 6 | import { parse, resolveSpecText, type ParsedDocument } from "./parse"; |
| 5 | 7 | import { extract } from "./extract"; |
| 8 | +import { compileToolDefinitions } from "./definitions"; | |
| 6 | 9 | import { DocResolver } from "./openapi-utils"; |
| 7 | −import { HttpMethod, ServerInfo, type ExtractionResult } from "./types"; | |
| 10 | +import { HttpMethod, ServerInfo, type ExtractedOperation, type ExtractionResult } from "./types"; | |
| 11 | + | |
| 12 | +// Mutating HTTP methods — mirrors `REQUIRE_APPROVAL` in `./invoke` but kept | |
| 13 | +// inline so this browser-safe preview module never pulls in the HTTP execution | |
| 14 | +// path. A health check should be safe to re-run, so these rank last. | |
| 15 | +const DESTRUCTIVE_METHODS = new Set(["post", "put", "patch", "delete"]); | |
| 16 | + | |
| 17 | +// Cap on health-check candidate METADATA carried in the preview, so the add | |
| 18 | +// screen's operation picker can search the whole spec (not just a top few). | |
| 19 | +// Building this is cheap (the rank/sort already runs over every operation); only | |
| 20 | +// the payload grows, so the cap bounds Graph-sized specs (16k+ ops) to the | |
| 21 | +// top-ranked 1000. Beyond that, the picker stays freeform (type an exact op). | |
| 22 | +const MAX_PREVIEW_CANDIDATES = 1000; | |
| 8 | 23 | |
| 9 | 24 | // --------------------------------------------------------------------------- |
| 10 | 25 | // OAuth 2.0 flows — one entry per supported grant type |
| @@ -155,6 +170,9 @@ export const SpecPreview = Schema.Struct({ · 144 unmodified lines | ||
| 155 | 170 | headerPresets: Schema.Array(HeaderPreset), |
| 156 | 171 | /** OAuth2 presets — one per (oauth2 scheme × supported flow) combination */ |
| 157 | 172 | oauth2Presets: Schema.Array(OAuth2Preset), |
| 173 | + /** Top-ranked health-check candidates (bounded), so the add screen can offer a | |
| 174 | + * typed operation picker before the integration is registered. */ | |
| 175 | + healthCheckCandidates: Schema.Array(HealthCheckCandidate), | |
| 158 | 176 | }); |
| 159 | 177 | export type SpecPreview = typeof SpecPreview.Type; |
| 160 | 178 | |
| @@ -172,6 +190,7 @@ export const SpecPreviewSummary = Schema.Struct({ · 11 unmodified lines | ||
| 172 | 190 | authStrategies: Schema.Array(AuthStrategy), |
| 173 | 191 | headerPresets: Schema.Array(HeaderPreset), |
| 174 | 192 | oauth2Presets: Schema.Array(OAuth2Preset), |
| 193 | + healthCheckCandidates: Schema.Array(HealthCheckCandidate), | |
| 175 | 194 | }); |
| 176 | 195 | export type SpecPreviewSummary = typeof SpecPreviewSummary.Type; |
| 177 | 196 | |
| @@ -187,6 +206,7 @@ export const specPreviewSummary = (preview: SpecPreview): SpecPreviewSummary => · 9 unmodified lines | ||
| 187 | 206 | authStrategies: preview.authStrategies, |
| 188 | 207 | headerPresets: preview.headerPresets, |
| 189 | 208 | oauth2Presets: preview.oauth2Presets, |
| 209 | + healthCheckCandidates: preview.healthCheckCandidates, | |
| 190 | 210 | }); |
| 191 | 211 | |
| 192 | 212 | // --------------------------------------------------------------------------- |
| @@ -409,6 +429,57 @@ const collectTags = (result: ExtractionResult): string[] => { · 216 unmodified lines | ||
| 409 | 429 | return [...tagSet].sort(); |
| 410 | 430 | }; |
| 411 | 431 | |
| 432 | +// --------------------------------------------------------------------------- | |
| 433 | +// Health-check candidates (bounded) for the add screen | |
| 434 | +// --------------------------------------------------------------------------- | |
| 435 | + | |
| 436 | +/** | |
| 437 | + * Project the top-ranked health-check candidates from a parsed doc + its | |
| 438 | + * extracted operations, so the add screen can offer a typed operation picker | |
| 439 | + * before registration. | |
| 440 | + * | |
| 441 | + * Tool paths are computed on the FULL operation set (`compileToolDefinitions` | |
| 442 | + * collision resolution is stateful, so they must match the paths the operations | |
| 443 | + * get at registration). Candidates are ranked and sliced to | |
| 444 | + * `MAX_PREVIEW_CANDIDATES` (enough for the operation picker to search the whole | |
| 445 | + * spec). | |
| 446 | + */ | |
| 447 | +const buildPreviewHealthCheckCandidates = ( | |
| 448 | + _doc: ParsedDocument, | |
| 449 | + operations: readonly ExtractedOperation[], | |
| 450 | +): HealthCheckCandidate[] => { | |
| 451 | + if (operations.length === 0) return []; | |
| 452 | + | |
| 453 | + const definitions = compileToolDefinitions(operations); | |
| 454 | + | |
| 455 | + return definitions | |
| 456 | + .map((def): HealthCheckCandidate => { | |
| 457 | + const op = def.operation; | |
| 458 | + const method = op.method.toLowerCase(); | |
| 459 | + const parameters = op.parameters.map((parameter) => ({ | |
| 460 | + name: parameter.name, | |
| 461 | + location: parameter.location, | |
| 462 | + required: parameter.required, | |
| 463 | + ...(Option.isSome(parameter.description) | |
| 464 | + ? { description: parameter.description.value } | |
| 465 | + : {}), | |
| 466 | + })); | |
| 467 | + return { | |
| 468 | + operation: def.toolPath, | |
| 469 | + method, | |
| 470 | + requiredArgCount: op.parameters.filter((parameter) => parameter.required).length, | |
| 471 | + destructive: DESTRUCTIVE_METHODS.has(method), | |
| 472 | + summary: | |
| 473 | + Option.getOrUndefined(op.summary) ?? | |
| 474 | + Option.getOrUndefined(op.description) ?? | |
| 475 | + `${method.toUpperCase()} ${op.pathTemplate}`, | |
| 476 | + ...(parameters.length > 0 ? { parameters } : {}), | |
| 477 | + }; | |
| 478 | + }) | |
| 479 | + .sort(compareHealthCheckCandidates) | |
| 480 | + .slice(0, MAX_PREVIEW_CANDIDATES); | |
| 481 | +}; | |
| 482 | + | |
| 412 | 483 | // --------------------------------------------------------------------------- |
| 413 | 484 | // Public API |
| 414 | 485 | // --------------------------------------------------------------------------- |
| @@ -454,6 +525,7 @@ export const previewSpecText = Effect.fn("OpenApi.previewSpecText")(function* (s · 39 unmodified lines | ||
| 454 | 525 | authStrategies, |
| 455 | 526 | headerPresets: buildHeaderPresets(securitySchemes, authStrategies), |
| 456 | 527 | oauth2Presets: buildOAuth2Presets(securitySchemes), |
| 528 | + healthCheckCandidates: buildPreviewHealthCheckCandidates(doc, result.operations), | |
| 457 | 529 | }); |
| 458 | 530 | }); |
| 459 | 531 | |
| @@ -76,6 +76,25 @@ export const integrationAtom = (slug: IntegrationSlug) => · 75 unmodified lines | ||
| 76 | 76 | (integrations) => integrations.find((i) => i.slug === slug) ?? null, |
| 77 | 77 | ); |
| 78 | 78 | |
| 79 | +/** The integration's currently declared health check (null when none is set). | |
| 80 | + * Backs the editor's "current selection" and the status surfaces deciding | |
| 81 | + * whether a connection can be probed at all. */ | |
| 82 | +export const integrationHealthCheckAtom = (slug: IntegrationSlug) => | |
| 83 | + ExecutorApiClient.query("integrations", "healthCheckGet", { | |
| 84 | + params: { slug }, | |
| 85 | + timeToLive: "30 seconds", | |
| 86 | + reactivityKeys: [ReactivityKey.healthChecks], | |
| 87 | + }); | |
| 88 | + | |
| 89 | +/** Operations the user can pick as the health check, server-ranked | |
| 90 | + * (non-destructive + fewest-required-args first). Backs the editor picker. */ | |
| 91 | +export const integrationHealthCheckCandidatesAtom = (slug: IntegrationSlug) => | |
| 92 | + ExecutorApiClient.query("integrations", "healthCheckCandidates", { | |
| 93 | + params: { slug }, | |
| 94 | + timeToLive: "5 minutes", | |
| 95 | + reactivityKeys: [ReactivityKey.integrations], | |
| 96 | + }); | |
| 97 | + | |
| 79 | 98 | // --------------------------------------------------------------------------- |
| 80 | 99 | // Connections — owner-scoped credentials (was `secrets` + `connections`). |
| 81 | 100 | // --------------------------------------------------------------------------- |
| @@ -147,12 +166,28 @@ export const updateConnection = ExecutorApiClient.mutation("connections", "updat · 65 unmodified lines | ||
| 147 | 166 | |
| 148 | 167 | export const refreshConnection = ExecutorApiClient.mutation("connections", "refresh"); |
| 149 | 168 | |
| 169 | +/** Probe a SAVED connection's health on demand (the "Check now" button). A | |
| 170 | + * read-only probe: returns a classified `HealthCheckResult`, persists nothing, | |
| 171 | + * so no reactivity keys. */ | |
| 172 | +export const checkConnectionHealth = ExecutorApiClient.mutation("connections", "checkHealth"); | |
| 173 | + | |
| 174 | +/** Validate an IN-FLIGHT credential without saving it (the key-first connect | |
| 175 | + * flow). Returns the probe result the UI derives a connection name from. */ | |
| 176 | +export const validateConnection = ExecutorApiClient.mutation("connections", "validate"); | |
| 177 | + | |
| 150 | 178 | export const updateIntegration = ExecutorApiClient.mutation("integrations", "update"); |
| 151 | 179 | |
| 152 | 180 | export const removeIntegration = ExecutorApiClient.mutation("integrations", "remove"); |
| 153 | 181 | |
| 154 | 182 | export const detectIntegration = ExecutorApiClient.mutation("integrations", "detect"); |
| 155 | 183 | |
| 184 | +/** Set or clear an integration's declared health check. | |
| 185 | + * Pass `reactivityKeys: healthCheckWriteKeys` at the call site. */ | |
| 186 | +export const setIntegrationHealthCheck = ExecutorApiClient.mutation( | |
| 187 | + "integrations", | |
| 188 | + "healthCheckSet", | |
| 189 | +); | |
| 190 | + | |
| 156 | 191 | // --------------------------------------------------------------------------- |
| 157 | 192 | // OAuth — v2 flow. `start` runs a registered client to mint a connection for an |
| 158 | 193 | // integration; `complete` exchanges the authorization code; `cancel` drops an |
| @@ -28,6 +28,8 @@ export const ReactivityKey = { · 27 unmodified lines | ||
| 28 | 28 | policies: "policies", |
| 29 | 29 | /** Registered OAuth clients (apps). */ |
| 30 | 30 | oauthClients: "oauth-clients", |
| 31 | + /** An integration's declared health check (the operation/identity-field spec). */ | |
| 32 | + healthChecks: "health-checks", | |
| 31 | 33 | // cloud-only resources |
| 32 | 34 | orgMembers: "org:members", |
| 33 | 35 | orgDomains: "org:domains", |
| @@ -47,6 +49,13 @@ export const connectionWriteKeys = [ReactivityKey.connections, ReactivityKey.too · 13 unmodified lines | ||
| 47 | 49 | /** Mutations that register / replace an OAuth client (app). */ |
| 48 | 50 | export const oauthClientWriteKeys = [ReactivityKey.oauthClients] as const; |
| 49 | 51 | |
| 52 | +/** Mutations that set/clear an integration's health check. Touches `integrations` | |
| 53 | + * so any integration view re-reads (the spec is derived from integration config). */ | |
| 54 | +export const healthCheckWriteKeys = [ | |
| 55 | + ReactivityKey.healthChecks, | |
| 56 | + ReactivityKey.integrations, | |
| 57 | +] as const; | |
| 58 | + | |
| 50 | 59 | /** Mutations that mutate tool policies. Also touches `tools` because |
| 51 | 60 | * `tools.list` filters blocked tools — adding/removing a `block` |
| 52 | 61 | * policy changes what the tools page shows. */ |
| @@ -2,18 +2,26 @@ import { useEffect, useMemo, useState } from "react"; · 1 unmodified line | ||
| 2 | 2 | import { useAtomValue, useAtomSet } from "@effect/atom-react"; |
| 3 | 3 | import * as AsyncResult from "effect/unstable/reactivity/AsyncResult"; |
| 4 | 4 | import * as Exit from "effect/Exit"; |
| 5 | −import { IntegrationSlug, type Connection, type Owner } from "@executor-js/sdk/shared"; | |
| 5 | +import { | |
| 6 | + IntegrationSlug, | |
| 7 | + type Connection, | |
| 8 | + type HealthCheckResult, | |
| 9 | + type HealthStatus, | |
| 10 | + type Owner, | |
| 11 | +} from "@executor-js/sdk/shared"; | |
| 6 | 12 | import type { IntegrationAccountHandoff } from "@executor-js/sdk/client"; |
| 7 | 13 | import { toast } from "sonner"; |
| 8 | 14 | |
| 9 | 15 | import { |
| 10 | 16 | addConnectionOptimistic, |
| 17 | + checkConnectionHealth, | |
| 11 | 18 | connectionsForIntegrationAtom, |
| 12 | 19 | refreshConnection, |
| 13 | 20 | removeConnectionOptimistic, |
| 14 | 21 | startOAuth, |
| 15 | 22 | } from "../api/atoms"; |
| 16 | 23 | import { connectionWriteKeys } from "../api/reactivity-keys"; |
| 24 | +import { HEALTH_INDICATOR_COLOR, HEALTH_STATUS_LABEL } from "../lib/health-display"; | |
| 17 | 25 | import { messageFromExit } from "../api/error-reporting"; |
| 18 | 26 | import { ownerLabel, useOwnerDisplay } from "../api/owner-display"; |
| 19 | 27 | import { trackEvent } from "../api/analytics"; |
| @@ -69,16 +77,67 @@ function AccountRow(props: { · 49 unmodified lines | ||
| 69 | 77 | readonly onRemove: () => void; |
| 70 | 78 | }) { |
| 71 | 79 | const { connection, needsReconsent } = props; |
| 80 | + // A live probe result, once "Check now" has run, drives the status indicator. | |
| 81 | + const [probe, setProbe] = useState<HealthCheckResult | null>(null); | |
| 82 | + const [checking, setChecking] = useState(false); | |
| 83 | + const doCheck = useAtomSet(checkConnectionHealth, { mode: "promiseExit" }); | |
| 84 | + | |
| 85 | + // Status comes only from a live probe ("Check now"). We deliberately do NOT | |
| 86 | + // derive expiry from the stored `expiresAt`: that's the access-token lifetime, | |
| 87 | + // which refreshes, so a passive countdown / "expired" reads as alarming but | |
| 88 | + // means nothing. Until a probe runs the connection is "Unchecked". | |
| 89 | + const status: HealthStatus = probe?.status ?? "unknown"; | |
| 90 | + const indicator = HEALTH_INDICATOR_COLOR[status]; | |
| 91 | + | |
| 72 | 92 | const displayLabel = |
| 73 | 93 | connection.identityLabel && connection.identityLabel.length > 0 |
| 74 | 94 | ? connection.identityLabel |
| 75 | 95 | : String(connection.name); |
| 76 | 96 | |
| 97 | + const expired = status === "expired"; | |
| 98 | + | |
| 99 | + const handleCheck = async () => { | |
| 100 | + if (checking) return; | |
| 101 | + setChecking(true); | |
| 102 | + const exit = await doCheck({ | |
| 103 | + params: { | |
| 104 | + owner: connection.owner, | |
| 105 | + integration: connection.integration, | |
| 106 | + name: connection.name, | |
| 107 | + }, | |
| 108 | + }); | |
| 109 | + setChecking(false); | |
| 110 | + if (Exit.isFailure(exit)) { | |
| 111 | + toast.error(messageFromExit(exit, "Health check failed")); | |
| 112 | + return; | |
| 113 | + } | |
| 114 | + setProbe(exit.value); | |
| 115 | + if (exit.value.status === "healthy") { | |
| 116 | + toast.success("Connection is healthy"); | |
| 117 | + } else if (exit.value.status === "expired") { | |
| 118 | + toast.error("Connection expired — reconnect to restore access"); | |
| 119 | + } else if (exit.value.status === "degraded") { | |
| 120 | + toast.warning(exit.value.detail ?? "Connection check returned an error"); | |
| 121 | + } else { | |
| 122 | + toast.message("No health check is configured for this integration"); | |
| 123 | + } | |
| 124 | + }; | |
| 125 | + | |
| 77 | 126 | return ( |
| 78 | 127 | <CardStackEntry className="flex-wrap items-start"> |
| 79 | 128 | <CardStackEntryContent> |
| 80 | 129 | <CardStackEntryTitle className="flex min-w-0 items-center gap-2"> |
| 130 | + <span | |
| 131 | + aria-label={`Status: ${HEALTH_STATUS_LABEL[status]}`} | |
| 132 | + title={HEALTH_STATUS_LABEL[status]} | |
| 133 | + className={`size-2 shrink-0 rounded-full ${indicator.dot}`} | |
| 134 | + /> | |
| 81 | 135 | <span className="truncate">{displayLabel}</span> |
| 136 | + {expired ? ( | |
| 137 | + <Badge variant="destructive" className="shrink-0"> | |
| 138 | + Expired | |
| 139 | + </Badge> | |
| 140 | + ) : null} | |
| 82 | 141 | {needsReconsent ? ( |
| 83 | 142 | <Badge variant="outline" className="shrink-0 border-border text-muted-foreground"> |
| 84 | 143 | Reconnect to grant access |
| @@ -115,6 +174,13 @@ function AccountRow(props: { · 30 unmodified lines | ||
| 115 | 174 | </Button> |
| 116 | 175 | </DropdownMenuTrigger> |
| 117 | 176 | <DropdownMenuContent align="end" className="w-40"> |
| 177 | + <DropdownMenuItem | |
| 178 | + className="text-sm" | |
| 179 | + disabled={checking} | |
| 180 | + onClick={() => void handleCheck()} | |
| 181 | + > | |
| 182 | + {checking ? "Checking…" : "Check now"} | |
| 183 | + </DropdownMenuItem> | |
| 118 | 184 | <DropdownMenuItem className="text-sm" onClick={props.onEdit}> |
| 119 | 185 | Edit |
| 120 | 186 | </DropdownMenuItem> |
| @@ -8,6 +8,8 @@ import { · 7 unmodified lines | ||
| 8 | 8 | OAuthClientSlug, |
| 9 | 9 | ProviderItemId, |
| 10 | 10 | ProviderKey, |
| 11 | + type HealthCheckResult, | |
| 12 | + type HealthCheckSpec, | |
| 11 | 13 | type OAuthClientSummary, |
| 12 | 14 | type Owner, |
| 13 | 15 | } from "@executor-js/sdk/shared"; |
| @@ -18,15 +20,25 @@ import { · 4 unmodified lines | ||
| 18 | 20 | addConnectionOptimistic, |
| 19 | 21 | connectionsAllAtom, |
| 20 | 22 | createOAuthClientOptimistic, |
| 23 | + integrationHealthCheckAtom, | |
| 24 | + integrationHealthCheckCandidatesAtom, | |
| 21 | 25 | oauthClientsOptimisticAtom, |
| 22 | 26 | probeOAuth, |
| 23 | 27 | providerItemsAtom, |
| 24 | 28 | providersAtom, |
| 25 | 29 | registerDynamicOAuthClient, |
| 26 | 30 | removeOAuthClientOptimistic, |
| 31 | + setIntegrationHealthCheck, | |
| 27 | 32 | startOAuth, |
| 33 | + validateConnection, | |
| 28 | 34 | } from "../api/atoms"; |
| 29 | −import { connectionWriteKeys, oauthClientWriteKeys } from "../api/reactivity-keys"; | |
| 35 | +import { | |
| 36 | + connectionWriteKeys, | |
| 37 | + healthCheckWriteKeys, | |
| 38 | + oauthClientWriteKeys, | |
| 39 | +} from "../api/reactivity-keys"; | |
| 40 | +import { HEALTH_INDICATOR_COLOR, HEALTH_STATUS_LABEL } from "../lib/health-display"; | |
| 41 | +import { HealthCheckConfigFields } from "./health-check-editor"; | |
| 30 | 42 | import { messageFromExit } from "../api/error-reporting"; |
| 31 | 43 | import { trackEvent } from "../api/analytics"; |
| 32 | 44 | import { useOrganizationId } from "../api/organization-context"; |
| @@ -835,6 +847,38 @@ export function AddAccountModal(props: AddAccountModalProps) { · 802 unmodified lines | ||
| 835 | 847 | return props.open ? <AddAccountModalView {...props} /> : null; |
| 836 | 848 | } |
| 837 | 849 | |
| 850 | +// --------------------------------------------------------------------------- | |
| 851 | +// Key-check status: the inline line under the credential field that reports the | |
| 852 | +// live probe result. `validating` shows a neutral "Checking..."; a result shows | |
| 853 | +// the status dot + label, and any upstream detail for a non-healthy verdict. | |
| 854 | +// --------------------------------------------------------------------------- | |
| 855 | +function KeyValidationStatus(props: { | |
| 856 | + readonly validating: boolean; | |
| 857 | + readonly result: HealthCheckResult | null; | |
| 858 | +}) { | |
| 859 | + if (props.validating) { | |
| 860 | + return ( | |
| 861 | + <p className="flex items-center gap-2 text-xs text-muted-foreground"> | |
| 862 | + <span className="size-2 shrink-0 animate-pulse rounded-full bg-muted-foreground/50" /> | |
| 863 | + Checking the key... | |
| 864 | + </p> | |
| 865 | + ); | |
| 866 | + } | |
| 867 | + if (!props.result) return null; | |
| 868 | + const { status, detail } = props.result; | |
| 869 | + const indicator = HEALTH_INDICATOR_COLOR[status]; | |
| 870 | + const tone = status === "healthy" ? "text-muted-foreground" : "text-destructive"; | |
| 871 | + return ( | |
| 872 | + <div className={`flex items-start gap-2 text-xs ${tone}`}> | |
| 873 | + <span aria-hidden className={`mt-[3px] size-2 shrink-0 rounded-full ${indicator.dot}`} /> | |
| 874 | + <span className="min-w-0"> | |
| 875 | + <span className="font-medium">{HEALTH_STATUS_LABEL[status]}</span> | |
| 876 | + {status !== "healthy" && detail ? <span className="block opacity-80">{detail}</span> : null} | |
| 877 | + </span> | |
| 878 | + </div> | |
| 879 | + ); | |
| 880 | +} | |
| 881 | + | |
| 838 | 882 | function AddAccountModalView(props: AddAccountModalProps) { |
| 839 | 883 | const { |
| 840 | 884 | integration, |
| @@ -878,6 +922,15 @@ function AddAccountModalView(props: AddAccountModalProps) { · 37 unmodified lines | ||
| 878 | 922 | const [credentialOrigin, setCredentialOrigin] = useState<CredentialOrigin>("paste"); |
| 879 | 923 | const [onePasswordItemId, setOnePasswordItemId] = useState(""); |
| 880 | 924 | const [label, setLabel] = useState(""); |
| 925 | + // Key check: the in-flight probe state and its last result. When the | |
| 926 | + // integration has no configured health check, `hcOperation`/`hcArgs` hold an | |
| 927 | + // inline-drafted check the user picks to test the key against (and which we | |
| 928 | + // save as the integration's check once it comes back healthy). All of this | |
| 929 | + // lives in the view, so closing the modal unmounts and resets it. | |
| 930 | + const [validating, setValidating] = useState(false); | |
| 931 | + const [validationResult, setValidationResult] = useState<HealthCheckResult | null>(null); | |
| 932 | + const [hcOperation, setHcOperation] = useState(""); | |
| 933 | + const [hcArgs, setHcArgs] = useState<Record<string, string>>({}); | |
| 881 | 934 | // Explicit create-time choice (no ambient owner). Cloud defaults to Personal; |
| 882 | 935 | // local/desktop hide the picker and save to the one local workspace. |
| 883 | 936 | const [owner, setOwner] = useState<Owner>(defaultOwner); |
| @@ -915,6 +968,19 @@ function AddAccountModalView(props: AddAccountModalProps) { · 31 unmodified lines | ||
| 915 | 968 | mode: "promiseExit", |
| 916 | 969 | }); |
| 917 | 970 | const doRemoveOAuthClient = useAtomSet(removeOAuthClientOptimistic, { mode: "promise" }); |
| 971 | + const doValidate = useAtomSet(validateConnection, { mode: "promiseExit" }); | |
| 972 | + const doSetHealthCheck = useAtomSet(setIntegrationHealthCheck, { mode: "promiseExit" }); | |
| 973 | + | |
| 974 | + // The integration's declared health check + its candidate operations. When a | |
| 975 | + // check is configured we probe against it; when not, the user picks one of the | |
| 976 | + // candidates inline to test the key (and we save it). | |
| 977 | + const healthCheckResult = useAtomValue(integrationHealthCheckAtom(integration)); | |
| 978 | + const hasHealthCheck = | |
| 979 | + AsyncResult.isSuccess(healthCheckResult) && healthCheckResult.value !== null; | |
| 980 | + const candidatesResult = useAtomValue(integrationHealthCheckCandidatesAtom(integration)); | |
| 981 | + const healthCheckCandidates = AsyncResult.isSuccess(candidatesResult) | |
| 982 | + ? candidatesResult.value | |
| 983 | + : []; | |
| 918 | 984 | |
| 919 | 985 | // Full registered-app summaries (carry endpoints + resource the picker's |
| 920 | 986 | // lightweight options omit) and the connection→app usage map that powers the |
| @@ -1016,6 +1082,21 @@ function AddAccountModalView(props: AddAccountModalProps) { · 95 unmodified lines | ||
| 1016 | 1082 | |
| 1017 | 1083 | const isOAuth = method?.kind === "oauth"; |
| 1018 | 1084 | const isNoAuth = method?.kind === "none"; |
| 1085 | + | |
| 1086 | + // Key check (pasteable credentials only): offer it whenever the integration | |
| 1087 | + // either has a configured check OR exposes candidate operations to test | |
| 1088 | + // against. The inline-picked candidate (when no check is configured) drives | |
| 1089 | + // both the probe and what we save as the integration's health check. | |
| 1090 | + const hcSelected = healthCheckCandidates.find((c) => c.operation === hcOperation) ?? null; | |
| 1091 | + const hcRequiredParams = (hcSelected?.parameters ?? []).filter((p) => p.required); | |
| 1092 | + const hcMissingRequired = hcRequiredParams.some( | |
| 1093 | + (p) => (hcArgs[p.name] ?? "").trim().length === 0, | |
| 1094 | + ); | |
| 1095 | + const canCheckKey = !isOAuth && !isNoAuth && (hasHealthCheck || healthCheckCandidates.length > 0); | |
| 1096 | + // True when we have something to probe against: a configured check, or a | |
| 1097 | + // complete inline-picked candidate. | |
| 1098 | + const keyCheckReady = hasHealthCheck || (hcOperation.length > 0 && !hcMissingRequired); | |
| 1099 | + | |
| 1019 | 1100 | // The distinct credential inputs the selected method needs — one per variable |
| 1020 | 1101 | // across its placements. A single-input method yields one field (`token`); a |
| 1021 | 1102 | // multi-input method (e.g. Datadog) yields one per key. Two placements sharing |
| @@ -1269,6 +1350,69 @@ function AddAccountModalView(props: AddAccountModalProps) { · 247 unmodified lines | ||
| 1269 | 1350 | close(); |
| 1270 | 1351 | }; |
| 1271 | 1352 | |
| 1353 | + // A pasted credential (or the picked operation) changed; the prior verdict is | |
| 1354 | + // stale. Clear it so the status line doesn't show a result for a key/operation | |
| 1355 | + // that is no longer what's in the form. | |
| 1356 | + const clearKeyCheck = (): void => { | |
| 1357 | + if (validationResult !== null) setValidationResult(null); | |
| 1358 | + }; | |
| 1359 | + | |
| 1360 | + // Check the key works: probe the pasted credential WITHOUT saving the | |
| 1361 | + // connection. When the integration has a configured health check we run it; | |
| 1362 | + // otherwise we run the inline-picked candidate and, if it comes back healthy, | |
| 1363 | + // save it as the integration's health check (so it's configured "then"). | |
| 1364 | + const handleValidate = async () => { | |
| 1365 | + const payloadOrigin = createCredentialPayloadOrigin({ | |
| 1366 | + origin: credentialOrigin, | |
| 1367 | + inputs: credentialInputs, | |
| 1368 | + values, | |
| 1369 | + onePasswordItemId, | |
| 1370 | + singleInput, | |
| 1371 | + }); | |
| 1372 | + if (!method || payloadOrigin === null || validating) return; | |
| 1373 | + let inlineSpec: HealthCheckSpec | undefined; | |
| 1374 | + if (!hasHealthCheck) { | |
| 1375 | + if (hcOperation.length === 0 || hcMissingRequired) return; | |
| 1376 | + const argEntries = Object.entries(hcArgs) | |
| 1377 | + .map(([key, value]) => [key, value.trim()] as const) | |
| 1378 | + .filter(([, value]) => value.length > 0); | |
| 1379 | + inlineSpec = { | |
| 1380 | + operation: hcOperation, | |
| 1381 | + ...(argEntries.length > 0 ? { args: Object.fromEntries(argEntries) } : {}), | |
| 1382 | + }; | |
| 1383 | + } | |
| 1384 | + setValidating(true); | |
| 1385 | + const exit = await doValidate({ | |
| 1386 | + payload: { | |
| 1387 | + owner, | |
| 1388 | + integration, | |
| 1389 | + template: method.template, | |
| 1390 | + ...(inlineSpec ? { spec: inlineSpec } : {}), | |
| 1391 | + ...("from" in payloadOrigin | |
| 1392 | + ? { from: payloadOrigin.from } | |
| 1393 | + : { values: payloadOrigin.values }), | |
| 1394 | + }, | |
| 1395 | + }); | |
| 1396 | + setValidating(false); | |
| 1397 | + if (Exit.isFailure(exit)) { | |
| 1398 | + setValidationResult(null); | |
| 1399 | + toast.error(messageFromExit(exit, "Couldn't check the key")); | |
| 1400 | + return; | |
| 1401 | + } | |
| 1402 | + const result = exit.value; | |
| 1403 | + setValidationResult(result); | |
| 1404 | + // Set it "then": a freshly-picked operation that probes healthy becomes the | |
| 1405 | + // integration's health check, so the editor + status surfaces pick it up. | |
| 1406 | + if (inlineSpec && result.status === "healthy") { | |
| 1407 | + const saved = await doSetHealthCheck({ | |
| 1408 | + params: { slug: integration }, | |
| 1409 | + payload: { spec: inlineSpec }, | |
| 1410 | + reactivityKeys: healthCheckWriteKeys, | |
| 1411 | + }); | |
| 1412 | + if (Exit.isSuccess(saved)) toast.success("Saved as this integration's health check"); | |
| 1413 | + } | |
| 1414 | + }; | |
| 1415 | + | |
| 1272 | 1416 | const handleOAuthConnect = async () => { |
| 1273 | 1417 | if (!method || !chosenClient) return; |
| 1274 | 1418 | // The connection is minted under the user-picked "saved to" owner, NOT the |
| @@ -1878,22 +2022,85 @@ function AddAccountModalView(props: AddAccountModalProps) { · 603 unmodified lines | ||
| 1878 | 2022 | </div> |
| 1879 | 2023 | ) |
| 1880 | 2024 | ) : ( |
| 1881 | − <CredentialValueFields | |
| 1882 | − inputs={credentialInputs} | |
| 1883 | − singleInput={singleInput} | |
| 1884 | − showLabels={isEnvMethod} | |
| 1885 | − affix={singleCredentialAffix} | |
| 1886 | − allowExternalProvider={!isEnvMethod} | |
| 1887 | − values={values} | |
| 1888 | − onValuesChange={setValues} | |
| 1889 | − origin={credentialOrigin} | |
| 1890 | − onOriginChange={(next) => { | |
| 1891 | − setCredentialOrigin(next); | |
| 1892 | − if (next === "paste") setOnePasswordItemId(""); | |
| 1893 | − }} | |
| 1894 | − onePasswordItemId={onePasswordItemId} | |
| 1895 | − onOnePasswordItemIdChange={setOnePasswordItemId} | |
| 1896 | − /> | |
| 2025 | + <div className="space-y-2"> | |
| 2026 | + <CredentialValueFields | |
| 2027 | + inputs={credentialInputs} | |
| 2028 | + singleInput={singleInput} | |
| 2029 | + showLabels={isEnvMethod} | |
| 2030 | + affix={singleCredentialAffix} | |
| 2031 | + allowExternalProvider={!isEnvMethod} | |
| 2032 | + values={values} | |
| 2033 | + onValuesChange={(next) => { | |
| 2034 | + setValues(next); | |
| 2035 | + clearKeyCheck(); | |
| 2036 | + }} | |
| 2037 | + origin={credentialOrigin} | |
| 2038 | + onOriginChange={(next) => { | |
| 2039 | + setCredentialOrigin(next); | |
| 2040 | + if (next === "paste") setOnePasswordItemId(""); | |
| 2041 | + clearKeyCheck(); | |
| 2042 | + }} | |
| 2043 | + onePasswordItemId={onePasswordItemId} | |
| 2044 | + onOnePasswordItemIdChange={(next) => { | |
| 2045 | + setOnePasswordItemId(next); | |
| 2046 | + clearKeyCheck(); | |
| 2047 | + }} | |
| 2048 | + /> | |
| 2049 | + {/* Check the key works before saving. Runs the | |
| 2050 | + integration's health check, or an operation you pick | |
| 2051 | + here (which we then save as the check). */} | |
| 2052 | + {canCheckKey ? ( | |
| 2053 | + <div className="flex flex-col gap-2"> | |
| 2054 | + {!hasHealthCheck ? ( | |
| 2055 | + <div className="space-y-2 rounded-md border border-border/60 bg-muted/20 p-3"> | |
| 2056 | + <p className="text-xs text-muted-foreground"> | |
| 2057 | + Pick a read-only operation to test the key against. We save | |
| 2058 | + it as this integration's health check. | |
| 2059 | + </p> | |
| 2060 | + <HealthCheckConfigFields | |
| 2061 | + candidates={healthCheckCandidates} | |
| 2062 | + selected={hcSelected} | |
| 2063 | + operation={hcOperation} | |
| 2064 | + onOperationChange={(next) => { | |
| 2065 | + setHcOperation(next); | |
| 2066 | + setHcArgs({}); | |
| 2067 | + clearKeyCheck(); | |
| 2068 | + }} | |
| 2069 | + args={hcArgs} | |
| 2070 | + onArgChange={(name, value) => { | |
| 2071 | + setHcArgs((prev) => ({ ...prev, [name]: value })); | |
| 2072 | + clearKeyCheck(); | |
| 2073 | + }} | |
| 2074 | + disabled={validating} | |
| 2075 | + idPrefix="connect-health-check" | |
| 2076 | + /> | |
| 2077 | + </div> | |
| 2078 | + ) : null} | |
| 2079 | + <div className="flex items-center justify-between gap-2"> | |
| 2080 | + <Button | |
| 2081 | + type="button" | |
| 2082 | + variant="outline" | |
| 2083 | + size="sm" | |
| 2084 | + disabled={ | |
| 2085 | + credentialPayloadOrigin === null || | |
| 2086 | + validating || | |
| 2087 | + !keyCheckReady | |
| 2088 | + } | |
| 2089 | + onClick={() => void handleValidate()} | |
| 2090 | + > | |
| 2091 | + {validating ? "Checking..." : "Check the key works"} | |
| 2092 | + </Button> | |
| 2093 | + <span className="text-xs text-muted-foreground"> | |
| 2094 | + Confirms the key authenticates. | |
| 2095 | + </span> | |
| 2096 | + </div> | |
| 2097 | + <KeyValidationStatus | |
| 2098 | + validating={validating} | |
| 2099 | + result={validationResult} | |
| 2100 | + /> | |
| 2101 | + </div> | |
| 2102 | + ) : null} | |
| 2103 | + </div> | |
| 1897 | 2104 | )} |
| 1898 | 2105 | {isOAuth && oauthPopup.error ? ( |
| 1899 | 2106 | <p className="text-xs text-destructive">{oauthPopup.error}</p> |
| @@ -103,7 +103,11 @@ function ComboboxContent({ · 102 unmodified lines | ||
| 103 | 103 | align={align} |
| 104 | 104 | alignOffset={alignOffset} |
| 105 | 105 | anchor={anchor} |
| 106 | − className="isolate z-50" | |
| 106 | + // `pointer-events-auto` re-enables interaction when the popup is portaled | |
| 107 | + // out of a modal dialog (Radix sets `pointer-events: none` on the body | |
| 108 | + // for modal dialogs/sheets; without this the portaled list can't be | |
| 109 | + // scrolled or clicked). Harmless outside a dialog (auto is the default). | |
| 110 | + className="isolate z-50 pointer-events-auto" | |
| 107 | 111 | > |
| 108 | 112 | <ComboboxPrimitive.Popup |
| 109 | 113 | data-slot="combobox-content" |
| @@ -268,6 +272,11 @@ export interface FreeformComboboxOption { · 158 unmodified lines | ||
| 268 | 272 | readonly description?: React.ReactNode; |
| 269 | 273 | } |
| 270 | 274 | |
| 275 | +/** How many options the popup renders at once. base-ui slices the filtered list | |
| 276 | + * to this, so a multi-thousand-operation spec stays cheap: the empty-query open | |
| 277 | + * shows the top slice, and typing narrows to the top matches. */ | |
| 278 | +const FREEFORM_COMBOBOX_LIMIT = 100; | |
| 279 | + | |
| 271 | 280 | function FreeformCombobox(props: { |
| 272 | 281 | readonly value: string; |
| 273 | 282 | readonly onValueChange: (value: string) => void; |
| @@ -277,25 +286,62 @@ function FreeformCombobox(props: { · 3 unmodified lines | ||
| 277 | 286 | readonly className?: string; |
| 278 | 287 | readonly inputClassName?: string; |
| 279 | 288 | readonly disabled?: boolean; |
| 289 | + /** Forwarded to the underlying text input so a `<Label htmlFor>` can target it | |
| 290 | + * (and tests get a stable selector). */ | |
| 291 | + readonly id?: string; | |
| 280 | 292 | }) { |
| 281 | 293 | const valueOption = props.value.trim(); |
| 282 | − const options = | |
| 283 | − valueOption.length > 0 && !props.options.some((option) => option.value === valueOption) | |
| 284 | − ? [{ value: valueOption, label: valueOption }, ...props.options] | |
| 285 | − : props.options; | |
| 294 | + const propsOptions = props.options; | |
| 295 | + const options = React.useMemo<readonly FreeformComboboxOption[]>( | |
| 296 | + () => | |
| 297 | + valueOption.length > 0 && !propsOptions.some((option) => option.value === valueOption) | |
| 298 | + ? [{ value: valueOption, label: valueOption }, ...propsOptions] | |
| 299 | + : propsOptions, | |
| 300 | + [valueOption, propsOptions], | |
| 301 | + ); | |
| 286 | 302 | const selectedValue = options.some((option) => option.value === props.value) ? props.value : null; |
| 287 | 303 | |
| 304 | + const byValue = React.useMemo(() => { | |
| 305 | + const map = new Map<string, FreeformComboboxOption>(); | |
| 306 | + for (const option of options) map.set(option.value, option); | |
| 307 | + return map; | |
| 308 | + }, [options]); | |
| 309 | + const items = React.useMemo(() => options.map((option) => option.value), [options]); | |
| 310 | + | |
| 311 | + // base-ui only filters the popup when the list renders from `items` (the | |
| 312 | + // function-child / closed-template path below); a statically-mapped list never | |
| 313 | + // narrows as you type. Match the query against the value AND its string | |
| 314 | + // label/description, so typing a summary word or the human label finds the | |
| 315 | + // option, not just its raw id. | |
| 316 | + const filter = React.useCallback( | |
| 317 | + (item: string, query: string) => { | |
| 318 | + const needle = query.trim().toLowerCase(); | |
| 319 | + if (needle === "") return true; | |
| 320 | + const option = byValue.get(item); | |
| 321 | + const haystacks = [ | |
| 322 | + item, | |
| 323 | + typeof option?.label === "string" ? option.label : "", | |
| 324 | + typeof option?.description === "string" ? option.description : "", | |
| 325 | + ]; | |
| 326 | + return haystacks.some((part) => part.toLowerCase().includes(needle)); | |
| 327 | + }, | |
| 328 | + [byValue], | |
| 329 | + ); | |
| 330 | + | |
| 288 | 331 | return ( |
| 289 | 332 | <Combobox |
| 290 | − items={options.map((option) => option.value)} | |
| 333 | + items={items} | |
| 291 | 334 | inputValue={props.value} |
| 292 | 335 | value={selectedValue} |
| 336 | + filter={filter} | |
| 337 | + limit={FREEFORM_COMBOBOX_LIMIT} | |
| 293 | 338 | onInputValueChange={props.onValueChange} |
| 294 | 339 | onValueChange={(value) => { |
| 295 | 340 | if (value !== null) props.onValueChange(value); |
| 296 | 341 | }} |
| 297 | 342 | > |
| 298 | 343 | <ComboboxInput |
| 344 | + id={props.id} | |
| 299 | 345 | placeholder={props.placeholder} |
| 300 | 346 | className={props.className} |
| 301 | 347 | inputClassName={props.inputClassName} |
| @@ -305,18 +351,21 @@ function FreeformCombobox(props: { · 3 unmodified lines | ||
| 305 | 351 | <ComboboxContent> |
| 306 | 352 | <ComboboxEmpty>{props.emptyLabel ?? "No options"}</ComboboxEmpty> |
| 307 | 353 | <ComboboxList> |
| 308 | − {options.map((option) => ( | |
| 309 | − <ComboboxItem key={option.value} value={option.value}> | |
| 310 | − <div className="min-w-0 flex-1"> | |
| 311 | − <div className="truncate">{option.label ?? option.value}</div> | |
| 312 | − {option.description && ( | |
| 313 | − <div className="mt-0.5 truncate text-[10px] text-muted-foreground"> | |
| 314 | − {option.description} | |
| 315 | − </div> | |
| 316 | − )} | |
| 317 | − </div> | |
| 318 | − </ComboboxItem> | |
| 319 | − ))} | |
| 354 | + {(item: string) => { | |
| 355 | + const option = byValue.get(item); | |
| 356 | + return ( | |
| 357 | + <ComboboxItem key={item} value={item}> | |
| 358 | + <div className="min-w-0 flex-1"> | |
| 359 | + <div className="truncate">{option?.label ?? item}</div> | |
| 360 | + {option?.description && ( | |
| 361 | + <div className="mt-0.5 truncate text-[10px] text-muted-foreground"> | |
| 362 | + {option.description} | |
| 363 | + </div> | |
| 364 | + )} | |
| 365 | + </div> | |
| 366 | + </ComboboxItem> | |
| 367 | + ); | |
| 368 | + }} | |
| 320 | 369 | </ComboboxList> |
| 321 | 370 | </ComboboxContent> |
| 322 | 371 | </Combobox> |
| @@ -37,10 +37,17 @@ function DialogOverlay({ · 36 unmodified lines | ||
| 37 | 37 | ); |
| 38 | 38 | } |
| 39 | 39 | |
| 40 | +// base-ui popups (combobox/select) portal their list OUTSIDE the dialog content, | |
| 41 | +// so clicking an option reads as an interaction outside the dialog and would | |
| 42 | +// dismiss it before the selection lands. Keep the dialog open for interactions | |
| 43 | +// that originate inside such a popup. | |
| 44 | +const PORTALED_POPUP_SELECTOR = "[data-slot='combobox-content'],[data-slot='select-content']"; | |
| 45 | + | |
| 40 | 46 | function DialogContent({ |
| 41 | 47 | className, |
| 42 | 48 | children, |
| 43 | 49 | showCloseButton = true, |
| 50 | + onInteractOutside, | |
| 44 | 51 | ...props |
| 45 | 52 | }: React.ComponentProps<typeof DialogPrimitive.Content> & { |
| 46 | 53 | showCloseButton?: boolean; |
| @@ -50,6 +57,13 @@ function DialogContent({ · 3 unmodified lines | ||
| 50 | 57 | <DialogOverlay /> |
| 51 | 58 | <DialogPrimitive.Content |
| 52 | 59 | data-slot="dialog-content" |
| 60 | + onInteractOutside={(event) => { | |
| 61 | + const target = event.detail.originalEvent.target; | |
| 62 | + if (target instanceof Element && target.closest(PORTALED_POPUP_SELECTOR)) { | |
| 63 | + event.preventDefault(); | |
| 64 | + } | |
| 65 | + onInteractOutside?.(event); | |
| 66 | + }} | |
| 53 | 67 | className={cn( |
| 54 | 68 | "fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg", |
| 55 | 69 | className, |
| @@ -0,0 +1,350 @@ | ||
| 1 | +import { useEffect, useMemo, useState } from "react"; | |
| 2 | +import { useAtomValue, useAtomSet } from "@effect/atom-react"; | |
| 3 | +import * as AsyncResult from "effect/unstable/reactivity/AsyncResult"; | |
| 4 | +import * as Exit from "effect/Exit"; | |
| 5 | +import { | |
| 6 | + type HealthCheckCandidate, | |
| 7 | + type HealthCheckSpec, | |
| 8 | + type IntegrationSlug, | |
| 9 | +} from "@executor-js/sdk/shared"; | |
| 10 | +import { toast } from "sonner"; | |
| 11 | + | |
| 12 | +import { | |
| 13 | + integrationHealthCheckAtom, | |
| 14 | + integrationHealthCheckCandidatesAtom, | |
| 15 | + setIntegrationHealthCheck, | |
| 16 | +} from "../api/atoms"; | |
| 17 | +import { healthCheckWriteKeys } from "../api/reactivity-keys"; | |
| 18 | +import { messageFromExit } from "../api/error-reporting"; | |
| 19 | +import { Button } from "./button"; | |
| 20 | +import { FreeformCombobox, type FreeformComboboxOption } from "./combobox"; | |
| 21 | +import { Input } from "./input"; | |
| 22 | +import { Label } from "./label"; | |
| 23 | +import { | |
| 24 | + Sheet, | |
| 25 | + SheetContent, | |
| 26 | + SheetDescription, | |
| 27 | + SheetFooter, | |
| 28 | + SheetHeader, | |
| 29 | + SheetTitle, | |
| 30 | +} from "./sheet"; | |
| 31 | + | |
| 32 | +// --------------------------------------------------------------------------- | |
| 33 | +// Health-check editor: the integration-level configuration for "what single | |
| 34 | +// authenticated call tells us a connection is still alive". It is the same shape | |
| 35 | +// as configuring an auth method: pick one of the integration's operations (ranked | |
| 36 | +// so the obvious read-only endpoint floats up) and optionally pin the required | |
| 37 | +// arguments (Google's People API needs `resourceName=people/me`). | |
| 38 | +// | |
| 39 | +// The check is run per-connection elsewhere (the AccountRow "Check now" probe); | |
| 40 | +// this surface only declares it. | |
| 41 | +// | |
| 42 | +// It hides itself when the owning integration exposes no candidate operations AND | |
| 43 | +// none is configured (i.e. the plugin has no health-check capability), so it | |
| 44 | +// costs nothing on integrations that can't support it. | |
| 45 | +// --------------------------------------------------------------------------- | |
| 46 | + | |
| 47 | +/** "GET /users/me" style label for a candidate, with a writes marker so a | |
| 48 | + * mutating operation picked as a health check reads as the hazard it is. */ | |
| 49 | +const candidateLabel = (candidate: HealthCheckCandidate): string => { | |
| 50 | + const head = `${candidate.method.toUpperCase()} ${candidate.operation}`; | |
| 51 | + return candidate.destructive ? `${head} (writes)` : head; | |
| 52 | +}; | |
| 53 | + | |
| 54 | +/** The summary line for the configured spec: the operation, prefixed with its | |
| 55 | + * method when we can still find it among the candidates. */ | |
| 56 | +const specSummary = ( | |
| 57 | + spec: HealthCheckSpec, | |
| 58 | + candidates: readonly HealthCheckCandidate[], | |
| 59 | +): string => { | |
| 60 | + const match = candidates.find((c) => c.operation === spec.operation); | |
| 61 | + return match ? `${match.method.toUpperCase()} ${spec.operation}` : spec.operation; | |
| 62 | +}; | |
| 63 | + | |
| 64 | +// --------------------------------------------------------------------------- | |
| 65 | +// HealthCheckConfigFields: the presentational operation + pinned-arg form, | |
| 66 | +// shared by the edit sheet and the add-integration screen so the two stay in | |
| 67 | +// lockstep. State (and the `selected` candidate) is owned by the parent; this | |
| 68 | +// component only renders and reports edits. | |
| 69 | +// --------------------------------------------------------------------------- | |
| 70 | + | |
| 71 | +function HealthCheckConfigFields(props: { | |
| 72 | + readonly candidates: readonly HealthCheckCandidate[]; | |
| 73 | + readonly selected: HealthCheckCandidate | null; | |
| 74 | + readonly operation: string; | |
| 75 | + readonly onOperationChange: (operation: string) => void; | |
| 76 | + readonly args: Record<string, string>; | |
| 77 | + readonly onArgChange: (name: string, value: string) => void; | |
| 78 | + readonly disabled?: boolean; | |
| 79 | + readonly idPrefix: string; | |
| 80 | +}) { | |
| 81 | + const { candidates, selected, operation, args, disabled, idPrefix } = props; | |
| 82 | + | |
| 83 | + const operationOptions = useMemo<FreeformComboboxOption[]>( | |
| 84 | + () => | |
| 85 | + candidates.map((c) => ({ | |
| 86 | + value: c.operation, | |
| 87 | + label: candidateLabel(c), | |
| 88 | + description: c.summary, | |
| 89 | + })), | |
| 90 | + [candidates], | |
| 91 | + ); | |
| 92 | + | |
| 93 | + const requiredParams = useMemo( | |
| 94 | + () => (selected?.parameters ?? []).filter((p) => p.required), | |
| 95 | + [selected], | |
| 96 | + ); | |
| 97 | + | |
| 98 | + return ( | |
| 99 | + <> | |
| 100 | + <div className="space-y-1.5"> | |
| 101 | + <Label htmlFor={`${idPrefix}-operation`}>Operation</Label> | |
| 102 | + <FreeformCombobox | |
| 103 | + id={`${idPrefix}-operation`} | |
| 104 | + value={operation} | |
| 105 | + onValueChange={props.onOperationChange} | |
| 106 | + options={operationOptions} | |
| 107 | + placeholder={candidates.length === 0 ? "No operations available" : "Pick an operation"} | |
| 108 | + emptyLabel="No matching operations" | |
| 109 | + disabled={disabled} | |
| 110 | + /> | |
| 111 | + {selected?.summary ? ( | |
| 112 | + <p className="text-xs text-muted-foreground">{selected.summary}</p> | |
| 113 | + ) : null} | |
| 114 | + {selected?.destructive ? ( | |
| 115 | + <p className="text-xs text-destructive"> | |
| 116 | + This operation writes data. Prefer a read-only (GET) operation for a health check. | |
| 117 | + </p> | |
| 118 | + ) : null} | |
| 119 | + </div> | |
| 120 | + | |
| 121 | + {requiredParams.length > 0 ? ( | |
| 122 | + <div className="space-y-3"> | |
| 123 | + <div className="space-y-0.5"> | |
| 124 | + <p className="text-sm font-medium">Required arguments</p> | |
| 125 | + <p className="text-xs text-muted-foreground"> | |
| 126 | + Pinned into every probe. A liveness endpoint often needs a fixed value here (for | |
| 127 | + example <span className="font-mono">resourceName</span> ={" "} | |
| 128 | + <span className="font-mono">people/me</span>). | |
| 129 | + </p> | |
| 130 | + </div> | |
| 131 | + {requiredParams.map((param) => ( | |
| 132 | + <div key={param.name} className="space-y-1.5"> | |
| 133 | + <Label htmlFor={`${idPrefix}-arg-${param.name}`}> | |
| 134 | + {param.name} | |
| 135 | + <span className="ml-1.5 text-xs font-normal text-muted-foreground"> | |
| 136 | + ({param.location}) | |
| 137 | + </span> | |
| 138 | + </Label> | |
| 139 | + <Input | |
| 140 | + id={`${idPrefix}-arg-${param.name}`} | |
| 141 | + value={args[param.name] ?? ""} | |
| 142 | + onChange={(e: React.ChangeEvent<HTMLInputElement>) => | |
| 143 | + props.onArgChange(param.name, e.target.value) | |
| 144 | + } | |
| 145 | + placeholder={param.description ?? `Value for ${param.name}`} | |
| 146 | + disabled={disabled} | |
| 147 | + /> | |
| 148 | + {param.description ? ( | |
| 149 | + <p className="text-xs text-muted-foreground">{param.description}</p> | |
| 150 | + ) : null} | |
| 151 | + </div> | |
| 152 | + ))} | |
| 153 | + </div> | |
| 154 | + ) : null} | |
| 155 | + </> | |
| 156 | + ); | |
| 157 | +} | |
| 158 | + | |
| 159 | +function HealthCheckEditorSheet(props: { | |
| 160 | + readonly integration: IntegrationSlug; | |
| 161 | + readonly spec: HealthCheckSpec | null; | |
| 162 | + readonly candidates: readonly HealthCheckCandidate[]; | |
| 163 | + readonly open: boolean; | |
| 164 | + readonly onOpenChange: (open: boolean) => void; | |
| 165 | +}) { | |
| 166 | + const { integration, spec, candidates, open, onOpenChange } = props; | |
| 167 | + const doSet = useAtomSet(setIntegrationHealthCheck, { mode: "promiseExit" }); | |
| 168 | + | |
| 169 | + const [operation, setOperation] = useState(""); | |
| 170 | + // Pinned argument values keyed by parameter name; stored as strings (the form | |
| 171 | + // input value) and trimmed/dropped when empty at save. | |
| 172 | + const [args, setArgs] = useState<Record<string, string>>({}); | |
| 173 | + const [saving, setSaving] = useState(false); | |
| 174 | + | |
| 175 | + // Re-seed the drafts from the persisted spec each time the sheet opens. | |
| 176 | + useEffect(() => { | |
| 177 | + if (!open) return; | |
| 178 | + setOperation(spec?.operation ?? candidates[0]?.operation ?? ""); | |
| 179 | + setArgs( | |
| 180 | + spec?.args | |
| 181 | + ? Object.fromEntries( | |
| 182 | + Object.entries(spec.args).map(([key, value]) => [ | |
| 183 | + key, | |
| 184 | + value == null ? "" : String(value), | |
| 185 | + ]), | |
| 186 | + ) | |
| 187 | + : {}, | |
| 188 | + ); | |
| 189 | + }, [open, spec, candidates]); | |
| 190 | + | |
| 191 | + const selected = useMemo( | |
| 192 | + () => candidates.find((c) => c.operation === operation) ?? null, | |
| 193 | + [candidates, operation], | |
| 194 | + ); | |
| 195 | + | |
| 196 | + const requiredParams = useMemo( | |
| 197 | + () => (selected?.parameters ?? []).filter((p) => p.required), | |
| 198 | + [selected], | |
| 199 | + ); | |
| 200 | + const missingRequired = requiredParams.some((p) => (args[p.name] ?? "").trim().length === 0); | |
| 201 | + | |
| 202 | + const onOperationChange = (next: string) => { | |
| 203 | + setOperation(next); | |
| 204 | + // Parameters differ per operation; drop the prior pick's pinned args so none | |
| 205 | + // dangle onto a new op. | |
| 206 | + setArgs({}); | |
| 207 | + }; | |
| 208 | + | |
| 209 | + const onArgChange = (name: string, value: string) => | |
| 210 | + setArgs((prev) => ({ ...prev, [name]: value })); | |
| 211 | + | |
| 212 | + const handleSave = async () => { | |
| 213 | + if (operation.length === 0) return; | |
| 214 | + setSaving(true); | |
| 215 | + const argEntries = Object.entries(args) | |
| 216 | + .map(([key, value]) => [key, value.trim()] as const) | |
| 217 | + .filter(([, value]) => value.length > 0); | |
| 218 | + const nextSpec: HealthCheckSpec = { | |
| 219 | + operation, | |
| 220 | + ...(argEntries.length > 0 ? { args: Object.fromEntries(argEntries) } : {}), | |
| 221 | + }; | |
| 222 | + const exit = await doSet({ | |
| 223 | + params: { slug: integration }, | |
| 224 | + payload: { spec: nextSpec }, | |
| 225 | + reactivityKeys: healthCheckWriteKeys, | |
| 226 | + }); | |
| 227 | + setSaving(false); | |
| 228 | + if (Exit.isFailure(exit)) { | |
| 229 | + toast.error(messageFromExit(exit, "Failed to save health check")); | |
| 230 | + return; | |
| 231 | + } | |
| 232 | + toast.success("Health check saved"); | |
| 233 | + onOpenChange(false); | |
| 234 | + }; | |
| 235 | + | |
| 236 | + const handleClear = async () => { | |
| 237 | + setSaving(true); | |
| 238 | + const exit = await doSet({ | |
| 239 | + params: { slug: integration }, | |
| 240 | + payload: { spec: null }, | |
| 241 | + reactivityKeys: healthCheckWriteKeys, | |
| 242 | + }); | |
| 243 | + setSaving(false); | |
| 244 | + if (Exit.isFailure(exit)) { | |
| 245 | + toast.error(messageFromExit(exit, "Failed to clear health check")); | |
| 246 | + return; | |
| 247 | + } | |
| 248 | + toast.success("Health check cleared"); | |
| 249 | + onOpenChange(false); | |
| 250 | + }; | |
| 251 | + | |
| 252 | + return ( | |
| 253 | + // Non-modal: a modal sheet's `react-remove-scroll` locks the wheel to the | |
| 254 | + // sheet subtree, so the operation combobox's portaled popup can't scroll. | |
| 255 | + <Sheet open={open} onOpenChange={onOpenChange} modal={false}> | |
| 256 | + <SheetContent side="right"> | |
| 257 | + <SheetHeader> | |
| 258 | + <SheetTitle>Health check</SheetTitle> | |
| 259 | + <SheetDescription> | |
| 260 | + One read-only call Executor runs to tell whether a connection's credential is still | |
| 261 | + alive. A 401 or 403 marks the connection expired. | |
| 262 | + </SheetDescription> | |
| 263 | + </SheetHeader> | |
| 264 | + | |
| 265 | + <div className="flex-1 space-y-5 overflow-y-auto px-4"> | |
| 266 | + <HealthCheckConfigFields | |
| 267 | + candidates={candidates} | |
| 268 | + selected={selected} | |
| 269 | + operation={operation} | |
| 270 | + onOperationChange={onOperationChange} | |
| 271 | + args={args} | |
| 272 | + onArgChange={onArgChange} | |
| 273 | + disabled={saving} | |
| 274 | + idPrefix="health-check" | |
| 275 | + /> | |
| 276 | + </div> | |
| 277 | + | |
| 278 | + <SheetFooter> | |
| 279 | + <Button | |
| 280 | + onClick={() => void handleSave()} | |
| 281 | + disabled={saving || operation.length === 0 || missingRequired} | |
| 282 | + > | |
| 283 | + {saving ? "Saving..." : "Save"} | |
| 284 | + </Button> | |
| 285 | + {spec ? ( | |
| 286 | + <Button variant="outline" onClick={() => void handleClear()} disabled={saving}> | |
| 287 | + Clear | |
| 288 | + </Button> | |
| 289 | + ) : null} | |
| 290 | + <Button variant="ghost" onClick={() => onOpenChange(false)} disabled={saving}> | |
| 291 | + Cancel | |
| 292 | + </Button> | |
| 293 | + </SheetFooter> | |
| 294 | + </SheetContent> | |
| 295 | + </Sheet> | |
| 296 | + ); | |
| 297 | +} | |
| 298 | + | |
| 299 | +export function HealthCheckEditor(props: { readonly integration: IntegrationSlug }) { | |
| 300 | + const { integration } = props; | |
| 301 | + const specResult = useAtomValue(integrationHealthCheckAtom(integration)); | |
| 302 | + const candidatesResult = useAtomValue(integrationHealthCheckCandidatesAtom(integration)); | |
| 303 | + const [open, setOpen] = useState(false); | |
| 304 | + | |
| 305 | + const spec = AsyncResult.isSuccess(specResult) ? specResult.value : null; | |
| 306 | + const candidates: readonly HealthCheckCandidate[] = AsyncResult.isSuccess(candidatesResult) | |
| 307 | + ? candidatesResult.value | |
| 308 | + : []; | |
| 309 | + | |
| 310 | + // No capability (no candidate operations) and nothing configured: render | |
| 311 | + // nothing. This also covers the still-loading window, so the section doesn't | |
| 312 | + // flash an empty shell before the candidates arrive. | |
| 313 | + if (candidates.length === 0 && spec === null) return null; | |
| 314 | + | |
| 315 | + return ( | |
| 316 | + <section className="space-y-3"> | |
| 317 | + <div className="space-y-1"> | |
| 318 | + <h3 className="text-sm font-medium">Health check</h3> | |
| 319 | + <p className="text-xs text-muted-foreground"> | |
| 320 | + A read-only call Executor runs to tell whether a connection's credential is still alive. | |
| 321 | + </p> | |
| 322 | + </div> | |
| 323 | + <div className="flex items-center justify-between gap-3 rounded-md border border-border/60 bg-muted/30 px-3 py-2.5"> | |
| 324 | + <div className="min-w-0 space-y-0.5"> | |
| 325 | + {spec ? ( | |
| 326 | + <p className="truncate font-mono text-xs text-foreground"> | |
| 327 | + {specSummary(spec, candidates)} | |
| 328 | + </p> | |
| 329 | + ) : ( | |
| 330 | + <p className="text-xs text-muted-foreground">No health check configured.</p> | |
| 331 | + )} | |
| 332 | + </div> | |
| 333 | + <Button variant="outline" size="sm" onClick={() => setOpen(true)}> | |
| 334 | + {spec ? "Edit" : "Set up"} | |
| 335 | + </Button> | |
| 336 | + </div> | |
| 337 | + <HealthCheckEditorSheet | |
| 338 | + integration={integration} | |
| 339 | + spec={spec} | |
| 340 | + candidates={candidates} | |
| 341 | + open={open} | |
| 342 | + onOpenChange={setOpen} | |
| 343 | + /> | |
| 344 | + </section> | |
| 345 | + ); | |
| 346 | +} | |
| 347 | + | |
| 348 | +// Re-exported so the add-integration screen can compose the same operation + | |
| 349 | +// pinned-arg form without the sheet chrome. | |
| 350 | +export { HealthCheckConfigFields }; | |
| @@ -38,11 +38,18 @@ function SheetOverlay({ · 37 unmodified lines | ||
| 38 | 38 | ); |
| 39 | 39 | } |
| 40 | 40 | |
| 41 | +// base-ui popups (combobox/select) portal their list OUTSIDE the dialog content, | |
| 42 | +// so clicking an option reads as an interaction outside the sheet and would | |
| 43 | +// dismiss it before the selection lands. Keep the sheet open for interactions | |
| 44 | +// that originate inside such a popup. | |
| 45 | +const PORTALED_POPUP_SELECTOR = "[data-slot='combobox-content'],[data-slot='select-content']"; | |
| 46 | + | |
| 41 | 47 | function SheetContent({ |
| 42 | 48 | className, |
| 43 | 49 | children, |
| 44 | 50 | side = "right", |
| 45 | 51 | showCloseButton = true, |
| 52 | + onInteractOutside, | |
| 46 | 53 | ...props |
| 47 | 54 | }: React.ComponentProps<typeof SheetPrimitive.Content> & { |
| 48 | 55 | side?: "top" | "right" | "bottom" | "left"; |
| @@ -53,6 +60,13 @@ function SheetContent({ · 4 unmodified lines | ||
| 53 | 60 | <SheetOverlay /> |
| 54 | 61 | <SheetPrimitive.Content |
| 55 | 62 | data-slot="sheet-content" |
| 63 | + onInteractOutside={(event) => { | |
| 64 | + const target = event.detail.originalEvent.target; | |
| 65 | + if (target instanceof Element && target.closest(PORTALED_POPUP_SELECTOR)) { | |
| 66 | + event.preventDefault(); | |
| 67 | + } | |
| 68 | + onInteractOutside?.(event); | |
| 69 | + }} | |
| 56 | 70 | className={cn( |
| 57 | 71 | "fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500", |
| 58 | 72 | side === "right" && |
| @@ -0,0 +1,39 @@ | ||
| 1 | +// Shared display strings + colors for connection health. Several surfaces (the | |
| 2 | +// AccountRow status dot, the "Check now" result, the health-check editor preview) | |
| 3 | +// render the same `HealthStatus`, so the labels and indicator colors live here: | |
| 4 | +// a rename or palette change happens in one place. Mirrors the convention of | |
| 5 | +// `policy-display.ts`. | |
| 6 | + | |
| 7 | +import type { HealthStatus } from "@executor-js/sdk/shared"; | |
| 8 | + | |
| 9 | +/** State form — badge text, indicator tooltips, "what is the current state". */ | |
| 10 | +export const HEALTH_STATUS_LABEL: Record<HealthStatus, string> = { | |
| 11 | + healthy: "Healthy", | |
| 12 | + expired: "Expired", | |
| 13 | + degraded: "Degraded", | |
| 14 | + unknown: "Unchecked", | |
| 15 | +}; | |
| 16 | + | |
| 17 | +/** Dot + ring color classes for the per-connection indicator. `unknown` is the | |
| 18 | + * neutral never-probed state; `expired` reuses the destructive token so it reads | |
| 19 | + * the same as a blocked policy. */ | |
| 20 | +export const HEALTH_INDICATOR_COLOR: Record< | |
| 21 | + HealthStatus, | |
| 22 | + { readonly dot: string; readonly ring: string } | |
| 23 | +> = { | |
| 24 | + healthy: { dot: "bg-emerald-500", ring: "ring-emerald-500/70" }, | |
| 25 | + expired: { dot: "bg-destructive", ring: "ring-destructive/70" }, | |
| 26 | + degraded: { dot: "bg-amber-500", ring: "ring-amber-500/70" }, | |
| 27 | + unknown: { dot: "bg-muted-foreground/40", ring: "ring-muted-foreground/40" }, | |
| 28 | +}; | |
| 29 | + | |
| 30 | +/** Badge variant per status — semantic color via the Badge component. */ | |
| 31 | +export const HEALTH_BADGE_VARIANT: Record< | |
| 32 | + HealthStatus, | |
| 33 | + "default" | "secondary" | "outline" | "destructive" | |
| 34 | +> = { | |
| 35 | + healthy: "secondary", | |
| 36 | + expired: "destructive", | |
| 37 | + degraded: "outline", | |
| 38 | + unknown: "outline", | |
| 39 | +}; | |
| @@ -17,6 +17,10 @@ const readOnlyMutations = new Set([ · 16 unmodified lines | ||
| 17 | 17 | "resolveSecret", |
| 18 | 18 | "detectSource", |
| 19 | 19 | "getDomainVerificationLink", |
| 20 | + // Health-check probes: they hit the live upstream and return a result, but | |
| 21 | + // persist nothing, so there is no cached query for them to invalidate. | |
| 22 | + "validateConnection", | |
| 23 | + "checkConnectionHealth", | |
| 20 | 24 | ]); |
| 21 | 25 | |
| 22 | 26 | export default { |