Skip to content

: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.

chore(desktop): remove invite codes (#89004)

Jonathan Mieloo7e924acac164
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index c01c67317cad..098b88c0726b 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -152,8 +152,6 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"Artifact",
"BatchExportLogEntry",
"BatchExportRun",
- "CodeInvite",
- "CodeInviteRedemption",
# Comment↔Slack-thread mirror mapping — looked up by source_comment FK or
# (scope, item_id) within team scope, and by internally-generated task-arg id;
# never by user-supplied CommentSlackThread id through an API. Fail-closed via
@@ -371,8 +369,6 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
# --- Other models missing direct team_id ---
"BatchExportDestination", # via Integration
"BatchExportRun", # via BatchExport
- "CodeInvite", # user-scoped but stores team data
- "CodeInviteRedemption", # via CodeInvite
"SandboxSnapshot", # via Integration
"SlackUserProfileCache", # via Integration
"SlackSettings", # via Integration
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index 28d1cae3d5eb..7e1ab2f1e847 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -1347,11 +1347,6 @@ class SharePasswordThrottle(_SharedLinkAtomicThrottle):
rate = "10/minute"
-class CodeInviteThrottle(UserRateThrottle):
- scope = "code_invite"
- rate = "20000/hour"
-
-
class RunSavedQueryRateThrottle(PersonalApiKeyRateThrottle):
# Rate limit running a saved query per saved query per team.
# Prevents agents from running the same query repeatedly without reason.
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index c4975c5775a6..447823d811a2 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -4275,7 +4275,6 @@ export namespace Schemas {
created_at: string;
updated_at: string;
};
- export type CodeInviteRedeemRequest = { code: string };
export type CodexRuntimeAdapterEnum = "codex";
export type CodexTaskRunCreateSchemaInitialPermissionModeEnum = "plan" | "auto" | "read-only" | "full-access";
export type CodexTaskRunCreateSchema = {
diff --git a/products/desktop/packages/core/src/auth/auth.test.ts b/products/desktop/packages/core/src/auth/auth.test.ts
index 752fd9fad9a4..f04d7b941cfa 100644
--- a/products/desktop/packages/core/src/auth/auth.test.ts
+++ b/products/desktop/packages/core/src/auth/auth.test.ts
@@ -161,7 +161,6 @@ describe("AuthService", () => {
{ name: string; projects: { id: number; name: string }[] }
>;
desktopAccessResponse?: (url: string) => Response;
- redeemInviteCodeResponse?: () => Response;
} = {},
) => {
const accountKey =
@@ -205,13 +204,6 @@ describe("AuthService", () => {
} as unknown as Response;
}
- if (
- url.includes("/api/code/invites/redeem/") &&
- options.redeemInviteCodeResponse
- ) {
- return options.redeemInviteCodeResponse();
- }
-
if (options.desktopAccessResponse) {
return options.desktopAccessResponse(url);
}
@@ -2320,33 +2312,6 @@ describe("AuthService", () => {
});
});
- it("rechecks access after redeeming a legacy invite code", async () => {
- let redeemed = false;
- stubAuthFetch({
- redeemInviteCodeResponse: () => {
- redeemed = true;
- return okBody({ success: true });
- },
- desktopAccessResponse: () =>
- okBody(
- redeemed
- ? { allowed: true, reason: null }
- : { allowed: false, reason: null },
- ),
- });
-
- await service.initialize();
- expect(service.getState().desktopAccess.status).toBe("blocked");
-
- const state = await service.redeemInviteCode("test-code");
-
- expect(state.desktopAccess).toEqual({
- projectId: 42,
- status: "allowed",
- reason: null,
- });
- });
-
it.each([
{
name: "keeps the current result on screen while a refresh for the same account rechecks it",
diff --git a/products/desktop/packages/core/src/auth/auth.ts b/products/desktop/packages/core/src/auth/auth.ts
index c6501710a513..08037be0f179 100644
--- a/products/desktop/packages/core/src/auth/auth.ts
+++ b/products/desktop/packages/core/src/auth/auth.ts
@@ -264,29 +264,6 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {
return response;
}
- async redeemInviteCode(code: string): Promise<AuthState> {
- const { apiHost } = await this.getValidAccessToken();
- const response = await this.authenticatedFetch(
- fetch,
- `${apiHost}/api/code/invites/redeem/`,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ code }),
- },
- );
-
- const data = (await response.json().catch(() => ({}))) as {
- success?: boolean;
- error?: string;
- };
-
- if (!response.ok || !data.success) {
- throw new Error(data.error || "Failed to redeem invite code");
- }
-
- return this.retryDesktopAccess();
- }
async retryDesktopAccess(): Promise<AuthState> {
await this.initialize();
const session = await this.ensureValidSession();
diff --git a/products/desktop/packages/core/src/auth/schemas.ts b/products/desktop/packages/core/src/auth/schemas.ts
index 2e6567697fa1..9f582482041e 100644
--- a/products/desktop/packages/core/src/auth/schemas.ts
+++ b/products/desktop/packages/core/src/auth/schemas.ts
@@ -139,10 +139,6 @@ export const loginOutput = z.object({
});
export type LoginOutput = z.infer<typeof loginOutput>;
-export const redeemInviteCodeInput = z.object({
- code: z.string().min(1),
-});
-
export const selectProjectInput = z.object({
projectId: z.number(),
});
diff --git a/products/desktop/packages/host-router/src/routers/auth.router.ts b/products/desktop/packages/host-router/src/routers/auth.router.ts
index 5c9144df239c..5415f1978e23 100644
--- a/products/desktop/packages/host-router/src/routers/auth.router.ts
+++ b/products/desktop/packages/host-router/src/routers/auth.router.ts
@@ -5,7 +5,6 @@ import {
authStateSchema,
loginInput,
loginOutput,
- redeemInviteCodeInput,
selectProjectInput,
switchOrgInput,
validAccessTokenOutput,
@@ -73,13 +72,6 @@ export const authRouter = router({
ctx.container.get<AuthService>(AUTH_SERVICE).switchOrg(input.orgId),
),
- redeemInviteCode: publicProcedure
- .input(redeemInviteCodeInput)
- .output(authStateSchema)
- .mutation(async ({ ctx, input }) =>
- ctx.container.get<AuthService>(AUTH_SERVICE).redeemInviteCode(input.code),
- ),
-
retryDesktopAccess: publicProcedure
.output(authStateSchema)
.mutation(async ({ ctx }) =>
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index d5c3b2eaf9b3..c95367f556b1 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -479,7 +479,6 @@ export interface TaskFeedbackProperties {
// Onboarding events
export type OnboardingStepId =
| "project-select"
- | "invite-code"
| "consent"
| "connect-github"
| "install-cli"
@@ -519,11 +518,6 @@ export interface OnboardingProjectSelectedProperties {
had_multiple_projects: boolean;
}
-export interface OnboardingInviteCodeSubmittedProperties {
- success: boolean;
- error_type?: string;
-}
-
export interface OnboardingFolderSelectedProperties {
has_git_remote: boolean;
repository_provider: RepositoryProvider;
@@ -1458,7 +1452,6 @@ export const ANALYTICS_EVENTS = {
ONBOARDING_STEP_SKIPPED: "Onboarding step skipped",
ONBOARDING_SIGN_IN_INITIATED: "Onboarding sign in initiated",
ONBOARDING_PROJECT_SELECTED: "Onboarding project selected",
- ONBOARDING_INVITE_CODE_SUBMITTED: "Onboarding invite code submitted",
ONBOARDING_FOLDER_SELECTED: "Onboarding folder selected",
ONBOARDING_GITHUB_CONNECT_STARTED: "Onboarding github connect started",
ONBOARDING_GITHUB_CONNECT_FAILED: "Onboarding github connect failed",
@@ -1650,7 +1643,6 @@ export type EventPropertyMap = {
[ANALYTICS_EVENTS.ONBOARDING_STEP_SKIPPED]: OnboardingStepSkippedProperties;
[ANALYTICS_EVENTS.ONBOARDING_SIGN_IN_INITIATED]: OnboardingSignInInitiatedProperties;
[ANALYTICS_EVENTS.ONBOARDING_PROJECT_SELECTED]: OnboardingProjectSelectedProperties;
- [ANALYTICS_EVENTS.ONBOARDING_INVITE_CODE_SUBMITTED]: OnboardingInviteCodeSubmittedProperties;
[ANALYTICS_EVENTS.ONBOARDING_FOLDER_SELECTED]: OnboardingFolderSelectedProperties;
[ANALYTICS_EVENTS.ONBOARDING_GITHUB_CONNECT_STARTED]: OnboardingGithubConnectStartedProperties;
[ANALYTICS_EVENTS.ONBOARDING_GITHUB_CONNECT_FAILED]: OnboardingGithubConnectFailedProperties;
diff --git a/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.stories.tsx b/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.stories.tsx
index bd85c14a7e6b..c5fd0c1c5cd7 100644
--- a/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.stories.tsx
+++ b/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.stories.tsx
@@ -25,13 +25,10 @@ const meta = {
currentProjectId: 1,
isSwitching: false,
isRetrying: false,
- isRedeemingInviteCode: false,
isLoggingOut: false,
switchError: null,
- redemptionError: null,
onSelectOrganization: fn(),
onSelectProject: fn(),
- onRedeemInviteCode: fn(),
onRetry: fn(),
onLogout: fn(),
onOpenSupport: fn(),
@@ -49,12 +46,6 @@ export const PrepaidCredits: Story = {
},
};
-export const LegacyInviteCode: Story = {
- args: {
- access: { projectId: 1, status: "blocked", reason: null },
- },
-};
-
export const TechnicalError: Story = {
args: {
access: { projectId: 1, status: "error", reason: null },
diff --git a/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.test.tsx b/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.test.tsx
index d3f78862d1ab..c4e3fe12f02c 100644
--- a/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.test.tsx
+++ b/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.test.tsx
@@ -28,7 +28,6 @@ function renderScreen(
) {
const onSelectOrganization = vi.fn();
const onSelectProject = vi.fn();
- const onRedeemInviteCode = vi.fn();
const onRetry = vi.fn();
const onLogout = vi.fn();
const onOpenSupport = vi.fn();
@@ -40,13 +39,10 @@ function renderScreen(
currentProjectId={1}
isSwitching={false}
isRetrying={false}
- isRedeemingInviteCode={false}
isLoggingOut={false}
switchError={null}
- redemptionError={null}
onSelectOrganization={onSelectOrganization}
onSelectProject={onSelectProject}
- onRedeemInviteCode={onRedeemInviteCode}
onRetry={onRetry}
onLogout={onLogout}
onOpenSupport={onOpenSupport}
@@ -56,7 +52,6 @@ function renderScreen(
...result,
onSelectOrganization,
onSelectProject,
- onRedeemInviteCode,
onRetry,
onLogout,
onOpenSupport,
@@ -75,21 +70,6 @@ describe("DesktopAccessScreen", () => {
expect(screen.getByText("Website")).toBeInTheDocument();
});
- it("preserves invite-code redemption for a legacy denial", async () => {
- const user = userEvent.setup();
- const { onRedeemInviteCode } = renderScreen({
- projectId: 1,
- status: "blocked",
- reason: null,
- });
-
- expect(screen.getByText("Enter your invite code")).toBeInTheDocument();
- await user.type(screen.getByLabelText("Invite code"), "INVITE");
- await user.click(screen.getByText("Redeem invite code"));
-
- expect(onRedeemInviteCode).toHaveBeenCalledWith("INVITE");
- });
-
it.each([
[{ projectId: 1, status: "error", reason: null }, "Try again"],
[
diff --git a/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.tsx b/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.tsx
index f58c8765e750..76bfc2807aec 100644
--- a/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.tsx
+++ b/products/desktop/packages/ui/src/features/auth/components/DesktopAccessScreen.tsx
@@ -2,7 +2,6 @@ import {
ArrowClockwise,
CaretDown,
Coins,
- Key,
RocketLaunch,
SignOut,
WarningCircle,
@@ -25,7 +24,6 @@ import {
EmptyTitle,
Field,
FieldLabel,
- Input,
Spinner,
} from "@posthog/quill";
import { FullScreenLayout } from "@posthog/ui/primitives/FullScreenLayout";
@@ -67,13 +65,10 @@ interface DesktopAccessScreenProps {
currentProjectId: number | null;
isSwitching: boolean;
isRetrying: boolean;
- isRedeemingInviteCode: boolean;
isLoggingOut: boolean;
switchError: string | null;
- redemptionError: string | null;
onSelectOrganization: (organizationId: string) => void;
onSelectProject: (projectId: number) => void;
- onRedeemInviteCode: (inviteCode: string) => void;
onRetry: () => void;
onLogout: () => void;
onOpenSupport: () => void;
@@ -86,20 +81,16 @@ export function DesktopAccessScreen({
currentProjectId,
isSwitching,
isRetrying,
- isRedeemingInviteCode,
isLoggingOut,
switchError,
- redemptionError,
onSelectOrganization,
onSelectProject,
- onRedeemInviteCode,
onRetry,
onLogout,
onOpenSupport,
}: DesktopAccessScreenProps) {
const [organizationOpen, setOrganizationOpen] = useState(false);
const [projectOpen, setProjectOpen] = useState(false);
- const [inviteCode, setInviteCode] = useState("");
const organizationAnchorRef = useRef<HTMLButtonElement>(null);
const projectAnchorRef = useRef<HTMLButtonElement>(null);
@@ -123,18 +114,14 @@ export function DesktopAccessScreen({
null;
const selectedProject =
projects.find((project) => project.id === currentProjectId) ?? null;
- const controlsDisabled =
- isSwitching || isRedeemingInviteCode || access.status === "checking";
- const isLegacyAccessRequired =
- access.status === "blocked" && access.reason === null;
+ const controlsDisabled = isSwitching || access.status === "checking";
const blockedContent = access.reason
? BLOCKED_CONTENT[access.reason]
: {
- icon: <Key />,
- title: "Enter your invite code",
- description:
- "This organization needs an invite code to use PostHog Desktop. Enter one below or select another organization.",
+ icon: <WarningCircle />,
+ title: "Desktop isn't available for this organization",
+ description: "Select another organization or project to continue.",
};
const isTechnicalError = access.status === "error";
const icon = isTechnicalError ? <WarningCircle /> : blockedContent?.icon;
@@ -150,9 +137,7 @@ export function DesktopAccessScreen({
variant="link-muted"
size="sm"
loading={isLoggingOut}
- disabled={
- isLoggingOut || isSwitching || isRetrying || isRedeemingInviteCode
- }
+ disabled={isLoggingOut || isSwitching || isRetrying}
onClick={onLogout}
data-attr="desktop-access-logout"
>
@@ -172,49 +157,6 @@ export function DesktopAccessScreen({
<EmptyDescription>{description}</EmptyDescription>
</EmptyHeader>
<EmptyContent className="w-full max-w-md gap-4">
- {isLegacyAccessRequired && (
- <form
- className="flex w-full flex-col gap-2"
- onSubmit={(event) => {
- event.preventDefault();
- onRedeemInviteCode(inviteCode.trim());
- }}
- >
- <Field>
- <FieldLabel htmlFor="desktop-access-invite-code">
- Invite code
- </FieldLabel>
- <Input
- id="desktop-access-invite-code"
- value={inviteCode}
- onChange={(event) =>
- setInviteCode(event.currentTarget.value)
- }
- disabled={isRedeemingInviteCode || isSwitching}
- autoComplete="off"
- />
- </Field>
- {redemptionError && (
- <p role="alert" className="text-destructive text-sm">
- {redemptionError}
- </p>
- )}
- <Button
- type="submit"
- variant="primary"
- loading={isRedeemingInviteCode}
- disabled={
- isRedeemingInviteCode ||
- isSwitching ||
- inviteCode.trim().length === 0
- }
- data-attr="desktop-access-redeem-invite-code"
- >
- Redeem invite code
- </Button>
- </form>
- )}
-
<div className="flex w-full flex-col gap-4">
<Field className="min-w-0">
<FieldLabel htmlFor="desktop-access-organization">
@@ -359,18 +301,16 @@ export function DesktopAccessScreen({
</p>
)}
- {!isLegacyAccessRequired && (
- <Button
- variant="primary"
- loading={isRetrying}
- disabled={isRetrying || isSwitching}
- onClick={onRetry}
- data-attr="desktop-access-retry"
- >
- <ArrowClockwise />
- {isTechnicalError ? "Try again" : "Check again"}
- </Button>
- )}
+ <Button
+ variant="primary"
+ loading={isRetrying}
+ disabled={isRetrying || isSwitching}
+ onClick={onRetry}
+ data-attr="desktop-access-retry"
+ >
+ <ArrowClockwise />
+ {isTechnicalError ? "Try again" : "Check again"}
+ </Button>
</EmptyContent>
</Empty>
</div>
diff --git a/products/desktop/packages/ui/src/features/auth/useAuthMutations.ts b/products/desktop/packages/ui/src/features/auth/useAuthMutations.ts
index 340831fa1cb3..b0531b442474 100644
--- a/products/desktop/packages/ui/src/features/auth/useAuthMutations.ts
+++ b/products/desktop/packages/ui/src/features/auth/useAuthMutations.ts
@@ -51,14 +51,6 @@ export function useSwitchOrgMutation() {
});
}
-export function useRedeemInviteCodeMutation() {
- const hostClient = useHostTRPCClient();
- return useMutation({
- mutationFn: (code: string) =>
- hostClient.auth.redeemInviteCode.mutate({ code }),
- });
-}
-
export function useRetryDesktopAccessMutation() {
const hostClient = useHostTRPCClient();
return useMutation({
diff --git a/products/desktop/packages/ui/src/shell/App.tsx b/products/desktop/packages/ui/src/shell/App.tsx
index e5fac98a2a98..278a3502a9db 100644
--- a/products/desktop/packages/ui/src/shell/App.tsx
+++ b/products/desktop/packages/ui/src/shell/App.tsx
@@ -8,7 +8,6 @@ import { DesktopAccessScreen } from "@posthog/ui/features/auth/components/Deskto
import { ScopeReauthPrompt } from "@posthog/ui/features/auth/components/ScopeReauthPrompt";
import {
useLogoutMutation,
- useRedeemInviteCodeMutation,
useRetryDesktopAccessMutation,
useSelectProjectMutation,
useSwitchOrgMutation,
@@ -63,7 +62,6 @@ function App({ devToolbar }: AppProps) {
const selectProjectMutation = useSelectProjectMutation();
const switchOrgMutation = useSwitchOrgMutation();
const retryDesktopAccessMutation = useRetryDesktopAccessMutation();
- const redeemInviteCodeMutation = useRedeemInviteCodeMutation();
const logoutMutation = useLogoutMutation();
const desktopAccessIsCurrent =
desktopAccess.projectId === authState.currentProjectId;
@@ -242,19 +240,14 @@ function App({ devToolbar }: AppProps) {
selectProjectMutation.isPending || switchOrgMutation.isPending
}
isRetrying={retryDesktopAccessMutation.isPending}
- isRedeemingInviteCode={redeemInviteCodeMutation.isPending}
isLoggingOut={logoutMutation.isPending}
switchError={switchError}
- redemptionError={redeemInviteCodeMutation.error?.message ?? null}
onSelectOrganization={(organizationId) =>
switchOrgMutation.mutate(organizationId)
}
onSelectProject={(projectId) =>
selectProjectMutation.mutate(projectId)
}
- onRedeemInviteCode={(inviteCode) =>
- redeemInviteCodeMutation.mutate(inviteCode)
- }
onRetry={() => retryDesktopAccessMutation.mutate()}
onLogout={() => logoutMutation.mutate()}
onOpenSupport={() => openExternalUrl(EXTERNAL_LINKS.talkToHuman)}
diff --git a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts
index 8b58b9872be1..4ca9aa2cca40 100644
--- a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts
+++ b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts
@@ -443,7 +443,6 @@ export function getFeatureFlagVariant(flagKey: string): string | undefined {
/**
* Reload feature flags from the server.
- * Useful after a person property change (e.g., invite code redemption).
*/
export function reloadFeatureFlags(): void {
if (!isInitialized) {
diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txt
index d1013f5de475..b3d9fddbfaf2 100644
--- a/products/model_crossing_uses_baseline.txt
+++ b/products/model_crossing_uses_baseline.txt
@@ -108,8 +108,6 @@ product_analytics.Insight products.reminders.backend.constants in-collection 1
product_analytics.Insight products.slack_app.backend.slack_link_unfurl instance-single 1
product_analytics.Insight products.surveys.backend.api.survey instance-single 1
surveys.Survey products.early_access_features.backend.management.commands.migrate_enrollments_to_waitlist_surveys get_model 1
-tasks.CodeInvite products.posthog_ai.eval_harness.harness.demo_data get_model 1
-tasks.CodeInviteRedemption products.posthog_ai.eval_harness.harness.demo_data get_model 1
tasks.TaskRun products.review_hog.backend.receivers get_model 1
warehouse_sources.DataWarehouseCredential posthog.hogql.database.database instance-many(filter) 1
warehouse_sources.DataWarehouseCredential products.data_warehouse.backend.presentation.views.table drf-model-serializer 1
diff --git a/products/posthog_ai/eval_harness/harness/demo_data.py b/products/posthog_ai/eval_harness/harness/demo_data.py
index 1f8de0e3ec80..361b6416be38 100644
--- a/products/posthog_ai/eval_harness/harness/demo_data.py
+++ b/products/posthog_ai/eval_harness/harness/demo_data.py
@@ -3,8 +3,6 @@ from __future__ import annotations
import logging
from datetime import timedelta
-from django.apps import apps
-
from posthog.clickhouse.client import sync_execute
from products.posthog_ai.eval_harness.data_setup import (
@@ -31,8 +29,8 @@ class SandboxedDemoData:
One instance per harness run: seeds the master Hedgebox team (or reuses
a healthy one), then produces a fresh isolated ``CustomPromptSandboxContext``
for every eval case via ``make_context(label)``. Each call copies the master
- into a brand-new org/team/user with its own core memory and tasks-API
- access, so concurrent eval cases can't pollute each other's state.
+ into a brand-new org/team/user with its own core memory, so concurrent
+ eval cases can't pollute each other's state.
"""
def __init__(
@@ -52,14 +50,8 @@ class SandboxedDemoData:
self.sandbox_timeout_seconds = sandbox_timeout_seconds
def make_context(self, case_label: str) -> CustomPromptSandboxContext:
- CodeInvite = apps.get_model("tasks", "CodeInvite")
- CodeInviteRedemption = apps.get_model("tasks", "CodeInviteRedemption")
-
- org, team, user = copy_demo_data_to_new_team(self.master_team_id, self._django_db_blocker, label=case_label)
+ _, team, user = copy_demo_data_to_new_team(self.master_team_id, self._django_db_blocker, label=case_label)
create_core_memory(team, self._django_db_blocker)
- with self._django_db_blocker.unblock():
- invite, _ = CodeInvite.objects.get_or_create(code="eval-harness", max_redemptions=0, is_active=True)
- CodeInviteRedemption.objects.get_or_create(invite_code=invite, user=user, organization=org)
logger.info("Case %r assigned team_id=%d user_id=%d", case_label, team.id, user.id)
return CustomPromptSandboxContext(
team_id=team.id,
diff --git a/products/tasks/backend/access.py b/products/tasks/backend/access.py
index 0606d7a69780..3166cfbacc17 100644
--- a/products/tasks/backend/access.py
+++ b/products/tasks/backend/access.py
@@ -7,7 +7,6 @@ from posthog.ph_client import feature_enabled_or_false, get_feature_flag_or_none
from products.tasks.backend.facade.contracts import DesktopAccessReason
from products.tasks.backend.metrics import observe_desktop_access_decision
-from products.tasks.backend.models import CodeInviteRedemption
from ee.billing.billing_manager import (
BillingManager,
@@ -20,7 +19,6 @@ if TYPE_CHECKING:
from posthog.models.organization import Organization
from posthog.models.team.team import Team
-DESKTOP_ACCESS_GATE_FLAG = "posthog-desktop-access-gate"
DESKTOP_ACCESS_OVERRIDE_FLAG = "posthog-desktop-access-override"
@@ -30,7 +28,6 @@ class DesktopAccessResolutionError(Exception):
class DesktopAccessDecision(StrEnum):
ALLOWED = "allowed"
- LEGACY_ACCESS_REQUIRED = "legacy_access_required"
STARTUP_PLAN = "startup_plan"
PREPAID_CREDITS = "prepaid_credits"
@@ -47,37 +44,6 @@ class DesktopAccessDecision(StrEnum):
return None
-# Either flag grants the same access. `tasks` is the Desktop waitlist. `phai-sandbox-mode` is the
-# PostHog AI composer, which reaches the same cloud runs through a different entry point, and rolls
-# out to organizations that are not on the Desktop waitlist.
-TASKS_ACCESS_FEATURE_FLAGS = ("tasks", "phai-sandbox-mode")
-
-
-def has_tasks_access(user: User) -> bool:
- """
- User has access to PostHog Desktop if one of the `TASKS_ACCESS_FEATURE_FLAGS` is enabled for
- them OR they have redeemed an invite code.
- """
- if not user or not user.is_authenticated or not user.distinct_id:
- return False
-
- organization = getattr(user, "organization", None)
- organization_id = str(organization.id) if organization is not None else None
- if any(
- feature_enabled_or_false(
- flag_key,
- str(user.distinct_id),
- groups={"organization": organization_id} if organization_id is not None else None,
- group_properties={"organization": {"id": organization_id}} if organization_id is not None else None,
- only_evaluate_locally=False,
- send_feature_flag_events=False,
- )
- for flag_key in TASKS_ACCESS_FEATURE_FLAGS
- ):
- return True
- return CodeInviteRedemption.objects.filter(user=user).exists()
-
-
def _get_funding_status(user: User, organization: "Organization") -> OrganizationFundingStatus:
try:
return BillingManager(get_cached_instance_license(), user).get_funding_status(organization)
@@ -92,29 +58,6 @@ def get_desktop_access_decision(user: User, organization: "Organization") -> Des
organization_id = str(organization.id)
groups = {"organization": organization_id}
group_properties = {"organization": {"id": organization_id}}
- rollout_enabled = get_feature_flag_or_none(
- DESKTOP_ACCESS_GATE_FLAG,
- str(user.distinct_id),
- groups=groups,
- group_properties=group_properties,
- only_evaluate_locally=False,
- send_feature_flag_events=False,
- )
- if not isinstance(rollout_enabled, bool):
- observe_desktop_access_decision(outcome="resolution_failure")
- raise DesktopAccessResolutionError("Could not evaluate the Desktop access rollout")
- if not rollout_enabled:
- try:
- legacy_access_allowed = has_tasks_access(user)
- except Exception as error:
- observe_desktop_access_decision(outcome="resolution_failure")
- raise DesktopAccessResolutionError("Could not evaluate legacy Desktop access") from error
- if legacy_access_allowed:
- observe_desktop_access_decision(outcome="legacy_allowed")
- return DesktopAccessDecision.ALLOWED
- observe_desktop_access_decision(outcome="legacy_denied")
- return DesktopAccessDecision.LEGACY_ACCESS_REQUIRED
-
override_enabled = get_feature_flag_or_none(
DESKTOP_ACCESS_OVERRIDE_FLAG,
str(user.distinct_id),
diff --git a/products/tasks/backend/admin.py b/products/tasks/backend/admin.py
index 6ee67c975901..42507a5c76a3 100644
--- a/products/tasks/backend/admin.py
+++ b/products/tasks/backend/admin.py
@@ -13,16 +13,7 @@ from posthog.storage import object_storage
from . import loop_service
from .loop_lifecycle import DISABLED_REASON_ADMIN_PAUSED, pause_loop
-from .models import (
- CodeInvite,
- CodeInviteQuerySet,
- CodeInviteRedemption,
- Loop,
- LoopTrigger,
- SandboxSnapshot,
- Task,
- TaskRun,
-)
+from .models import Loop, LoopTrigger, SandboxSnapshot, Task, TaskRun
from .visibility import task_run_visibility_q, task_visibility_q
logger = logging.getLogger(__name__)
@@ -137,66 +128,6 @@ class SandboxSnapshotAdmin(admin.ModelAdmin):
)
-class CodeInviteRedemptionInline(admin.TabularInline):
- model = CodeInviteRedemption
- extra = 0
- can_delete = False
- readonly_fields = ("id", "user", "organization", "redeemed_at")
-
-
[email protected](CodeInvite)
-class CodeInviteAdmin(admin.ModelAdmin):
- list_display = (
- "code",
- "description",
- "is_active",
- "redemption_count",
- "max_redemptions",
- "expires_at",
- "created_at",
- )
- list_filter = ("is_active", "created_at")
- search_fields = ("code", "description")
- readonly_fields = ("id", "redemption_count", "created_at")
- autocomplete_fields = ("created_by",)
- inlines = []
- actions = ["expire_invites"]
-
- @admin.action(description="Expire selected invites")
- def expire_invites(self, request: HttpRequest, queryset: CodeInviteQuerySet) -> None:
- selected = queryset.count()
- expired = queryset.expire()
- message = f"Expired {expired} of {selected} selected invite(s)."
- if expired < selected:
- message += " Invites that were already expired were left unchanged."
- self.message_user(request, message)
-
- def get_fieldsets(self, request, obj=None):
- if obj:
- return (
- (None, {"fields": ("id", "code", "description")}),
- ("Limits", {"fields": ("is_active", "max_redemptions", "redemption_count", "expires_at")}),
- ("Metadata", {"fields": ("created_by", "created_at")}),
- )
- # On add, code may be set manually or left blank to auto-generate on save
- return (
- (None, {"fields": ("id", "code", "description")}),
- ("Limits", {"fields": ("is_active", "max_redemptions", "expires_at")}),
- ("Metadata", {"fields": ("created_by",)}),
- )
-
- def get_inlines(self, request, obj=None):
- return [CodeInviteRedemptionInline]
-
-
[email protected](CodeInviteRedemption)
-class CodeInviteRedemptionAdmin(admin.ModelAdmin):
- list_display = ("invite_code", "user", "organization", "redeemed_at")
- list_filter = ("redeemed_at",)
- search_fields = ("user__email", "invite_code__code")
- readonly_fields = ("id", "invite_code", "user", "organization", "redeemed_at")
-
-
@admin.register(Loop)
class LoopAdmin(admin.ModelAdmin):
list_display = (
diff --git a/products/tasks/backend/facade/access.py b/products/tasks/backend/facade/access.py
index b4096f2013f0..4f4def7041e2 100644
--- a/products/tasks/backend/facade/access.py
+++ b/products/tasks/backend/facade/access.py
@@ -3,7 +3,6 @@ from products.tasks.backend.access import (
DesktopAccessResolutionError,
get_desktop_access_decision,
has_loops_access,
- has_tasks_access,
)
from products.tasks.backend.facade.contracts import DesktopAccessReason
from products.tasks.backend.logic.services.code_usage_gate import (
@@ -20,6 +19,5 @@ __all__ = [
"compute_quota_limit_response",
"get_desktop_access_decision",
"has_loops_access",
- "has_tasks_access",
"usage_limit_response",
]
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 20df2dd86aa9..7a01bc6a1d93 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -106,8 +106,6 @@ from products.tasks.backend.models import (
ChannelFeedMessage,
ChannelInstructions,
ChannelStar,
- CodeInvite,
- CodeInviteRedemption,
DesktopBetaTermsAcceptance,
InvalidTaskOriginError,
MCPBuiltInAgentKey,
@@ -154,14 +152,6 @@ TaskRuntime = Task.Runtime
SandboxNetworkAccessLevel = SandboxEnvironment.NetworkAccessLevel
SandboxSnapshotStatus = SandboxSnapshot.Status
-# --- Code-invite redeem outcomes ---
-# Returned on ``CodeInviteRedeemResult.outcome``; the presentation layer maps each to an
-# HTTP response. ``REDEEMED`` covers both a fresh redemption and the idempotent no-op when
-# the user already redeemed this code (both surface as success).
-CODE_INVITE_REDEEMED = "redeemed"
-CODE_INVITE_INVALID_CODE = "invalid_code"
-CODE_INVITE_NOT_REDEEMABLE = "not_redeemable"
-
WIZARD_PR_READY_EMAIL_FEATURE_FLAG = "wizard-cloud-run-pr-ready-email-enabled"
# Runtime posture for a setup-wizard cloud run, applied in create_wizard_cloud_run. The model is
@@ -172,9 +162,6 @@ WIZARD_CLOUD_RUN_MODEL = "claude-sonnet-5"
WIZARD_CLOUD_RUN_AI_STAGE = "wizard_pr_agent"
__all__ = [
- "CODE_INVITE_INVALID_CODE",
- "CODE_INVITE_NOT_REDEEMABLE",
- "CODE_INVITE_REDEEMED",
"SandboxNetworkAccessLevel",
"SandboxSnapshotStatus",
"TaskOriginProduct",
@@ -264,7 +251,6 @@ __all__ = [
"read_task_run_logs",
"record_comment_activity",
"signal_task_run_client_activity",
- "redeem_code_invite",
"redispatch_task_run",
"relay_task_run_message",
"resolve_slack_thread_context",
@@ -1680,9 +1666,6 @@ def create_completed_sandbox_snapshot(external_id: str) -> UUID:
return snapshot.id
-# --- Desktop invites ---
-
-
def get_desktop_beta_terms_acceptance(organization_id: UUID) -> contracts.DesktopBetaTermsAcceptanceDTO:
return contracts.DesktopBetaTermsAcceptanceDTO(
is_desktop_beta_terms_accepted=DesktopBetaTermsAcceptance.objects.filter(
@@ -1699,51 +1682,6 @@ def accept_desktop_beta_terms(organization_id: UUID, user_id: int) -> contracts.
return contracts.DesktopBetaTermsAcceptanceDTO(is_desktop_beta_terms_accepted=True)
-def redeem_code_invite(code: str, user_id: int) -> contracts.CodeInviteRedeemResult:
- """Redeem a PostHog Desktop invite for a user.
-
- Idempotent: a user who already redeemed this code gets ``REDEEMED`` without a second
- redemption row. A fresh redemption takes a row lock on the invite, re-checks
- redeemability under the lock, records the redemption, bumps ``redemption_count``, and
- captures the activation analytics — all in one transaction, mirroring the original view.
- """
- code_str = code.strip()
-
- try:
- invite_code = CodeInvite.objects.get(code__iexact=code_str)
- except CodeInvite.DoesNotExist:
- return contracts.CodeInviteRedeemResult(outcome=CODE_INVITE_INVALID_CODE)
-
- user = User.objects.get(pk=user_id)
-
- if CodeInviteRedemption.objects.filter(invite_code=invite_code, user=user).exists():
- return contracts.CodeInviteRedeemResult(outcome=CODE_INVITE_REDEEMED)
-
- with transaction.atomic():
- invite_code = CodeInvite.objects.select_for_update().get(id=invite_code.id)
-
- if not invite_code.is_redeemable:
- return contracts.CodeInviteRedeemResult(outcome=CODE_INVITE_NOT_REDEEMABLE)
-
- organization = user.organization if hasattr(user, "organization") else None
-
- CodeInviteRedemption.objects.create(
- invite_code=invite_code,
- user=user,
- organization=organization,
- )
-
- CodeInvite.objects.filter(id=invite_code.id).update(redemption_count=F("redemption_count") + 1)
-
- posthoganalytics.capture(
- distinct_id=str(user.distinct_id),
- event="code_invite_redeemed",
- groups=groups(organization=organization),
- )
-
- return contracts.CodeInviteRedeemResult(outcome=CODE_INVITE_REDEEMED)
-
-
# --- Sandbox environments (presentation CRUD) ---
# Visibility: an environment is reachable by a team member if it is non-private, or it is
# theirs (``created_by``). ``list`` additionally hides ``internal`` environments.
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index c9594d0a9b0b..d978e118385d 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -679,19 +679,6 @@ class WorkflowTaskSlackContext:
is_ext_shared_channel: bool = False
-@dataclass(frozen=True)
-class CodeInviteRedeemResult:
- """Outcome of attempting to redeem a PostHog Desktop invite.
-
- ``outcome`` is one of ``redeemed`` (or ``already_redeemed``), ``invalid_code``, or
- ``not_redeemable``. The presentation layer maps it to the success/error HTTP response;
- the ORM redemption, idempotency check, count increment, and analytics capture all
- happen inside the facade so no model leaks across the boundary.
- """
-
- outcome: str
-
-
@dataclass(frozen=True)
class DesktopBetaTermsAcceptanceDTO:
is_desktop_beta_terms_accepted: bool
diff --git a/products/tasks/backend/management/commands/expire_code_invites.py b/products/tasks/backend/management/commands/expire_code_invites.py
deleted file mode 100644
index d775d9b7a3bd..000000000000
--- a/products/tasks/backend/management/commands/expire_code_invites.py
+++ /dev/null
@@ -1,119 +0,0 @@
-import sys
-from datetime import UTC, datetime
-from typing import Any
-
-from django.core.management.base import BaseCommand, CommandError, CommandParser
-from django.db.models import Q
-from django.utils import timezone as django_timezone
-
-from posthog.models.user import User
-
-from products.tasks.backend.models import CodeInvite, CodeInviteQuerySet
-
-FILTER_OPTIONS = ("code", "created_before", "created_after", "created_by", "unredeemed")
-
-
-class Command(BaseCommand):
- help = (
- "Expire PostHog Code invite codes by setting expires_at to now. "
- "Invites that are already expired are left unchanged. "
- "Pass at least one filter, or --all to expire every invite."
- )
-
- def add_arguments(self, parser: CommandParser) -> None:
- parser.add_argument("--all", action="store_true", help="Expire every invite. Cannot be combined with filters.")
- parser.add_argument("--code", nargs="+", metavar="CODE", help="Only these invite codes (case-insensitive)")
- parser.add_argument(
- "--created-before", metavar="DATETIME", help="Invites created before this ISO 8601 datetime (UTC if naive)"
- )
- parser.add_argument(
- "--created-after",
- metavar="DATETIME",
- help="Invites created at or after this ISO 8601 datetime (UTC if naive)",
- )
- parser.add_argument("--created-by", metavar="EMAIL", help="Invites created by the user with this email")
- parser.add_argument("--unredeemed", action="store_true", help="Only invites that were never redeemed")
- parser.add_argument("--dry-run", action="store_true", help="List matching invites without changing anything")
- parser.add_argument("--yes", action="store_true", help="Skip the confirmation prompt")
-
- def handle(self, *args: Any, **options: Any) -> None:
- has_filters = any(options[name] for name in FILTER_OPTIONS)
- if options["all"] and has_filters:
- raise CommandError("--all cannot be combined with filters")
- if not options["all"] and not has_filters:
- raise CommandError(
- "Pass at least one filter (--code, --created-before, --created-after, --created-by, --unredeemed) or --all"
- )
-
- now = django_timezone.now()
- matched = self._apply_filters(CodeInvite.objects.all(), options)
- to_expire = list(matched.unexpired(now).order_by("created_at"))
- already_expired = matched.count() - len(to_expire)
-
- for invite in to_expire:
- limit = "unlimited" if invite.max_redemptions == 0 else str(invite.max_redemptions)
- expires = invite.expires_at.isoformat() if invite.expires_at else "never"
- self.stdout.write(
- f"{invite.code} {invite.description or '-'} redemptions {invite.redemption_count}/{limit} "
- f"created {invite.created_at:%Y-%m-%d %H:%M} expires {expires}"
- )
- self.stdout.write(f"{len(to_expire)} to expire, {already_expired} already expired (skipped)")
-
- if not to_expire:
- self.stdout.write(self.style.WARNING("No invites to expire."))
- return
- if options["dry_run"]:
- self.stdout.write(self.style.WARNING(f"Dry run: {len(to_expire)} invite(s) would be expired."))
- return
-
- self._confirm(f"Expire {len(to_expire)} invite(s)? Type 'yes' to continue: ", yes=options["yes"])
- # Expire exactly the invites shown in the preview. Re-running the filter here would also
- # catch invites created during the confirmation prompt, expiring rows the operator never saw.
- count = CodeInvite.objects.filter(pk__in=[invite.pk for invite in to_expire]).expire(now)
- self.stdout.write(self.style.SUCCESS(f"Expired {count} invite(s)."))
-
- def _apply_filters(self, queryset: CodeInviteQuerySet, options: dict[str, Any]) -> CodeInviteQuerySet:
- if options["code"]:
- requested = {code.strip() for code in options["code"]}
- code_filter = Q()
- for code in requested:
- code_filter |= Q(code__iexact=code)
- queryset = queryset.filter(code_filter)
- found = {code.lower() for code in queryset.values_list("code", flat=True)}
- unknown = sorted(code for code in requested if code.lower() not in found)
- if unknown:
- raise CommandError(f"Unknown invite codes: {', '.join(unknown)}")
- before = (
- self._parse_datetime(options["created_before"], "--created-before") if options["created_before"] else None
- )
- after = self._parse_datetime(options["created_after"], "--created-after") if options["created_after"] else None
- if before and after and after >= before:
- raise CommandError("--created-after must be earlier than --created-before")
- if before:
- queryset = queryset.filter(created_at__lt=before)
- if after:
- queryset = queryset.filter(created_at__gte=after)
- if options["created_by"]:
- if not User.objects.filter(email__iexact=options["created_by"]).exists():
- raise CommandError(f"No user with email {options['created_by']!r}")
- queryset = queryset.filter(created_by__email__iexact=options["created_by"])
- if options["unredeemed"]:
- queryset = queryset.filter(redemption_count=0)
- return queryset
-
- @staticmethod
- def _parse_datetime(raw: str, flag: str) -> datetime:
- try:
- parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))
- except ValueError:
- raise CommandError(f"{flag} is not a valid ISO 8601 datetime: {raw!r}")
- return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
-
- @staticmethod
- def _confirm(prompt: str, *, yes: bool) -> None:
- if yes:
- return
- if not sys.stdin.isatty():
- raise CommandError("Refusing to expire invites non-interactively without --yes")
- if input(prompt).strip() != "yes":
- raise CommandError("Aborted.")
diff --git a/products/tasks/backend/management/commands/test/test_expire_code_invites.py b/products/tasks/backend/management/commands/test/test_expire_code_invites.py
deleted file mode 100644
index a0bed403fee2..000000000000
--- a/products/tasks/backend/management/commands/test/test_expire_code_invites.py
+++ /dev/null
@@ -1,104 +0,0 @@
-from datetime import UTC, datetime
-from io import StringIO
-
-from freezegun import freeze_time
-from unittest.mock import patch
-
-from django.core.management import CommandError, call_command
-from django.test import TestCase
-
-from parameterized import parameterized
-
-from posthog.models.user import User
-
-from products.tasks.backend.models import CodeInvite
-
-NOW = datetime(2026, 4, 1, 12, 0, tzinfo=UTC)
-PAST_EXPIRY = datetime(2026, 1, 15, tzinfo=UTC)
-FUTURE_EXPIRY = datetime(2026, 12, 31, tzinfo=UTC)
-
-
-class TestExpireCodeInvites(TestCase):
- def setUp(self) -> None:
- super().setUp()
- self.alice = User.objects.create_user(email="[email protected]", first_name="Alice", password=None)
- self.bob = User.objects.create_user(email="[email protected]", first_name="Bob", password=None)
- with freeze_time("2026-01-01"):
- CodeInvite.objects.create(code="A", created_by=self.alice, redemption_count=1, max_redemptions=0)
- CodeInvite.objects.create(code="EXPIRED", created_by=self.alice, expires_at=PAST_EXPIRY)
- with freeze_time("2026-02-01"):
- CodeInvite.objects.create(code="B", created_by=self.bob, expires_at=FUTURE_EXPIRY)
- with freeze_time("2026-03-01"):
- CodeInvite.objects.create(code="C", created_by=self.alice)
-
- def _call(self, *args: str) -> str:
- stdout = StringIO()
- with freeze_time(NOW):
- call_command("expire_code_invites", *args, stdout=stdout)
- return stdout.getvalue()
-
- def _expires_at_by_code(self) -> dict[str, datetime | None]:
- return dict(CodeInvite.objects.values_list("code", "expires_at"))
-
- @parameterized.expand(
- [
- ("all", ["--all"], {"A", "B", "C"}),
- ("created_before", ["--created-before", "2026-02-15"], {"A", "B"}),
- ("created_after", ["--created-after", "2026-01-15T00:00:00Z"], {"B", "C"}),
- ("date_range", ["--created-after", "2026-01-15", "--created-before", "2026-02-15"], {"B"}),
- ("code_case_insensitive", ["--code", "a", "c"], {"A", "C"}),
- ("created_by", ["--created-by", "[email protected]"], {"A", "C"}),
- ("unredeemed", ["--unredeemed"], {"B", "C"}),
- ("created_by_and_unredeemed", ["--created-by", "[email protected]", "--unredeemed"], {"C"}),
- ]
- )
- def test_expires_only_matching_unexpired_invites(self, _name: str, args: list[str], expected: set[str]) -> None:
- output = self._call(*args, "--yes")
-
- expires_at = self._expires_at_by_code()
- assert {code for code in ("A", "B", "C") if expires_at[code] == NOW} == expected
- assert expires_at["EXPIRED"] == PAST_EXPIRY
- untouched = {"A", "B", "C"} - expected
- assert all(expires_at[code] in (None, FUTURE_EXPIRY) for code in untouched)
- assert f"Expired {len(expected)} invite(s)." in output
-
- def test_dry_run_changes_nothing(self) -> None:
- output = self._call("--all", "--dry-run")
-
- assert "Dry run: 3 invite(s) would be expired." in output
- assert self._expires_at_by_code() == {"A": None, "B": FUTURE_EXPIRY, "C": None, "EXPIRED": PAST_EXPIRY}
-
- @parameterized.expand(
- [
- ("no_filters", []),
- ("all_with_filter", ["--all", "--unredeemed"]),
- ("inverted_range", ["--created-after", "2026-03-01", "--created-before", "2026-01-01"]),
- ("bad_datetime", ["--created-before", "not-a-date"]),
- ("unknown_code", ["--code", "A", "NOPE"]),
- ("unknown_email", ["--created-by", "[email protected]"]),
- ]
- )
- def test_rejects_invalid_arguments(self, _name: str, args: list[str]) -> None:
- with self.assertRaises(CommandError):
- self._call(*args, "--yes")
-
- assert self._expires_at_by_code() == {"A": None, "B": FUTURE_EXPIRY, "C": None, "EXPIRED": PAST_EXPIRY}
-
- def test_leaves_invites_created_during_confirmation_alone(self) -> None:
- def confirm(_prompt: str) -> str:
- CodeInvite.objects.create(code="LATE", created_by=self.alice)
- return "yes"
-
- with patch("sys.stdin") as stdin, patch("builtins.input", side_effect=confirm):
- stdin.isatty.return_value = True
- output = self._call("--all")
-
- assert self._expires_at_by_code()["LATE"] is None
- assert "Expired 3 invite(s)." in output
-
- def test_refuses_without_yes_when_not_interactive(self) -> None:
- with patch("sys.stdin") as stdin, self.assertRaises(CommandError):
- stdin.isatty.return_value = False
- self._call("--all")
-
- assert self._expires_at_by_code()["A"] is None
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index f455b56ea4df..f5f5ea029558 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -312,8 +312,6 @@ CodeUsageGateOutcome = Literal["checked_allowed", "checked_blocked", "fail_open"
ComputeQuotaOutcome = Literal["checked_allowed", "checked_blocked", "fail_open"]
DesktopAccessOutcome = Literal[
"allowed",
- "legacy_allowed",
- "legacy_denied",
"startup_plan",
"prepaid_credits",
"override",
diff --git a/products/tasks/backend/migrations/0107_remove_code_invites_from_state.py b/products/tasks/backend/migrations/0107_remove_code_invites_from_state.py
new file mode 100644
index 000000000000..0f26e5e02496
--- /dev/null
+++ b/products/tasks/backend/migrations/0107_remove_code_invites_from_state.py
@@ -0,0 +1,54 @@
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [("tasks", "0106_sandboxsession_sandbox_backend")]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ database_operations=[
+ migrations.RunSQL(
+ sql="""
+ DO $$
+ DECLARE r RECORD;
+ BEGIN
+ FOR r IN (
+ SELECT conname FROM pg_constraint
+ WHERE conrelid = 'posthog_code_invite'::regclass
+ AND contype = 'f'
+ ) LOOP
+ EXECUTE format(
+ 'ALTER TABLE posthog_code_invite DROP CONSTRAINT %I', r.conname
+ );
+ END LOOP;
+ EXCEPTION WHEN undefined_table THEN NULL;
+ END $$;
+ """,
+ reverse_sql=migrations.RunSQL.noop,
+ ),
+ migrations.RunSQL(
+ sql="""
+ DO $$
+ DECLARE r RECORD;
+ BEGIN
+ FOR r IN (
+ SELECT conname FROM pg_constraint
+ WHERE conrelid = 'posthog_code_invite_redemption'::regclass
+ AND contype = 'f'
+ ) LOOP
+ EXECUTE format(
+ 'ALTER TABLE posthog_code_invite_redemption DROP CONSTRAINT %I', r.conname
+ );
+ END LOOP;
+ EXCEPTION WHEN undefined_table THEN NULL;
+ END $$;
+ """,
+ reverse_sql=migrations.RunSQL.noop,
+ ),
+ ],
+ state_operations=[
+ migrations.DeleteModel(name="CodeInviteRedemption"),
+ migrations.DeleteModel(name="CodeInvite"),
+ ],
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index 0100e5715935..fc041ae0ed81 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0106_sandboxsession_sandbox_backend
+0107_remove_code_invites_from_state
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 9e6ae04c56a6..4304e2848864 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -2,8 +2,6 @@ import os
import re
import json
import uuid
-import string
-import secrets
from collections.abc import Callable, Iterable
from datetime import datetime
from typing import TYPE_CHECKING, Any, Literal, Optional
@@ -22,7 +20,7 @@ from django.conf import settings
from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.indexes import GinIndex, OpClass
from django.core.exceptions import ValidationError
-from django.db import IntegrityError, connection, models, transaction
+from django.db import connection, models, transaction
from django.db.models.fields.json import KeyTransform
from django.utils import timezone as django_timezone
@@ -3446,79 +3444,6 @@ class SandboxCustomImage(TeamScopedRootMixin):
return f"posthog-sandbox-custom-{self.team_id}-{self.id.hex}:latest"
-class CodeInviteQuerySet(models.QuerySet["CodeInvite"]):
- def unexpired(self, at: datetime | None = None) -> "CodeInviteQuerySet":
- at = at or django_timezone.now()
- return self.filter(models.Q(expires_at__isnull=True) | models.Q(expires_at__gt=at))
-
- def expire(self, at: datetime | None = None) -> int:
- at = at or django_timezone.now()
- return self.unexpired(at).update(expires_at=at)
-
-
-class CodeInvite(UUIDModel):
- """Invite codes for PostHog Desktop access."""
-
- objects = CodeInviteQuerySet.as_manager()
-
- code = models.CharField(max_length=50, unique=True, db_index=True, blank=True)
- max_redemptions = models.PositiveIntegerField(default=1, help_text="Maximum number of redemptions. 0 = unlimited.")
- redemption_count = models.PositiveIntegerField(default=0)
- is_active = models.BooleanField(default=True)
- expires_at = models.DateTimeField(null=True, blank=True, help_text="Optional expiration date.")
- description = models.TextField(blank=True, help_text="Internal admin note.")
- created_by = models.ForeignKey(
- "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="created_code_invites"
- )
- created_at = models.DateTimeField(auto_now_add=True)
-
- class Meta:
- db_table = "posthog_code_invite"
-
- def __str__(self):
- return self.code
-
- def save(self, *args, **kwargs):
- if not self.code:
- alphabet = string.ascii_uppercase + string.digits
- for attempt in range(10):
- self.code = "".join(secrets.choice(alphabet) for _ in range(8))
- try:
- with transaction.atomic():
- return super().save(*args, **kwargs)
- except IntegrityError:
- if attempt == 9:
- raise
- return
- super().save(*args, **kwargs)
-
- @property
- def is_redeemable(self) -> bool:
- if not self.is_active:
- return False
- if self.expires_at and self.expires_at <= django_timezone.now():
- return False
- if self.max_redemptions > 0 and self.redemption_count >= self.max_redemptions:
- return False
- return True
-
-
-class CodeInviteRedemption(UUIDModel):
- """Tracks each redemption of a PostHog Desktop invite."""
-
- invite_code = models.ForeignKey(CodeInvite, on_delete=models.CASCADE, related_name="redemptions")
- user = models.ForeignKey("posthog.User", on_delete=models.CASCADE)
- organization = models.ForeignKey("posthog.Organization", on_delete=models.SET_NULL, null=True, blank=True)
- redeemed_at = models.DateTimeField(auto_now_add=True)
-
- class Meta:
- db_table = "posthog_code_invite_redemption"
- unique_together = [("invite_code", "user")]
-
- def __str__(self):
- return f"{self.user} redeemed {self.invite_code}"
-
-
class DesktopBetaTermsAcceptance(models.Model):
organization = models.OneToOneField(
"posthog.Organization",
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 411cb44f4d99..3eae5989064b 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -968,7 +968,7 @@ class DesktopAccessResponseSerializer(serializers.Serializer):
class LegacyDesktopAccessResponseSerializer(serializers.Serializer):
- has_access = serializers.BooleanField(help_text="Whether the user has legacy PostHog Desktop access.")
+ has_access = serializers.BooleanField(help_text="Whether the current project can use PostHog Desktop.")
has_loops_access = serializers.BooleanField(help_text="Whether the independent Loops feature is enabled.")
@@ -3780,10 +3780,6 @@ class TaskRunCommandResponseSerializer(serializers.Serializer):
error = serializers.DictField(required=False, help_text="Error details on failure")
-class CodeInviteRedeemRequestSerializer(serializers.Serializer):
- code = serializers.CharField(max_length=50)
-
-
class TaskRunSessionLogsQuerySerializer(serializers.Serializer):
"""Query parameters for filtering task run log events"""
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 5da07b1988da..34029e9af81d 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -52,7 +52,7 @@ from posthog.permissions import (
get_authenticator_scopes,
is_mcp_built_in_agent_oauth_request,
)
-from posthog.rate_limit import CodeInviteThrottle, TaskRunChartRenderThrottle
+from posthog.rate_limit import TaskRunChartRenderThrottle
from posthog.renderers import ServerSentEventRenderer
from posthog.schema_migrations.upgrade import upgrade
from posthog.temporal.oauth import SANDBOX_OAUTH_APP_CLIENT_IDS, TASK_AGENT_OAUTH_APP_CLIENT_IDS
@@ -97,7 +97,6 @@ from products.tasks.backend.facade.streams import (
run_uses_dedicated_stream,
)
from products.tasks.backend.presentation.serializers import (
- CodeInviteRedeemRequestSerializer,
ConnectionTokenResponseSerializer,
LegacyDesktopAccessResponseSerializer,
ModelCatalogueResponseSerializer,
@@ -3645,69 +3644,62 @@ class TaskRunLivingArtifactViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
return Response(serializer.data)
-@extend_schema(tags=["code-invites"])
-class CodeInviteViewSet(viewsets.ViewSet):
- """API for redeeming PostHog Desktop invite codes."""
-
+@extend_schema(tags=["tasks"])
+class LegacyDesktopAccessViewSet(viewsets.ViewSet):
authentication_classes = [
SessionAuthentication,
PersonalAPIKeyAuthentication,
OAuthAccessTokenAuthentication,
]
permission_classes = [IsAuthenticated, APIScopePermission]
-
scope_object = "task"
-
- http_method_names = ["get", "post", "head", "options"]
- throttle_classes = [CodeInviteThrottle]
+ http_method_names = ["get", "head", "options"]
def get_permissions(self):
- # Both endpoints are user-account-level operations (not project data).
- if self.action in ("check_access", "redeem"):
- return [IsAuthenticated()]
- return super().get_permissions()
+ return [IsAuthenticated()]
- @validated_request(
- request_serializer=CodeInviteRedeemRequestSerializer,
+ @extend_schema(
responses={
- 200: OpenApiResponse(description="Invite code redeemed successfully"),
- 400: OpenApiResponse(
- response=TaskRunErrorResponseSerializer,
- description="Invalid or expired invite code",
- ),
+ 200: OpenApiResponse(response=LegacyDesktopAccessResponseSerializer),
+ 503: OpenApiResponse(response=TaskRunErrorResponseSerializer),
},
- summary="Redeem invite code",
- description="Redeem a PostHog Desktop invite code to enable legacy access.",
+ summary="Check PostHog Desktop access",
+ description="Compatibility endpoint for released PostHog Desktop clients.",
)
- @action(detail=False, methods=["post"], url_path="redeem")
- def redeem(self, request, **kwargs):
- result = tasks_facade.redeem_code_invite(request.validated_data["code"], request.user.id)
-
- if result.outcome == tasks_facade.CODE_INVITE_INVALID_CODE:
+ @action(detail=False, methods=["get"], url_path="check-access")
+ def check_access(self, request, **kwargs):
+ team = getattr(request.user, "team", None)
+ if team is None:
return Response(
- TaskRunErrorResponseSerializer({"error": "Invalid invite code"}).data,
- status=status.HTTP_400_BAD_REQUEST,
+ TaskRunErrorResponseSerializer(
+ {
+ "type": "service_unavailable",
+ "code": "desktop_access_unavailable",
+ "error": "We couldn't verify PostHog Desktop access. Try again.",
+ }
+ ).data,
+ status=status.HTTP_503_SERVICE_UNAVAILABLE,
)
- if result.outcome == tasks_facade.CODE_INVITE_NOT_REDEEMABLE:
+
+ try:
+ decision = tasks_access.get_desktop_access_decision(request.user, team.organization)
+ except tasks_access.DesktopAccessResolutionError:
return Response(
- TaskRunErrorResponseSerializer({"error": "This invite code is no longer valid"}).data,
- status=status.HTTP_400_BAD_REQUEST,
+ TaskRunErrorResponseSerializer(
+ {
+ "type": "service_unavailable",
+ "code": "desktop_access_unavailable",
+ "error": "We couldn't verify PostHog Desktop access. Try again.",
+ }
+ ).data,
+ status=status.HTTP_503_SERVICE_UNAVAILABLE,
)
- return Response({"success": True})
-
- @extend_schema(
- responses={200: OpenApiResponse(response=LegacyDesktopAccessResponseSerializer)},
- summary="Check access",
- description="Check whether the authenticated user has legacy PostHog Desktop access and Loops access.",
- )
- @action(detail=False, methods=["get"], url_path="check-access")
- def check_access(self, request, **kwargs):
return Response(
LegacyDesktopAccessResponseSerializer(
{
- "has_access": tasks_access.has_tasks_access(request.user),
- "has_loops_access": tasks_access.has_loops_access(request.user),
+ "has_access": decision.allowed,
+ "has_loops_access": tasks_access.has_loops_access(request.user, team),
}
).data
)
diff --git a/products/tasks/backend/routes.py b/products/tasks/backend/routes.py
index 927c6aa819a5..0ceb2e1059c0 100644
--- a/products/tasks/backend/routes.py
+++ b/products/tasks/backend/routes.py
@@ -49,7 +49,7 @@ def register_routes(routers: RouterRegistry) -> None:
routers.projects.register(
r"sandbox_custom_images", tasks.SandboxCustomImageViewSet, "project_sandbox_custom_images", ["team_id"]
)
- routers.root.register(r"code/invites", tasks.CodeInviteViewSet, "code_invites")
+ routers.root.register(r"code/invites", tasks.LegacyDesktopAccessViewSet, "code_invites")
routers.root.register(
r"code/sandbox-pricing", sandbox_pricing.SandboxComputePricingViewSet, "sandbox_compute_pricing"
)
diff --git a/products/tasks/backend/tests/test_admin.py b/products/tasks/backend/tests/test_admin.py
index d15cac752070..d93419df3a10 100644
--- a/products/tasks/backend/tests/test_admin.py
+++ b/products/tasks/backend/tests/test_admin.py
@@ -8,7 +8,7 @@ from django.urls import reverse
from posthog.admin import register_all_admin
-from products.tasks.backend.models import Channel, CodeInvite, Loop, Task, TaskRun
+from products.tasks.backend.models import Channel, Loop, Task, TaskRun
register_all_admin()
@@ -109,29 +109,6 @@ class TestTaskRunAdminDownloadLogs(BaseTest):
self.assertIn("/login", resp["Location"])
-class TestCodeInviteAdminExpireAction(BaseTest):
- def setUp(self):
- super().setUp()
- self.user.is_staff = True
- self.user.save()
- self.client.force_login(self.user)
-
- def test_expires_selected_invites_only(self):
- selected = CodeInvite.objects.create(code="SELECTED")
- other = CodeInvite.objects.create(code="OTHER")
-
- resp = self.client.post(
- reverse("admin:tasks_codeinvite_changelist"),
- {"action": "expire_invites", "_selected_action": [str(selected.id)]},
- )
-
- self.assertEqual(resp.status_code, 302)
- selected.refresh_from_db()
- other.refresh_from_db()
- self.assertIsNotNone(selected.expires_at)
- self.assertIsNone(other.expires_at)
-
-
class TestLoopAdminPauseAction(BaseTest):
def setUp(self) -> None:
super().setUp()
diff --git a/products/tasks/backend/tests/test_desktop_access.py b/products/tasks/backend/tests/test_desktop_access.py
index 744e42124108..b17f3648c39b 100644
--- a/products/tasks/backend/tests/test_desktop_access.py
+++ b/products/tasks/backend/tests/test_desktop_access.py
@@ -1,4 +1,4 @@
-from posthog.test.base import APIBaseTest, BaseTest
+from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
from django.core.cache import cache
@@ -8,15 +8,8 @@ from rest_framework import status
from posthog.models import Organization, OrganizationMembership, Team
-from products.tasks.backend.access import (
- DESKTOP_ACCESS_GATE_FLAG,
- DesktopAccessReason,
- DesktopAccessResolutionError,
- get_desktop_access_decision,
- has_tasks_access,
-)
+from products.tasks.backend.access import DesktopAccessReason, DesktopAccessResolutionError, get_desktop_access_decision
from products.tasks.backend.logic.services.code_usage_gate import code_access_required_response
-from products.tasks.backend.models import CodeInvite, CodeInviteRedemption
from ee.billing.billing_manager import OrganizationFundingStatus, PrepaidCreditState, StartupProgramLabel
@@ -28,8 +21,8 @@ class TestDesktopAccessPolicy(APIBaseTest):
self.feature_flag_patcher = patch("products.tasks.backend.access.get_feature_flag_or_none")
self.mock_feature_flag = self.feature_flag_patcher.start()
- def feature_flag_value(flag_key: str, *_args: object, **_kwargs: object) -> bool:
- return flag_key == DESKTOP_ACCESS_GATE_FLAG
+ def feature_flag_value(*_args: object, **_kwargs: object) -> bool:
+ return False
self.mock_feature_flag.side_effect = feature_flag_value
@@ -81,53 +74,9 @@ class TestDesktopAccessPolicy(APIBaseTest):
self.assertEqual(decision.allowed, expected_allowed)
self.assertEqual(decision.reason, expected_reason)
- @patch("products.tasks.backend.access._get_funding_status")
- @patch("products.tasks.backend.access.feature_enabled_or_false", return_value=True)
- def test_rollout_flag_off_preserves_legacy_feature_flag_access(self, _mock_legacy_flag, mock_funding) -> None:
- self.mock_feature_flag.side_effect = [False]
-
- decision = get_desktop_access_decision(self.user, self.organization)
-
- self.assertTrue(decision.allowed)
- self.assertEqual(self.mock_feature_flag.call_count, 1)
- mock_funding.assert_not_called()
-
- @patch("products.tasks.backend.access._get_funding_status")
- @patch("products.tasks.backend.access.feature_enabled_or_false", return_value=False)
- def test_rollout_flag_off_preserves_legacy_invite_access(self, _mock_legacy_flag, mock_funding) -> None:
- invite = CodeInvite.objects.create(code="LEGACYCODE", max_redemptions=1, is_active=True)
- CodeInviteRedemption.objects.create(invite_code=invite, user=self.user)
- self.mock_feature_flag.side_effect = [False]
-
- decision = get_desktop_access_decision(self.user, self.organization)
-
- self.assertTrue(decision.allowed)
- mock_funding.assert_not_called()
-
- @patch("products.tasks.backend.access._get_funding_status")
- @patch("products.tasks.backend.access.feature_enabled_or_false", return_value=False)
- def test_rollout_flag_off_preserves_legacy_denial(self, _mock_legacy_flag, mock_funding) -> None:
- self.mock_feature_flag.side_effect = [False]
-
- decision = get_desktop_access_decision(self.user, self.organization)
-
- self.assertFalse(decision.allowed)
- self.assertIsNone(decision.reason)
- mock_funding.assert_not_called()
-
- @patch("products.tasks.backend.access._get_funding_status")
- def test_indeterminate_rollout_flag_fails_closed(self, mock_funding) -> None:
- self.mock_feature_flag.side_effect = [None]
-
- with self.assertRaises(DesktopAccessResolutionError):
- get_desktop_access_decision(self.user, self.organization)
-
- self.assertEqual(self.mock_feature_flag.call_count, 1)
- mock_funding.assert_not_called()
-
@patch("products.tasks.backend.access._get_funding_status")
def test_override_grants_access_before_funding_resolution(self, mock_funding) -> None:
- self.mock_feature_flag.side_effect = [True, True]
+ self.mock_feature_flag.side_effect = [True]
decision = get_desktop_access_decision(self.user, self.organization)
@@ -147,23 +96,9 @@ class TestDesktopAccessPolicy(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)
self.assertEqual(response.data["code"], "desktop_access_unavailable")
- @patch("products.tasks.backend.access._get_funding_status")
- def test_access_code_does_not_affect_authorization_after_rollout(self, mock_funding) -> None:
- invite = CodeInvite.objects.create(code="ACCESSCODE", max_redemptions=1, is_active=True)
- CodeInviteRedemption.objects.create(invite_code=invite, user=self.user)
- mock_funding.return_value = OrganizationFundingStatus(
- startup_program_label="Startup",
- prepaid_credit_state=PrepaidCreditState.NONE,
- )
-
- decision = get_desktop_access_decision(self.user, self.organization)
-
- self.assertFalse(decision.allowed)
- self.assertEqual(decision.reason, DesktopAccessReason.STARTUP_PLAN)
-
@parameterized.expand([(None,), ("control",), ("false",)])
- def test_indeterminate_feature_flag_fails_closed(self, flag_value) -> None:
- self.mock_feature_flag.side_effect = [True, flag_value]
+ def test_indeterminate_override_flag_fails_closed(self, flag_value) -> None:
+ self.mock_feature_flag.side_effect = [flag_value]
with self.assertRaises(DesktopAccessResolutionError):
get_desktop_access_decision(self.user, self.organization)
@@ -207,32 +142,31 @@ class TestDesktopAccessPolicy(APIBaseTest):
self.assertEqual(blocked_response.status_code, status.HTTP_200_OK)
self.assertEqual(blocked_response.json(), {"allowed": False, "reason": "startup_plan"})
+ @parameterized.expand(
+ [
+ ("allowed", None, True),
+ ("startup", "Startup", False),
+ ]
+ )
@patch("products.tasks.backend.presentation.views.api.tasks_access.has_loops_access", return_value=True)
- @patch("products.tasks.backend.access.feature_enabled_or_false", return_value=True)
- def test_legacy_endpoint_preserves_feature_flag_access(self, _mock_legacy_flag, _mock_loops) -> None:
- response = self.client.get("/api/code/invites/check-access/")
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json(), {"has_access": True, "has_loops_access": True})
-
- @patch("products.tasks.backend.presentation.views.api.tasks_access.has_loops_access", return_value=False)
- @patch("products.tasks.backend.access.feature_enabled_or_false", return_value=False)
- def test_legacy_endpoint_preserves_invite_access(self, _mock_legacy_flag, _mock_loops) -> None:
- invite = CodeInvite.objects.create(code="ENDPOINTCODE", max_redemptions=1, is_active=True)
- CodeInviteRedemption.objects.create(invite_code=invite, user=self.user)
-
- response = self.client.get("/api/code/invites/check-access/")
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json(), {"has_access": True, "has_loops_access": False})
+ @patch("products.tasks.backend.access._get_funding_status")
+ def test_legacy_endpoint_uses_access_policy(
+ self,
+ _name: str,
+ startup_program_label: StartupProgramLabel | None,
+ expected_access: bool,
+ mock_funding,
+ _mock_loops,
+ ) -> None:
+ mock_funding.return_value = OrganizationFundingStatus(
+ startup_program_label=startup_program_label,
+ prepaid_credit_state=PrepaidCreditState.NONE,
+ )
- @patch("products.tasks.backend.presentation.views.api.tasks_access.has_loops_access", return_value=False)
- @patch("products.tasks.backend.access.feature_enabled_or_false", return_value=False)
- def test_legacy_endpoint_preserves_denial(self, _mock_legacy_flag, _mock_loops) -> None:
response = self.client.get("/api/code/invites/check-access/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json(), {"has_access": False, "has_loops_access": False})
+ self.assertEqual(response.json(), {"has_access": expected_access, "has_loops_access": True})
@patch(
"products.tasks.backend.presentation.views.desktop_access.get_desktop_access_decision",
@@ -243,19 +177,3 @@ class TestDesktopAccessPolicy(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)
self.assertEqual(response.json()["code"], "desktop_access_unavailable")
-
-
-class TestTasksAccessFlags(BaseTest):
- @parameterized.expand(
- [
- ("desktop_waitlist", {"tasks"}, True),
- ("posthog_ai_composer", {"phai-sandbox-mode"}, True),
- ("neither", set(), False),
- ]
- )
- def test_either_access_flag_grants_access(self, _name: str, enabled_flags: set[str], expected: bool) -> None:
- with patch(
- "products.tasks.backend.access.feature_enabled_or_false",
- side_effect=lambda flag_key, *_args, **_kwargs: flag_key in enabled_flags,
- ):
- assert has_tasks_access(self.user) is expected
diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.py
index d0e00700f906..7069904b2625 100644
--- a/products/tasks/backend/tests/test_models.py
+++ b/products/tasks/backend/tests/test_models.py
@@ -1,6 +1,5 @@
import json
import uuid
-import secrets
from datetime import UTC, datetime
from typing import ClassVar
@@ -8,7 +7,6 @@ from unittest.mock import AsyncMock, patch
from django.conf import settings
from django.core.exceptions import ValidationError
-from django.db import IntegrityError
from django.test import TestCase
from django.utils import timezone as django_timezone
@@ -24,7 +22,6 @@ from posthog.storage import object_storage
from products.tasks.backend.models import (
TASK_OWNERSHIP_VERSION_STATE_KEY,
- CodeInvite,
SandboxEnvironment,
SandboxSnapshot,
Task,
@@ -1966,42 +1963,3 @@ class TestTaskRunGetSandboxEnvironment(TestCase):
def test_returns_none_for_malformed_environment_id(self):
run = self._create_run("not-a-uuid")
self.assertIsNone(run.get_sandbox_environment())
-
-
-class TestCodeInvite(TestCase):
- def test_auto_generates_code_on_save(self):
- invite = CodeInvite.objects.create()
- self.assertEqual(len(invite.code), 8)
- self.assertTrue(all(c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" for c in invite.code))
-
- def test_preserves_explicit_code(self):
- invite = CodeInvite.objects.create(code="MYCODE42")
- self.assertEqual(invite.code, "MYCODE42")
-
- def test_retries_on_code_collision(self):
- existing = CodeInvite.objects.create(code="AAAAAAAA")
- self.assertEqual(existing.code, "AAAAAAAA")
-
- call_count = 0
- original_choice = secrets.choice
-
- def mock_choice(alphabet):
- nonlocal call_count
- call_count += 1
- # First 8 calls (first attempt) return "A" to collide, rest are random
- if call_count <= 8:
- return "A"
- return original_choice(alphabet)
-
- with patch("products.tasks.backend.models.secrets.choice", side_effect=mock_choice):
- invite = CodeInvite.objects.create()
-
- self.assertNotEqual(invite.code, "AAAAAAAA")
- self.assertEqual(len(invite.code), 8)
-
- def test_raises_after_max_retries(self):
- CodeInvite.objects.create(code="BBBBBBBB")
-
- with patch("products.tasks.backend.models.secrets.choice", return_value="B"):
- with self.assertRaises(IntegrityError):
- CodeInvite.objects.create()
diff --git a/products/tasks/docs/INSTRUMENTATION.md b/products/tasks/docs/INSTRUMENTATION.md
index f03212aeb6c2..1d409655e9a3 100644
--- a/products/tasks/docs/INSTRUMENTATION.md
+++ b/products/tasks/docs/INSTRUMENTATION.md
@@ -233,14 +233,6 @@ Tracked when a GitHub `pull_request.closed` webhook is received with `merged=tru
Tracked when a GitHub `pull_request.closed` webhook is received with `merged=false`. Same additional properties as `pr_created`.
-## API Events
-
-Source: `products/tasks/backend/api.py`
-
-### `code_invite_redeemed`
-
-Tracked when a user redeems a Desktop invite. Includes `organization` group analytics. No additional properties.
-
## Activity Observability Events
Source: `products/tasks/backend/temporal/observability.py`
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 2178e49d606b..7e8a30af58a1 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -8,17 +8,12 @@
* OpenAPI spec version: 1.0.0
*/
export interface LegacyDesktopAccessResponseApi {
- /** Whether the user has legacy PostHog Desktop access. */
+ /** Whether the current project can use PostHog Desktop. */
has_access: boolean
/** Whether the independent Loops feature is enabled. */
has_loops_access: boolean
}
-export interface CodeInviteRedeemRequestApi {
- /** @maxLength 50 */
- code: string
-}
-
/**
* * `startup_plan` - startup_plan
* * `prepaid_credits` - prepaid_credits
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index 17c8a2d60460..ee2ea58b92a5 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -17,7 +17,6 @@ import type {
ChannelInstructionsWriteApi,
ChannelStarWriteApi,
ChannelWriteApi,
- CodeInviteRedeemRequestApi,
ConnectionTokenResponseApi,
DesktopAccessResponseApi,
DesktopBetaTermsAcceptanceDTOApi,
@@ -158,8 +157,8 @@ export const getCodeInvitesCheckAccessRetrieveUrl = () => {
}
/**
- * Check whether the authenticated user has legacy PostHog Desktop access and Loops access.
- * @summary Check access
+ * Compatibility endpoint for released PostHog Desktop clients.
+ * @summary Check PostHog Desktop access
*/
export const codeInvitesCheckAccessRetrieve = async (
options?: RequestInit
@@ -170,26 +169,6 @@ export const codeInvitesCheckAccessRetrieve = async (
})
}
-export const getCodeInvitesRedeemCreateUrl = () => {
- return `/api/code/invites/redeem/`
-}
-
-/**
- * Redeem a PostHog Desktop invite code to enable legacy access.
- * @summary Redeem invite code
- */
-export const codeInvitesRedeemCreate = async (
- codeInviteRedeemRequestApi: CodeInviteRedeemRequestApi,
- options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getCodeInvitesRedeemCreateUrl(), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(codeInviteRedeemRequestApi),
- })
-}
-
export const getCodeSandboxPricingListUrl = () => {
return `/api/code/sandbox-pricing/`
}
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index f914030211f6..5ce0681e83d5 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -9,16 +9,6 @@
*/
import * as zod from 'zod'
-/**
- * Redeem a PostHog Desktop invite code to enable legacy access.
- * @summary Redeem invite code
- */
-export const codeInvitesRedeemCreateBodyCodeMax = 50
-
-export const CodeInvitesRedeemCreateBody = /* @__PURE__ */ zod.object({
- code: zod.string().max(codeInvitesRedeemCreateBodyCodeMax),
-})
-
/**
* API for managing loops — named, cloud-executed agent automations triggered by
* schedule, GitHub events or authenticated API calls. See `products/tasks/docs/LOOPS.md`.
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index e947f5d66b41..b76054b10519 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -98,9 +98,6 @@ tools:
code-invites-check-access-retrieve:
operation: code_invites_check_access_retrieve
enabled: false
- code-invites-redeem-create:
- operation: code_invites_redeem_create
- enabled: false
code-sandbox-pricing-list:
operation: code_sandbox_pricing_list
enabled: false
diff --git a/services/llm-gateway/README.md b/services/llm-gateway/README.md
index 33b5121d70d3..48184fd0d461 100644
--- a/services/llm-gateway/README.md
+++ b/services/llm-gateway/README.md
@@ -267,7 +267,7 @@ Aliases: `twig`, `array` resolve to `posthog_code`; `slack-twig` resolves to `sl
`posthog_code` additionally requires a project-scoped PostHog Desktop decision. The OAuth application allowlist only proves that the Desktop app issued the token. It does not grant Desktop access.
-After OAuth validates the selected project, the gateway asks Django at `GET /api/projects/{project_id}/desktop/access/`. While `posthog-desktop-access-gate` is off, Django preserves the existing `tasks` flag and invite-code policy. When rollout is on, Django applies `posthog-desktop-access-override` before Startup-program and prepaid-credit restrictions. The gateway preserves `code_access_required` as its error code and forwards `startup_plan` or `prepaid_credits` when Django provides a reason. Server-minted credentials carrying `internal_run:read` bypass the human gate because their run already passed Django's trusted task path.
+After OAuth validates the selected project, the gateway asks Django at `GET /api/projects/{project_id}/desktop/access/`. Django applies `posthog-desktop-access-override` before Startup-program and prepaid-credit restrictions. The gateway preserves `code_access_required` as its error code and forwards `startup_plan` or `prepaid_credits` when Django provides a reason. Server-minted credentials carrying `internal_run:read` bypass the human gate because their run already passed Django's trusted task path.
The check fails closed. Django transport errors, 404, 429, 5xx responses, and malformed payloads return `503 desktop_access_unavailable` and are not cached. Django 401 and 403 credential rejections return a generic `403 code_access_required` without a funding reason and cache for 30 seconds per credential and project to limit repeated rejected lookups. Deploy the Django project endpoint everywhere before deploying this gateway contract; old gateway instances continue using the compatibility endpoint during that rollout. The Gateway allows six seconds for Django because Django can spend up to five seconds resolving a Billing cache miss. Grants cache for 60 seconds and business denials for 30 seconds. Cache keys include the user, validated team, and a non-reversible credential fingerprint. Desktop access checks use a separate outbound connection pool, capped at 10 connections per Gateway instance, so failures cannot exhaust the pool used by other policy resolvers. `LLM_GATEWAY_DESKTOP_ACCESS_GATE_ENABLED=false` disables the gateway gate.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ef30cf19f9af..111fe3c0b709 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -17638,11 +17638,6 @@ export namespace Schemas {
StaleVersion: 'stale_version',
} as const;
- export interface CodeInviteRedeemRequest {
- /** @maxLength 50 */
- code: string;
- }
-
/**
* * `codex` - codex
*/
@@ -46533,7 +46528,7 @@ export namespace Schemas {
}
export interface LegacyDesktopAccessResponse {
- /** Whether the user has legacy PostHog Desktop access. */
+ /** Whether the current project can use PostHog Desktop. */
has_access: boolean;
/** Whether the independent Loops feature is enabled. */
has_loops_access: boolean;