:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(provisioning): stop the agentic consent page dead-ending on confirm (#88883)
posthog[bot]f492da80225c
diff --git a/frontend/src/scenes/agentic/agenticAuthorizeLogic.test.ts b/frontend/src/scenes/agentic/agenticAuthorizeLogic.test.tsnew file mode 100644index 000000000000..8e579281095a--- /dev/null+++ b/frontend/src/scenes/agentic/agenticAuthorizeLogic.test.ts@@ -0,0 +1,88 @@+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { agenticAuthorizeLogic } from './agenticAuthorizeLogic'++jest.mock('posthog-js')++describe('agenticAuthorizeLogic', () => {+ let logic: ReturnType<typeof agenticAuthorizeLogic.build>+ let errorToast: jest.SpyInstance+ let confirmResponse: [number, any?]++ const startConfirm = (): void => {+ logic = agenticAuthorizeLogic()+ logic.mount()+ logic.actions.setState('valid_state')+ logic.actions.setAgenticAuthorizationValues({ scoped_organizations: ['org-1'], scoped_teams: [1] })+ logic.actions.submitAgenticAuthorization()+ }++ beforeEach(() => {+ errorToast = jest.spyOn(lemonToast, 'error').mockReturnValue('id')+ useMocks({+ get: {+ '/api/projects': () => [200, { results: [] }],+ },+ post: {+ '/api/agentic/authorize/confirm/': () => confirmResponse,+ },+ })+ initKeaTests()+ })++ afterEach(() => {+ errorToast.mockRestore()+ logic?.unmount()+ })++ it.each<[string, [number, any?]]>([+ ['a 200 with an empty object body', [200, {}]],+ ['a 204 with no body', [204]],+ ])('surfaces an error and stops submitting when confirm returns %s', async (_label, response) => {+ confirmResponse = response+ startConfirm()++ await expectLogic(logic).toDispatchActions(['submitAgenticAuthorizationFailure']).toMatchValues({+ isAgenticAuthorizationSubmitting: false,+ })++ expect(errorToast).toHaveBeenCalledWith('Something went wrong while authorizing. Try again.', expect.anything())+ expect(posthog.capture).toHaveBeenCalledWith('agentic authorize confirm failed', {+ reason: 'missing_redirect_url',+ retryable: true,+ })+ })++ it.each([+ [+ 'expired_or_invalid_state',+ 400,+ 'This authorization request expired. Start it again from the app that sent you here.',+ ],+ ['team_not_accessible', 403, 'You do not have access to that project. Pick a project you can access.'],+ [+ 'partner_deactivated',+ 403,+ 'the requesting app is no longer active, so PostHog cannot finish the authorization.',+ ],+ ])('maps the %s error to a specific message', async (code, status, message) => {+ confirmResponse = [status as number, { error: code }]+ startConfirm()++ await expectLogic(logic).toDispatchActions(['submitAgenticAuthorizationFailure']).toMatchValues({+ isAgenticAuthorizationSubmitting: false,+ })++ expect(errorToast).toHaveBeenCalledWith(message, expect.anything())+ expect(posthog.capture).toHaveBeenCalledWith('agentic authorize confirm failed', {+ reason: code,+ retryable: expect.any(Boolean),+ })+ })+})diff --git a/frontend/src/scenes/agentic/agenticAuthorizeLogic.ts b/frontend/src/scenes/agentic/agenticAuthorizeLogic.tsindex 0eb7aacfddb0..dc32b12de24d 100644--- a/frontend/src/scenes/agentic/agenticAuthorizeLogic.ts+++ b/frontend/src/scenes/agentic/agenticAuthorizeLogic.ts@@ -3,8 +3,9 @@ import { forms } from 'kea-forms'import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'import { loaders } from 'kea-loaders'import { urlToAction } from 'kea-router'+import posthog from 'posthog-js'-import api from 'lib/api'+import api, { ApiError, isAbortError } from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { getMinimumEquivalentScopes, getScopeDescription } from 'lib/scopes'import { userLogic } from 'scenes/userLogic'@@ -17,6 +18,89 @@ export type AgenticAuthorizationFormValues = {access_type: 'teams'}+// A stuck confirm request left the button spinning with no way out, so bound it.+const CONFIRM_TIMEOUT_MS = 20000++interface ConfirmFailure {+ reason: string+ message: string+ retryable: boolean+}++// Turn a confirm failure into a specific reason the user can act on. The server returns a+// plain { error: code } body; a timeout aborts the request before any body arrives.+function describeConfirmFailure(error: unknown, partnerName: string): ConfirmFailure {+ if (isAbortError(error)) {+ return {+ reason: 'timeout',+ message: 'Authorizing timed out. Check your connection and try again.',+ retryable: true,+ }+ }++ const code = error instanceof ApiError ? error.data?.error : undefined++ switch (code) {+ case 'expired_or_invalid_state':+ return {+ reason: code,+ message: 'This authorization request expired. Start it again from the app that sent you here.',+ retryable: false,+ }+ case 'email_mismatch':+ return {+ reason: code,+ message:+ 'You are signed in with a different account than the one that started this request. Sign in with the matching account, then start again.',+ retryable: false,+ }+ case 'team_not_found':+ return {+ reason: code,+ message: 'That project no longer exists. Pick a different project.',+ retryable: true,+ }+ case 'team_not_accessible':+ return {+ reason: code,+ message: 'You do not have access to that project. Pick a project you can access.',+ retryable: true,+ }+ case 'partner_deactivated':+ return {+ reason: code,+ message: `${partnerName} is no longer active, so PostHog cannot finish the authorization.`,+ retryable: false,+ }+ case 'missing_callback':+ return {+ reason: code,+ message: `${partnerName} has no redirect URL set, so PostHog cannot finish. Contact ${partnerName}.`,+ retryable: false,+ }+ default:+ return {+ reason: typeof code === 'string' ? code : 'unknown',+ message: 'Something went wrong while authorizing. Try again.',+ retryable: true,+ }+ }+}++// The consent page emitted no client telemetry, so a hung confirm left no trace. Record the+// reason and give the user a next step: retry when it may still work, restart when it will not.+function presentConfirmFailure(failure: ConfirmFailure, onRetry: () => void): void {+ posthog.capture('agentic authorize confirm failed', {+ reason: failure.reason,+ retryable: failure.retryable,+ })+ lemonToast.error(failure.message, {+ button: failure.retryable+ ? { label: 'Try again', action: onRetry }+ : { label: 'Start over', action: () => window.location.reload() },+ })+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface agenticAuthorizeLogicValues {user: UserType | null // userLogic@@ -194,7 +278,7 @@ export const agenticAuthorizeLogic = kea<agenticAuthorizeLogicType>([},],}),- forms(({ values }) => ({+ forms(({ actions, values }) => ({agenticAuthorization: {defaults: {scoped_organizations: [],@@ -206,19 +290,43 @@ export const agenticAuthorizeLogic = kea<agenticAuthorizeLogicType>([scoped_teams: !scoped_teams?.length ? ('Select a project' as any) : undefined,}),submit: async (formValues: AgenticAuthorizationFormValues) => {- try {- const response = await api.create('api/agentic/authorize/confirm/', {- state: values.state,- team_id: formValues.scoped_teams[0],- })+ const controller = new AbortController()+ const timeoutId = window.setTimeout(() => controller.abort(), CONFIRM_TIMEOUT_MS)- if (response.redirect_url) {- window.location.href = response.redirect_url- }- } catch (error: any) {- lemonToast.error('Something went wrong while authorizing')+ let response+ try {+ response = await api.create(+ 'api/agentic/authorize/confirm/',+ { state: values.state, team_id: formValues.scoped_teams[0] },+ { signal: controller.signal }+ )+ } catch (error) {+ presentConfirmFailure(+ describeConfirmFailure(error, values.partnerName),+ actions.submitAgenticAuthorization+ )throw error+ } finally {+ window.clearTimeout(timeoutId)}++ if (response?.redirect_url) {+ window.location.href = response.redirect_url+ return+ }++ // A 2xx with no redirect_url dead-ended the page silently; treat it as a failure.+ // An empty body (204, or a gateway answering 2xx with nothing) parses to a null+ // response, so read redirect_url optionally to route that through here too.+ presentConfirmFailure(+ {+ reason: 'missing_redirect_url',+ message: 'Something went wrong while authorizing. Try again.',+ retryable: true,+ },+ actions.submitAgenticAuthorization+ )+ throw new Error('Authorize confirm returned no redirect URL')},},})),