diff --git a/doc/observability.md b/doc/observability.md index b62a1263309..f71a6a2b304 100644 --- a/doc/observability.md +++ b/doc/observability.md @@ -443,6 +443,16 @@ evidence, unknown binding reasons, secret-provider failures, ambiguous missing secret-definition lookups remain reportable. This filter does not change task recovery, credentials, or execution policy. +AI account selection also stays local when the selection service proves a +missing responsible user, personal default, or selected connection; an +incompatible selection; or an account that needs reconnection. The service marks +the original error, and setup preserves its closed `selectionFailure` reason. +The same failed/preparing/setup/bootstrap checks apply, and resumed native runs +with persisted provider input remain reportable. The generic +`ai_connection_unavailable` wrapper alone is insufficient: database, credential +provider, controller, and unclassified errors still report. Failed runs, blocked +tasks, and account-repair actions remain unchanged. + A workspace policy conflict also stays local when the resolver proves that an explicit `local_path` or `non_git_path` project workspace has no repository URL, Git confirms the selected directory is not a repository, and the task requests diff --git a/server/src/__tests__/ai-connections.test.ts b/server/src/__tests__/ai-connections.test.ts index e7c56ecd830..57217dd2381 100644 --- a/server/src/__tests__/ai-connections.test.ts +++ b/server/src/__tests__/ai-connections.test.ts @@ -16,6 +16,7 @@ import { createDb, companies, agents, agentTaskSessions, heartbeatRuns, companyM import { startEmbeddedPostgresTestDatabase } from "@paperclipai/db/test-embedded-postgres"; import { fetchCompanyQuotaWindows } from "../services/quota-windows.js"; import { quotaCredentialRecoveryPath, quotaCredentialRecovery, quotaCredentialHash } from "../services/quota-credential-recovery.js"; +import { readAiConnectionConfigurationFailure } from "../services/ai-connection-configuration-failure.js"; import { aiConnectionService } from "../services/ai-connections.js"; import { syncConnectionCredentialBindings } from "../services/connection-credential-bindings.js"; import * as codexAdapter from "@paperclipai/adapter-codex-local/server"; @@ -60,6 +61,25 @@ beforeAll(async () => { afterAll(async () => { await database?.cleanup(); vi.unstubAllEnvs(); if (home) await rm(home, { recursive: true, force: true }); }); describe("managed AI connections", () => { + it("marks explicit AI selection rejections without changing their HTTP contract", async () => { + const owner = "selection-blocker-owner"; + await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" }); + const expectSelectionFailure = async (promise: Promise, reason: string) => { + const error = await promise.catch((error: unknown) => error); + expect(error).toMatchObject({ status: 422, details: { code: reason } }); + expect(readAiConnectionConfigurationFailure(error)).toBe(reason); + }; + await expectSelectionFailure(service.select({ ...input, userId: null }), "ai_connection_responsible_user_missing"); + await expectSelectionFailure(service.select({ ...input, userId: owner, adapterType: "codex_local" }), "ai_connection_incompatible"); + await expectSelectionFailure(service.select({ ...input, userId: owner }), "ai_connection_default_missing"); + await expectSelectionFailure(service.select({ ...input, userId: owner, binding: { + ...binding, mode: "delegated", connectionId: randomUUID(), grantId: randomUUID(), + } }), "ai_connection_missing"); + const account = await create(owner, "Selection blocker account"); + await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, account.grantId)); + await expectSelectionFailure(service.select({ ...input, userId: owner }), "ai_connection_unavailable"); + }); + it("persists first-time recovery directories before consuming a single-use token", async () => { const owner = "quota-durable-path"; await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" }); diff --git a/server/src/__tests__/heartbeat-process-recovery.test.ts b/server/src/__tests__/heartbeat-process-recovery.test.ts index 87c14e17b66..a4f6421e261 100644 --- a/server/src/__tests__/heartbeat-process-recovery.test.ts +++ b/server/src/__tests__/heartbeat-process-recovery.test.ts @@ -1,3 +1,5 @@ +import * as aiConnectionRuntime from "../services/ai-connection-runtime.js"; +import { unprocessable } from "../errors.js"; import * as executionContinuation from "../services/execution-continuation.js"; import * as environmentOrchestrator from "../services/environment-run-orchestrator.js"; import { remoteTerminationReceipt } from "../services/remote-execution-termination.js"; @@ -44,6 +46,7 @@ import { chatExternalPrincipals, chatMessageLinks, chatPublications, + companyMemberships, companySecretBindings, companySecrets, companySkills, @@ -1522,6 +1525,53 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => { return { companyId, agentId, runId, wakeupRequestId, issueId }; } + it.each(["missing_default", "database_error", "unmarked_http_error", "provider_error"] as const)( + "preserves AI configuration recovery and reports only unexpected causes: %s", async (cause) => { + const { companyId, agentId, issueId, runId, wakeupRequestId } = await seedQueuedIssueRunFixture(); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "responsible-user", status: "active", membershipRole: "member" }); + await db.update(agents).set({ runtimeConfig: { + heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 }, + aiConnection: { provider: "openai", method: "api_key", mode: "responsible_user" }, + } }).where(eq(agents.id, agentId)); + const prepare = vi.spyOn(aiConnectionRuntime, "prepareManagedAiRuntime"); + if (cause !== "missing_default") prepare.mockRejectedValueOnce( + cause === "unmarked_http_error" + ? unprocessable("Connect an account and choose your personal default", { code: "ai_connection_default_missing" }) + : new Error(cause), + ); + try { + const heartbeat = heartbeatService(db); + await heartbeat.resumeQueuedRuns(); + await waitForRunToSettle(heartbeat, runId, 5_000); + await heartbeat.waitForRunExecutionDrain(runId); + await waitForPendingRunFailureReports(); + expect(prepare).toHaveBeenCalled(); + const failed = await heartbeat.getRun(runId); + expect(failed).toMatchObject({ status: "failed", errorCode: "configuration_incomplete", + resultJson: { configurationIncomplete: { reason: "ai_connection_unavailable" }, executionRecovery: { kind: "bootstrap", providerWorkStarted: false } }, + }); + if (cause === "missing_default") { + expect(failed?.error).toBe("Connect an account and choose your personal default"); + expect(failed?.resultJson?.configurationIncomplete).toMatchObject({ selectionFailure: "ai_connection_default_missing" }); + expect(mockCaptureRunFailure).not.toHaveBeenCalled(); + } else { + expect(failed?.resultJson?.configurationIncomplete).not.toHaveProperty("selectionFailure"); + expect(mockCaptureRunFailure).toHaveBeenCalledWith(expect.objectContaining({ runId, errorCode: "configuration_incomplete" })); + } + expect(mockAdapterExecute).not.toHaveBeenCalled(); + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(issue).toMatchObject({ status: "blocked", executionRunId: null }); + const [action] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId)); + expect(action).toMatchObject({ status: "active", kind: "configuration_validation", cause: "configuration_incomplete", ownerType: "board" }); + const [wakeup] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakeupRequestId)); + expect(wakeup.status).toBe("failed"); + } finally { + prepare.mockRestore(); + await db.delete(companyMemberships).where(eq(companyMemberships.companyId, companyId)); + } + }, + ); + it.each(["timeout", "upstream", "cleanup_pending", "cleanup_pending_edited", "cleanup_pending_exhausted", "edited", "exhausted", "new_message", "no_claim", "reassigned", "superseded", "stopped"])( "settles explicit retry admission through real executor cleanup: %s", async scenario => { const { companyId, agentId, runId, issueId } = await seedQueuedIssueRunFixture(); diff --git a/server/src/services/__tests__/run-failure-report.test.ts b/server/src/services/__tests__/run-failure-report.test.ts index be38e96b93b..2b2120e99f9 100644 --- a/server/src/services/__tests__/run-failure-report.test.ts +++ b/server/src/services/__tests__/run-failure-report.test.ts @@ -283,6 +283,65 @@ describeEmbeddedPostgres("reportRunFailure", () => { expect(mockCaptureRunFailure).toHaveBeenCalledWith(expect.objectContaining({ agentAdapter: "unknown" })); }); + function aiSelectionRun(overrides: Partial = {}) { + return buildRun({ + errorCode: "configuration_incomplete", + executionStage: "preparing", + resultJson: { + configurationIncomplete: { + reason: "ai_connection_unavailable", + selectionFailure: "ai_connection_default_missing", + }, + executionRecovery: { kind: "bootstrap", providerWorkStarted: false }, + }, + ...overrides, + }); + } + + it.each([ + "ai_connection_responsible_user_missing", "ai_connection_default_missing", + "ai_connection_missing", "ai_connection_incompatible", "ai_connection_unavailable", + ])("keeps the proven AI selection blocker local: %s", async (selectionFailure) => { + await seedCompanyAndAgent(); + const run = aiSelectionRun(); + (run.resultJson!.configurationIncomplete as Record).selectionFailure = selectionFailure; + const saved = structuredClone(run); + await reportRunFailure(db, run, { phase: "setup" }); + expect(mockCaptureRunFailure).not.toHaveBeenCalled(); + expect(run).toEqual(saved); + }); + + it.each([undefined, null, {}, [], "", "database_error", "ai_connection_busy"])( + "reports AI connection wrappers without a known selection cause: %j", async (selectionFailure) => { + await seedCompanyAndAgent(); + const run = aiSelectionRun(); + (run.resultJson!.configurationIncomplete as Record).selectionFailure = selectionFailure; + await reportRunFailure(db, run, { phase: "setup" }); + expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1); + }, + ); + + it.each([ + { runtimeMode: "native", runnerProfileJson: { nativeExecutionInput: {} } }, + { status: "timed_out" }, { errorCode: "setup_failed" }, { executionStage: "executing" }, + { executionStage: null }, { exitCode: 1 }, { exitCode: 0 }, { signal: "SIGTERM" }, + { resultJson: { configurationIncomplete: { reason: "ai_connection_unavailable", selectionFailure: "ai_connection_default_missing" } } }, + { resultJson: { configurationIncomplete: { reason: "ai_connection_unavailable", selectionFailure: "ai_connection_default_missing" }, executionRecovery: { kind: "bootstrap", providerWorkStarted: true } } }, + { resultJson: { configurationIncomplete: { reason: "ai_connection_unavailable", selectionFailure: "ai_connection_default_missing" }, executionRecovery: { kind: "resume", providerWorkStarted: false } } }, + { resultJson: { configurationIncomplete: { reason: "ai_connection_unavailable", selectionFailure: "ai_connection_default_missing" }, executionRecovery: { kind: "bootstrap" } } }, + { resultJson: { configurationIncomplete: { reason: "controller_environment_unsupported", selectionFailure: "ai_connection_default_missing" }, executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } }, + ])("reports AI configuration without pre-provider selection proof: %j", async (overrides) => { + await seedCompanyAndAgent(); + await reportRunFailure(db, aiSelectionRun(overrides), { phase: "setup" }); + expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1); + }); + + it.each([undefined, "execute"] as const)("reports AI selection failures outside setup: %s", async (phase) => { + await seedCompanyAndAgent(); + await reportRunFailure(db, aiSelectionRun(), { phase }); + expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1); + }); + function missingSecretRun(overrides: Partial = {}) { return buildRun({ errorCode: "configuration_incomplete", diff --git a/server/src/services/ai-connection-configuration-failure.test.ts b/server/src/services/ai-connection-configuration-failure.test.ts new file mode 100644 index 00000000000..50e4a6a68f8 --- /dev/null +++ b/server/src/services/ai-connection-configuration-failure.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from "vitest"; +import { unprocessable } from "../errors.js"; +import { + aiConnectionConfigurationFailure, + isAiConnectionConfigurationReason, + readAiConnectionConfigurationFailure, +} from "./ai-connection-configuration-failure.js"; + +describe("AI selection failure provenance", () => { + it("preserves HTTP behavior while retaining only an owned bounded reason", () => { + const error = aiConnectionConfigurationFailure("ai_connection_default_missing", "Choose an account", { connectionId: "synthetic-connection" }); + expect(error).toMatchObject({ status: 422, message: "Choose an account", details: { + code: "ai_connection_default_missing", connectionId: "synthetic-connection", + } }); + expect(readAiConnectionConfigurationFailure(error)).toBe("ai_connection_default_missing"); + expect(Object.keys(error)).toEqual(["status", "details"]); + }); + + it.each([ + new Error("Connect an account and choose your personal default"), + unprocessable("Choose an account", { code: "ai_connection_default_missing" }), + { status: 422, details: { code: "ai_connection_default_missing" } }, + Object.assign(new Error("database failed"), { code: "configuration_incomplete" }), + null, + ])("does not infer provenance from an error name, message, or HTTP shape: %j", (error) => { + expect(readAiConnectionConfigurationFailure(error)).toBeNull(); + }); + + it.each([null, undefined, {}, [], "ai_connection_busy", "provider_error", "toString"])( + "rejects unknown or malformed persisted reasons: %j", (value) => { + expect(isAiConnectionConfigurationReason(value)).toBe(false); + }, + ); +}); diff --git a/server/src/services/ai-connection-configuration-failure.ts b/server/src/services/ai-connection-configuration-failure.ts new file mode 100644 index 00000000000..01053c24203 --- /dev/null +++ b/server/src/services/ai-connection-configuration-failure.ts @@ -0,0 +1,31 @@ +import { unprocessable } from "../errors.js"; + +const reasons = [ + "ai_connection_responsible_user_missing", + "ai_connection_default_missing", + "ai_connection_missing", + "ai_connection_incompatible", + "ai_connection_unavailable", +] as const; +type AiConnectionConfigurationReason = typeof reasons[number]; +const failures = new WeakMap(); + +/** Preserve the existing HTTP error while recording an explicit selection rejection. */ +export function aiConnectionConfigurationFailure( + reason: AiConnectionConfigurationReason, + message: string, + details: Record = {}, +) { + const error = unprocessable(message, { ...details, code: reason }); + failures.set(error, reason); + return error; +} + +/** Only owned producers supply this evidence; matching names or HTTP codes do not. */ +export function readAiConnectionConfigurationFailure(error: unknown): AiConnectionConfigurationReason | null { + return error instanceof Error ? failures.get(error) ?? null : null; +} + +export function isAiConnectionConfigurationReason(value: unknown): value is AiConnectionConfigurationReason { + return typeof value === "string" && reasons.some((reason) => reason === value); +} diff --git a/server/src/services/ai-connections.ts b/server/src/services/ai-connections.ts index 46494d580a9..e73c0c64fd7 100644 --- a/server/src/services/ai-connections.ts +++ b/server/src/services/ai-connections.ts @@ -39,6 +39,7 @@ import { type AiConnectionLoginIntent, } from "@paperclipai/shared"; import { forbidden, notFound, unprocessable } from "../errors.js"; +import { aiConnectionConfigurationFailure } from "./ai-connection-configuration-failure.js"; import { quotaCredentialRecovery, quotaCredentialHash } from "./quota-credential-recovery.js"; import { logger } from "../middleware/logger.js"; import { logActivity } from "./activity-log.js"; @@ -266,15 +267,9 @@ export function aiConnectionService(db: Db) { input.acpxAgent, ) ) - throw unprocessable( - "Select an AI connection compatible with this harness and model", - { code: "ai_connection_incompatible" }, - ); + throw aiConnectionConfigurationFailure("ai_connection_incompatible", "Select an AI connection compatible with this harness and model"); if (binding.mode === "responsible_user" && !userId) - throw unprocessable( - "This run needs a responsible user to select an AI connection", - { code: "ai_connection_responsible_user_missing" }, - ); + throw aiConnectionConfigurationFailure("ai_connection_responsible_user_missing", "This run needs a responsible user to select an AI connection"); if (userId && !(await membership(companyId, userId))) throw forbidden("The responsible user is not an active company member"); const defaultRow = @@ -298,10 +293,7 @@ export function aiConnectionService(db: Db) { ? defaultRow?.grantId : binding.grantId; if (!grantId) - throw unprocessable( - "Connect an account and choose your personal default", - { code: "ai_connection_default_missing" }, - ); + throw aiConnectionConfigurationFailure("ai_connection_default_missing", "Connect an account and choose your personal default"); const row = (await rows(companyId)).find( (r) => r.grant.id === grantId && @@ -309,9 +301,7 @@ export function aiConnectionService(db: Db) { r.connection.id === binding.connectionId), ); if (!row) - throw unprocessable("The selected AI connection is unavailable", { - code: "ai_connection_missing", - }); + throw aiConnectionConfigurationFailure("ai_connection_missing", "The selected AI connection is unavailable"); const { connection, grant } = row; const metadata = aiConnectionMetadataSchema.safeParse(connection.config.ai); if ( @@ -320,13 +310,9 @@ export function aiConnectionService(db: Db) { (binding.mode !== "responsible_user" && metadata.data.method !== binding.method) || !isAiConnectionCompatible(metadata.data, input.adapterType, input.model, input.runnerProvider, input.acpxAgent) ) - throw unprocessable("The selected AI connection is incompatible", { - code: "ai_connection_incompatible", - }); + throw aiConnectionConfigurationFailure("ai_connection_incompatible", "The selected AI connection is incompatible"); if (aiSubscriptionNeedsIsolatedLogin(connection.config)) - throw unprocessable("Reconnect this subscription with a separate sign-in to protect your existing terminal login.", { - code: "ai_connection_unavailable", connectionId: connection.id, - }); + throw aiConnectionConfigurationFailure("ai_connection_unavailable", "Reconnect this subscription with a separate sign-in to protect your existing terminal login.", { connectionId: connection.id }); if ( grant.status !== "active" || !connection.enabled || @@ -337,10 +323,7 @@ export function aiConnectionService(db: Db) { connection.config.aiLegacyAdoption === true )) ) - throw unprocessable("Reconnect or validate the selected AI account", { - code: "ai_connection_unavailable", - connectionId: connection.id, - }); + throw aiConnectionConfigurationFailure("ai_connection_unavailable", "Reconnect or validate the selected AI account", { connectionId: connection.id }); if ( grant.kind === "user" && !(await membership(companyId, grant.subjectUserId)) diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index efc951317f4..a3a8969166a 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -537,6 +537,7 @@ import { emitAgentTaskRun, emitAgentTaskRunById, } from "./agent-task-run-telemetry.js"; +import { readAiConnectionConfigurationFailure } from "./ai-connection-configuration-failure.js"; import { reportRunFailure } from "./run-failure-report.js"; import { performance } from "node:perf_hooks"; import { buildProcessLossDiagnostic } from "./process-loss-diagnostics.js"; @@ -11870,6 +11871,8 @@ export function heartbeatService( } throw new ConfigurationIncompleteFailure(error instanceof Error ? error.message : "Configure this agent’s AI connection", { configurationIncomplete: { reason: "ai_connection_unavailable", companyId: agent.companyId, agentId: agent.id, responsibleUserId, + ...(!persistedNativeExecutionInput && readAiConnectionConfigurationFailure(error) + ? { selectionFailure: readAiConnectionConfigurationFailure(error) } : {}), provider: aiBinding.provider, method: aiBinding.method, actionUrl: `/agents/${agent.id}/runtime`, fingerprint: `ai:${agent.id}:${responsibleUserId}:${JSON.stringify(aiBinding)}` }, }); diff --git a/server/src/services/run-failure-report.ts b/server/src/services/run-failure-report.ts index d44a1329280..a059bf523d0 100644 --- a/server/src/services/run-failure-report.ts +++ b/server/src/services/run-failure-report.ts @@ -12,6 +12,7 @@ import { import { logger } from "../middleware/logger.js"; import { isUnexpectedRunCancellation } from "./run-cancellation.js"; import { readConnectionFailure, type ConnectionFailure } from "@paperclipai/adapter-utils/connection-failure"; +import { isAiConnectionConfigurationReason } from "./ai-connection-configuration-failure.js"; type HeartbeatRun = typeof heartbeatRuns.$inferSelect; @@ -47,6 +48,22 @@ function asRecord(value: unknown): Record | null { : null; } +/** An owned AI selection rejection before dispatch, not its broad catch wrapper. */ +function isAiConnectionSelectionBlocker(run: HeartbeatRun, options: RunFailureReportOptions): boolean { + // Resumed native input may already have provider effects, even during preparation. + if (run.runtimeMode === "native" && asRecord(run.runnerProfileJson)?.nativeExecutionInput !== undefined) return false; + if ( + run.status !== "failed" || run.errorCode !== "configuration_incomplete" || + run.executionStage !== "preparing" || options.phase !== "setup" || + run.exitCode != null || run.signal != null + ) return false; + const configuration = asRecord(run.resultJson?.configurationIncomplete); + const recovery = asRecord(run.resultJson?.executionRecovery); + return configuration?.reason === "ai_connection_unavailable" && + isAiConnectionConfigurationReason(configuration.selectionFailure) && + recovery?.kind === "bootstrap" && recovery.providerWorkStarted === false; +} + /** A known owner action before dispatch, not a secret-provider or runtime failure. */ function isMissingSecretConfigurationBlocker(run: HeartbeatRun, options: RunFailureReportOptions): boolean { if ( @@ -162,6 +179,7 @@ export function reportRunFailure(db: Db, run: HeartbeatRun, options: RunFailureR if (!isRunFailureStatus(run.status)) return Promise.resolve(); if (run.status === "cancelled" && !isUnexpectedRunCancellation(run)) return Promise.resolve(); if (isMissingSecretConfigurationBlocker(run, options)) return Promise.resolve(); + if (isAiConnectionSelectionBlocker(run, options)) return Promise.resolve(); if (isLocalPathWorkspaceConfigurationBlocker(run, options)) return Promise.resolve(); if (isGitConnectionFailure(run, options)) return Promise.resolve(); const runStatus = run.status;