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(tasks): remove the task automations feature (#85092)

Charles Vien0a59cb8b5b11
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index eb981f392914..4d3b5564cbd0 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -361,7 +361,6 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"SourceBatchStatus", # via SourceBatch
"StreamlitAppSandbox", # via StreamlitApp
"TaggedItem", # via Tag/Dashboard/Insight
- "TaskAutomation", # via Task
"TicketAssignment", # via Ticket
"UserGroupMembership", # via UserGroup
# --- Other models missing direct team_id ---
diff --git a/products/desktop/apps/mobile/README.md b/products/desktop/apps/mobile/README.md
index c68a3daad0d2..3d9eb1e12a0c 100644
--- a/products/desktop/apps/mobile/README.md
+++ b/products/desktop/apps/mobile/README.md
@@ -63,7 +63,7 @@ Mobile and desktop use the same cloud-task architecture. New work must preserve
- `@posthog/shared` owns runtime contracts and Zod schemas.
- `@posthog/api-client` owns authenticated PostHog HTTPS transport and its request/response types.
-- `@posthog/core` owns cloud-task orchestration and headless presentation decisions, including sessions, queues, permissions, models, repositories, inbox rules, and automation semantics.
+- `@posthog/core` owns cloud-task orchestration and headless presentation decisions, including sessions, queues, permissions, models, repositories, and inbox rules.
- `apps/mobile` owns Expo lifecycle, React Native rendering, gestures, sheets, notifications, audio, secure storage, and small persisted view-state stores.
- `@posthog/ui` owns the DOM/Quill renderer and web view state.
diff --git a/products/desktop/apps/mobile/src/app/(tabs)/_layout.tsx b/products/desktop/apps/mobile/src/app/(tabs)/_layout.tsx
index 71fddbbbe824..9aa167a8a8f3 100644
--- a/products/desktop/apps/mobile/src/app/(tabs)/_layout.tsx
+++ b/products/desktop/apps/mobile/src/app/(tabs)/_layout.tsx
@@ -11,7 +11,7 @@ import { useThemeColors } from "@/lib/theme";
const EDGE_SWIPE_HIT_WIDTH = 22;
const HOME_ROUTE = "/tasks";
-const TAB_ROUTES = new Set(["/tasks", "/inbox", "/automations"]);
+const TAB_ROUTES = new Set(["/tasks", "/inbox"]);
export default function TabsLayout() {
const themeColors = useThemeColors();
@@ -53,7 +53,7 @@ export default function TabsLayout() {
return true;
}
// Only intercept when we're actually on a tab destination. Modals
- // pushed on top of the tabs (e.g. /automation, /task) keep this
+ // pushed on top of the tabs (e.g. /task) keep this
// handler mounted; without the guard we'd redirect to /tasks instead
// of letting the modal dismiss naturally.
if (!TAB_ROUTES.has(pathname)) return false;
@@ -75,7 +75,6 @@ export default function TabsLayout() {
>
<Stack.Screen name="tasks" />
<Stack.Screen name="inbox" />
- <Stack.Screen name="automations" />
</Stack>
{/* Invisible left-edge strip that captures the open-drawer gesture. */}
<View
diff --git a/products/desktop/apps/mobile/src/app/(tabs)/automations.tsx b/products/desktop/apps/mobile/src/app/(tabs)/automations.tsx
deleted file mode 100644
index e684085a24c3..000000000000
--- a/products/desktop/apps/mobile/src/app/(tabs)/automations.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { useFocusEffect, useRouter } from "expo-router";
-import { useCallback, useRef } from "react";
-import { InteractionManager, View } from "react-native";
-import { useSafeAreaInsets } from "react-native-safe-area-context";
-import { AutomationList } from "@/features/tasks/components/AutomationList";
-import { FloatingAutomationsHeader } from "@/features/tasks/components/FloatingAutomationsHeader";
-import { FloatingNewAutomationButton } from "@/features/tasks/components/FloatingNewAutomationButton";
-import { useAutomations } from "@/features/tasks/hooks/useAutomations";
-
-export default function AutomationsScreen() {
- const router = useRouter();
- const insets = useSafeAreaInsets();
- const readyRef = useRef(true);
- const { automations } = useAutomations();
- const hasAutomations = automations.length > 0;
-
- useFocusEffect(
- useCallback(() => {
- const handle = InteractionManager.runAfterInteractions(() => {
- readyRef.current = true;
- });
- return () => {
- readyRef.current = false;
- handle.cancel();
- };
- }, []),
- );
-
- const handleCreateAutomation = useCallback(() => {
- if (!readyRef.current) return;
- readyRef.current = false;
- router.push("/automation");
- }, [router]);
-
- const handleAutomationPress = useCallback(
- (automationId: string) => {
- if (!readyRef.current) return;
- readyRef.current = false;
- router.push(`/automation/${automationId}`);
- },
- [router],
- );
-
- // Matches FloatingTasksHeader: top inset + 6 (top pad) + 40 (button) + 8
- // (bottom pad) plus a small visual buffer so rows don't hug the fade.
- const headerHeight = insets.top + 64;
-
- return (
- <View className="flex-1 bg-background">
- <AutomationList
- onAutomationPress={handleAutomationPress}
- onCreateAutomation={handleCreateAutomation}
- contentInsetTop={headerHeight}
- />
-
- <FloatingAutomationsHeader />
-
- {hasAutomations ? (
- <FloatingNewAutomationButton onPress={handleCreateAutomation} />
- ) : null}
- </View>
- );
-}
diff --git a/products/desktop/apps/mobile/src/app/_layout.tsx b/products/desktop/apps/mobile/src/app/_layout.tsx
index 95c632f49332..10f829e7742d 100644
--- a/products/desktop/apps/mobile/src/app/_layout.tsx
+++ b/products/desktop/apps/mobile/src/app/_layout.tsx
@@ -127,35 +127,6 @@ function RootLayoutNav({ isConnected }: RootLayoutNavProps) {
name="task/[id]"
options={{ presentation: "modal", headerShown: false }}
/>
- <Stack.Screen
- name="automation/index"
- options={{
- presentation: "modal",
- headerShown: true,
- title: "Create automation",
- headerStyle: { backgroundColor: themeColors.background },
- headerTintColor: themeColors.gray[12],
- }}
- />
- <Stack.Screen
- name="automation/create"
- options={{
- presentation: "modal",
- headerShown: true,
- title: "New automation",
- headerStyle: { backgroundColor: themeColors.background },
- headerTintColor: themeColors.gray[12],
- }}
- />
- <Stack.Screen
- name="automation/[id]"
- options={{
- presentation: "modal",
- headerShown: true,
- headerStyle: { backgroundColor: themeColors.background },
- headerTintColor: themeColors.gray[12],
- }}
- />
<Stack.Screen
name="pr-diff"
options={{
diff --git a/products/desktop/apps/mobile/src/app/automation/[id].tsx b/products/desktop/apps/mobile/src/app/automation/[id].tsx
deleted file mode 100644
index 159742297c6b..000000000000
--- a/products/desktop/apps/mobile/src/app/automation/[id].tsx
+++ /dev/null
@@ -1,227 +0,0 @@
-import { Text } from "@components/text";
-import { TaskAutomationValidationError } from "@posthog/api-client/posthog-client";
-import { parseSkillTemplateId } from "@posthog/core/automations/automationTemplatePresentation";
-import { Stack, useLocalSearchParams, useRouter } from "expo-router";
-import { useState } from "react";
-import {
- ActivityIndicator,
- Alert,
- KeyboardAvoidingView,
- Platform,
- Pressable,
- ScrollView,
- View,
-} from "react-native";
-import { AutomationDetail } from "@/features/tasks/components/AutomationDetail";
-import { AutomationForm } from "@/features/tasks/components/AutomationForm";
-import {
- useAutomation,
- useDeleteTaskAutomation,
- useRunTaskAutomation,
- useUpdateTaskAutomation,
-} from "@/features/tasks/hooks/useAutomations";
-import { useTask } from "@/features/tasks/hooks/useTasks";
-import { useThemeColors } from "@/lib/theme";
-
-export default function AutomationDetailScreen() {
- const { id } = useLocalSearchParams<{ id: string }>();
- const router = useRouter();
- const themeColors = useThemeColors();
- const { data: automation, isLoading, error } = useAutomation(id);
- const { data: lastTask } = useTask(automation?.last_task_id ?? "");
- const updateAutomation = useUpdateTaskAutomation();
- const deleteAutomation = useDeleteTaskAutomation();
- const runAutomation = useRunTaskAutomation();
- const [isEditing, setIsEditing] = useState(false);
- const [fieldError, setFieldError] = useState<{
- attr: string | null;
- message: string | null;
- } | null>(null);
- const [generalError, setGeneralError] = useState<string | null>(null);
- const repositoryRequired = automation
- ? parseSkillTemplateId(automation.template_id) !== null ||
- automation.repository.trim().length > 0
- : true;
-
- if (error || (!automation && !isLoading)) {
- return (
- <>
- <Stack.Screen
- options={{
- headerShown: true,
- headerTitle: "Automation",
- headerStyle: { backgroundColor: themeColors.background },
- headerTintColor: themeColors.gray[12],
- presentation: "modal",
- }}
- />
- <View className="flex-1 items-center justify-center bg-background px-4">
- <Text className="mb-4 text-center text-status-error">
- {error?.message ?? "Automation not found"}
- </Text>
- <Pressable
- onPress={() => router.back()}
- className="rounded-lg bg-gray-3 px-4 py-2"
- >
- <Text className="text-gray-12">Go back</Text>
- </Pressable>
- </View>
- </>
- );
- }
-
- return (
- <>
- <Stack.Screen
- options={{
- headerShown: true,
- headerTitle: isEditing
- ? "Edit automation"
- : (automation?.name ?? "Automation"),
- headerStyle: { backgroundColor: themeColors.background },
- headerTintColor: themeColors.gray[12],
- presentation: "modal",
- }}
- />
- <KeyboardAvoidingView
- className="flex-1 bg-background"
- behavior={Platform.OS === "ios" ? "padding" : "height"}
- keyboardVerticalOffset={90}
- >
- <ScrollView
- className="flex-1 px-3 pt-4"
- keyboardShouldPersistTaps="handled"
- contentContainerStyle={{ paddingBottom: 40 }}
- >
- {isLoading || !automation ? (
- <View className="items-center pt-12">
- <ActivityIndicator size="large" color={themeColors.accent[9]} />
- <Text className="mt-4 text-gray-11">Loading automation...</Text>
- </View>
- ) : isEditing ? (
- <AutomationForm
- initialValues={{
- name: automation.name,
- prompt: automation.prompt,
- repositorySelection: {
- integrationId: automation.github_integration ?? null,
- repository: automation.repository || null,
- },
- cronExpression: automation.cron_expression,
- timezone: automation.timezone ?? "UTC",
- enabled: automation.enabled,
- }}
- isSubmitting={updateAutomation.isPending}
- submitLabel="Save changes"
- fieldError={fieldError}
- generalError={generalError}
- repositoryRequired={repositoryRequired}
- onCancel={() => {
- setFieldError(null);
- setGeneralError(null);
- setIsEditing(false);
- }}
- onSubmit={async (values) => {
- setFieldError(null);
- setGeneralError(null);
-
- try {
- await updateAutomation.mutateAsync({
- automationId: automation.id,
- updates: {
- ...values,
- template_id: automation.template_id ?? null,
- },
- });
- setIsEditing(false);
- } catch (error) {
- if (error instanceof TaskAutomationValidationError) {
- setFieldError({
- attr: error.attr,
- message: error.message,
- });
- return;
- }
-
- setGeneralError("Could not save automation changes.");
- }
- }}
- />
- ) : (
- <AutomationDetail
- automation={automation}
- lastTaskRunStatus={lastTask?.latest_run?.status ?? null}
- isWorking={runAutomation.isPending || updateAutomation.isPending}
- onEdit={() => setIsEditing(true)}
- onToggleEnabled={async () => {
- setFieldError(null);
- setGeneralError(null);
- try {
- await updateAutomation.mutateAsync({
- automationId: automation.id,
- updates: {
- enabled: !automation.enabled,
- },
- });
- } catch {
- setGeneralError("Could not update automation state.");
- }
- }}
- onRunNow={async () => {
- setFieldError(null);
- setGeneralError(null);
- try {
- const updatedAutomation = await runAutomation.mutateAsync(
- automation.id,
- );
- if (updatedAutomation.last_task_id) {
- router.push({
- pathname: "/task/[id]",
- params: {
- id: updatedAutomation.last_task_id,
- fromAutomation: "1",
- automationName: updatedAutomation.name,
- },
- });
- }
- } catch {
- setGeneralError("Could not start the automation run.");
- }
- }}
- onDelete={() => {
- Alert.alert(
- "Delete automation?",
- "This will remove the schedule and stop future runs.",
- [
- {
- text: "Cancel",
- style: "cancel",
- },
- {
- text: "Delete",
- style: "destructive",
- onPress: async () => {
- try {
- await deleteAutomation.mutateAsync(automation.id);
- router.back();
- } catch {
- setGeneralError("Could not delete automation.");
- }
- },
- },
- ],
- );
- }}
- />
- )}
-
- {generalError && !isEditing && (
- <Text className="mt-4 text-sm text-status-error">
- {generalError}
- </Text>
- )}
- </ScrollView>
- </KeyboardAvoidingView>
- </>
- );
-}
diff --git a/products/desktop/apps/mobile/src/app/automation/create.tsx b/products/desktop/apps/mobile/src/app/automation/create.tsx
deleted file mode 100644
index 1fe2c452c04e..000000000000
--- a/products/desktop/apps/mobile/src/app/automation/create.tsx
+++ /dev/null
@@ -1,243 +0,0 @@
-import { TaskAutomationValidationError } from "@posthog/api-client/posthog-client";
-import { formatSkillTemplateId } from "@posthog/core/automations/automationTemplatePresentation";
-import { getCalendars } from "expo-localization";
-import { Stack, useLocalSearchParams, useRouter } from "expo-router";
-import { useMemo, useRef, useState } from "react";
-import {
- ActivityIndicator,
- KeyboardAvoidingView,
- Platform,
- Pressable,
- ScrollView,
- View,
-} from "react-native";
-import { Text } from "@/components/text";
-import { AutomationForm } from "@/features/tasks/components/AutomationForm";
-import { useCreateTaskAutomation } from "@/features/tasks/hooks/useAutomations";
-import { useSkillStoreSkill } from "@/features/tasks/skills/hooks";
-import { useScreenInsets } from "@/hooks/useScreenInsets";
-import { useThemeColors } from "@/lib/theme";
-
-// Reserved space below the scrolling form content. Tall enough that the
-// floating Create button never covers the prompt editor's tail — the
-// user can scroll the very last line of the prompt up above the button.
-// Composed of the button's own area + safe-area inset at the bottom of
-// the screen.
-const FLOATING_BUTTON_AREA_HEIGHT = 64;
-const FLOATING_BUTTON_DEAD_SPACE = 32;
-
-export default function CreateAutomationScreen() {
- const { skillName: skillNameParam } = useLocalSearchParams<{
- skillName?: string | string[];
- }>();
- const skillName = Array.isArray(skillNameParam)
- ? skillNameParam[0]
- : skillNameParam;
- const router = useRouter();
- const themeColors = useThemeColors();
- const { insets, bottom } = useScreenInsets();
- const createAutomation = useCreateTaskAutomation();
- const defaultTimezone = useMemo(
- () => getCalendars()[0]?.timeZone ?? "UTC",
- [],
- );
- const selectedSkill = useSkillStoreSkill(skillName ?? null);
- const selectedSkillName = selectedSkill.data?.name ?? skillName ?? null;
- const skillInitialValues = useMemo(
- () =>
- selectedSkill.data && selectedSkillName
- ? {
- name: selectedSkill.data.name,
- prompt: selectedSkill.data.body,
- enabled: true,
- template_id: formatSkillTemplateId(selectedSkillName),
- }
- : null,
- [selectedSkill.data, selectedSkillName],
- );
- const [fieldError, setFieldError] = useState<{
- attr: string | null;
- message: string | null;
- } | null>(null);
- const [generalError, setGeneralError] = useState<string | null>(null);
-
- // Bridge to the form's internal submit handler so the floating button
- // — rendered outside the form's tree — can trigger validation+submit.
- // Mirrored `canSubmit` lets us disable the button in lockstep with form
- // validity without lifting all of the form's state up to the screen.
- const submitRef = useRef<(() => void) | null>(null);
- const [canSubmit, setCanSubmit] = useState(false);
- const isSubmitting = createAutomation.isPending;
-
- // Whether the form is even mounted yet — controls whether the floating
- // button is shown. While the skill is still loading or failed to load,
- // the form isn't on screen, so there's nothing to submit.
- const formMounted =
- !skillName || (!selectedSkill.isPending && !!selectedSkill.data);
-
- // Dead space at the bottom of the scroll content so the floating button
- // can sit over a region with no form content. When the user scrolls to
- // the very end of the prompt editor, the last line clears above the
- // button instead of being hidden behind it.
- const scrollPaddingBottom =
- FLOATING_BUTTON_AREA_HEIGHT + insets.bottom + FLOATING_BUTTON_DEAD_SPACE;
-
- const handleCreate = () => submitRef.current?.();
-
- return (
- <>
- <Stack.Screen
- options={{
- headerShown: true,
- headerTitle: "Create automation",
- headerStyle: { backgroundColor: themeColors.background },
- headerTintColor: themeColors.gray[12],
- presentation: "modal",
- }}
- />
- <KeyboardAvoidingView
- className="flex-1 bg-background"
- behavior={Platform.OS === "ios" ? "padding" : "height"}
- keyboardVerticalOffset={90}
- >
- <ScrollView
- className="flex-1 px-4 pt-4"
- keyboardShouldPersistTaps="handled"
- contentContainerStyle={{ paddingBottom: scrollPaddingBottom }}
- >
- <View className="gap-4">
- {skillName && selectedSkill.isPending ? (
- <View className="items-center rounded-xl border border-gray-6 bg-gray-2 p-5">
- <ActivityIndicator size="small" color={themeColors.accent[9]} />
- <Text className="mt-3 text-gray-11 text-sm">
- Loading the selected skill...
- </Text>
- </View>
- ) : skillName && (selectedSkill.error || !selectedSkill.data) ? (
- <View className="rounded-xl border border-gray-6 bg-gray-2 p-4">
- <Text className="font-semibold text-[15px] text-gray-12">
- Could not load this skill
- </Text>
- <Text className="mt-2 text-gray-11 text-sm">
- {selectedSkill.error?.message ??
- "The selected skill is unavailable right now."}
- </Text>
- <View className="mt-4 flex-row gap-3">
- <Pressable
- onPress={() => void selectedSkill.refetch()}
- className="flex-1 rounded-xl border border-gray-6 bg-gray-1 py-3"
- >
- <Text className="text-center font-medium text-gray-12">
- Try again
- </Text>
- </Pressable>
- <Pressable
- onPress={() => router.replace("/automation/create")}
- className="flex-1 rounded-xl border border-gray-6 bg-gray-1 py-3"
- >
- <Text className="text-center font-medium text-gray-12">
- Start from scratch
- </Text>
- </Pressable>
- </View>
- </View>
- ) : (
- <>
- {selectedSkillName && (
- <View>
- <Text className="text-[11px] text-gray-9 uppercase">
- Skill
- </Text>
- <Text className="mt-1 font-semibold text-[16px] text-gray-12">
- {selectedSkillName}
- </Text>
- </View>
- )}
-
- <AutomationForm
- initialValues={{
- name: skillInitialValues?.name,
- prompt: skillInitialValues?.prompt,
- timezone: defaultTimezone,
- enabled: skillInitialValues?.enabled ?? true,
- }}
- initialPromptMode={selectedSkillName ? "preview" : "edit"}
- isSubmitting={isSubmitting}
- submitLabel="Create"
- fieldError={fieldError}
- generalError={generalError}
- // Footer is rendered by the screen as a floating button.
- hideFooter
- submitRef={submitRef}
- onCanSubmitChange={setCanSubmit}
- onSubmit={async (values) => {
- setFieldError(null);
- setGeneralError(null);
-
- try {
- const automation = await createAutomation.mutateAsync({
- ...values,
- template_id: skillInitialValues?.template_id ?? null,
- });
- router.replace(`/automation/${automation.id}`);
- } catch (error) {
- if (error instanceof TaskAutomationValidationError) {
- setFieldError({
- attr: error.attr,
- message: error.message,
- });
- return;
- }
-
- setGeneralError(
- "Could not create automation. Please try again.",
- );
- }
- }}
- />
- </>
- )}
- </View>
- </ScrollView>
-
- {/* Floating Create button — sits inside the KeyboardAvoidingView
- so it rises with the keyboard, but outside the ScrollView so
- it stays anchored to the bottom of the screen regardless of
- how far the user has scrolled. The ScrollView's bottom padding
- (above) reserves enough dead space that the prompt editor's
- last line can always be scrolled clear of this button. */}
- {formMounted && (
- <View
- className="absolute inset-x-0 bottom-0 border-gray-6 border-t bg-background px-4 pt-3"
- style={{ paddingBottom: bottom("compact") }}
- >
- <Pressable
- onPress={handleCreate}
- disabled={!canSubmit || isSubmitting}
- accessibilityRole="button"
- accessibilityLabel="Create automation"
- className={`rounded-xl py-3.5 ${
- canSubmit && !isSubmitting ? "bg-accent-9" : "bg-gray-3"
- }`}
- >
- {isSubmitting ? (
- <ActivityIndicator
- size="small"
- color={themeColors.accent.contrast}
- />
- ) : (
- <Text
- className={`text-center font-semibold text-[15px] ${
- canSubmit ? "text-accent-contrast" : "text-gray-9"
- }`}
- >
- Create
- </Text>
- )}
- </Pressable>
- </View>
- )}
- </KeyboardAvoidingView>
- </>
- );
-}
diff --git a/products/desktop/apps/mobile/src/app/automation/index.tsx b/products/desktop/apps/mobile/src/app/automation/index.tsx
deleted file mode 100644
index 6bc68e490e5a..000000000000
--- a/products/desktop/apps/mobile/src/app/automation/index.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-import { Stack, useRouter } from "expo-router";
-import { ScrollView, View } from "react-native";
-import { Text } from "@/components/text";
-import { AutomationSkillChooser } from "@/features/tasks/components/AutomationSkillChooser";
-import { useThemeColors } from "@/lib/theme";
-
-export default function AutomationTemplateScreen() {
- const router = useRouter();
- const themeColors = useThemeColors();
-
- return (
- <>
- <Stack.Screen
- options={{
- headerShown: true,
- headerTitle: "Create automation",
- headerStyle: { backgroundColor: themeColors.background },
- headerTintColor: themeColors.gray[12],
- presentation: "modal",
- }}
- />
- <ScrollView
- className="flex-1 bg-background px-4 pt-4"
- contentContainerStyle={{ paddingBottom: 40 }}
- >
- <View className="gap-4">
- <View>
- <Text className="font-semibold text-[16px] text-gray-12">
- Choose how to start
- </Text>
- <Text className="mt-2 text-gray-11 text-sm">
- Start from scratch, or pick a shared skill from the store and
- tailor it before saving.
- </Text>
- </View>
-
- <AutomationSkillChooser
- onSelectSkill={(skillName) =>
- router.push({
- pathname: "/automation/create",
- params: { skillName },
- })
- }
- onCreateCustom={() => router.push("/automation/create")}
- />
- </View>
- </ScrollView>
- </>
- );
-}
diff --git a/products/desktop/apps/mobile/src/app/settings/index.tsx b/products/desktop/apps/mobile/src/app/settings/index.tsx
index b0d13b163e6e..9cc91eb2186a 100644
--- a/products/desktop/apps/mobile/src/app/settings/index.tsx
+++ b/products/desktop/apps/mobile/src/app/settings/index.tsx
@@ -513,7 +513,7 @@ export default function SettingsScreen() {
{canSwitchProject ? (
<SettingsRow
label="Active project"
- description="Tasks, inbox and automations use this project"
+ description="Tasks and inbox use this project"
onPress={() => setProjectSheetOpen(true)}
showDivider={false}
rightSlot={
diff --git a/products/desktop/apps/mobile/src/app/task/[id].tsx b/products/desktop/apps/mobile/src/app/task/[id].tsx
index f9e0e83a59de..f4f5786899c6 100644
--- a/products/desktop/apps/mobile/src/app/task/[id].tsx
+++ b/products/desktop/apps/mobile/src/app/task/[id].tsx
@@ -88,15 +88,8 @@ function getFirstParam(value?: string | string[]): string | undefined {
}
export default function TaskDetailScreen() {
- const {
- id: taskId,
- fromAutomation,
- automationName,
- prompt: initialPrompt,
- } = useLocalSearchParams<{
+ const { id: taskId, prompt: initialPrompt } = useLocalSearchParams<{
id: string;
- fromAutomation?: string;
- automationName?: string;
prompt?: string;
}>();
const router = useRouter();
@@ -760,13 +753,6 @@ export default function TaskDetailScreen() {
// show — the user just submitted and seeing their own text + a connecting
// indicator is friendlier than a blank spinner.
const showLoading = (loading || isHistoryLoading) && !optimisticPrompt;
- const showAutomationContext =
- fromAutomation === "1" || task?.origin_product === "automation";
- const automationContextLabel =
- automationName ??
- (task?.origin_product === "automation"
- ? "This run was started from a task automation."
- : null);
// Haptic pulse when connecting/thinking indicators dismiss
const prevWaiting = useRef(false);
@@ -815,19 +801,6 @@ export default function TaskDetailScreen() {
}
/>
<Animated.View className="flex-1" style={contentPosition}>
- {showAutomationContext && automationContextLabel && (
- <View
- className="absolute inset-x-3 z-10 rounded-lg border border-accent-6 bg-accent-2 px-3 py-2"
- style={{ top: (Platform.OS === "ios" ? 6 : insets.top) + 52 }}
- >
- <Text className="text-accent-11 text-xs">
- {automationName
- ? `Started from automation: ${automationName}`
- : automationContextLabel}
- </Text>
- </View>
- )}
-
{/* Always render TaskSessionView so the FlatList can layout behind
the loading overlay. This prevents the "flash of messages" when
switching from loading spinner to rendered content. The FlatList
@@ -859,10 +832,7 @@ export default function TaskDetailScreen() {
}
contentContainerStyle={{
paddingTop: 8,
- paddingBottom:
- (Platform.OS === "ios" ? 6 : insets.top) +
- 60 +
- (showAutomationContext ? 44 : 0),
+ paddingBottom: (Platform.OS === "ios" ? 6 : insets.top) + 60,
}}
/>
diff --git a/products/desktop/apps/mobile/src/features/auth/stores/authStore.ts b/products/desktop/apps/mobile/src/features/auth/stores/authStore.ts
index 56dabb875778..49f353e0782f 100644
--- a/products/desktop/apps/mobile/src/features/auth/stores/authStore.ts
+++ b/products/desktop/apps/mobile/src/features/auth/stores/authStore.ts
@@ -127,7 +127,7 @@ export const useAuthStore = create<AuthState>()(
if (!scopedTeams.includes(projectId) || projectId === current) return;
set({ projectId });
// Drop cached data scoped to the previous project so tasks, inbox,
- // automations, etc. refetch against the newly-selected one.
+ // etc. refetch against the newly-selected one.
queryClient.clear();
},
diff --git a/products/desktop/apps/mobile/src/features/chat/components/MarkdownText.tsx b/products/desktop/apps/mobile/src/features/chat/components/MarkdownText.tsx
index c8ca3a0997f4..17da74ac9555 100644
--- a/products/desktop/apps/mobile/src/features/chat/components/MarkdownText.tsx
+++ b/products/desktop/apps/mobile/src/features/chat/components/MarkdownText.tsx
@@ -16,7 +16,7 @@ import { PostHogRefChip } from "./PostHogRefChip";
const IMAGE_LINE_PATTERN = /^!\[([^\]]*)\]\(([^)\s]+)\)\s*$/;
const BARE_POSTHOG_REF_PATTERN =
- /(https?:\/\/(?:app\.posthog\.com|(?:us|eu)\.posthog\.com|code\.posthog\.com|(?:www\.)?posthog\.com|localhost(?::\d+)?)\/[^\s<>()\]]+|\/(?:insights|project|organization|settings|feature_flags|experiments|dashboard|dashboards|replay|session_replay|recordings|error_tracking|task|inbox|automation)\b[^\s<>()\]]*)/g;
+ /(https?:\/\/(?:app\.posthog\.com|(?:us|eu)\.posthog\.com|code\.posthog\.com|(?:www\.)?posthog\.com|localhost(?::\d+)?)\/[^\s<>()\]]+|\/(?:insights|project|organization|settings|feature_flags|experiments|dashboard|dashboards|replay|session_replay|recordings|error_tracking|task|inbox)\b[^\s<>()\]]*)/g;
interface MarkdownTextProps {
content: string;
diff --git a/products/desktop/apps/mobile/src/features/navigation/components/NavDrawer.tsx b/products/desktop/apps/mobile/src/features/navigation/components/NavDrawer.tsx
index bccaed5ab79c..b5805ccd4cd1 100644
--- a/products/desktop/apps/mobile/src/features/navigation/components/NavDrawer.tsx
+++ b/products/desktop/apps/mobile/src/features/navigation/components/NavDrawer.tsx
@@ -2,7 +2,6 @@ import { Text } from "@components/text";
import { usePathname, useRouter } from "expo-router";
import {
CaretRight,
- Clock,
GearSix,
ListBullets,
PuzzlePiece,
@@ -108,7 +107,6 @@ const NavDrawerContent = memo(function NavDrawerContent({
const handleTasks = () => navigateTo("/tasks");
const handleInbox = () => navigateTo("/inbox");
- const handleAutomations = () => navigateTo("/automations");
// Settings is pushed (not replaced) so back / swipe-back returns the user
// to whichever tab they were viewing when they opened the drawer.
const handleSettings = () => {
@@ -132,7 +130,6 @@ const NavDrawerContent = memo(function NavDrawerContent({
const iconColorActive = themeColors.gray[12];
const isOnTasks = pathname === "/tasks";
const isOnInbox = pathname === "/inbox";
- const isOnAutomations = pathname === "/automations";
const isOnSettings = pathname === "/settings";
const isOnMcpServers = pathname === "/mcp-servers";
@@ -170,18 +167,6 @@ const NavDrawerContent = memo(function NavDrawerContent({
active={isOnInbox}
onPress={handleInbox}
/>
- <DrawerItem
- icon={
- <Clock
- size={22}
- color={isOnAutomations ? iconColorActive : iconColor}
- weight={isOnAutomations ? "fill" : "regular"}
- />
- }
- label="Automations"
- active={isOnAutomations}
- onPress={handleAutomations}
- />
<DrawerItem
icon={
<PuzzlePiece
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/AutomationDetail.tsx b/products/desktop/apps/mobile/src/features/tasks/components/AutomationDetail.tsx
deleted file mode 100644
index dc7d02643938..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/components/AutomationDetail.tsx
+++ /dev/null
@@ -1,141 +0,0 @@
-import { Text } from "@components/text";
-import type { TaskAutomation } from "@posthog/api-client/posthog-client";
-import { formatAutomationScheduleSummary } from "@posthog/core/automations/automationSchedule";
-import { getAutomationTemplatePresentation } from "@posthog/core/automations/automationTemplatePresentation";
-import type { TaskRun } from "@posthog/shared";
-import { ActivityIndicator, Pressable, View } from "react-native";
-import { AutomationStatusBadge } from "./AutomationStatusBadge";
-
-interface AutomationDetailProps {
- automation: TaskAutomation;
- lastTaskRunStatus?: TaskRun["status"] | null;
- isWorking?: boolean;
- onRunNow: () => void;
- onToggleEnabled: () => void;
- onEdit: () => void;
- onDelete: () => void;
-}
-
-export function AutomationDetail({
- automation,
- lastTaskRunStatus,
- isWorking = false,
- onRunNow,
- onToggleEnabled,
- onEdit,
- onDelete,
-}: AutomationDetailProps) {
- const presentation = getAutomationTemplatePresentation(automation);
-
- return (
- <View>
- <View className="rounded-xl border border-gray-6 bg-gray-1 px-4 py-4">
- <Text className="font-semibold text-gray-12 text-lg">
- {automation.name}
- </Text>
- <View className="mt-3">
- <AutomationStatusBadge
- enabled={automation.enabled}
- lastRunStatus={automation.last_run_status}
- lastTaskRunStatus={lastTaskRunStatus}
- />
- </View>
-
- <View className="mt-4 gap-3">
- {presentation.templateName && (
- <View>
- <Text className="text-gray-9 text-xs">Template</Text>
- <Text className="mt-1 text-gray-12 text-sm">
- {presentation.templateName}
- </Text>
- </View>
- )}
- {presentation.repositoryLabel ? (
- <View>
- <Text className="text-gray-9 text-xs">Repository</Text>
- <Text className="mt-1 text-gray-12 text-sm">
- {presentation.repositoryLabel}
- </Text>
- </View>
- ) : presentation.contextLabel ? (
- <View>
- <Text className="text-gray-9 text-xs">Context</Text>
- <Text className="mt-1 text-gray-12 text-sm">
- {presentation.contextLabel}
- </Text>
- </View>
- ) : null}
- <View>
- <Text className="text-gray-9 text-xs">Schedule</Text>
- <Text className="mt-1 text-gray-12 text-sm">
- {formatAutomationScheduleSummary(automation)}
- </Text>
- </View>
- <View>
- <Text className="text-gray-9 text-xs">Prompt</Text>
- <Text className="mt-1 text-gray-12 text-sm">
- {automation.prompt}
- </Text>
- </View>
- <View>
- <Text className="text-gray-9 text-xs">Last task</Text>
- <Text className="mt-1 text-gray-12 text-sm">
- {automation.last_task_id ?? "No runs yet"}
- </Text>
- </View>
- </View>
-
- {automation.last_error && (
- <View className="mt-4 rounded-lg bg-status-error/10 px-3 py-3">
- <Text className="text-status-error text-xs">Last error</Text>
- <Text className="mt-1 text-sm text-status-error">
- {automation.last_error}
- </Text>
- </View>
- )}
- </View>
-
- <View className="mt-4 gap-3">
- <Pressable
- onPress={onRunNow}
- disabled={isWorking}
- className="rounded-lg bg-accent-9 py-3"
- >
- {isWorking ? (
- <ActivityIndicator size="small" color="white" />
- ) : (
- <Text className="text-center font-medium text-accent-contrast">
- Run now
- </Text>
- )}
- </Pressable>
-
- <View className="flex-row gap-3">
- <Pressable
- onPress={onEdit}
- className="flex-1 rounded-lg border border-gray-6 py-3"
- >
- <Text className="text-center font-medium text-gray-12">Edit</Text>
- </Pressable>
- <Pressable
- onPress={onToggleEnabled}
- className="flex-1 rounded-lg border border-gray-6 py-3"
- >
- <Text className="text-center font-medium text-gray-12">
- {automation.enabled ? "Pause" : "Resume"}
- </Text>
- </Pressable>
- </View>
-
- <Pressable
- onPress={onDelete}
- className="rounded-lg border border-status-error/30 py-3"
- >
- <Text className="text-center font-medium text-status-error">
- Delete automation
- </Text>
- </Pressable>
- </View>
- </View>
- );
-}
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/AutomationForm.test.tsx b/products/desktop/apps/mobile/src/features/tasks/components/AutomationForm.test.tsx
deleted file mode 100644
index b53f959db089..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/components/AutomationForm.test.tsx
+++ /dev/null
@@ -1,263 +0,0 @@
-import { createElement } from "react";
-import { TextInput } from "react-native";
-import { act, create } from "react-test-renderer";
-import { describe, expect, it, vi } from "vitest";
-
-const { mockUseIntegrations } = vi.hoisted(() => ({
- mockUseIntegrations: vi.fn(),
-}));
-
-vi.mock("@/lib/theme", () => ({
- useThemeColors: () => ({
- gray: {
- 9: "#666666",
- 12: "#111111",
- },
- accent: {
- 9: "#ff5500",
- contrast: "#ffffff",
- },
- }),
-}));
-
-vi.mock("../hooks/useIntegrations", () => ({
- useIntegrations: mockUseIntegrations,
-}));
-
-vi.mock("./GitHubConnectionPrompt", () => ({
- GitHubConnectionPrompt: (props: Record<string, unknown>) =>
- createElement("GitHubConnectionPrompt", props),
-}));
-
-vi.mock("./GitHubLoadNotice", () => ({
- GitHubLoadNotice: (props: Record<string, unknown>) =>
- createElement("GitHubLoadNotice", props, props.message as string),
-}));
-
-vi.mock("../composer/RepositoryPickerInline", () => ({
- RepositoryPickerInline: (props: Record<string, unknown>) =>
- createElement("RepositoryPickerInline", props),
-}));
-
-vi.mock("./ScheduleEditor", () => ({
- ScheduleEditor: (props: Record<string, unknown>) =>
- createElement("ScheduleEditor", props),
-}));
-
-vi.mock("@/features/chat/components/MarkdownText", () => ({
- MarkdownText: (props: Record<string, unknown>) =>
- createElement("MarkdownText", props),
-}));
-
-import { AutomationForm } from "./AutomationForm";
-
-describe("AutomationForm", () => {
- it("submits successfully when repository selection is optional", async () => {
- mockUseIntegrations.mockReturnValue({
- error: null,
- hasGithubIntegration: null,
- repositoryOptions: [],
- repositoryWarning: null,
- isLoading: false,
- refetch: vi.fn(),
- });
- const onSubmit = vi.fn().mockResolvedValue(undefined);
- let renderer: ReturnType<typeof create> | null = null;
-
- act(() => {
- renderer = create(
- createElement(AutomationForm, {
- initialValues: {
- name: "PM product pulse",
- prompt: "Summarize my product signals",
- timezone: "UTC",
- enabled: true,
- },
- isSubmitting: false,
- submitLabel: "Create automation",
- repositoryRequired: false,
- onSubmit,
- }),
- );
- });
-
- if (!renderer) {
- throw new Error("Renderer not created");
- }
-
- // Repository picker is only mounted when `repositoryRequired` is true.
- expect(renderer.root.findAllByType("RepositoryPickerInline")).toHaveLength(
- 0,
- );
-
- const submitButton = renderer.root
- .findAll(
- (node) =>
- typeof node.props.onPress === "function" &&
- node.props.disabled === false,
- )
- .at(-1);
-
- await act(async () => {
- await submitButton?.props.onPress();
- });
-
- expect(onSubmit).toHaveBeenCalledWith(
- expect.objectContaining({
- name: "PM product pulse",
- prompt: "Summarize my product signals",
- repository: "",
- github_integration: null,
- timezone: "UTC",
- }),
- );
- });
-
- it("shows the GitHub connection prompt when repository access is required", () => {
- mockUseIntegrations.mockReturnValue({
- error: null,
- hasGithubIntegration: false,
- repositoryOptions: [],
- repositoryWarning: null,
- isLoading: false,
- refetch: vi.fn(),
- });
- let renderer: ReturnType<typeof create> | null = null;
-
- act(() => {
- renderer = create(
- createElement(AutomationForm, {
- initialValues: {
- name: "Developer morning briefing",
- prompt: "Summarize my PRs",
- timezone: "UTC",
- enabled: true,
- },
- isSubmitting: false,
- submitLabel: "Create automation",
- repositoryRequired: true,
- onSubmit: vi.fn(),
- }),
- );
- });
-
- if (!renderer) {
- throw new Error("Renderer not created");
- }
-
- expect(renderer.root.findAllByType("GitHubConnectionPrompt")).toHaveLength(
- 1,
- );
- });
-
- it("renders markdown preview when the prompt starts in preview mode", () => {
- mockUseIntegrations.mockReturnValue({
- error: null,
- hasGithubIntegration: null,
- repositoryOptions: [],
- repositoryWarning: null,
- isLoading: false,
- refetch: vi.fn(),
- });
- let renderer: ReturnType<typeof create> | null = null;
-
- act(() => {
- renderer = create(
- createElement(AutomationForm, {
- initialValues: {
- name: "Daily brief",
- prompt: "## Summary\n- Check PRs",
- timezone: "UTC",
- enabled: true,
- },
- initialPromptMode: "preview",
- isSubmitting: false,
- submitLabel: "Create automation",
- repositoryRequired: false,
- onSubmit: vi.fn(),
- }),
- );
- });
-
- if (!renderer) {
- throw new Error("Renderer not created");
- }
-
- expect(renderer.root.findAllByType(TextInput)).toHaveLength(1);
- expect(renderer.root.findByType("MarkdownText").props.content).toBe(
- "## Summary\n- Check PRs",
- );
- });
-
- it("requires repository selection for repo-backed submissions", async () => {
- mockUseIntegrations.mockReturnValue({
- error: null,
- hasGithubIntegration: true,
- repositoryOptions: [
- {
- integrationId: 7,
- integrationLabel: "PostHog",
- repository: "posthog/posthog",
- },
- ],
- repositoryWarning: null,
- isLoading: false,
- refetch: vi.fn(),
- });
- const onSubmit = vi.fn().mockResolvedValue(undefined);
- let renderer: ReturnType<typeof create> | null = null;
-
- act(() => {
- renderer = create(
- createElement(AutomationForm, {
- initialValues: {
- name: "Developer morning briefing",
- prompt: "Summarize my PRs",
- timezone: "UTC",
- enabled: true,
- },
- isSubmitting: false,
- submitLabel: "Create automation",
- repositoryRequired: true,
- onSubmit,
- }),
- );
- });
-
- if (!renderer) {
- throw new Error("Renderer not created");
- }
-
- const repositoryPicker = renderer.root.findByType("RepositoryPickerInline");
-
- // The new picker emits `RepositoryOption` objects (with the integration
- // label too) rather than the raw `RepositorySelection` shape used by
- // the old inline list.
- act(() => {
- repositoryPicker.props.onChange({
- integrationId: 7,
- integrationLabel: "PostHog",
- repository: "posthog/posthog",
- });
- });
-
- const submitButton = renderer.root
- .findAll(
- (node) =>
- typeof node.props.onPress === "function" &&
- node.props.disabled === false,
- )
- .at(-1);
-
- await act(async () => {
- await submitButton?.props.onPress();
- });
-
- expect(onSubmit).toHaveBeenCalledWith(
- expect.objectContaining({
- repository: "posthog/posthog",
- github_integration: 7,
- }),
- );
- });
-});
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/AutomationForm.tsx b/products/desktop/apps/mobile/src/features/tasks/components/AutomationForm.tsx
deleted file mode 100644
index 56387f474df4..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/components/AutomationForm.tsx
+++ /dev/null
@@ -1,517 +0,0 @@
-import { Text } from "@components/text";
-import type { CreateTaskAutomationOptions } from "@posthog/api-client/posthog-client";
-import {
- type AutomationScheduleDraft,
- buildCronExpression,
- createDefaultScheduleDraft,
- deriveAutomationName,
- parseCronExpression,
-} from "@posthog/core/automations/automationSchedule";
-import { CaretDown, GithubLogo } from "phosphor-react-native";
-import { type MutableRefObject, useEffect, useMemo, useState } from "react";
-import {
- ActivityIndicator,
- Pressable,
- Switch,
- TextInput,
- View,
-} from "react-native";
-import { MarkdownText } from "@/features/chat/components/MarkdownText";
-import { useThemeColors } from "@/lib/theme";
-import { RepositoryPickerInline } from "../composer/RepositoryPickerInline";
-import { useIntegrations } from "../hooks/useIntegrations";
-import type { RepositorySelection } from "../types";
-import {
- findRepositoryOption,
- isRepositorySelectionComplete,
- toRepositorySelection,
-} from "../utils/repositorySelection";
-import { GitHubConnectionPrompt } from "./GitHubConnectionPrompt";
-import { GitHubLoadNotice } from "./GitHubLoadNotice";
-import { ScheduleEditor } from "./ScheduleEditor";
-
-interface AutomationFormProps {
- initialValues?: {
- name?: string;
- prompt?: string;
- repositorySelection?: RepositorySelection;
- cronExpression?: string;
- timezone?: string;
- enabled?: boolean;
- };
- isSubmitting: boolean;
- submitLabel: string;
- fieldError?: {
- attr: string | null;
- message: string | null;
- } | null;
- generalError?: string | null;
- onSubmit: (values: CreateTaskAutomationOptions) => Promise<void> | void;
- onCancel?: () => void;
- repositoryRequired?: boolean;
- initialPromptMode?: "edit" | "preview";
- /** When true, suppress the built-in Cancel + Submit row. The parent
- * screen is then responsible for rendering its own footer and
- * triggering submission via `submitRef`. Used by screens that want a
- * floating action button anchored to the screen instead of an inline
- * footer that scrolls with the form. */
- hideFooter?: boolean;
- /** Mutable ref that the form populates with its internal submit handler.
- * Lets a parent screen trigger validation+submission from a button
- * rendered outside the form's tree (e.g. a screen-anchored FAB).
- * Only meaningful alongside `hideFooter`. */
- submitRef?: MutableRefObject<(() => void) | null>;
- /** Fires whenever the form's derived `canSubmit` flag changes, so the
- * parent can mirror the disabled/enabled state on an external button. */
- onCanSubmitChange?: (canSubmit: boolean) => void;
-}
-
-export function AutomationForm({
- initialValues,
- isSubmitting,
- submitLabel,
- fieldError,
- generalError,
- onSubmit,
- onCancel,
- repositoryRequired = true,
- initialPromptMode = "edit",
- hideFooter = false,
- submitRef,
- onCanSubmitChange,
-}: AutomationFormProps) {
- const themeColors = useThemeColors();
- const {
- error,
- hasGithubIntegration,
- repositoryOptions,
- repositoryWarning,
- isLoading,
- isRefreshingInBackground,
- refetch,
- } = useIntegrations({ enabled: repositoryRequired });
-
- const [name, setName] = useState(initialValues?.name ?? "");
- const [prompt, setPrompt] = useState(initialValues?.prompt ?? "");
- const [timezone, setTimezone] = useState(initialValues?.timezone ?? "UTC");
- const [enabled, setEnabled] = useState(initialValues?.enabled ?? true);
- const [repositorySelection, setRepositorySelection] =
- useState<RepositorySelection>(
- initialValues?.repositorySelection ?? {
- integrationId: null,
- repository: null,
- },
- );
- const [scheduleDraft, setScheduleDraft] = useState<AutomationScheduleDraft>(
- initialValues?.cronExpression
- ? parseCronExpression(initialValues.cronExpression)
- : createDefaultScheduleDraft(),
- );
- const [hasEditedName, setHasEditedName] = useState(
- !!initialValues?.name?.trim(),
- );
- const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);
- const [promptMode, setPromptMode] = useState<"edit" | "preview">(
- initialPromptMode,
- );
- const [repoPickerOpen, setRepoPickerOpen] = useState(false);
-
- useEffect(() => {
- if (hasEditedName) {
- return;
- }
-
- setName(deriveAutomationName(prompt));
- }, [prompt, hasEditedName]);
-
- const validationErrors = useMemo(
- () => ({
- name:
- fieldError?.attr === "name"
- ? fieldError.message
- : hasAttemptedSubmit && !name.trim()
- ? "Name is required."
- : null,
- prompt:
- fieldError?.attr === "prompt"
- ? fieldError.message
- : hasAttemptedSubmit && !prompt.trim()
- ? "Prompt is required."
- : null,
- repository:
- fieldError?.attr === "repository"
- ? fieldError.message
- : repositoryRequired &&
- hasAttemptedSubmit &&
- !isRepositorySelectionComplete(repositorySelection)
- ? "Repository selection is required."
- : null,
- cronExpression:
- fieldError?.attr === "cron_expression" ? fieldError.message : null,
- timezone:
- fieldError?.attr === "timezone"
- ? fieldError.message
- : hasAttemptedSubmit && !timezone.trim()
- ? "Timezone is required."
- : null,
- }),
- [
- fieldError,
- hasAttemptedSubmit,
- name,
- prompt,
- repositorySelection,
- repositoryRequired,
- timezone,
- ],
- );
-
- const canSubmit =
- !!name.trim() &&
- !!prompt.trim() &&
- !!timezone.trim() &&
- (!repositoryRequired ||
- isRepositorySelectionComplete(repositorySelection)) &&
- !isSubmitting;
- const repositoryLoadBlocked =
- repositoryRequired && !!repositoryWarning && repositoryOptions.length === 0;
-
- const selectedRepositoryOption = useMemo(
- () => findRepositoryOption(repositoryOptions, repositorySelection),
- [repositoryOptions, repositorySelection],
- );
-
- // Disambiguate repos that exist across multiple integrations by appending
- // the integration label — matches the new-task screen's pill behaviour.
- const repositoryPillLabel = useMemo(() => {
- if (!selectedRepositoryOption) return "Select repository…";
- const sameRepoCount = repositoryOptions.filter(
- (option) => option.repository === selectedRepositoryOption.repository,
- ).length;
- return sameRepoCount > 1
- ? `${selectedRepositoryOption.repository} · ${selectedRepositoryOption.integrationLabel}`
- : selectedRepositoryOption.repository;
- }, [repositoryOptions, selectedRepositoryOption]);
-
- const handleSubmit = async () => {
- setHasAttemptedSubmit(true);
- if (!canSubmit) {
- return;
- }
-
- await onSubmit({
- name: name.trim(),
- prompt: prompt.trim(),
- repository: repositoryRequired
- ? (repositorySelection.repository ?? "")
- : "",
- github_integration: repositoryRequired
- ? repositorySelection.integrationId
- : null,
- cron_expression: buildCronExpression(scheduleDraft),
- timezone: timezone.trim(),
- enabled,
- });
- };
-
- // Expose the submit handler to a parent screen that wants to render its
- // own footer (e.g. a floating action button). We re-assign on every
- // render so the ref always points at the latest closure — the handler
- // captures current form state via the surrounding `useState` values.
- useEffect(() => {
- if (!submitRef) return;
- submitRef.current = handleSubmit;
- return () => {
- if (submitRef.current === handleSubmit) submitRef.current = null;
- };
- });
-
- // Mirror `canSubmit` to the parent so an external button can disable
- // itself the moment the form becomes invalid.
- useEffect(() => {
- onCanSubmitChange?.(canSubmit);
- }, [onCanSubmitChange, canSubmit]);
-
- if (repositoryRequired && isLoading && hasGithubIntegration === null) {
- return (
- <View className="items-center rounded-xl border border-gray-6 bg-gray-2 p-5">
- <ActivityIndicator size="small" color={themeColors.accent[9]} />
- <Text className="mt-2 text-gray-11 text-sm">
- Loading repositories...
- </Text>
- </View>
- );
- }
-
- if (repositoryRequired && (error || repositoryLoadBlocked)) {
- return (
- <GitHubLoadNotice
- message={
- error ?? repositoryWarning ?? "Could not load GitHub repositories."
- }
- onRetry={refetch}
- />
- );
- }
-
- if (repositoryRequired && hasGithubIntegration === false) {
- return (
- <GitHubConnectionPrompt
- scope="team"
- onConnected={refetch}
- title="Connect GitHub to create automations"
- description="Automations need repository access before they can run."
- />
- );
- }
-
- return (
- <View className="gap-4">
- {/* 1. Name — first config field. Auto-populates from the prompt until
- the user edits it manually. */}
- <View className="rounded-xl bg-gray-2 p-4">
- <Text
- className="mb-2 text-[11px] text-gray-9 uppercase"
- style={{ letterSpacing: 0.5 }}
- >
- Name
- </Text>
- <TextInput
- className="rounded-xl border border-gray-5 bg-background px-3.5 py-3 text-[15px] text-gray-12"
- placeholder="Daily PR review"
- placeholderTextColor={themeColors.gray[9]}
- value={name}
- onChangeText={(nextName) => {
- setHasEditedName(true);
- setName(nextName);
- }}
- />
- {validationErrors.name && (
- <Text className="mt-1 text-status-error text-xs">
- {validationErrors.name}
- </Text>
- )}
- </View>
-
- {/* 2. Repository — pill trigger + inline dropdown. Mirrors the
- new-task screen so the picker UX is consistent across the app. */}
- {repositoryRequired && (
- <View className="rounded-xl bg-gray-2 p-4">
- {repositoryWarning && (
- <View className="mb-3">
- <GitHubLoadNotice
- message={repositoryWarning}
- onRetry={refetch}
- tone="warning"
- />
- </View>
- )}
- <Text
- className="mb-2 text-[11px] text-gray-9 uppercase"
- style={{ letterSpacing: 0.5 }}
- >
- Repository
- </Text>
- <Pressable
- onPress={() => setRepoPickerOpen((prev) => !prev)}
- accessibilityRole="button"
- accessibilityLabel="Select repository"
- className={`flex-row items-center gap-2 rounded-xl border px-3.5 py-3 active:bg-gray-3 ${
- repoPickerOpen
- ? "border-accent-7 bg-accent-3"
- : "border-gray-5 bg-background"
- }`}
- >
- <GithubLogo
- size={16}
- color={
- selectedRepositoryOption
- ? themeColors.gray[12]
- : themeColors.gray[10]
- }
- weight={selectedRepositoryOption ? "fill" : "regular"}
- />
- <Text
- className={`flex-1 text-[15px] ${
- selectedRepositoryOption ? "text-gray-12" : "text-gray-9"
- }`}
- numberOfLines={1}
- >
- {repositoryPillLabel}
- </Text>
- <CaretDown
- size={12}
- color={themeColors.gray[10]}
- style={{
- transform: [{ rotate: repoPickerOpen ? "180deg" : "0deg" }],
- }}
- />
- </Pressable>
-
- {/* Inline dropdown — same component used by the new-task screen.
- Renders directly below the pill, so the form pushes content
- down rather than popping a modal. The picker self-unmounts
- once its exit animation finishes, so we only need the
- wrapper margin while it's open. */}
- <View className={repoPickerOpen ? "mt-2" : ""}>
- <RepositoryPickerInline
- open={repoPickerOpen}
- repositoryOptions={repositoryOptions}
- selected={selectedRepositoryOption}
- loading={isLoading && repositoryOptions.length === 0}
- isRefreshing={isRefreshingInBackground}
- // The automation form lives inside a parent ScrollView, so
- // the picker can't use its internal FlatList without
- // triggering RN's nested-VirtualizedList warning.
- nested
- onChange={(option) =>
- setRepositorySelection(toRepositorySelection(option))
- }
- onClose={() => setRepoPickerOpen(false)}
- />
- </View>
-
- {validationErrors.repository && (
- <Text className="mt-1 text-status-error text-xs">
- {validationErrors.repository}
- </Text>
- )}
- </View>
- )}
-
- {/* 3. Schedule */}
- <View className="rounded-xl bg-gray-2 p-4">
- <ScheduleEditor
- value={scheduleDraft}
- timezone={timezone}
- onChange={setScheduleDraft}
- onTimezoneChange={setTimezone}
- />
- {(validationErrors.cronExpression || validationErrors.timezone) && (
- <Text className="mt-1 text-status-error text-xs">
- {validationErrors.cronExpression || validationErrors.timezone}
- </Text>
- )}
- </View>
-
- {/* 4. Enabled */}
- <View className="flex-row items-center justify-between rounded-xl bg-gray-2 px-4 py-4">
- <View className="flex-1 pr-3">
- <Text className="font-semibold text-[15px] text-gray-12">
- Enabled
- </Text>
- <Text className="mt-1 text-gray-9 text-xs">
- Turn this off to pause scheduled runs without deleting it.
- </Text>
- </View>
- <Switch value={enabled} onValueChange={setEnabled} />
- </View>
-
- {/* 5. Prompt — the "skill" content. Placed last so the configuration
- (name, repo, schedule, enabled) is visible above the fold and the
- potentially-long prompt sits at the bottom for editing/preview. */}
- <View className="rounded-xl bg-gray-2 p-4">
- <Text
- className="mb-2 text-[11px] text-gray-9 uppercase"
- style={{ letterSpacing: 0.5 }}
- >
- Prompt
- </Text>
- <View className="mb-2 flex-row gap-2">
- {(["edit", "preview"] as const).map((mode) => {
- const active = promptMode === mode;
-
- return (
- <Pressable
- key={mode}
- onPress={() => setPromptMode(mode)}
- className={`rounded-lg border px-3 py-2 ${
- active
- ? "border-accent-9 bg-accent-3"
- : "border-gray-5 bg-background"
- }`}
- >
- <Text
- className={`font-medium text-[13px] ${
- active ? "text-accent-11" : "text-gray-11"
- }`}
- >
- {mode === "edit" ? "Edit" : "Preview"}
- </Text>
- </Pressable>
- );
- })}
- </View>
- {promptMode === "edit" ? (
- <TextInput
- className="min-h-[128px] rounded-xl border border-gray-5 bg-background px-3.5 py-3 text-[15px] text-gray-12"
- placeholder="What should this automation ask the agent to do?"
- placeholderTextColor={themeColors.gray[9]}
- value={prompt}
- onChangeText={setPrompt}
- multiline
- textAlignVertical="top"
- />
- ) : (
- <View className="min-h-[128px] rounded-xl border border-gray-5 bg-background px-3.5 py-3">
- {prompt.trim() ? (
- <MarkdownText content={prompt} />
- ) : (
- <Text className="text-gray-9 text-sm">
- Nothing to preview yet.
- </Text>
- )}
- </View>
- )}
- {validationErrors.prompt && (
- <Text className="mt-1 text-status-error text-xs">
- {validationErrors.prompt}
- </Text>
- )}
- </View>
-
- {generalError && (
- <View className="rounded-xl bg-status-error/10 px-4 py-3">
- <Text className="text-sm text-status-error">{generalError}</Text>
- </View>
- )}
-
- {!hideFooter && (
- <View className="flex-row gap-3">
- {onCancel && (
- <Pressable
- onPress={onCancel}
- className="flex-1 rounded-xl border border-gray-6 bg-gray-2 py-3"
- >
- <Text className="text-center font-medium text-gray-12">
- Cancel
- </Text>
- </Pressable>
- )}
- <Pressable
- onPress={handleSubmit}
- disabled={!canSubmit}
- className={`rounded-xl py-3 ${
- onCancel ? "flex-1" : ""
- } ${canSubmit ? "bg-accent-9" : "bg-gray-3"}`}
- >
- {isSubmitting ? (
- <ActivityIndicator
- size="small"
- color={themeColors.accent.contrast}
- />
- ) : (
- <Text
- className={`text-center font-medium ${
- canSubmit ? "text-accent-contrast" : "text-gray-9"
- }`}
- >
- {submitLabel}
- </Text>
- )}
- </Pressable>
- </View>
- )}
- </View>
- );
-}
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/AutomationItem.tsx b/products/desktop/apps/mobile/src/features/tasks/components/AutomationItem.tsx
deleted file mode 100644
index 220f58fdebb3..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/components/AutomationItem.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import { Text } from "@components/text";
-import type { TaskAutomation } from "@posthog/api-client/posthog-client";
-import { formatAutomationScheduleSummary } from "@posthog/core/automations/automationSchedule";
-import { getAutomationTemplatePresentation } from "@posthog/core/automations/automationTemplatePresentation";
-import type { TaskRun } from "@posthog/shared";
-import { format, formatDistanceToNow } from "date-fns";
-import { memo } from "react";
-import { Pressable, View } from "react-native";
-import { AutomationStatusBadge } from "./AutomationStatusBadge";
-
-interface AutomationItemProps {
- automation: TaskAutomation;
- onPress: (automation: TaskAutomation) => void;
- lastTaskRunStatus?: TaskRun["status"] | null;
-}
-
-function AutomationItemComponent({
- automation,
- onPress,
- lastTaskRunStatus,
-}: AutomationItemProps) {
- const presentation = getAutomationTemplatePresentation(automation);
- const lastRunDisplay = automation.last_run_at
- ? new Date(automation.last_run_at).getTime() >
- Date.now() - 24 * 60 * 60 * 1000
- ? formatDistanceToNow(new Date(automation.last_run_at), {
- addSuffix: true,
- })
- : format(new Date(automation.last_run_at), "MMM d")
- : "No runs yet";
-
- return (
- <Pressable
- onPress={() => onPress(automation)}
- className="border-gray-6 border-b px-3 py-3 active:bg-gray-3"
- >
- <View className="flex-row items-center justify-between gap-3">
- <Text
- className="flex-1 font-medium text-gray-12 text-sm"
- numberOfLines={1}
- >
- {automation.name}
- </Text>
- <Text className="text-gray-8 text-xs">{lastRunDisplay}</Text>
- </View>
-
- <View className="mt-1">
- <AutomationStatusBadge
- enabled={automation.enabled}
- lastRunStatus={automation.last_run_status}
- lastTaskRunStatus={lastTaskRunStatus}
- />
- </View>
-
- <Text className="mt-2 text-gray-11 text-xs" numberOfLines={1}>
- {presentation.secondaryLabel}
- </Text>
- <Text className="mt-0.5 text-gray-9 text-xs" numberOfLines={1}>
- {formatAutomationScheduleSummary(automation)}
- </Text>
-
- {automation.last_error && (
- <Text className="mt-2 text-status-error text-xs" numberOfLines={2}>
- {automation.last_error}
- </Text>
- )}
- </Pressable>
- );
-}
-
-export const AutomationItem = memo(AutomationItemComponent);
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/AutomationList.tsx b/products/desktop/apps/mobile/src/features/tasks/components/AutomationList.tsx
deleted file mode 100644
index 1027a5aa463e..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/components/AutomationList.tsx
+++ /dev/null
@@ -1,130 +0,0 @@
-import { Text } from "@components/text";
-import type { TaskAutomation } from "@posthog/api-client/posthog-client";
-import { Plus } from "phosphor-react-native";
-import {
- ActivityIndicator,
- FlatList,
- Pressable,
- RefreshControl,
- View,
-} from "react-native";
-import { useThemeColors } from "@/lib/theme";
-import { useAutomations } from "../hooks/useAutomations";
-import { useTasks } from "../hooks/useTasks";
-import { AutomationItem } from "./AutomationItem";
-
-interface AutomationListProps {
- onAutomationPress?: (automationId: string) => void;
- onCreateAutomation?: () => void;
- /** Top inset so the list can scroll behind a floating header. */
- contentInsetTop?: number;
-}
-
-function EmptyAutomationState({
- onCreateAutomation,
-}: Pick<AutomationListProps, "onCreateAutomation">) {
- const themeColors = useThemeColors();
-
- return (
- <View className="flex-1 items-center justify-center p-6">
- <Text className="mb-2 text-center font-semibold text-gray-12 text-lg">
- No automations yet
- </Text>
- <Text className="mb-6 text-center text-gray-11 text-sm">
- Schedule recurring tasks
- </Text>
- {onCreateAutomation && (
- <Pressable
- onPress={onCreateAutomation}
- className="flex-row items-center gap-2 rounded-full px-6 py-3.5 active:opacity-80"
- style={{ backgroundColor: themeColors.accent[9] }}
- >
- <Plus size={18} color={themeColors.accent.contrast} weight="bold" />
- <Text className="font-semibold text-[15px] text-accent-contrast">
- New automation
- </Text>
- </Pressable>
- )}
- </View>
- );
-}
-
-export function AutomationList({
- onAutomationPress,
- onCreateAutomation,
- contentInsetTop = 0,
-}: AutomationListProps) {
- const { automations, isLoading, error, refetch } = useAutomations();
- const { allTasks: automationTasks } = useTasks({
- originProduct: "automation",
- });
- const themeColors = useThemeColors();
-
- const handleRefresh = async () => {
- await refetch();
- };
-
- const handleAutomationPress = (automation: TaskAutomation) => {
- onAutomationPress?.(automation.id);
- };
-
- const taskStatusById = new Map(
- automationTasks.map((task) => [task.id, task.latest_run?.status ?? null]),
- );
-
- if (error) {
- return (
- <View className="flex-1 items-center justify-center p-6">
- <Text className="mb-4 text-center text-status-error">{error}</Text>
- <Pressable
- onPress={handleRefresh}
- className="rounded-lg bg-gray-3 px-4 py-2"
- >
- <Text className="text-gray-12">Retry</Text>
- </Pressable>
- </View>
- );
- }
-
- if (isLoading && automations.length === 0) {
- return (
- <View className="flex-1 items-center justify-center">
- <ActivityIndicator size="large" color={themeColors.accent[9]} />
- <Text className="mt-4 text-gray-11">Loading automations...</Text>
- </View>
- );
- }
-
- if (automations.length === 0) {
- return <EmptyAutomationState onCreateAutomation={onCreateAutomation} />;
- }
-
- return (
- <FlatList
- data={automations}
- keyExtractor={(item) => item.id}
- renderItem={({ item }) => (
- <AutomationItem
- automation={item}
- onPress={handleAutomationPress}
- lastTaskRunStatus={
- item.last_task_id
- ? (taskStatusById.get(item.last_task_id) ?? null)
- : null
- }
- />
- )}
- refreshControl={
- <RefreshControl
- refreshing={isLoading}
- onRefresh={handleRefresh}
- tintColor={themeColors.accent[9]}
- />
- }
- contentContainerStyle={{
- paddingTop: contentInsetTop,
- paddingBottom: 100,
- }}
- />
- );
-}
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/AutomationSkillCard.test.tsx b/products/desktop/apps/mobile/src/features/tasks/components/AutomationSkillCard.test.tsx
deleted file mode 100644
index dfb3ec0879d1..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/components/AutomationSkillCard.test.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-import { createElement } from "react";
-import { act, create } from "react-test-renderer";
-import { describe, expect, it, vi } from "vitest";
-
-vi.mock("@/lib/theme", () => ({
- useThemeColors: () => ({
- accent: {
- 11: "#ff5500",
- },
- }),
-}));
-
-vi.mock("phosphor-react-native", () => ({
- CaretDown: (props: Record<string, unknown>) =>
- createElement("CaretDown", props),
- CaretUp: (props: Record<string, unknown>) => createElement("CaretUp", props),
-}));
-
-import { AutomationSkillCard } from "./AutomationSkillCard";
-
-describe("AutomationSkillCard", () => {
- it("collapses long descriptions by default and expands on demand", () => {
- const onPress = vi.fn();
- let renderer: ReturnType<typeof create> | null = null;
-
- act(() => {
- renderer = create(
- createElement(AutomationSkillCard, {
- skill: {
- name: "shared-daily-brief",
- description:
- "A longer description that should overflow two lines in the card preview when measured by the native text layout callback.",
- },
- onPress,
- }),
- );
- });
-
- if (!renderer) {
- throw new Error("Renderer not created");
- }
-
- const descriptionText =
- "A longer description that should overflow two lines in the card preview when measured by the native text layout callback.";
- const visibleDescriptionNode = renderer.root.findAll(
- (node) =>
- node.props.numberOfLines === 2 &&
- node.props.children === descriptionText,
- )[0];
- const measurementNode = renderer.root.findAll(
- (node) =>
- typeof node.props.onTextLayout === "function" &&
- node.props.children === descriptionText,
- )[0];
-
- if (!visibleDescriptionNode || !measurementNode) {
- throw new Error("Description node not found");
- }
-
- expect(visibleDescriptionNode.props.numberOfLines).toBe(2);
-
- act(() => {
- measurementNode.props.onTextLayout({
- nativeEvent: {
- lines: [{}, {}, {}],
- },
- });
- });
-
- const toggle = renderer.root.findAll(
- (node) =>
- typeof node.props.onPress === "function" &&
- node.props.children?.[1]?.props?.children === "Show more",
- )[0];
-
- act(() => {
- toggle.props.onPress({ stopPropagation: vi.fn() });
- });
-
- const updatedDescriptionNode = renderer.root.findAll(
- (node) =>
- node.props.children === descriptionText &&
- "numberOfLines" in node.props &&
- node.props.children === descriptionText,
- )[0];
-
- expect(updatedDescriptionNode?.props.numberOfLines).toBeUndefined();
- expect(
- renderer.root.findAll((node) => node.props.children === "Show less")
- .length,
- ).toBeGreaterThan(0);
- });
-});
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/AutomationSkillCard.tsx b/products/desktop/apps/mobile/src/features/tasks/components/AutomationSkillCard.tsx
deleted file mode 100644
index 12d7eba64ff0..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/components/AutomationSkillCard.tsx
+++ /dev/null
@@ -1,92 +0,0 @@
-import type { LlmSkillListItem } from "@posthog/api-client";
-import { CaretDown, CaretUp } from "phosphor-react-native";
-import { useState } from "react";
-import {
- type NativeSyntheticEvent,
- Pressable,
- type TextLayoutEventData,
- View,
-} from "react-native";
-import { Text } from "@/components/text";
-import { useThemeColors } from "@/lib/theme";
-
-interface AutomationSkillCardProps {
- skill: LlmSkillListItem;
- onPress: (skillName: string) => void;
-}
-
-export function AutomationSkillCard({
- skill,
- onPress,
-}: AutomationSkillCardProps) {
- const themeColors = useThemeColors();
- const [isExpanded, setIsExpanded] = useState(false);
- const [hasMeasuredOverflow, setHasMeasuredOverflow] = useState(false);
- const [isOverflowing, setIsOverflowing] = useState(false);
- const description =
- skill.description ?? "Shared automation starter from your team.";
-
- function handleTextLayout(
- event: NativeSyntheticEvent<TextLayoutEventData>,
- ): void {
- if (hasMeasuredOverflow) {
- return;
- }
-
- setIsOverflowing(event.nativeEvent.lines.length > 2);
- setHasMeasuredOverflow(true);
- }
-
- return (
- <Pressable
- accessibilityRole="button"
- onPress={() => onPress(skill.name)}
- className="rounded-xl border border-gray-6 bg-gray-1 px-4 py-4 active:opacity-80"
- >
- <Text className="font-semibold text-[16px] text-gray-12">
- {skill.name}
- </Text>
- <View className="relative">
- <Text
- className="mt-2 text-gray-11 text-sm"
- numberOfLines={isExpanded ? undefined : 2}
- >
- {description}
- </Text>
- {!hasMeasuredOverflow && (
- <View
- className="pointer-events-none absolute inset-x-0 opacity-0"
- accessible={false}
- >
- <Text
- className="mt-2 text-gray-11 text-sm"
- onTextLayout={handleTextLayout}
- >
- {description}
- </Text>
- </View>
- )}
- </View>
- {isOverflowing && (
- <Pressable
- accessibilityRole="button"
- onPress={(event) => {
- event.stopPropagation();
- setIsExpanded((value) => !value);
- }}
- hitSlop={6}
- className="mt-1 flex-row items-center gap-1 self-start py-1 active:opacity-60"
- >
- {isExpanded ? (
- <CaretUp size={12} color={themeColors.accent[11]} />
- ) : (
- <CaretDown size={12} color={themeColors.accent[11]} />
- )}
- <Text className="text-[12px] text-accent-11">
- {isExpanded ? "Show less" : "Show more"}
- </Text>
- </Pressable>
- )}
- </Pressable>
- );
-}
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/AutomationSkillChooser.test.tsx b/products/desktop/apps/mobile/src/features/tasks/components/AutomationSkillChooser.test.tsx
deleted file mode 100644
index e9cd9bc0f584..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/components/AutomationSkillChooser.test.tsx
+++ /dev/null
@@ -1,167 +0,0 @@
-import { createElement } from "react";
-import { act, create } from "react-test-renderer";
-import { describe, expect, it, vi } from "vitest";
-
-const { mockUseSkillStoreSkills } = vi.hoisted(() => ({
- mockUseSkillStoreSkills: vi.fn(),
-}));
-
-vi.mock("@/lib/theme", () => ({
- useThemeColors: () => ({
- gray: {
- 9: "#666666",
- },
- accent: {
- 9: "#ff5500",
- },
- }),
-}));
-
-vi.mock("../skills/hooks", () => ({
- useSkillStoreSkills: mockUseSkillStoreSkills,
-}));
-
-vi.mock("./AutomationSkillCard", () => ({
- AutomationSkillCard: ({
- skill,
- onPress,
- }: {
- skill: { name: string };
- onPress: (skillName: string) => void;
- }) =>
- createElement(
- "AutomationSkillCard",
- {
- onPress: () => onPress(skill.name),
- title: skill.name,
- },
- skill.name,
- ),
-}));
-
-import { AutomationSkillChooser } from "./AutomationSkillChooser";
-
-describe("AutomationSkillChooser", () => {
- it("renders start from scratch before skill-store entries", () => {
- mockUseSkillStoreSkills.mockReturnValue({
- data: [
- { name: "shared-daily-brief", description: "Briefing starter" },
- { name: "shared-pr-triage", description: "PR triage starter" },
- ],
- isLoading: false,
- error: null,
- refetch: vi.fn(),
- });
-
- let renderer: ReturnType<typeof create> | null = null;
- act(() => {
- renderer = create(
- createElement(AutomationSkillChooser, {
- onCreateCustom: vi.fn(),
- onSelectSkill: vi.fn(),
- }),
- );
- });
-
- if (!renderer) {
- throw new Error("Renderer not created");
- }
-
- const labels = renderer.root
- .findAll((node) => typeof node.props.children === "string")
- .map((node) => node.props.children);
-
- expect(labels).toContain("Start from scratch");
- expect(labels).toContain("shared-daily-brief");
- expect(labels).toContain("shared-pr-triage");
- expect(labels.indexOf("Start from scratch")).toBeLessThan(
- labels.indexOf("shared-daily-brief"),
- );
- });
-
- it("routes scratch and skill selections through the expected callbacks", () => {
- mockUseSkillStoreSkills.mockReturnValue({
- data: [{ name: "shared-daily-brief", description: "Briefing starter" }],
- isLoading: false,
- error: null,
- refetch: vi.fn(),
- });
-
- const onCreateCustom = vi.fn();
- const onSelectSkill = vi.fn();
- let renderer: ReturnType<typeof create> | null = null;
- act(() => {
- renderer = create(
- createElement(AutomationSkillChooser, {
- onCreateCustom,
- onSelectSkill,
- }),
- );
- });
-
- if (!renderer) {
- throw new Error("Renderer not created");
- }
-
- const buttons = renderer.root.findAll(
- (node) => typeof node.props.onPress === "function",
- );
- const skillCard = renderer.root.findByType("AutomationSkillCard");
-
- buttons[0]?.props.onPress();
- skillCard.props.onPress();
-
- expect(onCreateCustom).toHaveBeenCalledOnce();
- expect(onSelectSkill).toHaveBeenCalledWith("shared-daily-brief");
- });
-
- it("filters the skill list by search text and shows a no-match state", () => {
- mockUseSkillStoreSkills.mockReturnValue({
- data: [
- { name: "shared-daily-brief", description: "Morning update" },
- { name: "shared-pr-triage", description: "Pull request queue" },
- ],
- isLoading: false,
- error: null,
- refetch: vi.fn(),
- });
-
- let renderer: ReturnType<typeof create> | null = null;
- act(() => {
- renderer = create(
- createElement(AutomationSkillChooser, {
- onCreateCustom: vi.fn(),
- onSelectSkill: vi.fn(),
- }),
- );
- });
-
- if (!renderer) {
- throw new Error("Renderer not created");
- }
-
- const searchInput = renderer.root.findByProps({
- placeholder: "Search skills",
- });
-
- act(() => {
- searchInput.props.onChangeText("triage");
- });
-
- expect(renderer.root.findAllByType("AutomationSkillCard")).toHaveLength(1);
- expect(renderer.root.findByType("AutomationSkillCard").props.title).toBe(
- "shared-pr-triage",
- );
-
- act(() => {
- searchInput.props.onChangeText("missing");
- });
-
- expect(renderer.root.findAllByType("AutomationSkillCard")).toHaveLength(0);
- expect(
- renderer.root.findAll(
- (node) => node.props.children === "No matching skills",
- ).length,
- ).toBeGreaterThan(0);
- });
-});
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/AutomationSkillChooser.tsx b/products/desktop/apps/mobile/src/features/tasks/components/AutomationSkillChooser.tsx
deleted file mode 100644
index 48990823a602..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/components/AutomationSkillChooser.tsx
+++ /dev/null
@@ -1,123 +0,0 @@
-import { useMemo, useState } from "react";
-import { ActivityIndicator, Pressable, TextInput, View } from "react-native";
-import { Text } from "@/components/text";
-import { useThemeColors } from "@/lib/theme";
-import { useSkillStoreSkills } from "../skills/hooks";
-import { AutomationSkillCard } from "./AutomationSkillCard";
-
-interface AutomationSkillChooserProps {
- onCreateCustom: () => void;
- onSelectSkill: (skillName: string) => void;
-}
-
-export function AutomationSkillChooser({
- onCreateCustom,
- onSelectSkill,
-}: AutomationSkillChooserProps) {
- const themeColors = useThemeColors();
- const { data, isLoading, error, refetch } = useSkillStoreSkills();
- const skills = data ?? [];
- const [search, setSearch] = useState("");
- const filteredSkills = useMemo(() => {
- const query = search.trim().toLowerCase();
-
- if (!query) {
- return skills;
- }
-
- return skills.filter(
- (skill) =>
- skill.name.toLowerCase().includes(query) ||
- skill.description?.toLowerCase().includes(query),
- );
- }, [search, skills]);
-
- return (
- <View className="gap-4">
- <Pressable
- accessibilityRole="button"
- onPress={onCreateCustom}
- className="rounded-xl border border-accent-6 bg-accent-2 px-4 py-4 active:opacity-80"
- >
- <Text className="font-semibold text-[15px] text-gray-12">
- Start from scratch
- </Text>
- <Text className="mt-2 text-gray-11 text-sm">
- Create a custom automation prompt and schedule it yourself.
- </Text>
- </Pressable>
-
- <View className="gap-2">
- <Text className="font-semibold text-[14px] text-gray-12">
- Skill store
- </Text>
- <Text className="text-gray-10 text-sm">
- Shared team skills you can use as automation starters.
- </Text>
- </View>
-
- {isLoading ? (
- <View className="items-center rounded-xl border border-gray-6 bg-gray-1 px-4 py-6">
- <ActivityIndicator size="small" color={themeColors.accent[9]} />
- <Text className="mt-3 text-gray-11 text-sm">Loading skills...</Text>
- </View>
- ) : error ? (
- <View className="rounded-xl border border-gray-6 bg-gray-1 px-4 py-4">
- <Text className="font-medium text-[15px] text-gray-12">
- Skills unavailable
- </Text>
- <Text className="mt-2 text-gray-11 text-sm">{error.message}</Text>
- <Pressable
- accessibilityRole="button"
- onPress={() => void refetch()}
- className="mt-4 self-start rounded-lg border border-gray-6 bg-gray-2 px-3 py-2"
- >
- <Text className="font-medium text-gray-12 text-sm">Try again</Text>
- </Pressable>
- </View>
- ) : skills.length === 0 ? (
- <View className="rounded-xl border border-gray-6 bg-gray-1 px-4 py-4">
- <Text className="font-medium text-[15px] text-gray-12">
- No skills available
- </Text>
- <Text className="mt-2 text-gray-11 text-sm">
- You can still start from scratch above and create a custom
- automation.
- </Text>
- </View>
- ) : (
- <>
- <TextInput
- className="rounded-xl border border-gray-5 bg-background px-3.5 py-3 text-[15px] text-gray-12"
- placeholder="Search skills"
- placeholderTextColor={themeColors.gray[9]}
- value={search}
- onChangeText={setSearch}
- autoCapitalize="none"
- autoCorrect={false}
- clearButtonMode="while-editing"
- />
-
- {filteredSkills.length === 0 ? (
- <View className="rounded-xl border border-gray-6 bg-gray-1 px-4 py-4">
- <Text className="font-medium text-[15px] text-gray-12">
- No matching skills
- </Text>
- <Text className="mt-2 text-gray-11 text-sm">
- {`No skills match "${search.trim()}" yet.`}
- </Text>
- </View>
- ) : (
- filteredSkills.map((skill) => (
- <AutomationSkillCard
- key={skill.name}
- skill={skill}
- onPress={onSelectSkill}
- />
- ))
- )}
- </>
- )}
- </View>
- );
-}
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/AutomationStatusBadge.test.tsx b/products/desktop/apps/mobile/src/features/tasks/components/AutomationStatusBadge.test.tsx
deleted file mode 100644
index 3be63af42cee..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/components/AutomationStatusBadge.test.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import { createElement } from "react";
-import { act, create } from "react-test-renderer";
-import { describe, expect, it } from "vitest";
-import { AutomationStatusBadge } from "./AutomationStatusBadge";
-
-describe("AutomationStatusBadge", () => {
- it("does not render a running chip for active automation runs", () => {
- let renderer: ReturnType<typeof create> | null = null;
-
- act(() => {
- renderer = create(
- createElement(AutomationStatusBadge, {
- enabled: true,
- lastRunStatus: "running",
- lastTaskRunStatus: "in_progress",
- }),
- );
- });
-
- if (!renderer) {
- throw new Error("Renderer not created");
- }
-
- const output = JSON.stringify(renderer.toJSON());
-
- expect(output).toContain("Enabled");
- expect(output).not.toContain("Running");
- });
-
- it("still renders non-running run states", () => {
- let renderer: ReturnType<typeof create> | null = null;
-
- act(() => {
- renderer = create(
- createElement(AutomationStatusBadge, {
- enabled: true,
- lastRunStatus: "success",
- }),
- );
- });
-
- if (!renderer) {
- throw new Error("Renderer not created");
- }
-
- expect(JSON.stringify(renderer.toJSON())).toContain("Success");
- });
-});
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/AutomationStatusBadge.tsx b/products/desktop/apps/mobile/src/features/tasks/components/AutomationStatusBadge.tsx
deleted file mode 100644
index 600b36302e08..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/components/AutomationStatusBadge.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-import { Text } from "@components/text";
-import type { TaskRun } from "@posthog/shared";
-import { View } from "react-native";
-import { getAutomationStatusPresentation } from "../utils/automationStatus";
-
-interface AutomationStatusBadgeProps {
- enabled: boolean;
- lastRunStatus: string | null;
- lastTaskRunStatus?: TaskRun["status"] | null;
-}
-
-export function AutomationStatusBadge({
- enabled,
- lastRunStatus,
- lastTaskRunStatus,
-}: AutomationStatusBadgeProps) {
- const runStatus = getAutomationStatusPresentation({
- lastRunStatus,
- lastTaskRunStatus,
- });
-
- return (
- <View className="flex-row flex-wrap gap-2">
- <View
- className={`rounded px-1.5 py-0.5 ${
- enabled ? "bg-accent-3" : "bg-gray-4"
- }`}
- >
- <Text
- className={`text-xs ${enabled ? "text-accent-11" : "text-gray-11"}`}
- >
- {enabled ? "Enabled" : "Paused"}
- </Text>
- </View>
- {runStatus ? (
- <View className={`rounded px-1.5 py-0.5 ${runStatus.className}`}>
- <Text className={`text-xs ${runStatus.className.split(" ")[1]}`}>
- {runStatus.label}
- </Text>
- </View>
- ) : null}
- </View>
- );
-}
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/CreateAutomationScreen.test.tsx b/products/desktop/apps/mobile/src/features/tasks/components/CreateAutomationScreen.test.tsx
deleted file mode 100644
index 87fb99701468..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/components/CreateAutomationScreen.test.tsx
+++ /dev/null
@@ -1,217 +0,0 @@
-import { createElement } from "react";
-import { act, create } from "react-test-renderer";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const {
- mockReplace,
- mockBack,
- mockMutateAsync,
- mockUseCreateTaskAutomation,
- mockUseSkillStoreSkill,
- routeParams,
-} = vi.hoisted(() => ({
- mockReplace: vi.fn(),
- mockBack: vi.fn(),
- mockMutateAsync: vi.fn(),
- mockUseCreateTaskAutomation: vi.fn(),
- mockUseSkillStoreSkill: vi.fn(),
- routeParams: {} as { skillName?: string | string[] },
-}));
-
-vi.mock("expo-router", () => ({
- Stack: {
- Screen: (props: Record<string, unknown>) =>
- createElement("StackScreen", props),
- },
- useLocalSearchParams: () => routeParams,
- useRouter: () => ({
- replace: mockReplace,
- back: mockBack,
- }),
-}));
-
-vi.mock("expo-localization", () => ({
- getCalendars: () => [{ timeZone: "UTC" }],
-}));
-
-vi.mock("@/lib/theme", () => ({
- useThemeColors: () => ({
- background: "#ffffff",
- gray: {
- 11: "#666666",
- 12: "#111111",
- },
- accent: {
- 9: "#ff5500",
- },
- }),
-}));
-
-vi.mock("@/features/tasks/hooks/useAutomations", () => ({
- useCreateTaskAutomation: mockUseCreateTaskAutomation,
-}));
-
-vi.mock("@/features/tasks/skills/hooks", () => ({
- useSkillStoreSkill: mockUseSkillStoreSkill,
-}));
-
-vi.mock("@/features/tasks/components/AutomationForm", () => ({
- AutomationForm: (props: Record<string, unknown>) =>
- createElement("AutomationForm", props),
-}));
-
-vi.mock("@posthog/api-client/posthog-client", () => ({
- TaskAutomationValidationError: class TaskAutomationValidationError extends Error {
- code: string;
- attr: string | null;
-
- constructor(
- message: string,
- code = "invalid_input",
- attr: string | null = null,
- ) {
- super(message);
- this.code = code;
- this.attr = attr;
- }
- },
-}));
-
-import CreateAutomationScreen from "@/app/automation/create";
-
-describe("CreateAutomationScreen", () => {
- beforeEach(() => {
- mockReplace.mockReset();
- mockBack.mockReset();
- mockMutateAsync.mockReset();
- mockUseCreateTaskAutomation.mockReset();
- mockUseSkillStoreSkill.mockReset();
- routeParams.skillName = undefined;
-
- mockUseCreateTaskAutomation.mockReturnValue({
- isPending: false,
- mutateAsync: mockMutateAsync,
- });
- });
-
- it("seeds the form from the selected skill and saves a prefixed template id", async () => {
- routeParams.skillName = "shared-daily-brief";
- mockUseSkillStoreSkill.mockReturnValue({
- data: {
- name: "shared-daily-brief",
- description: "Shared briefing starter",
- body: "Summarize the most important work for today.",
- },
- isPending: false,
- error: null,
- refetch: vi.fn(),
- });
- mockMutateAsync.mockResolvedValueOnce({ id: "automation-1" });
-
- let renderer: ReturnType<typeof create> | null = null;
- act(() => {
- renderer = create(createElement(CreateAutomationScreen));
- });
-
- if (!renderer) {
- throw new Error("Renderer not created");
- }
-
- const stackScreen = renderer.root.findByType("StackScreen");
- expect(stackScreen.props.options.headerTitle).toBe("Create automation");
- expect(
- renderer.root.findAll(
- (node) => node.props.children === "shared-daily-brief",
- ).length,
- ).toBeGreaterThan(0);
- expect(
- renderer.root.findAll(
- (node) => node.props.children === "Shared briefing starter",
- ).length,
- ).toBe(0);
-
- const form = renderer.root.findByType("AutomationForm");
- expect(form.props.initialValues).toMatchObject({
- name: "shared-daily-brief",
- prompt: "Summarize the most important work for today.",
- timezone: "UTC",
- enabled: true,
- });
- expect(form.props.initialPromptMode).toBe("preview");
-
- await act(async () => {
- await form.props.onSubmit({
- name: "shared-daily-brief",
- prompt: "Summarize the most important work for today.",
- repository: "posthog/posthog",
- github_integration: 7,
- cron_expression: "0 9 * * 1-5",
- timezone: "UTC",
- enabled: true,
- });
- });
-
- expect(mockMutateAsync).toHaveBeenCalledWith({
- name: "shared-daily-brief",
- prompt: "Summarize the most important work for today.",
- repository: "posthog/posthog",
- github_integration: 7,
- cron_expression: "0 9 * * 1-5",
- timezone: "UTC",
- enabled: true,
- template_id: "llm-skill:shared-daily-brief",
- });
- expect(mockReplace).toHaveBeenCalledWith("/automation/automation-1");
- });
-
- it("keeps scratch creation untemplated when no skill is selected", async () => {
- mockUseSkillStoreSkill.mockReturnValue({
- data: undefined,
- isPending: false,
- error: null,
- refetch: vi.fn(),
- });
- mockMutateAsync.mockResolvedValueOnce({ id: "automation-2" });
-
- let renderer: ReturnType<typeof create> | null = null;
- act(() => {
- renderer = create(createElement(CreateAutomationScreen));
- });
-
- if (!renderer) {
- throw new Error("Renderer not created");
- }
-
- const form = renderer.root.findByType("AutomationForm");
- expect(form.props.initialValues).toMatchObject({
- name: undefined,
- prompt: undefined,
- timezone: "UTC",
- enabled: true,
- });
- expect(form.props.initialPromptMode).toBe("edit");
-
- await act(async () => {
- await form.props.onSubmit({
- name: "Custom automation",
- prompt: "Check the repo every morning.",
- repository: "posthog/posthog",
- github_integration: 7,
- cron_expression: "0 9 * * 1-5",
- timezone: "UTC",
- enabled: true,
- });
- });
-
- expect(mockMutateAsync).toHaveBeenCalledWith({
- name: "Custom automation",
- prompt: "Check the repo every morning.",
- repository: "posthog/posthog",
- github_integration: 7,
- cron_expression: "0 9 * * 1-5",
- timezone: "UTC",
- enabled: true,
- template_id: null,
- });
- });
-});
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/FloatingAutomationsHeader.tsx b/products/desktop/apps/mobile/src/features/tasks/components/FloatingAutomationsHeader.tsx
deleted file mode 100644
index 39e6aa08c96b..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/components/FloatingAutomationsHeader.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import { Text } from "@components/text";
-import { LinearGradient } from "expo-linear-gradient";
-import { View } from "react-native";
-import { useSafeAreaInsets } from "react-native-safe-area-context";
-import { MenuButton } from "@/features/navigation/components/MenuButton";
-import { toRgba, useThemeColors } from "@/lib/theme";
-
-/**
- * Floating header for the Automations list — mirrors FloatingTasksHeader so
- * the two tabs feel like siblings. Hamburger on the left, centered title,
- * gradient fade so the list content disappears gracefully behind it.
- */
-export function FloatingAutomationsHeader() {
- const insets = useSafeAreaInsets();
- const themeColors = useThemeColors();
-
- const fadeHeight = insets.top + 88;
-
- return (
- <View
- pointerEvents="box-none"
- className="absolute inset-x-0 top-0 z-10"
- style={{ height: fadeHeight }}
- >
- <LinearGradient
- pointerEvents="none"
- colors={[
- toRgba(themeColors.background, 1),
- toRgba(themeColors.background, 0.92),
- toRgba(themeColors.background, 0),
- ]}
- locations={[0, 0.65, 1]}
- style={{ position: "absolute", top: 0, left: 0, right: 0, bottom: 0 }}
- />
-
- <View
- className="flex-row items-center px-3"
- style={{ paddingTop: insets.top + 6, paddingBottom: 8 }}
- >
- <MenuButton />
-
- <View className="min-w-0 flex-1 items-center px-2">
- <Text
- className="font-semibold text-[17px] text-gray-12"
- numberOfLines={1}
- >
- Automations
- </Text>
- </View>
-
- {/* Spacer mirroring the MenuButton width so the title stays
- optically centered. */}
- <View className="h-10 w-10" />
- </View>
- </View>
- );
-}
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/FloatingNewAutomationButton.tsx b/products/desktop/apps/mobile/src/features/tasks/components/FloatingNewAutomationButton.tsx
deleted file mode 100644
index ce73885f6e12..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/components/FloatingNewAutomationButton.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { Plus } from "phosphor-react-native";
-import { Pressable } from "react-native";
-import { Text } from "@/components/text";
-import { useScreenInsets } from "@/hooks/useScreenInsets";
-import { useThemeColors } from "@/lib/theme";
-
-interface FloatingNewAutomationButtonProps {
- onPress: () => void;
-}
-
-/**
- * Pill-shaped FAB anchored to the bottom-right corner — mirrors
- * FloatingNewTaskButton so the two tabs feel like siblings.
- */
-export function FloatingNewAutomationButton({
- onPress,
-}: FloatingNewAutomationButtonProps) {
- const { fabBottom } = useScreenInsets();
- const themeColors = useThemeColors();
-
- return (
- <Pressable
- onPress={onPress}
- hitSlop={8}
- accessibilityLabel="Create new automation"
- accessibilityRole="button"
- className="absolute right-5 z-10 h-14 flex-row items-center justify-center gap-2 rounded-full bg-accent-9 pr-5 pl-4 active:opacity-85"
- style={{
- bottom: fabBottom(),
- shadowColor: "#000",
- shadowOpacity: 0.22,
- shadowRadius: 12,
- shadowOffset: { width: 0, height: 4 },
- elevation: 6,
- }}
- >
- <Plus size={22} color={themeColors.accent.contrast} weight="bold" />
- <Text className="font-semibold text-[15px] text-accent-contrast leading-tight">
- New automation
- </Text>
- </Pressable>
- );
-}
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/GitHubConnectionPrompt.tsx b/products/desktop/apps/mobile/src/features/tasks/components/GitHubConnectionPrompt.tsx
index 0da19fca214c..202e9f62184d 100644
--- a/products/desktop/apps/mobile/src/features/tasks/components/GitHubConnectionPrompt.tsx
+++ b/products/desktop/apps/mobile/src/features/tasks/components/GitHubConnectionPrompt.tsx
@@ -13,14 +13,6 @@ interface GitHubConnectionPromptProps {
mode?: "card" | "empty";
title?: string;
description?: string;
- /**
- * Which GitHub integration to create:
- * - `"user"` (default): the per-user flow (matches desktop) for interactive
- * task creation — detected via `/api/users/@me/integrations/`.
- * - `"team"`: the environment-level flow for automations, which run
- * server-side and need a team integration.
- */
- scope?: "user" | "team";
}
export function GitHubConnectionPrompt({
@@ -28,9 +20,8 @@ export function GitHubConnectionPrompt({
mode = "card",
title = "Connect GitHub to continue",
description = "You need to connect your GitHub account before using this workflow.",
- scope = "user",
}: GitHubConnectionPromptProps) {
- const { cloudRegion, projectId, getCloudUrlFromRegion } = useAuthStore();
+ const { cloudRegion, projectId } = useAuthStore();
const themeColors = useThemeColors();
const handleConnectGitHub = async () => {
@@ -38,24 +29,17 @@ export function GitHubConnectionPrompt({
return;
}
+ // Per-user flow (like desktop): the backend picks the right GitHub flow
+ // and, because we pass `connect_from: "posthog_mobile"`, redirects the
+ // callback to `posthog://github/callback` so this in-app browser closes.
let authorizeUrl: string;
- if (scope === "user") {
- // Per-user flow (like desktop): the backend picks the right GitHub flow
- // and, because we pass `connect_from: "posthog_mobile"`, redirects the
- // callback to `posthog://github/callback` so this in-app browser closes.
- try {
- const { install_url } =
- await getPostHogApiClient().startGithubUserIntegrationConnect();
- authorizeUrl = install_url;
- } catch (error) {
- log.error("Failed to start GitHub connection", { error });
- return;
- }
- } else {
- // Team/environment flow for automations: creates an environment-scoped
- // integration that `useIntegrations` detects.
- const baseUrl = getCloudUrlFromRegion(cloudRegion);
- authorizeUrl = `${baseUrl}/api/environments/${projectId}/integrations/authorize/?kind=github`;
+ try {
+ const { install_url } =
+ await getPostHogApiClient().startGithubUserIntegrationConnect();
+ authorizeUrl = install_url;
+ } catch (error) {
+ log.error("Failed to start GitHub connection", { error });
+ return;
}
const result = await WebBrowser.openAuthSessionAsync(
diff --git a/products/desktop/apps/mobile/src/features/tasks/components/ScheduleEditor.tsx b/products/desktop/apps/mobile/src/features/tasks/components/ScheduleEditor.tsx
deleted file mode 100644
index 726973a63960..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/components/ScheduleEditor.tsx
+++ /dev/null
@@ -1,185 +0,0 @@
-import { Text } from "@components/text";
-import {
- type AutomationScheduleDraft,
- type AutomationScheduleMode,
- buildCronExpression,
- sanitizeHour,
- sanitizeMinute,
- WEEKDAY_OPTIONS,
-} from "@posthog/core/automations/automationSchedule";
-import { Pressable, TextInput, View } from "react-native";
-
-interface ScheduleEditorProps {
- value: AutomationScheduleDraft;
- timezone: string;
- onChange: (value: AutomationScheduleDraft) => void;
- onTimezoneChange: (timezone: string) => void;
-}
-
-const MODE_OPTIONS: Array<{
- value: AutomationScheduleMode;
- label: string;
-}> = [
- { value: "hourly", label: "Hourly" },
- { value: "daily", label: "Daily" },
- { value: "weekdays", label: "Weekdays" },
- { value: "weekly", label: "Weekly" },
- { value: "custom", label: "Custom" },
-];
-
-export function ScheduleEditor({
- value,
- timezone,
- onChange,
- onTimezoneChange,
-}: ScheduleEditorProps) {
- const updateDraft = (updates: Partial<AutomationScheduleDraft>) => {
- const nextDraft = {
- ...value,
- ...updates,
- };
-
- onChange({
- ...nextDraft,
- rawCron:
- nextDraft.mode === "custom"
- ? nextDraft.rawCron
- : buildCronExpression(nextDraft),
- });
- };
-
- return (
- <View>
- <Text
- className="mb-3 text-[11px] text-gray-9 uppercase"
- style={{ letterSpacing: 0.5 }}
- >
- Schedule
- </Text>
-
- <View className="mb-3 flex-row flex-wrap gap-2">
- {MODE_OPTIONS.map((option) => {
- const isSelected = value.mode === option.value;
- return (
- <Pressable
- key={option.value}
- onPress={() => updateDraft({ mode: option.value })}
- className={`rounded-xl border px-3 py-2 ${
- isSelected
- ? "border-accent-8 bg-accent-3"
- : "border-gray-5 bg-background"
- }`}
- >
- <Text
- className={`text-sm ${
- isSelected ? "text-accent-11" : "text-gray-11"
- }`}
- >
- {option.label}
- </Text>
- </Pressable>
- );
- })}
- </View>
-
- {value.mode === "custom" ? (
- <TextInput
- className="mb-3 rounded-xl border border-gray-5 bg-background px-3.5 py-3 text-[15px] text-gray-12"
- placeholder="0 9 * * 1-5"
- value={value.rawCron}
- onChangeText={(rawCron) => onChange({ ...value, rawCron })}
- autoCapitalize="none"
- autoCorrect={false}
- />
- ) : (
- <>
- {value.mode === "hourly" ? (
- <View className="mb-3">
- <Text className="mb-1 text-gray-9 text-xs">
- Minute past the hour
- </Text>
- <TextInput
- className="rounded-xl border border-gray-5 bg-background px-3.5 py-3 text-[15px] text-gray-12"
- placeholder="00"
- value={value.minute}
- onChangeText={(minute) =>
- updateDraft({ minute: sanitizeMinute(minute) })
- }
- keyboardType="number-pad"
- />
- </View>
- ) : (
- <View className="mb-3 flex-row gap-3">
- <View className="flex-1">
- <Text className="mb-1 text-gray-9 text-xs">Hour</Text>
- <TextInput
- className="rounded-xl border border-gray-5 bg-background px-3.5 py-3 text-[15px] text-gray-12"
- placeholder="09"
- value={value.hour}
- onChangeText={(hour) =>
- updateDraft({ hour: sanitizeHour(hour) })
- }
- keyboardType="number-pad"
- />
- </View>
- <View className="flex-1">
- <Text className="mb-1 text-gray-9 text-xs">Minute</Text>
- <TextInput
- className="rounded-xl border border-gray-5 bg-background px-3.5 py-3 text-[15px] text-gray-12"
- placeholder="00"
- value={value.minute}
- onChangeText={(minute) =>
- updateDraft({ minute: sanitizeMinute(minute) })
- }
- keyboardType="number-pad"
- />
- </View>
- </View>
- )}
-
- {value.mode === "weekly" && (
- <View className="mb-3">
- <Text className="mb-2 text-gray-9 text-xs">Day</Text>
- <View className="flex-row flex-wrap gap-2">
- {WEEKDAY_OPTIONS.map((option) => {
- const isSelected = value.weekday === option.value;
- return (
- <Pressable
- key={option.value}
- onPress={() => updateDraft({ weekday: option.value })}
- className={`rounded-xl border px-3 py-2 ${
- isSelected
- ? "border-accent-8 bg-accent-3"
- : "border-gray-5 bg-background"
- }`}
- >
- <Text
- className={`text-sm ${
- isSelected ? "text-accent-11" : "text-gray-11"
- }`}
- >
- {option.label}
- </Text>
- </Pressable>
- );
- })}
- </View>
- </View>
- )}
- </>
- )}
-
- <View className="mb-3">
- <Text className="mb-1 text-gray-9 text-xs">Timezone</Text>
- <TextInput
- className="rounded-xl border border-gray-5 bg-background px-3.5 py-3 text-[15px] text-gray-12"
- placeholder="Europe/London"
- value={timezone}
- onChangeText={onTimezoneChange}
- autoCapitalize="none"
- autoCorrect={false}
- />
- </View>
- </View>
- );
-}
diff --git a/products/desktop/apps/mobile/src/features/tasks/composer/RepositoryPickerInline.tsx b/products/desktop/apps/mobile/src/features/tasks/composer/RepositoryPickerInline.tsx
index 6e39aead0614..861ff3b45a9e 100644
--- a/products/desktop/apps/mobile/src/features/tasks/composer/RepositoryPickerInline.tsx
+++ b/products/desktop/apps/mobile/src/features/tasks/composer/RepositoryPickerInline.tsx
@@ -5,7 +5,6 @@ import {
ActivityIndicator,
FlatList,
Pressable,
- ScrollView,
TextInput,
View,
} from "react-native";
@@ -18,14 +17,6 @@ import Animated, {
import { useThemeColors } from "@/lib/theme";
import type { RepositoryOption } from "../types";
-// Tuning for the nested (ScrollView) path's progressive mount. The first
-// chunk needs to cover the rows the user can actually see (~5 with the
-// 240px height cap) plus a small buffer so a quick flick scroll doesn't
-// hit empty space. Subsequent chunks fill in over the next few frames.
-const NESTED_INITIAL_RENDER = 30;
-const NESTED_RENDER_CHUNK = 100;
-const NESTED_RENDER_INTERVAL_MS = 16;
-
interface RepositoryPickerInlineProps {
open: boolean;
repositoryOptions: RepositoryOption[];
@@ -36,12 +27,6 @@ interface RepositoryPickerInlineProps {
/** True when we're rendering cached data while a background refetch runs.
* Surfaces as a small spinner badge instead of a blocking state. */
isRefreshing?: boolean;
- /** Set when this picker lives inside a parent `ScrollView`/`FlatList` of
- * the same orientation (e.g. the automation form). Disables the
- * internal `FlatList` and uses a plain `ScrollView` instead, since
- * React Native warns about nested VirtualizedLists. Default `false`
- * keeps `FlatList`'s windowing so opening with many repos is instant. */
- nested?: boolean;
onChange: (option: RepositoryOption) => void;
onClose: () => void;
}
@@ -59,7 +44,6 @@ export function RepositoryPickerInline({
selected,
loading,
isRefreshing,
- nested = false,
onChange,
onClose,
}: RepositoryPickerInlineProps) {
@@ -116,39 +100,6 @@ export function RepositoryPickerInline({
return () => clearTimeout(t);
}, [open]);
- // Progressive row mount for the nested (ScrollView) path. Without this,
- // opening the picker on a screen with hundreds of repos would block the
- // entrance animation while every row materializes synchronously. We
- // mount a small first batch (enough to fill the visible area), then
- // grow the slice every frame until the list is complete. The FlatList
- // path doesn't need this because `initialNumToRender` already windows
- // its initial mount.
- const [nestedRenderedCount, setNestedRenderedCount] = useState(
- NESTED_INITIAL_RENDER,
- );
- // Reset whenever the picker reopens or the filtered set changes (e.g.
- // the user typed a query, or new data arrived from a background
- // refetch). Reusing a stale `renderedCount` across filter changes would
- // either show too few rows (after broadening the filter) or be wasted.
- useEffect(() => {
- if (!nested) return;
- if (!open) return;
- setNestedRenderedCount(NESTED_INITIAL_RENDER);
- }, [nested, open]);
- useEffect(() => {
- if (!nested) return;
- if (!open) return;
- if (nestedRenderedCount >= filtered.length) return;
- const t = setTimeout(() => {
- setNestedRenderedCount((current) =>
- Math.min(current + NESTED_RENDER_CHUNK, filtered.length),
- );
- }, NESTED_RENDER_INTERVAL_MS);
- return () => clearTimeout(t);
- }, [nested, open, nestedRenderedCount, filtered.length]);
-
- // Hoisted row renderer so both the ScrollView and FlatList paths share
- // identical row markup without duplicating the closure.
const renderRow = (item: RepositoryOption) => {
const isSelected =
item.integrationId === selected?.integrationId &&
@@ -247,26 +198,9 @@ export function RepositoryPickerInline({
: "No repositories available"}
</Text>
</View>
- ) : nested ? (
- // ScrollView path — used when the picker lives inside a parent
- // ScrollView (e.g. the automation form). Plain `.map()` because
- // RN warns about nested VirtualizedLists. Rows are mounted
- // progressively via `nestedRenderedCount` so opening with many
- // repos doesn't block the entrance animation.
- <ScrollView
- style={{ maxHeight: 240 }}
- contentContainerStyle={{ paddingVertical: 4 }}
- keyboardShouldPersistTaps="handled"
- nestedScrollEnabled
- >
- {filtered
- .slice(0, nestedRenderedCount)
- .map((item) => renderRow(item))}
- </ScrollView>
) : (
- // FlatList path — default. Windowing keeps the open animation
- // snappy even when the user has hundreds of repos, by only
- // mounting the visible rows up front.
+ // Windowing keeps the open animation snappy even when the user has
+ // hundreds of repos, by only mounting the visible rows up front.
<FlatList
data={filtered}
keyExtractor={(item) => `${item.integrationId}:${item.repository}`}
diff --git a/products/desktop/apps/mobile/src/features/tasks/hooks/useAutomations.test.ts b/products/desktop/apps/mobile/src/features/tasks/hooks/useAutomations.test.ts
deleted file mode 100644
index fb47817a8c04..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/hooks/useAutomations.test.ts
+++ /dev/null
@@ -1,294 +0,0 @@
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { createElement, type PropsWithChildren } from "react";
-import { act, create } from "react-test-renderer";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const {
- mockUseAuthStore,
- mockGetTaskAutomations,
- mockCreateTaskAutomation,
- mockUpdateTaskAutomation,
-} = vi.hoisted(() => ({
- mockUseAuthStore: vi.fn(),
- mockGetTaskAutomations: vi.fn(),
- mockCreateTaskAutomation: vi.fn(),
- mockUpdateTaskAutomation: vi.fn(),
-}));
-
-vi.mock("@/features/auth", () => ({
- useAuthStore: mockUseAuthStore,
-}));
-
-vi.mock("@/lib/posthogApiClient", () => ({
- getPostHogApiClient: vi.fn(() => ({
- listTaskAutomations: mockGetTaskAutomations,
- getTaskAutomation: vi.fn(),
- createTaskAutomation: mockCreateTaskAutomation,
- updateTaskAutomation: mockUpdateTaskAutomation,
- deleteTaskAutomation: vi.fn(),
- runTaskAutomation: vi.fn(),
- })),
-}));
-
-import {
- automationKeys,
- getAutomationPollingInterval,
- useAutomations,
- useCreateTaskAutomation,
- useUpdateTaskAutomation,
-} from "./useAutomations";
-import { taskKeys } from "./useTasks";
-
-function createWrapper(queryClient: QueryClient) {
- return function Wrapper({ children }: PropsWithChildren) {
- return createElement(
- QueryClientProvider,
- { client: queryClient },
- children,
- );
- };
-}
-
-function renderTestHook<Result>(
- useHook: () => Result,
- wrapper:
- | ((props: PropsWithChildren) => ReturnType<typeof createElement>)
- | undefined,
-) {
- let currentResult: Result;
-
- function HookProbe() {
- currentResult = useHook();
- return null;
- }
-
- function TestTree() {
- if (!wrapper) {
- return createElement(HookProbe);
- }
-
- const Wrapper = wrapper;
- return createElement(Wrapper, null, createElement(HookProbe));
- }
-
- let renderer: ReturnType<typeof create>;
- act(() => {
- renderer = create(createElement(TestTree));
- });
-
- return {
- result: {
- get current() {
- return currentResult;
- },
- },
- unmount() {
- act(() => {
- renderer.unmount();
- });
- },
- };
-}
-
-async function waitForAssertion(assertion: () => void): Promise<void> {
- const timeoutAt = Date.now() + 2_000;
-
- while (Date.now() < timeoutAt) {
- try {
- assertion();
- return;
- } catch (error) {
- await new Promise((resolve) => setTimeout(resolve, 10));
- if (Date.now() >= timeoutAt) {
- throw error;
- }
- }
- }
-}
-
-const automationPayload = {
- id: "automation-1",
- name: "Daily PRs",
- prompt: "Check PRs",
- repository: "posthog/posthog",
- github_integration: 7,
- cron_expression: "0 9 * * *",
- timezone: "Europe/London",
- template_id: "llm-skill:shared-daily-brief",
- enabled: true,
- last_run_at: null,
- last_run_status: null,
- last_task_id: "task-1",
- last_task_run_id: null,
- last_error: null,
- created_at: "2026-05-13T00:00:00Z",
- updated_at: "2026-05-13T00:00:00Z",
-};
-
-describe("useAutomations", () => {
- beforeEach(() => {
- mockUseAuthStore.mockImplementation((selector) =>
- selector
- ? selector({
- projectId: 42,
- oauthAccessToken: "token",
- })
- : {
- projectId: 42,
- oauthAccessToken: "token",
- },
- );
- mockGetTaskAutomations.mockReset();
- mockCreateTaskAutomation.mockReset();
- mockUpdateTaskAutomation.mockReset();
- });
-
- it("loads automation lists through the dedicated query key", async () => {
- mockGetTaskAutomations.mockResolvedValueOnce([automationPayload]);
-
- const queryClient = new QueryClient();
- const { result, unmount } = renderTestHook(
- () => useAutomations(),
- createWrapper(queryClient),
- );
-
- await waitForAssertion(() => {
- expect(result.current.automations).toHaveLength(1);
- });
-
- expect(mockGetTaskAutomations).toHaveBeenCalledOnce();
- expect(queryClient.getQueryData(automationKeys.list())).toEqual([
- automationPayload,
- ]);
- unmount();
- });
-
- it("only polls automation queries while a run is still active", () => {
- expect(getAutomationPollingInterval(undefined)).toBe(false);
- expect(getAutomationPollingInterval(automationPayload)).toBe(false);
- expect(
- getAutomationPollingInterval({
- ...automationPayload,
- last_run_status: "running",
- }),
- ).toBe(5_000);
- expect(
- getAutomationPollingInterval([
- automationPayload,
- {
- ...automationPayload,
- id: "automation-2",
- last_run_status: "running",
- },
- ]),
- ).toBe(5_000);
- });
-
- it("invalidates automation and task lists after create", async () => {
- const queryClient = new QueryClient();
- const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries");
- mockCreateTaskAutomation.mockResolvedValueOnce(automationPayload);
-
- const { result, unmount } = renderTestHook(
- () => useCreateTaskAutomation(),
- createWrapper(queryClient),
- );
-
- await act(async () => {
- await result.current.mutateAsync({
- name: "Daily PRs",
- prompt: "Check PRs",
- repository: "posthog/posthog",
- github_integration: 7,
- cron_expression: "0 9 * * *",
- timezone: "Europe/London",
- template_id: "llm-skill:shared-daily-brief",
- });
- });
-
- expect(mockCreateTaskAutomation).toHaveBeenCalledWith({
- name: "Daily PRs",
- prompt: "Check PRs",
- repository: "posthog/posthog",
- github_integration: 7,
- cron_expression: "0 9 * * *",
- timezone: "Europe/London",
- template_id: "llm-skill:shared-daily-brief",
- });
- expect(invalidateSpy).toHaveBeenCalledWith({
- queryKey: automationKeys.lists(),
- });
- expect(invalidateSpy).toHaveBeenCalledWith({
- queryKey: taskKeys.lists(),
- });
- unmount();
- });
-
- it("updates the detail cache immediately after automation edits", async () => {
- const queryClient = new QueryClient();
- queryClient.setQueryData(
- automationKeys.detail("automation-1"),
- automationPayload,
- );
- mockUpdateTaskAutomation.mockResolvedValueOnce({
- ...automationPayload,
- enabled: false,
- cron_expression: "30 14 * * *",
- });
-
- const { result, unmount } = renderTestHook(
- () => useUpdateTaskAutomation(),
- createWrapper(queryClient),
- );
-
- await act(async () => {
- await result.current.mutateAsync({
- automationId: "automation-1",
- updates: {
- enabled: false,
- cron_expression: "30 14 * * *",
- },
- });
- });
-
- expect(
- queryClient.getQueryData(automationKeys.detail("automation-1")),
- ).toMatchObject({
- enabled: false,
- cron_expression: "30 14 * * *",
- template_id: "llm-skill:shared-daily-brief",
- });
- unmount();
- });
-
- it("does not populate automation caches when creation fails", async () => {
- const queryClient = new QueryClient();
- const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries");
- mockCreateTaskAutomation.mockRejectedValueOnce(
- new Error("Repository is still required for this template."),
- );
-
- const { result, unmount } = renderTestHook(
- () => useCreateTaskAutomation(),
- createWrapper(queryClient),
- );
-
- await expect(
- result.current.mutateAsync({
- name: "Shared daily brief",
- prompt: "Summarize feature usage for my product areas.",
- repository: "",
- github_integration: null,
- cron_expression: "0 8 * * 1-5",
- timezone: "America/New_York",
- template_id: "llm-skill:shared-daily-brief",
- }),
- ).rejects.toThrow("Repository is still required for this template.");
-
- expect(
- queryClient.getQueryData(automationKeys.detail("automation-1")),
- ).toBe(undefined);
- expect(invalidateSpy).not.toHaveBeenCalled();
- unmount();
- });
-});
diff --git a/products/desktop/apps/mobile/src/features/tasks/hooks/useAutomations.ts b/products/desktop/apps/mobile/src/features/tasks/hooks/useAutomations.ts
deleted file mode 100644
index e6db7c11bdf3..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/hooks/useAutomations.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-import type {
- CreateTaskAutomationOptions,
- TaskAutomation,
- UpdateTaskAutomationOptions,
-} from "@posthog/api-client/posthog-client";
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { useAuthStore } from "@/features/auth";
-import { logger } from "@/lib/logger";
-import { getPostHogApiClient } from "@/lib/posthogApiClient";
-import { taskKeys } from "./useTasks";
-
-const log = logger.scope("automations-mutations");
-const ACTIVE_AUTOMATION_POLLING_INTERVAL_MS = 5_000;
-
-export const automationKeys = {
- all: ["task-automations"] as const,
- lists: () => [...automationKeys.all, "list"] as const,
- list: () => [...automationKeys.lists(), "all"] as const,
- details: () => [...automationKeys.all, "detail"] as const,
- detail: (id: string) => [...automationKeys.details(), id] as const,
-};
-
-export function getAutomationPollingInterval(
- automationData: TaskAutomation | TaskAutomation[] | undefined,
-): number | false {
- if (!automationData) {
- return false;
- }
-
- if (Array.isArray(automationData)) {
- return automationData.some(
- (automation) => automation.last_run_status === "running",
- )
- ? ACTIVE_AUTOMATION_POLLING_INTERVAL_MS
- : false;
- }
-
- return automationData.last_run_status === "running"
- ? ACTIVE_AUTOMATION_POLLING_INTERVAL_MS
- : false;
-}
-
-function invalidateAutomationAndTaskLists(
- queryClient: ReturnType<typeof useQueryClient>,
-) {
- queryClient.invalidateQueries({ queryKey: automationKeys.lists() });
- queryClient.invalidateQueries({ queryKey: taskKeys.lists() });
-}
-
-export function useAutomations() {
- const { projectId, oauthAccessToken } = useAuthStore();
-
- const query = useQuery({
- queryKey: automationKeys.list(),
- queryFn: () => getPostHogApiClient().listTaskAutomations(),
- enabled: !!projectId && !!oauthAccessToken,
- refetchInterval: (query) =>
- getAutomationPollingInterval(
- query.state.data as TaskAutomation[] | undefined,
- ),
- });
-
- return {
- automations: query.data ?? [],
- isLoading: query.isLoading,
- error: query.error?.message ?? null,
- refetch: query.refetch,
- };
-}
-
-export function useAutomation(automationId: string) {
- const { projectId, oauthAccessToken } = useAuthStore();
-
- return useQuery({
- queryKey: automationKeys.detail(automationId),
- queryFn: () => getPostHogApiClient().getTaskAutomation(automationId),
- enabled: !!projectId && !!oauthAccessToken && !!automationId,
- refetchInterval: (query) =>
- getAutomationPollingInterval(
- query.state.data as TaskAutomation | undefined,
- ),
- });
-}
-
-export function useCreateTaskAutomation() {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: (options: CreateTaskAutomationOptions) =>
- getPostHogApiClient().createTaskAutomation(options),
- onSuccess: (automation) => {
- queryClient.setQueryData(
- automationKeys.detail(automation.id),
- automation,
- );
- invalidateAutomationAndTaskLists(queryClient);
- },
- onError: (error) => {
- log.error("Failed to create automation", error.message);
- },
- });
-}
-
-export function useUpdateTaskAutomation() {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: ({
- automationId,
- updates,
- }: {
- automationId: string;
- updates: UpdateTaskAutomationOptions;
- }) => getPostHogApiClient().updateTaskAutomation(automationId, updates),
- onSuccess: (automation, { automationId }) => {
- queryClient.setQueryData<TaskAutomation>(
- automationKeys.detail(automationId),
- automation,
- );
- invalidateAutomationAndTaskLists(queryClient);
- },
- onError: (error) => {
- log.error("Failed to update automation", error.message);
- },
- });
-}
-
-export function useDeleteTaskAutomation() {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: (automationId: string) =>
- getPostHogApiClient().deleteTaskAutomation(automationId),
- onSuccess: (_, automationId) => {
- queryClient.removeQueries({
- queryKey: automationKeys.detail(automationId),
- });
- invalidateAutomationAndTaskLists(queryClient);
- },
- onError: (error) => {
- log.error("Failed to delete automation", error.message);
- },
- });
-}
-
-export function useRunTaskAutomation() {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: (automationId: string) =>
- getPostHogApiClient().runTaskAutomation(automationId),
- onSuccess: (automation, automationId) => {
- queryClient.setQueryData<TaskAutomation>(
- automationKeys.detail(automationId),
- automation,
- );
- invalidateAutomationAndTaskLists(queryClient);
- },
- onError: (error) => {
- log.error("Failed to run automation", error.message);
- },
- });
-}
diff --git a/products/desktop/apps/mobile/src/features/tasks/hooks/useUserIntegrations.ts b/products/desktop/apps/mobile/src/features/tasks/hooks/useUserIntegrations.ts
index c95195040912..8cd5d44b0381 100644
--- a/products/desktop/apps/mobile/src/features/tasks/hooks/useUserIntegrations.ts
+++ b/products/desktop/apps/mobile/src/features/tasks/hooks/useUserIntegrations.ts
@@ -15,13 +15,12 @@ import {
* than the team-level ones, matching how the desktop app links GitHub per user.
*
* Used by the interactive task-creation flow (new task screen, task list empty
- * state, connect prompt). Automations stay on {@link useIntegrations} because
- * they run server-side without a user and need the team integration.
+ * state, connect prompt).
*
* Repos are keyed by the numeric GitHub `installation_id` so the existing
* number-based picker/`RepositoryOption` keep working; `getUserIntegrationId`
* maps that back to the `UserIntegration` UUID for task creation. No persisted
- * cache here (unlike the team hook) so it can't clobber the automations cache.
+ * cache here (unlike the team hook) so it can't clobber the team cache.
*/
export const userIntegrationKeys = {
all: ["user-integrations"] as const,
diff --git a/products/desktop/apps/mobile/src/features/tasks/skills/hooks.ts b/products/desktop/apps/mobile/src/features/tasks/skills/hooks.ts
deleted file mode 100644
index fcba3e552308..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/skills/hooks.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import { getPostHogApiClient } from "@/lib/posthogApiClient";
-
-const skillStoreKeys = {
- all: ["skill-store"] as const,
- lists: () => [...skillStoreKeys.all, "list"] as const,
- list: () => [...skillStoreKeys.lists(), "all"] as const,
- details: () => [...skillStoreKeys.all, "detail"] as const,
- detail: (skillName: string) =>
- [...skillStoreKeys.details(), skillName] as const,
-};
-
-export function useSkillStoreSkills() {
- return useQuery({
- queryKey: skillStoreKeys.list(),
- queryFn: async () => (await getPostHogApiClient().listLlmSkills()) ?? [],
- staleTime: 5 * 60 * 1000,
- });
-}
-
-export function useSkillStoreSkill(skillName: string | null) {
- return useQuery({
- queryKey: skillStoreKeys.detail(skillName ?? ""),
- queryFn: () => getPostHogApiClient().getLlmSkillByName(skillName as string),
- enabled: !!skillName,
- staleTime: 5 * 60 * 1000,
- });
-}
-
-export const SKILL_STORE_QUERY_KEYS = skillStoreKeys;
diff --git a/products/desktop/apps/mobile/src/features/tasks/utils/automationStatus.test.ts b/products/desktop/apps/mobile/src/features/tasks/utils/automationStatus.test.ts
deleted file mode 100644
index 7a24d5d05051..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/utils/automationStatus.test.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { getAutomationStatusPresentation } from "./automationStatus";
-
-describe("automationStatus", () => {
- it("shows queued when the linked task run has not started work yet", () => {
- expect(
- getAutomationStatusPresentation({
- lastRunStatus: "running",
- lastTaskRunStatus: "queued",
- }),
- ).toMatchObject({ label: "Queued" });
- });
-
- it("hides the running badge while the linked task run is actively in progress", () => {
- expect(
- getAutomationStatusPresentation({
- lastRunStatus: "running",
- lastTaskRunStatus: "in_progress",
- }),
- ).toBeNull();
- });
-
- it("hides the running badge when only the automation-level status is available", () => {
- expect(
- getAutomationStatusPresentation({ lastRunStatus: "running" }),
- ).toBeNull();
- });
-
- it("falls back to automation status when task-run detail is unavailable", () => {
- expect(
- getAutomationStatusPresentation({ lastRunStatus: "success" }),
- ).toMatchObject({ label: "Success" });
- });
-});
diff --git a/products/desktop/apps/mobile/src/features/tasks/utils/automationStatus.ts b/products/desktop/apps/mobile/src/features/tasks/utils/automationStatus.ts
deleted file mode 100644
index 5e8b7f553f7d..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/utils/automationStatus.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import type { TaskRun } from "@posthog/shared";
-
-export interface AutomationStatusInput {
- lastRunStatus: string | null;
- lastTaskRunStatus?: TaskRun["status"] | null;
-}
-
-export interface AutomationStatusPresentation {
- label: string;
- className: string;
-}
-
-export function getAutomationStatusPresentation({
- lastRunStatus,
- lastTaskRunStatus,
-}: AutomationStatusInput): AutomationStatusPresentation | null {
- switch (lastTaskRunStatus) {
- case "not_started":
- case "queued":
- return {
- label: "Queued",
- className: "bg-status-warning/20 text-status-warning",
- };
- case "in_progress":
- return null;
- case "completed":
- return {
- label: "Success",
- className: "bg-status-success/20 text-status-success",
- };
- case "failed":
- case "cancelled":
- return {
- label: "Failed",
- className: "bg-status-error/20 text-status-error",
- };
- default:
- break;
- }
-
- switch (lastRunStatus) {
- case "running":
- return null;
- case "success":
- return {
- label: "Success",
- className: "bg-status-success/20 text-status-success",
- };
- case "failed":
- return {
- label: "Failed",
- className: "bg-status-error/20 text-status-error",
- };
- default:
- return {
- label: "Never run",
- className: "bg-gray-4 text-gray-11",
- };
- }
-}
diff --git a/products/desktop/apps/mobile/src/features/tasks/utils/automationTemplatePresentation.test.ts b/products/desktop/apps/mobile/src/features/tasks/utils/automationTemplatePresentation.test.ts
deleted file mode 100644
index 2020007f005d..000000000000
--- a/products/desktop/apps/mobile/src/features/tasks/utils/automationTemplatePresentation.test.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { getAutomationTemplatePresentation } from "@posthog/core/automations/automationTemplatePresentation";
-import { describe, expect, it } from "vitest";
-
-describe("automationTemplatePresentation", () => {
- it("prefers repository context when one exists for skill-backed automations", () => {
- expect(
- getAutomationTemplatePresentation({
- repository: "posthog/posthog",
- template_id: "llm-skill:shared-daily-brief",
- }),
- ).toMatchObject({
- templateName: "shared-daily-brief",
- repositoryLabel: "posthog/posthog",
- contextLabel: "Skill store",
- secondaryLabel: "posthog/posthog",
- });
- });
-
- it("falls back to skill-store context when no repository is present", () => {
- expect(
- getAutomationTemplatePresentation({
- repository: "",
- template_id: "llm-skill:shared-daily-brief",
- }),
- ).toMatchObject({
- templateName: "shared-daily-brief",
- repositoryLabel: null,
- contextLabel: "Skill store",
- secondaryLabel: "Skill store",
- });
- });
-
- it("handles unknown template ids and blank repositories safely", () => {
- expect(
- getAutomationTemplatePresentation({
- repository: "",
- template_id: "unknown-template",
- }),
- ).toMatchObject({
- templateName: "Template automation",
- repositoryLabel: null,
- contextLabel: null,
- secondaryLabel: "No repository context",
- });
- });
-});
diff --git a/products/desktop/apps/mobile/src/lib/deep-links.ts b/products/desktop/apps/mobile/src/lib/deep-links.ts
index 0e1d01aa95e8..ad790fcd3fec 100644
--- a/products/desktop/apps/mobile/src/lib/deep-links.ts
+++ b/products/desktop/apps/mobile/src/lib/deep-links.ts
@@ -33,14 +33,10 @@ export const UNIVERSAL_LINK_PREFIX = `https://${UNIVERSAL_LINK_HOST}`;
export const paths = {
tasksTab: "/(tabs)/tasks" as const,
inboxTab: "/(tabs)/inbox" as const,
- automationsTab: "/(tabs)/automations" as const,
settings: "/settings" as const,
newTask: "/task" as const,
task: (taskId: string) => `/task/${taskId}` as const,
inboxReport: (reportId: string) => `/inbox/${reportId}` as const,
- automation: (automationId: string) => `/automation/${automationId}` as const,
- newAutomation: "/automation/create" as const,
- automationTemplates: "/automation" as const,
} as const;
/** A path is the part after the host: starts with `/`, no scheme. */
diff --git a/products/desktop/apps/mobile/src/lib/posthogUrl.ts b/products/desktop/apps/mobile/src/lib/posthogUrl.ts
index fe2deac21026..3a0dbf1d6b1f 100644
--- a/products/desktop/apps/mobile/src/lib/posthogUrl.ts
+++ b/products/desktop/apps/mobile/src/lib/posthogUrl.ts
@@ -29,7 +29,7 @@ const POSTHOG_APP_HOSTS = new Set([
"us.posthog.com",
]);
-const POSTHOG_CODE_PATH_PATTERN = /^\/(?:task|inbox|automation)(?:\/|$)/;
+const POSTHOG_CODE_PATH_PATTERN = /^\/(?:task|inbox)(?:\/|$)/;
function decodeSegment(segment: string): string {
try {
@@ -75,10 +75,6 @@ function labelForCode(segments: string[]): string {
return labelWithId("Code / Inbox", segments[1] ?? null);
}
- if (segments[0] === "automation") {
- return labelWithId("Code / Automation", segments[1] ?? null);
- }
-
return fallbackLabel("Code", segments);
}
@@ -89,7 +85,7 @@ function refIdForCode(segments: string[]): string | null {
: (segments[1] ?? null);
}
- if (segments[0] === "inbox" || segments[0] === "automation") {
+ if (segments[0] === "inbox") {
return segments[1] ?? null;
}
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index 036544056d32..c4975c5775a6 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -9943,7 +9943,6 @@ export namespace Schemas {
| "error_tracking"
| "eval_clusters"
| "user_created"
- | "automation"
| "slack"
| "support_queue"
| "session_summaries"
@@ -10998,30 +10997,6 @@ export namespace Schemas {
previous?: (string | null) | undefined;
results: Array<Table>;
};
- export type TaskAutomation = {
- id: string;
- name: string;
- prompt: string;
- repository: string;
- github_integration?: (number | null) | undefined;
- cron_expression: string;
- timezone?: string | undefined;
- template_id?: (string | null) | undefined;
- enabled?: boolean | undefined;
- last_run_at: string | null;
- last_run_status: string | null;
- last_task_id: string | null;
- last_task_run_id: string | null;
- last_error: string | null;
- created_at: string;
- updated_at: string;
- };
- export type PaginatedTaskAutomationList = {
- count: number;
- next?: (string | null) | undefined;
- previous?: (string | null) | undefined;
- results: Array<TaskAutomation>;
- };
export type SignalReportTaskRelationshipEnum = "implementation";
export type Task = {
id: string;
@@ -12800,24 +12775,6 @@ export namespace Schemas {
created_by: UserBasic & unknown;
ci_prompt: string | null;
}>;
- export type PatchedTaskAutomation = Partial<{
- id: string;
- name: string;
- prompt: string;
- repository: string;
- github_integration: number | null;
- cron_expression: string;
- timezone: string;
- template_id: string | null;
- enabled: boolean;
- last_run_at: string | null;
- last_run_status: string | null;
- last_task_id: string | null;
- last_task_run_id: string | null;
- last_error: string | null;
- created_at: string;
- updated_at: string;
- }>;
export type PatchedTaskRunSetOutputRequest = Partial<{ output: unknown }>;
export type TaskRunUpdateStatusEnum = "not_started" | "queued" | "in_progress" | "completed" | "failed" | "cancelled";
export type TaskRunUpdateEnvironmentEnum = "local";
@@ -24531,78 +24488,6 @@ export namespace Endpoints {
};
responses: { 200: Schemas.SurveyGlobalStatsResponse };
};
- export type get_Task_automations_list = {
- method: "GET";
- path: "/api/projects/{project_id}/task_automations/";
- requestFormat: "json";
- parameters: {
- query: Partial<{ limit: number; offset: number }>;
- path: { project_id: string };
- };
- responses: { 200: Schemas.PaginatedTaskAutomationList };
- };
- export type post_Task_automations_create = {
- method: "POST";
- path: "/api/projects/{project_id}/task_automations/";
- requestFormat: "json";
- parameters: {
- path: { project_id: string };
-
- body: Schemas.TaskAutomation;
- };
- responses: { 201: Schemas.TaskAutomation };
- };
- export type get_Task_automations_retrieve = {
- method: "GET";
- path: "/api/projects/{project_id}/task_automations/{id}/";
- requestFormat: "json";
- parameters: {
- path: { id: string; project_id: string };
- };
- responses: { 200: Schemas.TaskAutomation };
- };
- export type put_Task_automations_update = {
- method: "PUT";
- path: "/api/projects/{project_id}/task_automations/{id}/";
- requestFormat: "json";
- parameters: {
- path: { id: string; project_id: string };
-
- body: Schemas.TaskAutomation;
- };
- responses: { 200: Schemas.TaskAutomation };
- };
- export type patch_Task_automations_partial_update = {
- method: "PATCH";
- path: "/api/projects/{project_id}/task_automations/{id}/";
- requestFormat: "json";
- parameters: {
- path: { id: string; project_id: string };
-
- body: Schemas.PatchedTaskAutomation;
- };
- responses: { 200: Schemas.TaskAutomation };
- };
- export type delete_Task_automations_destroy = {
- method: "DELETE";
- path: "/api/projects/{project_id}/task_automations/{id}/";
- requestFormat: "json";
- parameters: {
- path: { id: string; project_id: string };
- };
- responses: { 204: unknown };
- };
- export type post_Task_automations_run_create = {
- method: "POST";
- path: "/api/projects/{project_id}/task_automations/{id}/run/";
- requestFormat: "json";
- parameters: {
- path: { id: string; project_id: string };
-
- body: Schemas.TaskAutomation;
- };
- responses: { 200: Schemas.TaskAutomation };
- };
export type get_Tasks_list = {
method: "GET";
path: "/api/projects/{project_id}/tasks/";
@@ -26131,8 +26016,6 @@ export type EndpointByMethod = {
"/api/projects/{project_id}/surveys/activity/": Endpoints.get_Surveys_all_activity_retrieve;
"/api/projects/{project_id}/surveys/responses_count/": Endpoints.get_Surveys_responses_count_retrieve;
"/api/projects/{project_id}/surveys/stats/": Endpoints.get_Surveys_global_stats_retrieve;
- "/api/projects/{project_id}/task_automations/": Endpoints.get_Task_automations_list;
- "/api/projects/{project_id}/task_automations/{id}/": Endpoints.get_Task_automations_retrieve;
"/api/projects/{project_id}/tasks/": Endpoints.get_Tasks_list;
"/api/projects/{project_id}/tasks/{id}/": Endpoints.get_Tasks_retrieve;
"/api/projects/{project_id}/tasks/{task_id}/runs/": Endpoints.get_Tasks_runs_list;
@@ -26431,8 +26314,6 @@ export type EndpointByMethod = {
"/api/projects/{project_id}/surveys/{id}/responses/{response_uuid}/unarchive/": Endpoints.post_Surveys_responses_unarchive_create;
"/api/projects/{project_id}/surveys/{id}/summarize_responses/": Endpoints.post_Surveys_summarize_responses_create;
"/api/projects/{project_id}/surveys/{id}/summary_headline/": Endpoints.post_Surveys_summary_headline_create;
- "/api/projects/{project_id}/task_automations/": Endpoints.post_Task_automations_create;
- "/api/projects/{project_id}/task_automations/{id}/run/": Endpoints.post_Task_automations_run_create;
"/api/projects/{project_id}/tasks/": Endpoints.post_Tasks_create;
"/api/projects/{project_id}/tasks/{id}/run/": Endpoints.post_Tasks_run_create;
"/api/projects/{project_id}/tasks/{id}/staged_artifacts/finalize_upload/": Endpoints.post_Tasks_staged_artifacts_finalize_upload_create;
@@ -26553,7 +26434,6 @@ export type EndpointByMethod = {
"/api/projects/{project_id}/signals/source_configs/{id}/": Endpoints.put_Signals_source_configs_update;
"/api/projects/{project_id}/subscriptions/{id}/": Endpoints.put_Subscriptions_update;
"/api/projects/{project_id}/surveys/{id}/": Endpoints.put_Surveys_update;
- "/api/projects/{project_id}/task_automations/{id}/": Endpoints.put_Task_automations_update;
"/api/projects/{project_id}/tasks/{id}/": Endpoints.put_Tasks_update;
"/api/projects/{project_id}/warehouse_saved_queries/{id}/": Endpoints.put_Warehouse_saved_queries_update;
"/api/projects/{project_id}/warehouse_tables/{id}/": Endpoints.put_Warehouse_tables_update;
@@ -26659,7 +26539,6 @@ export type EndpointByMethod = {
"/api/projects/{project_id}/signals/source_configs/{id}/": Endpoints.patch_Signals_source_configs_partial_update;
"/api/projects/{project_id}/subscriptions/{id}/": Endpoints.patch_Subscriptions_partial_update;
"/api/projects/{project_id}/surveys/{id}/": Endpoints.patch_Surveys_partial_update;
- "/api/projects/{project_id}/task_automations/{id}/": Endpoints.patch_Task_automations_partial_update;
"/api/projects/{project_id}/tasks/{id}/": Endpoints.patch_Tasks_partial_update;
"/api/projects/{project_id}/tasks/{task_id}/runs/{id}/": Endpoints.patch_Tasks_runs_partial_update;
"/api/projects/{project_id}/tasks/{task_id}/runs/{id}/set_output/": Endpoints.patch_Tasks_runs_set_output_partial_update;
@@ -26758,7 +26637,6 @@ export type EndpointByMethod = {
"/api/projects/{project_id}/signals/source_configs/{id}/": Endpoints.delete_Signals_source_configs_destroy;
"/api/projects/{project_id}/subscriptions/{id}/": Endpoints.delete_Subscriptions_destroy;
"/api/projects/{project_id}/surveys/{id}/": Endpoints.delete_Surveys_destroy;
- "/api/projects/{project_id}/task_automations/{id}/": Endpoints.delete_Task_automations_destroy;
"/api/projects/{project_id}/tasks/{id}/": Endpoints.delete_Tasks_destroy;
"/api/projects/{project_id}/warehouse_saved_queries/{id}/": Endpoints.delete_Warehouse_saved_queries_destroy;
"/api/projects/{project_id}/warehouse_saved_query_folders/{id}/": Endpoints.delete_Warehouse_saved_query_folders_destroy;
diff --git a/products/desktop/packages/api-client/src/posthog-client.automations.test.ts b/products/desktop/packages/api-client/src/posthog-client.automations.test.ts
deleted file mode 100644
index 3d3386ef3a48..000000000000
--- a/products/desktop/packages/api-client/src/posthog-client.automations.test.ts
+++ /dev/null
@@ -1,192 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import {
- PostHogAPIClient,
- TaskAutomationValidationError,
-} from "./posthog-client";
-
-const automationPayload = {
- id: "automation-1",
- name: "Daily PRs",
- prompt: "Check PRs",
- repository: "posthog/posthog",
- github_integration: 7,
- cron_expression: "0 9 * * *",
- timezone: "Europe/London",
- template_id: "llm-skill:daily-prs",
- enabled: true,
- last_run_at: null,
- last_run_status: null,
- last_task_id: null,
- last_task_run_id: null,
- last_error: null,
- created_at: "2026-07-21T00:00:00Z",
- updated_at: "2026-07-21T00:00:00Z",
-};
-
-function jsonResponse(body: unknown, status = 200): Response {
- return new Response(JSON.stringify(body), {
- status,
- headers: { "Content-Type": "application/json" },
- });
-}
-
-describe("PostHogAPIClient task automations", () => {
- const fetch = vi.fn();
- const client = new PostHogAPIClient(
- "https://app.posthog.test",
- async () => "access-token",
- async () => "refreshed-token",
- 42,
- { appVersion: "test", fetch },
- );
-
- beforeEach(() => {
- fetch.mockReset();
- });
-
- it("lists automations and normalizes optional response fields", async () => {
- const minimalPayload = {
- ...automationPayload,
- github_integration: undefined,
- timezone: undefined,
- template_id: undefined,
- enabled: undefined,
- };
- fetch.mockResolvedValueOnce(
- jsonResponse({
- count: 1,
- next: null,
- previous: null,
- results: [minimalPayload],
- }),
- );
-
- await expect(client.listTaskAutomations()).resolves.toEqual([
- expect.objectContaining({
- id: "automation-1",
- github_integration: null,
- timezone: null,
- template_id: null,
- enabled: true,
- }),
- ]);
- expect(fetch).toHaveBeenCalledWith(
- new URL(
- "https://app.posthog.test/api/projects/42/task_automations/?limit=500",
- ),
- expect.objectContaining({ method: "GET" }),
- );
- });
-
- it("gets and creates automations through generated endpoints", async () => {
- fetch
- .mockResolvedValueOnce(jsonResponse(automationPayload))
- .mockResolvedValueOnce(jsonResponse(automationPayload, 201));
-
- await expect(client.getTaskAutomation("automation-1")).resolves.toEqual(
- automationPayload,
- );
- await expect(
- client.createTaskAutomation({
- name: "Daily PRs",
- prompt: "Check PRs",
- repository: "posthog/posthog",
- github_integration: 7,
- cron_expression: "0 9 * * *",
- timezone: "Europe/London",
- template_id: "llm-skill:daily-prs",
- enabled: true,
- }),
- ).resolves.toEqual(automationPayload);
-
- expect(fetch).toHaveBeenNthCalledWith(
- 2,
- new URL("https://app.posthog.test/api/projects/42/task_automations/"),
- expect.objectContaining({
- method: "POST",
- body: JSON.stringify({
- name: "Daily PRs",
- prompt: "Check PRs",
- repository: "posthog/posthog",
- github_integration: 7,
- cron_expression: "0 9 * * *",
- timezone: "Europe/London",
- template_id: "llm-skill:daily-prs",
- enabled: true,
- }),
- }),
- );
- });
-
- it("updates, deletes, and runs automations", async () => {
- fetch
- .mockResolvedValueOnce(
- jsonResponse({ ...automationPayload, enabled: false }),
- )
- .mockResolvedValueOnce(new Response(null, { status: 204 }))
- .mockResolvedValueOnce(jsonResponse(automationPayload));
-
- await expect(
- client.updateTaskAutomation("automation-1", { enabled: false }),
- ).resolves.toMatchObject({ enabled: false });
- await expect(
- client.deleteTaskAutomation("automation-1"),
- ).resolves.toBeUndefined();
- await expect(client.runTaskAutomation("automation-1")).resolves.toEqual(
- automationPayload,
- );
-
- expect(fetch).toHaveBeenNthCalledWith(
- 1,
- new URL(
- "https://app.posthog.test/api/projects/42/task_automations/automation-1/",
- ),
- expect.objectContaining({
- method: "PATCH",
- body: JSON.stringify({ enabled: false }),
- }),
- );
- expect(fetch).toHaveBeenNthCalledWith(
- 3,
- new URL(
- "https://app.posthog.test/api/projects/42/task_automations/automation-1/run/",
- ),
- expect.objectContaining({ method: "POST" }),
- );
- expect(fetch.mock.calls[2]?.[1]?.body).toBeUndefined();
- });
-
- it("preserves validation detail, code, and field attribution", async () => {
- fetch.mockResolvedValueOnce(
- new Response(
- JSON.stringify({
- type: "validation_error",
- code: "invalid_input",
- detail: "Enter a valid cron expression.",
- attr: "cron_expression",
- }),
- {
- status: 400,
- statusText: "Bad Request",
- headers: { "Content-Type": "application/json" },
- },
- ),
- );
-
- const request = client.createTaskAutomation({
- name: "Daily PRs",
- prompt: "Check PRs",
- repository: "posthog/posthog",
- cron_expression: "not a cron",
- timezone: "Europe/London",
- });
-
- await expect(request).rejects.toBeInstanceOf(TaskAutomationValidationError);
- await expect(request).rejects.toMatchObject({
- status: 400,
- code: "invalid_input",
- attr: "cron_expression",
- message: "Enter a valid cron expression.",
- });
- });
-});
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index b53b4079d2b2..cdf07c742f48 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -3,31 +3,23 @@ import type {
Adapter,
CloudMcpServerRelayDesignation,
CloudRunSource,
- CreateTaskAutomationOptions,
ExecutionMode,
McpServerConnection,
PrAuthorshipMode,
SourceProduct,
SourceType,
StoredLogEntry,
- TaskAutomation,
TaskRunArtifactMetadata,
- UpdateTaskAutomationOptions,
} from "@posthog/shared";
import {
buildCloudTaskConfigOptions,
type CloudTaskConfigOption,
- createTaskAutomationSchema,
DISMISSAL_REASON_OPTIONS,
type DismissalReasonOptionValue,
getCloudTaskGatewayUrl,
isSupportedReasoningEffort,
normalizeGatewayModelsResponse,
resolveCloudInitialPermissionMode,
- taskAutomationListSchema,
- taskAutomationSchema,
- taskAutomationValidationErrorSchema,
- updateTaskAutomationSchema,
} from "@posthog/shared";
import type {
AgentAnalyticsData,
@@ -322,36 +314,6 @@ export class CloudUsageLimitError extends Error {
}
}
-export class TaskAutomationValidationError extends Error {
- readonly status = 400;
- readonly code: string;
- readonly attr: string | null;
-
- constructor(details: {
- detail: string;
- code: string;
- attr: string | null;
- }) {
- super(details.detail);
- this.name = "TaskAutomationValidationError";
- this.code = details.code;
- this.attr = details.attr;
- }
-}
-
-function rethrowTaskAutomationError(error: unknown): never {
- if (error instanceof ApiRequestError && error.status === 400) {
- const validationError = taskAutomationValidationErrorSchema.safeParse(
- error.body,
- );
- if (validationError.success) {
- throw new TaskAutomationValidationError(validationError.data);
- }
- }
-
- throw error;
-}
-
export const MCP_CATEGORIES = [
{ id: "all", label: "All" },
{ id: "business", label: "Business Operations" },
@@ -2504,101 +2466,6 @@ export class PostHogAPIClient {
return data.pinned;
}
- async listTaskAutomations(options?: {
- limit?: number;
- offset?: number;
- }): Promise<TaskAutomation[]> {
- const teamId = await this.getTeamId();
- const data = await this.api.get(
- `/api/projects/{project_id}/task_automations/`,
- {
- path: { project_id: teamId.toString() },
- query: {
- limit: options?.limit ?? 500,
- ...(options?.offset === undefined ? {} : { offset: options.offset }),
- },
- },
- );
-
- return taskAutomationListSchema.parse(data).results;
- }
-
- async getTaskAutomation(automationId: string): Promise<TaskAutomation> {
- const teamId = await this.getTeamId();
- const data = await this.api.get(
- `/api/projects/{project_id}/task_automations/{id}/`,
- {
- path: { project_id: teamId.toString(), id: automationId },
- },
- );
-
- return taskAutomationSchema.parse(data);
- }
-
- async createTaskAutomation(
- options: CreateTaskAutomationOptions,
- ): Promise<TaskAutomation> {
- const teamId = await this.getTeamId();
- const body = createTaskAutomationSchema.parse(options);
-
- try {
- const data = await this.api.post(
- `/api/projects/{project_id}/task_automations/`,
- {
- path: { project_id: teamId.toString() },
- body: body as Schemas.TaskAutomation,
- },
- );
- return taskAutomationSchema.parse(data);
- } catch (error) {
- rethrowTaskAutomationError(error);
- }
- }
-
- async updateTaskAutomation(
- automationId: string,
- updates: UpdateTaskAutomationOptions,
- ): Promise<TaskAutomation> {
- const teamId = await this.getTeamId();
- const body = updateTaskAutomationSchema.parse(updates);
-
- try {
- const data = await this.api.patch(
- `/api/projects/{project_id}/task_automations/{id}/`,
- {
- path: { project_id: teamId.toString(), id: automationId },
- body,
- },
- );
- return taskAutomationSchema.parse(data);
- } catch (error) {
- rethrowTaskAutomationError(error);
- }
- }
-
- async deleteTaskAutomation(automationId: string): Promise<void> {
- const teamId = await this.getTeamId();
- await this.api.delete(`/api/projects/{project_id}/task_automations/{id}/`, {
- path: { project_id: teamId.toString(), id: automationId },
- });
- }
-
- async runTaskAutomation(automationId: string): Promise<TaskAutomation> {
- const teamId = await this.getTeamId();
- const path = `/api/projects/${teamId}/task_automations/${automationId}/run/`;
-
- try {
- const response = await this.api.fetcher.fetch({
- method: "post",
- path,
- url: new URL(`${this.api.baseUrl}${path}`),
- });
- return taskAutomationSchema.parse(await response.json());
- } catch (error) {
- rethrowTaskAutomationError(error);
- }
- }
-
async createTask(
options: Pick<Task, "description"> &
Partial<
diff --git a/products/desktop/packages/core/src/automations/automationSchedule.test.ts b/products/desktop/packages/core/src/automations/automationSchedule.test.ts
deleted file mode 100644
index 5deb2487a0e0..000000000000
--- a/products/desktop/packages/core/src/automations/automationSchedule.test.ts
+++ /dev/null
@@ -1,223 +0,0 @@
-import { describe, expect, it } from "vitest";
-import {
- type AutomationScheduleDraft,
- buildCronExpression,
- createDefaultScheduleDraft,
- deriveAutomationName,
- formatAutomationScheduleSummary,
- formatScheduleSummary,
- parseCronExpression,
- sanitizeHour,
- sanitizeMinute,
- WEEKDAY_OPTIONS,
-} from "./automationSchedule";
-
-describe("automationSchedule", () => {
- it("creates the default daily schedule draft", () => {
- expect(createDefaultScheduleDraft()).toEqual({
- mode: "daily",
- hour: "09",
- minute: "00",
- weekday: "1",
- rawCron: "0 9 * * *",
- });
- });
-
- it("provides cron weekday values in display order", () => {
- expect(WEEKDAY_OPTIONS).toEqual([
- { value: "1", label: "Mon" },
- { value: "2", label: "Tue" },
- { value: "3", label: "Wed" },
- { value: "4", label: "Thu" },
- { value: "5", label: "Fri" },
- { value: "6", label: "Sat" },
- { value: "0", label: "Sun" },
- ]);
- });
-
- it.each([
- ["", ""],
- ["a", ""],
- ["7", "07"],
- ["09", "09"],
- ["2x3", "23"],
- ["24", "23"],
- ["999", "23"],
- ])("sanitizes hour input %j to %j", (input, expected) => {
- expect(sanitizeHour(input)).toBe(expected);
- });
-
- it.each([
- ["", ""],
- ["a", ""],
- ["7", "07"],
- ["09", "09"],
- ["5x9", "59"],
- ["60", "59"],
- ["999", "59"],
- ])("sanitizes minute input %j to %j", (input, expected) => {
- expect(sanitizeMinute(input)).toBe(expected);
- });
-
- it.each<{
- name: string;
- changes: Partial<AutomationScheduleDraft>;
- expected: string;
- }>([
- {
- name: "hourly",
- changes: { mode: "hourly", minute: "15" },
- expected: "15 * * * *",
- },
- {
- name: "daily",
- changes: { mode: "daily", hour: "09", minute: "15" },
- expected: "15 9 * * *",
- },
- {
- name: "weekdays",
- changes: { mode: "weekdays", hour: "10", minute: "00" },
- expected: "0 10 * * 1-5",
- },
- {
- name: "weekly",
- changes: {
- mode: "weekly",
- hour: "11",
- minute: "30",
- weekday: "4",
- },
- expected: "30 11 * * 4",
- },
- {
- name: "weekly with a missing weekday",
- changes: { mode: "weekly", weekday: "" },
- expected: "0 9 * * 1",
- },
- {
- name: "preset with missing time values",
- changes: { mode: "daily", hour: "", minute: "" },
- expected: "0 9 * * *",
- },
- {
- name: "custom",
- changes: { mode: "custom", rawCron: " */15 * * * * " },
- expected: "*/15 * * * *",
- },
- ])("builds the $name cron expression", ({ changes, expected }) => {
- expect(
- buildCronExpression({ ...createDefaultScheduleDraft(), ...changes }),
- ).toBe(expected);
- });
-
- it.each([
- [
- "15 * * * *",
- {
- mode: "hourly",
- hour: "09",
- minute: "15",
- weekday: "*",
- rawCron: "15 * * * *",
- },
- ],
- [
- "0 9 * * *",
- {
- mode: "daily",
- hour: "09",
- minute: "00",
- weekday: "*",
- rawCron: "0 9 * * *",
- },
- ],
- [
- "0 9 * * 1-5",
- {
- mode: "weekdays",
- hour: "09",
- minute: "00",
- weekday: "1",
- rawCron: "0 9 * * 1-5",
- },
- ],
- [
- "30 14 * * 2",
- {
- mode: "weekly",
- hour: "14",
- minute: "30",
- weekday: "2",
- rawCron: "30 14 * * 2",
- },
- ],
- ] as const)("parses %s into a schedule draft", (cron, expected) => {
- expect(parseCronExpression(cron)).toEqual(expected);
- });
-
- it.each(["*/15 * * * *", "0 9 1 * *", "0 9 * 1 *", "0 9 * * 1,3"])(
- "keeps unsupported cron expression %s in custom mode",
- (cron) => {
- expect(parseCronExpression(cron)).toMatchObject({
- mode: "custom",
- rawCron: cron,
- });
- },
- );
-
- it("normalizes surrounding and repeated cron whitespace", () => {
- expect(parseCronExpression(" 5 8 * * * ")).toEqual({
- mode: "daily",
- hour: "08",
- minute: "05",
- weekday: "*",
- rawCron: "5 8 * * *",
- });
- });
-
- it("uses default draft fields for a cron expression with the wrong arity", () => {
- expect(parseCronExpression("0 9 * *")).toEqual({
- mode: "custom",
- hour: "09",
- minute: "00",
- weekday: "1",
- rawCron: "0 9 * *",
- });
- });
-
- it("derives a compact name from the first non-empty prompt line", () => {
- expect(
- deriveAutomationName(
- "\n Review every open PostHog PR for stale comments \nIgnore this line",
- ),
- ).toBe("Review every open PostHog PR for stale comments");
- });
-
- it("returns an empty name for a blank prompt", () => {
- expect(deriveAutomationName(" \n\t\n ")).toBe("");
- });
-
- it("limits derived names to 80 characters", () => {
- expect(deriveAutomationName("a".repeat(100))).toBe("a".repeat(80));
- });
-
- it.each([
- ["15 * * * *", "Europe/London", "Every hour at :15 · Europe/London"],
- ["0 9 * * *", null, "Daily at 09:00"],
- ["0 9 * * 1-5", "UTC", "Weekdays at 09:00 · UTC"],
- ["30 14 * * 2", undefined, "Tue at 14:30"],
- ["30 14 * * 7", "UTC", "Weekly at 14:30 · UTC"],
- ["*/15 * * * *", "UTC", "Custom schedule · UTC"],
- ])("formats %s with timezone %j", (cronExpression, timezone, expected) => {
- expect(formatScheduleSummary(cronExpression, timezone)).toBe(expected);
- });
-
- it("formats a schedule from an automation-shaped input", () => {
- expect(
- formatAutomationScheduleSummary({
- cron_expression: "0 18 * * 0",
- timezone: "America/New_York",
- }),
- ).toBe("Sun at 18:00 · America/New_York");
- });
-});
diff --git a/products/desktop/packages/core/src/automations/automationSchedule.ts b/products/desktop/packages/core/src/automations/automationSchedule.ts
deleted file mode 100644
index 527e8da49747..000000000000
--- a/products/desktop/packages/core/src/automations/automationSchedule.ts
+++ /dev/null
@@ -1,216 +0,0 @@
-export type AutomationScheduleMode =
- | "hourly"
- | "daily"
- | "weekdays"
- | "weekly"
- | "custom";
-
-export interface AutomationScheduleDraft {
- mode: AutomationScheduleMode;
- hour: string;
- minute: string;
- weekday: string;
- rawCron: string;
-}
-
-export interface AutomationScheduleSummaryInput {
- cron_expression: string;
- timezone?: string | null;
-}
-
-export const WEEKDAY_OPTIONS = [
- { value: "1", label: "Mon" },
- { value: "2", label: "Tue" },
- { value: "3", label: "Wed" },
- { value: "4", label: "Thu" },
- { value: "5", label: "Fri" },
- { value: "6", label: "Sat" },
- { value: "0", label: "Sun" },
-] as const;
-
-export function createDefaultScheduleDraft(): AutomationScheduleDraft {
- return {
- mode: "daily",
- hour: "09",
- minute: "00",
- weekday: "1",
- rawCron: "0 9 * * *",
- };
-}
-
-function padTimePart(value: string): string {
- return value.padStart(2, "0");
-}
-
-export function sanitizeHour(value: string): string {
- const digitsOnly = value.replace(/\D/g, "").slice(0, 2);
- if (!digitsOnly) {
- return "";
- }
-
- return String(Math.min(23, Number(digitsOnly))).padStart(2, "0");
-}
-
-export function sanitizeMinute(value: string): string {
- const digitsOnly = value.replace(/\D/g, "").slice(0, 2);
- if (!digitsOnly) {
- return "";
- }
-
- return String(Math.min(59, Number(digitsOnly))).padStart(2, "0");
-}
-
-export function buildCronExpression(draft: AutomationScheduleDraft): string {
- if (draft.mode === "custom") {
- return draft.rawCron.trim();
- }
-
- const minute = draft.minute ? String(Number(draft.minute)) : "0";
- const hour = draft.hour ? String(Number(draft.hour)) : "9";
-
- switch (draft.mode) {
- case "hourly":
- return `${minute} * * * *`;
- case "weekdays":
- return `${minute} ${hour} * * 1-5`;
- case "weekly":
- return `${minute} ${hour} * * ${draft.weekday || "1"}`;
- default:
- return `${minute} ${hour} * * *`;
- }
-}
-
-export function parseCronExpression(
- cronExpression: string,
-): AutomationScheduleDraft {
- const normalized = cronExpression.trim();
- const parts = normalized.split(/\s+/);
-
- if (parts.length !== 5) {
- return {
- ...createDefaultScheduleDraft(),
- mode: "custom",
- rawCron: normalized,
- };
- }
-
- const [minute, hour, dayOfMonth, month, dayOfWeek] = parts;
- const isNumericMinute = /^\d{1,2}$/.test(minute);
- const isNumericHour = /^\d{1,2}$/.test(hour);
- const draftBase = {
- hour: padTimePart(hour),
- minute: padTimePart(minute),
- weekday: dayOfWeek,
- rawCron: normalized,
- };
-
- if (
- isNumericMinute &&
- hour === "*" &&
- dayOfMonth === "*" &&
- month === "*" &&
- dayOfWeek === "*"
- ) {
- return {
- ...draftBase,
- mode: "hourly",
- hour: "09",
- };
- }
-
- if (
- isNumericMinute &&
- isNumericHour &&
- dayOfMonth === "*" &&
- month === "*" &&
- dayOfWeek === "*"
- ) {
- return {
- ...draftBase,
- mode: "daily",
- };
- }
-
- if (
- isNumericMinute &&
- isNumericHour &&
- dayOfMonth === "*" &&
- month === "*" &&
- dayOfWeek === "1-5"
- ) {
- return {
- ...draftBase,
- mode: "weekdays",
- weekday: "1",
- };
- }
-
- if (
- isNumericMinute &&
- isNumericHour &&
- dayOfMonth === "*" &&
- month === "*" &&
- /^\d$/.test(dayOfWeek)
- ) {
- return {
- ...draftBase,
- mode: "weekly",
- };
- }
-
- return {
- ...draftBase,
- mode: "custom",
- };
-}
-
-export function deriveAutomationName(prompt: string): string {
- const normalized = prompt
- .split("\n")
- .map((line) => line.trim())
- .find(Boolean);
-
- if (!normalized) {
- return "";
- }
-
- return normalized.replace(/\s+/g, " ").slice(0, 80);
-}
-
-function formatTime(hour: string, minute: string): string {
- return `${padTimePart(hour)}:${padTimePart(minute)}`;
-}
-
-export function formatScheduleSummary(
- cronExpression: string,
- timezone: string | null | undefined,
-): string {
- const draft = parseCronExpression(cronExpression);
- const suffix = timezone ? ` · ${timezone}` : "";
-
- switch (draft.mode) {
- case "hourly":
- return `Every hour at :${padTimePart(draft.minute)}${suffix}`;
- case "weekdays":
- return `Weekdays at ${formatTime(draft.hour, draft.minute)}${suffix}`;
- case "weekly": {
- const label =
- WEEKDAY_OPTIONS.find((option) => option.value === draft.weekday)
- ?.label ?? "Weekly";
- return `${label} at ${formatTime(draft.hour, draft.minute)}${suffix}`;
- }
- case "custom":
- return `Custom schedule${suffix}`;
- default:
- return `Daily at ${formatTime(draft.hour, draft.minute)}${suffix}`;
- }
-}
-
-export function formatAutomationScheduleSummary(
- automation: AutomationScheduleSummaryInput,
-): string {
- return formatScheduleSummary(
- automation.cron_expression,
- automation.timezone ?? null,
- );
-}
diff --git a/products/desktop/packages/core/src/automations/automationStatus.test.ts b/products/desktop/packages/core/src/automations/automationStatus.test.ts
deleted file mode 100644
index 862fc3c0b5d4..000000000000
--- a/products/desktop/packages/core/src/automations/automationStatus.test.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { describe, expect, it } from "vitest";
-import {
- type AutomationStatusPresentation,
- type AutomationTaskRunStatus,
- getAutomationStatusPresentation,
-} from "./automationStatus";
-
-describe("automationStatus", () => {
- it.each<{
- status: AutomationTaskRunStatus;
- expected: AutomationStatusPresentation | null;
- }>([
- {
- status: "not_started",
- expected: { label: "Queued", tone: "warning", iconKind: "queued" },
- },
- {
- status: "queued",
- expected: { label: "Queued", tone: "warning", iconKind: "queued" },
- },
- { status: "started", expected: null },
- { status: "in_progress", expected: null },
- {
- status: "completed",
- expected: { label: "Success", tone: "success", iconKind: "success" },
- },
- {
- status: "failed",
- expected: { label: "Failed", tone: "error", iconKind: "failed" },
- },
- {
- status: "cancelled",
- expected: { label: "Failed", tone: "error", iconKind: "failed" },
- },
- ])(
- "maps task-run status $status to renderer-neutral presentation data",
- ({ status, expected }) => {
- expect(
- getAutomationStatusPresentation({
- lastRunStatus: "success",
- lastTaskRunStatus: status,
- }),
- ).toEqual(expected);
- },
- );
-
- it.each([
- ["running", null],
- ["success", { label: "Success", tone: "success", iconKind: "success" }],
- ["failed", { label: "Failed", tone: "error", iconKind: "failed" }],
- [null, { label: "Never run", tone: "neutral", iconKind: "never-run" }],
- ["unknown", { label: "Never run", tone: "neutral", iconKind: "never-run" }],
- ] as const)(
- "falls back from automation status %j to semantic presentation data",
- (lastRunStatus, expected) => {
- expect(getAutomationStatusPresentation({ lastRunStatus })).toEqual(
- expected,
- );
- },
- );
-
- it("prioritizes linked task-run detail over the automation-level status", () => {
- expect(
- getAutomationStatusPresentation({
- lastRunStatus: "failed",
- lastTaskRunStatus: "completed",
- }),
- ).toEqual({
- label: "Success",
- tone: "success",
- iconKind: "success",
- });
- });
-
- it("does not expose renderer-specific class names", () => {
- expect(
- getAutomationStatusPresentation({ lastRunStatus: "success" }),
- ).not.toHaveProperty("className");
- });
-});
diff --git a/products/desktop/packages/core/src/automations/automationStatus.ts b/products/desktop/packages/core/src/automations/automationStatus.ts
deleted file mode 100644
index 4bcc13735ed4..000000000000
--- a/products/desktop/packages/core/src/automations/automationStatus.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-export type AutomationTaskRunStatus =
- | "not_started"
- | "queued"
- | "started"
- | "in_progress"
- | "completed"
- | "failed"
- | "cancelled";
-
-export interface AutomationStatusInput {
- lastRunStatus: string | null;
- lastTaskRunStatus?: AutomationTaskRunStatus | null;
-}
-
-export type AutomationStatusTone = "neutral" | "warning" | "success" | "error";
-
-export type AutomationStatusIconKind =
- | "queued"
- | "success"
- | "failed"
- | "never-run";
-
-export interface AutomationStatusPresentation {
- label: string;
- tone: AutomationStatusTone;
- iconKind: AutomationStatusIconKind;
-}
-
-export function getAutomationStatusPresentation({
- lastRunStatus,
- lastTaskRunStatus,
-}: AutomationStatusInput): AutomationStatusPresentation | null {
- switch (lastTaskRunStatus) {
- case "not_started":
- case "queued":
- return {
- label: "Queued",
- tone: "warning",
- iconKind: "queued",
- };
- case "started":
- case "in_progress":
- return null;
- case "completed":
- return {
- label: "Success",
- tone: "success",
- iconKind: "success",
- };
- case "failed":
- case "cancelled":
- return {
- label: "Failed",
- tone: "error",
- iconKind: "failed",
- };
- default:
- break;
- }
-
- switch (lastRunStatus) {
- case "running":
- return null;
- case "success":
- return {
- label: "Success",
- tone: "success",
- iconKind: "success",
- };
- case "failed":
- return {
- label: "Failed",
- tone: "error",
- iconKind: "failed",
- };
- default:
- return {
- label: "Never run",
- tone: "neutral",
- iconKind: "never-run",
- };
- }
-}
diff --git a/products/desktop/packages/core/src/automations/automationTemplatePresentation.ts b/products/desktop/packages/core/src/automations/automationTemplatePresentation.ts
deleted file mode 100644
index d2acbc22b8ab..000000000000
--- a/products/desktop/packages/core/src/automations/automationTemplatePresentation.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import type { TaskAutomation } from "@posthog/shared";
-
-export const SKILL_TEMPLATE_ID_PREFIX = "llm-skill:";
-
-export function formatSkillTemplateId(skillName: string): string {
- return `${SKILL_TEMPLATE_ID_PREFIX}${skillName.trim()}`;
-}
-
-export function parseSkillTemplateId(
- templateId: string | null | undefined,
-): string | null {
- if (!templateId?.startsWith(SKILL_TEMPLATE_ID_PREFIX)) return null;
- const skillName = templateId.slice(SKILL_TEMPLATE_ID_PREFIX.length).trim();
- return skillName || null;
-}
-
-export interface AutomationTemplatePresentation {
- templateName: string | null;
- repositoryLabel: string | null;
- contextLabel: string | null;
- secondaryLabel: string;
-}
-
-export function getAutomationTemplatePresentation(
- automation: Pick<TaskAutomation, "repository" | "template_id">,
-): AutomationTemplatePresentation {
- const repositoryLabel = automation.repository.trim() || null;
- const skillName = parseSkillTemplateId(automation.template_id);
- const contextLabel = skillName ? "Skill store" : null;
- return {
- templateName:
- skillName ?? (automation.template_id ? "Template automation" : null),
- repositoryLabel,
- contextLabel,
- secondaryLabel: repositoryLabel ?? contextLabel ?? "No repository context",
- };
-}
diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.ts
index 4108c587643d..fbf7a1cfbbea 100644
--- a/products/desktop/packages/shared/src/index.ts
+++ b/products/desktop/packages/shared/src/index.ts
@@ -343,18 +343,6 @@ export {
stripFrontmatter,
} from "./skills";
export type { PostHogAPIConfig } from "./task";
-export {
- type CreateTaskAutomationOptions,
- createTaskAutomationSchema,
- type TaskAutomation,
- type TaskAutomationList,
- type TaskAutomationValidationErrorDetails,
- taskAutomationListSchema,
- taskAutomationSchema,
- taskAutomationValidationErrorSchema,
- type UpdateTaskAutomationOptions,
- updateTaskAutomationSchema,
-} from "./task-automation";
export type {
TaskCreationInput,
TaskCreationOutput,
diff --git a/products/desktop/packages/shared/src/task-automation.test.ts b/products/desktop/packages/shared/src/task-automation.test.ts
deleted file mode 100644
index 57e6fcaa979b..000000000000
--- a/products/desktop/packages/shared/src/task-automation.test.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { describe, expect, expectTypeOf, it } from "vitest";
-import {
- type CreateTaskAutomationOptions,
- createTaskAutomationSchema,
- taskAutomationSchema,
- taskAutomationValidationErrorSchema,
- type UpdateTaskAutomationOptions,
- updateTaskAutomationSchema,
-} from "./task-automation";
-
-describe("task automation contracts", () => {
- it("normalizes optional automation response fields", () => {
- expect(
- taskAutomationSchema.parse({
- id: "automation-1",
- name: "Daily PRs",
- prompt: "Check PRs",
- repository: "posthog/posthog",
- cron_expression: "0 9 * * *",
- last_run_at: null,
- last_run_status: null,
- last_task_id: null,
- last_task_run_id: null,
- last_error: null,
- created_at: "2026-07-21T00:00:00Z",
- updated_at: "2026-07-21T00:00:00Z",
- }),
- ).toMatchObject({
- github_integration: null,
- timezone: null,
- template_id: null,
- enabled: true,
- });
- });
-
- it("keeps create fields required and update fields partial", () => {
- const create = createTaskAutomationSchema.parse({
- name: "Daily PRs",
- prompt: "Check PRs",
- repository: "posthog/posthog",
- cron_expression: "0 9 * * *",
- timezone: "Europe/London",
- });
- const update = updateTaskAutomationSchema.parse({ enabled: false });
-
- expect(create.timezone).toBe("Europe/London");
- expect(update).toEqual({ enabled: false });
- expectTypeOf(create).toEqualTypeOf<CreateTaskAutomationOptions>();
- expectTypeOf(update).toEqualTypeOf<UpdateTaskAutomationOptions>();
- });
-
- it("preserves backend validation field attribution", () => {
- expect(
- taskAutomationValidationErrorSchema.parse({
- type: "validation_error",
- detail: "Enter a valid cron expression.",
- attr: "cron_expression",
- }),
- ).toEqual({
- type: "validation_error",
- code: "invalid_input",
- detail: "Enter a valid cron expression.",
- attr: "cron_expression",
- });
- });
-});
diff --git a/products/desktop/packages/shared/src/task-automation.ts b/products/desktop/packages/shared/src/task-automation.ts
deleted file mode 100644
index 0f3e4a4bde97..000000000000
--- a/products/desktop/packages/shared/src/task-automation.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { z } from "zod";
-
-export const taskAutomationSchema = z.object({
- id: z.string(),
- name: z.string(),
- prompt: z.string(),
- repository: z.string(),
- github_integration: z.number().nullable().default(null),
- cron_expression: z.string(),
- timezone: z.string().nullable().default(null),
- template_id: z.string().nullable().default(null),
- enabled: z.boolean().default(true),
- last_run_at: z.string().nullable(),
- last_run_status: z.string().nullable(),
- last_task_id: z.string().nullable(),
- last_task_run_id: z.string().nullable(),
- last_error: z.string().nullable(),
- created_at: z.string(),
- updated_at: z.string(),
-});
-export type TaskAutomation = z.infer<typeof taskAutomationSchema>;
-
-export const taskAutomationListSchema = z.object({
- count: z.number(),
- next: z.string().nullable().optional(),
- previous: z.string().nullable().optional(),
- results: z.array(taskAutomationSchema),
-});
-export type TaskAutomationList = z.infer<typeof taskAutomationListSchema>;
-
-export const createTaskAutomationSchema = z.object({
- name: z.string(),
- prompt: z.string(),
- repository: z.string(),
- github_integration: z.number().nullable().optional(),
- cron_expression: z.string(),
- timezone: z.string(),
- template_id: z.string().nullable().optional(),
- enabled: z.boolean().optional(),
-});
-export type CreateTaskAutomationOptions = z.infer<
- typeof createTaskAutomationSchema
->;
-
-export const updateTaskAutomationSchema = createTaskAutomationSchema.partial();
-export type UpdateTaskAutomationOptions = z.infer<
- typeof updateTaskAutomationSchema
->;
-
-export const taskAutomationValidationErrorSchema = z.object({
- type: z.string().optional(),
- code: z.string().default("invalid_input"),
- detail: z.string(),
- attr: z.string().nullable().default(null),
-});
-export type TaskAutomationValidationErrorDetails = z.infer<
- typeof taskAutomationValidationErrorSchema
->;
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/TaskIcon.tsx b/products/desktop/packages/ui/src/features/sidebar/components/items/TaskIcon.tsx
index 1e2443125226..daddd7fdcce3 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/items/TaskIcon.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/TaskIcon.tsx
@@ -13,7 +13,6 @@ import {
Lifebuoy,
Pause,
PushPin,
- Robot,
SlackLogo,
WarningCircle,
} from "@phosphor-icons/react";
@@ -50,7 +49,6 @@ const ORIGIN_PRODUCT_META: Record<string, OriginProductMeta> = {
session_summaries: { Icon: FilmSlate, label: "Session summary" },
error_tracking: { Icon: Bug, label: "Error tracking" },
eval_clusters: { Icon: Flask, label: "Evals" },
- automation: { Icon: Robot, label: "Automation" },
};
export function getOriginProductMeta(
diff --git a/products/desktop/scripts/mobile-type-baseline.json b/products/desktop/scripts/mobile-type-baseline.json
index 7ac42ce24ddc..d98222dc6cc2 100644
--- a/products/desktop/scripts/mobile-type-baseline.json
+++ b/products/desktop/scripts/mobile-type-baseline.json
@@ -42,40 +42,6 @@
"src/features/navigation/components/NavDrawer.tsx": {
"TS2551 Property 'absoluteFillObject' does not exist on type 'typeof StyleSheet'. Did you mean 'absoluteFill'?": 2
},
- "src/features/tasks/components/AutomationDetail.tsx": {
- "TS2459 Module '\"@posthog/api-client/posthog-client\"' declares 'TaskAutomation' locally, but it is not exported.": 1
- },
- "src/features/tasks/components/AutomationForm.test.tsx": {
- "TS2339 Property 'root' does not exist on type 'never'.": 7,
- "TS7006 Parameter 'node' implicitly has an 'any' type.": 2
- },
- "src/features/tasks/components/AutomationForm.tsx": {
- "TS2459 Module '\"@posthog/api-client/posthog-client\"' declares 'CreateTaskAutomationOptions' locally, but it is not exported.": 1
- },
- "src/features/tasks/components/AutomationItem.tsx": {
- "TS2459 Module '\"@posthog/api-client/posthog-client\"' declares 'TaskAutomation' locally, but it is not exported.": 1
- },
- "src/features/tasks/components/AutomationList.tsx": {
- "TS2459 Module '\"@posthog/api-client/posthog-client\"' declares 'TaskAutomation' locally, but it is not exported.": 1
- },
- "src/features/tasks/components/AutomationSkillCard.test.tsx": {
- "TS2339 Property 'root' does not exist on type 'never'.": 5,
- "TS7006 Parameter 'node' implicitly has an 'any' type.": 5
- },
- "src/features/tasks/components/AutomationSkillCard.tsx": {
- "TS2305 Module '\"@posthog/api-client\"' has no exported member 'LlmSkillListItem'.": 1
- },
- "src/features/tasks/components/AutomationSkillChooser.test.tsx": {
- "TS2339 Property 'root' does not exist on type 'never'.": 8,
- "TS7006 Parameter 'node' implicitly has an 'any' type.": 4
- },
- "src/features/tasks/components/AutomationStatusBadge.test.tsx": {
- "TS2339 Property 'toJSON' does not exist on type 'never'.": 2
- },
- "src/features/tasks/components/CreateAutomationScreen.test.tsx": {
- "TS2339 Property 'root' does not exist on type 'never'.": 5,
- "TS7006 Parameter 'node' implicitly has an 'any' type.": 2
- },
"src/features/tasks/components/PlanApprovalCard.test.tsx": {
"TS2339 Property 'root' does not exist on type 'never'.": 2
},
@@ -93,11 +59,6 @@
"src/features/tasks/composer/DotBackground.tsx": {
"TS2551 Property 'absoluteFillObject' does not exist on type 'typeof StyleSheet'. Did you mean 'absoluteFill'?": 1
},
- "src/features/tasks/hooks/useAutomations.ts": {
- "TS2459 Module '\"@posthog/api-client/posthog-client\"' declares 'CreateTaskAutomationOptions' locally, but it is not exported.": 1,
- "TS2459 Module '\"@posthog/api-client/posthog-client\"' declares 'TaskAutomation' locally, but it is not exported.": 1,
- "TS2459 Module '\"@posthog/api-client/posthog-client\"' declares 'UpdateTaskAutomationOptions' locally, but it is not exported.": 1
- },
"src/features/tasks/hooks/useCloudAttachmentPreview.ts": {
"TS2305 Module '\"../types\"' has no exported member 'CloudArtifactRef'.": 1
},
diff --git a/products/tasks/backend/automation_service.py b/products/tasks/backend/automation_service.py
deleted file mode 100644
index 04f65e8d2448..000000000000
--- a/products/tasks/backend/automation_service.py
+++ /dev/null
@@ -1,160 +0,0 @@
-import logging
-
-from django.conf import settings
-from django.core.exceptions import PermissionDenied
-from django.db import transaction
-
-from temporalio.client import Schedule, ScheduleActionStartWorkflow, ScheduleSpec, ScheduleState
-
-from posthog.temporal.common.client import sync_connect
-from posthog.temporal.common.schedule import (
- create_schedule,
- delete_schedule,
- pause_schedule,
- schedule_exists,
- unpause_schedule,
- update_schedule,
-)
-
-from .access import has_tasks_access
-from .models import Task, TaskAutomation, TaskRun
-
-logger = logging.getLogger(__name__)
-
-
-def build_automation_schedule(automation: TaskAutomation) -> Schedule:
- return Schedule(
- action=ScheduleActionStartWorkflow(
- "run-task-automation",
- str(automation.id),
- id=f'task-automation-run-{automation.id}-{{{{.ScheduledTime.Format "2006-01-02-15-04"}}}}',
- task_queue=settings.TASKS_TASK_QUEUE,
- ),
- spec=ScheduleSpec(
- cron_expressions=[automation.cron_expression],
- time_zone_name=automation.timezone,
- ),
- state=ScheduleState(
- paused=not automation.enabled,
- note=f"Schedule for task automation: {automation.id}",
- ),
- )
-
-
-def sync_automation_schedule(automation: TaskAutomation) -> None:
- temporal = sync_connect()
- schedule = build_automation_schedule(automation)
-
- if schedule_exists(temporal, automation.schedule_id):
- update_schedule(temporal, automation.schedule_id, schedule)
- if automation.enabled:
- unpause_schedule(temporal, automation.schedule_id, note="Automation enabled")
- else:
- pause_schedule(temporal, automation.schedule_id, note="Automation paused")
- else:
- create_schedule(temporal, automation.schedule_id, schedule)
-
-
-def delete_automation_schedule(automation: TaskAutomation) -> None:
- temporal = sync_connect()
- if schedule_exists(temporal, automation.schedule_id):
- delete_schedule(temporal, automation.schedule_id)
-
-
-def run_task_automation(automation_id: str, trigger_workflow_id: str | None = None) -> tuple[Task, TaskRun]:
- automation_id = str(automation_id)
-
- # Scheduled fires bypass the HTTP gate, so re-check the creator (fail closed if deleted) before
- # the run transaction, recording the reason to last_error instead of rolling it back.
- automation = TaskAutomation.objects.select_related("task", "task__created_by").get(id=automation_id)
- creator = automation.task.created_by
- if creator is None or not has_tasks_access(creator):
- automation.last_error = "PostHog Desktop access is required to run task automations"
- automation.save(update_fields=["last_error", "updated_at"])
- raise PermissionDenied("PostHog Desktop access is required to run task automations")
-
- with transaction.atomic():
- automation = TaskAutomation.objects.select_for_update(of=("self",)).select_related("task").get(id=automation_id)
- task = automation.task
-
- if trigger_workflow_id:
- existing_task_run_query = TaskRun.objects.select_related("task").filter(
- task__team_id=task.team_id,
- task_id=task.id,
- state__automation_id=automation_id,
- state__automation_trigger_workflow_id=trigger_workflow_id,
- )
- existing_task_run = existing_task_run_query.order_by("-created_at").first()
- if existing_task_run is not None:
- task_run = existing_task_run
- else:
- extra_state = {"automation_id": automation_id}
- if trigger_workflow_id:
- extra_state["automation_trigger_workflow_id"] = trigger_workflow_id
- task_run = task.create_run(mode="background", extra_state=extra_state)
- else:
- task_run = task.create_run(mode="background", extra_state={"automation_id": automation_id})
-
- team_id = task.team_id
- user_id = task.created_by_id
-
- automation.last_task_run = task_run
- automation.last_error = None
- automation.save(
- update_fields=[
- "last_task_run",
- "last_error",
- "updated_at",
- ]
- )
-
- transaction.on_commit(
- lambda: execute_task_processing_workflow_for_automation(
- team_id=team_id,
- user_id=user_id,
- task_id=str(task.id),
- run_id=str(task_run.id),
- )
- )
-
- logger.info(
- "task_automation_run_started",
- extra={
- "automation_id": automation_id,
- "task_id": str(task.id),
- "run_id": str(task_run.id),
- "team_id": team_id,
- },
- )
-
- return task, task_run
-
-
-def execute_task_processing_workflow_for_automation(
- *, team_id: int, user_id: int | None, task_id: str, run_id: str
-) -> None:
- from .temporal.client import execute_task_processing_workflow
-
- execute_task_processing_workflow(
- task_id=task_id,
- run_id=run_id,
- team_id=team_id,
- user_id=user_id,
- skip_user_check=True,
- )
-
-
-def update_automation_run_result(task_run: TaskRun) -> None:
- if task_run.task.origin_product != Task.OriginProduct.AUTOMATION:
- return
-
- try:
- automation = task_run.task.automation
- except TaskAutomation.DoesNotExist:
- return
-
- if task_run.status not in [TaskRun.Status.FAILED, TaskRun.Status.CANCELLED]:
- return
-
- automation.last_error = task_run.error_message
- automation.save(update_fields=["last_error", "updated_at"])
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 9a79569c3ef2..849a6c68e994 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -102,7 +102,6 @@ from products.tasks.backend.models import (
Task,
TaskActivity,
TaskArtifact,
- TaskAutomation,
TaskClientProvenance,
TaskCommentActivity,
TaskPin,
@@ -181,7 +180,6 @@ __all__ = [
"create_sandbox_environment",
"create_channel_task",
"create_task",
- "create_task_automation",
"create_task_without_run",
"create_shared_channel_task_without_run",
"create_task_run_connection_token",
@@ -193,7 +191,6 @@ __all__ = [
"delete_sandbox_environment",
"ensure_personal_channel_id",
"ensure_sandbox_custom_image_builder_task",
- "delete_task_automation",
"edit_task_run_living_artifact",
"enqueue_comment_activity_retry",
"complete_idle_local_task_run",
@@ -212,7 +209,6 @@ __all__ = [
"get_stale_prewarmed_queued_task_run_ids",
"get_stale_terminal_prewarmed_task_run_ids",
"get_stale_queued_task_run_ids",
- "get_task_automation",
"get_task_detail",
"get_task_id_for_run",
"get_task_run",
@@ -233,7 +229,6 @@ __all__ = [
"list_sandbox_custom_images",
"list_sandbox_environments",
"sandbox_custom_images_enabled",
- "list_task_automations",
"list_task_run_living_artifacts",
"list_task_repositories",
"list_task_runs",
@@ -255,7 +250,6 @@ __all__ = [
"resolve_slack_thread_context",
"resume_task_run_in_cloud",
"run_task",
- "run_task_automation_now",
"send_cancel",
"select_repository_for_message",
"set_task_run_output",
@@ -282,7 +276,6 @@ __all__ = [
"retrieve_task_comment",
"update_sandbox_environment",
"update_task",
- "update_task_automation",
"update_task_run",
"update_task_run_state",
"upsert_internal_sandbox_env",
@@ -1996,180 +1989,6 @@ def delete_sandbox_custom_image(image_id: str | UUID, team_id: int, user_id: int
return True
-# --- Task automations (presentation CRUD) ---
-# Visibility mirrors the task-run visibility filter traversed via the automation's ``task`` FK
-# (creator, legacy unowned tasks, and signals-pipeline tasks). Most read fields proxy off the
-# linked ``Task``; the schedule (Temporal) is kept in sync from inside the write functions.
-
-
-def _task_automation_to_dto(automation: TaskAutomation) -> contracts.TaskAutomationDTO:
- return contracts.TaskAutomationDTO(
- id=automation.id,
- name=automation.name,
- prompt=automation.prompt,
- repository=automation.repository,
- github_integration=automation.github_integration_id,
- cron_expression=automation.cron_expression,
- timezone=automation.timezone,
- template_id=automation.template_id,
- enabled=automation.enabled,
- last_run_at=automation.last_run_at,
- last_run_status=automation.last_run_status,
- last_task_id=str(automation.task_id),
- last_task_run_id=str(automation.last_task_run_id) if automation.last_task_run_id else None,
- last_error=automation.last_error,
- created_at=automation.created_at,
- updated_at=automation.updated_at,
- )
-
-
-def _visible_task_automations(team_id: int, user_id: int | None):
- return TaskAutomation.objects.filter(task__team_id=team_id, task__deleted=False).filter(
- task_run_visibility_q(user_id)
- )
-
-
-def list_task_automations(team_id: int, user_id: int | None) -> list[contracts.TaskAutomationDTO]:
- """Automations for the team visible to the user, ordered by task title then newest first."""
- automations = _visible_task_automations(team_id, user_id).order_by("task__title", "-created_at")
- return [_task_automation_to_dto(automation) for automation in automations]
-
-
-def get_task_automation(
- automation_id: str | UUID, team_id: int, user_id: int | None
-) -> contracts.TaskAutomationDTO | None:
- """A single automation visible to the user. Returns ``None`` if not found/visible."""
- automation = _visible_task_automations(team_id, user_id).filter(pk=automation_id).first()
- return _task_automation_to_dto(automation) if automation is not None else None
-
-
-def create_task_automation(
- team_id: int,
- user_id: int | None,
- *,
- name: str,
- prompt: str,
- repository: str,
- github_integration_id: int | None = None,
- cron_expression: str,
- timezone: str = "UTC",
- template_id: str | None = None,
- enabled: bool = True,
-) -> contracts.TaskAutomationDTO:
- """Create an automation (and its backing task) and sync its Temporal schedule.
-
- Falls back to the team's default GitHub integration when none is supplied, mirroring the
- original serializer behavior.
- """
- if github_integration_id is None:
- default_integration = Integration.objects.filter(team_id=team_id, kind="github").first()
- github_integration_id = default_integration.id if default_integration else None
-
- with transaction.atomic():
- task = Task.objects.create(
- team_id=team_id,
- created_by_id=user_id,
- title=name,
- description=prompt,
- origin_product=Task.OriginProduct.AUTOMATION,
- repository=repository,
- github_integration_id=github_integration_id,
- )
- automation = TaskAutomation.objects.create(
- task=task,
- cron_expression=cron_expression,
- timezone=timezone,
- template_id=template_id,
- enabled=enabled,
- )
-
- _sync_automation_schedule(automation)
- return _task_automation_to_dto(automation)
-
-
-def update_task_automation(
- automation_id: str | UUID, team_id: int, user_id: int | None, **fields
-) -> contracts.TaskAutomationDTO | None:
- """Partially update a visible automation (and its backing task) and re-sync its schedule.
-
- Returns ``None`` if the automation is not found/visible. The ``github_integration_id``
- key (when present) updates the backing task's GitHub integration.
- """
- automation = _visible_task_automations(team_id, user_id).filter(pk=automation_id).first()
- if automation is None:
- return None
-
- task_field_map = {
- "name": "title",
- "prompt": "description",
- "repository": "repository",
- "github_integration_id": "github_integration_id",
- }
- task_updates = {task_field_map[key]: fields.pop(key) for key in list(fields) if key in task_field_map}
-
- with transaction.atomic():
- for key, value in fields.items():
- setattr(automation, key, value)
- automation.save()
-
- if task_updates:
- task = automation.task
- fields_to_update = []
- for field, value in task_updates.items():
- if getattr(task, field) != value:
- setattr(task, field, value)
- fields_to_update.append(field)
- if fields_to_update:
- fields_to_update.append("updated_at")
- task.save(update_fields=fields_to_update)
-
- _sync_automation_schedule(automation)
- return _task_automation_to_dto(automation)
-
-
-def delete_task_automation(automation_id: str | UUID, team_id: int, user_id: int | None) -> bool:
- """Delete a visible automation and its Temporal schedule. Returns whether a row was deleted."""
- automation = _visible_task_automations(team_id, user_id).filter(pk=automation_id).first()
- if automation is None:
- return False
-
- from products.tasks.backend.automation_service import ( # noqa: PLC0415 — keep temporalio off the api import path
- delete_automation_schedule,
- )
-
- delete_automation_schedule(automation)
- automation.delete()
- return True
-
-
-def run_task_automation_now(
- automation_id: str | UUID, team_id: int, user_id: int | None
-) -> contracts.TaskAutomationDTO | None:
- """Trigger an automation run immediately and return the refreshed automation DTO.
-
- Returns ``None`` if the automation is not found/visible.
- """
- automation = _visible_task_automations(team_id, user_id).filter(pk=automation_id).first()
- if automation is None:
- return None
-
- from products.tasks.backend.automation_service import ( # noqa: PLC0415 — keep temporalio off the api import path
- run_task_automation,
- )
-
- run_task_automation(str(automation.id))
- automation.refresh_from_db()
- return _task_automation_to_dto(automation)
-
-
-def _sync_automation_schedule(automation: TaskAutomation) -> None:
- from products.tasks.backend.automation_service import ( # noqa: PLC0415 — keep temporalio off the api import path
- sync_automation_schedule,
- )
-
- sync_automation_schedule(automation)
-
-
# --- Task runs (presentation lifecycle) ---
# Every function takes ids/primitives and returns a TaskRunDetailDTO (or a small result),
# moving all ORM access and Temporal/Slack/S3 orchestration behind the facade. Visibility on
@@ -2596,9 +2415,6 @@ def update_task_run(
output/state merges take a row lock, terminal transitions signal Temporal + dispatch
push/Slack updates after commit, and a cloud→local transition cancels the workflow.
"""
- from products.tasks.backend.automation_service import ( # noqa: PLC0415 — keep temporalio off the api import path
- update_automation_run_result,
- )
from products.tasks.backend.logic.services.loop_runs import ( # noqa: PLC0415 (keep temporalio off the api import path)
handle_loop_run_terminal,
)
@@ -2676,7 +2492,6 @@ def update_task_run(
run.save(update_fields=list(update_fields))
run.publish_stream_state_event()
- update_automation_run_result(run)
# Only on the actual transition: a repeat PATCH with the same terminal status, or an
# output-only PATCH on an already-terminal run, must not re-run loop bookkeeping
# (consecutive_failures would double-count). The workflow's status-update activity
@@ -7664,9 +7479,9 @@ def request_canvas_fix(task_id: str | UUID, team_id: int, *, prompt: str, acting
``task_control_q``): the dispatched run executes with the task creator's
credentials, so nobody else may start or steer it. The task row is locked
for the duration so overlapping fix requests serialize instead of each
- creating a paid run. The fresh-run path mirrors ``run_task_automation``:
- create the run inside the transaction and dispatch its processing workflow
- on commit with ``skip_user_check``.
+ creating a paid run. The fresh-run path creates the run inside the
+ transaction and dispatches its processing workflow on commit with
+ ``skip_user_check``.
Returns ``signaled`` / ``new_run`` / ``already_queued`` / ``not_found`` /
``forbidden`` / ``quota_exhausted`` / ``organization_deactivated``.
"""
@@ -7755,8 +7570,8 @@ def request_canvas_change(
def _dispatch_server_run(*, team_id: int, user_id: int | None, task_id: str, run_id: str) -> None:
"""Dispatch a server-originated run's processing workflow, bypassing the per-user check.
- Nothing canvas-specific: the same shape as ``automation_service``'s dispatch, kept
- here because that module puts temporalio on its import path and this one must not.
+ Nothing canvas-specific: kept here because ``temporal.client`` puts temporalio on
+ its import path and this module must not.
"""
from products.tasks.backend.temporal.client import ( # noqa: PLC0415 — keep temporalio off the api import path
execute_task_processing_workflow,
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index 70ef548ed6f0..75eedb2326ac 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -634,36 +634,6 @@ class CodeInviteRedeemResult:
outcome: str
-@dataclass(frozen=True)
-class TaskAutomationDTO:
- """A scheduled task automation.
-
- Mirrors exactly the fields ``TaskAutomationSerializer`` emits. Most read fields are
- proxied off the underlying ``Task`` (``name``/``prompt``/``repository``/
- ``github_integration``) or derived from the linked last run (``last_run_at``/
- ``last_run_status``). ``github_integration`` is the integration's primary key (or
- ``None``). ``last_task_id`` is always present (the automation's task id as a string);
- ``last_task_run_id`` is the most recent run's id as a string, or ``None``.
- """
-
- id: UUID
- name: str
- prompt: str
- repository: str | None
- github_integration: int | None
- cron_expression: str
- timezone: str
- template_id: str | None
- enabled: bool
- last_run_at: datetime | None
- last_run_status: str | None
- last_task_id: str
- last_task_run_id: str | None
- last_error: str | None
- created_at: datetime
- updated_at: datetime
-
-
@dataclass(frozen=True)
class TaskUserBasicInfo:
"""Lightweight user info for display, mirroring core ``UserBasicSerializer`` output.
diff --git a/products/tasks/backend/migrations/0095_remove_task_automation.py b/products/tasks/backend/migrations/0095_remove_task_automation.py
new file mode 100644
index 000000000000..bddec3cccc74
--- /dev/null
+++ b/products/tasks/backend/migrations/0095_remove_task_automation.py
@@ -0,0 +1,137 @@
+# Generated by Django 5.2.17 on 2026-08-19 02:23
+
+from django.db import migrations, models
+
+DROP_TASK_AUTOMATION_FKS = """
+DO $$
+DECLARE
+ constraint_name text;
+BEGIN
+ FOR constraint_name IN
+ SELECT constraint_record.conname
+ FROM pg_constraint AS constraint_record
+ JOIN pg_class AS table_record ON table_record.oid = constraint_record.conrelid
+ WHERE table_record.relname = 'posthog_task_automation'
+ AND table_record.relnamespace = current_schema()::regnamespace
+ AND constraint_record.contype = 'f'
+ LOOP
+ EXECUTE format(
+ 'ALTER TABLE posthog_task_automation DROP CONSTRAINT IF EXISTS %I',
+ constraint_name
+ );
+ END LOOP;
+END
+$$;
+"""
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("tasks", "0094_task_last_activity_indexes"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="loop",
+ name="origin_product",
+ field=models.CharField(
+ choices=[
+ ("onboarding", "Onboarding"),
+ ("error_tracking", "Error Tracking"),
+ ("eval_clusters", "Eval Clusters"),
+ ("user_created", "User Created"),
+ ("slack", "Slack"),
+ ("support_queue", "Support Queue"),
+ ("session_summaries", "Session Summaries"),
+ ("posthog_ai", "PostHog AI"),
+ ("experiments", "Experiments"),
+ ("signal_report", "Signal Report"),
+ ("signals_scout", "Signals Scout"),
+ ("support_reply", "Support Reply"),
+ ("hogdesk", "HogDesk"),
+ ("review_hog", "ReviewHog"),
+ ("image_builder", "Image Builder"),
+ ("loop", "Loop"),
+ ("mcp_analytics", "MCP Analytics"),
+ ("signals_chat", "Signals Chat"),
+ ],
+ default="user_created",
+ help_text="Which product or flow created this loop.",
+ max_length=32,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="sandboxsession",
+ name="origin_product",
+ field=models.CharField(
+ blank=True,
+ choices=[
+ ("onboarding", "Onboarding"),
+ ("error_tracking", "Error Tracking"),
+ ("eval_clusters", "Eval Clusters"),
+ ("user_created", "User Created"),
+ ("slack", "Slack"),
+ ("support_queue", "Support Queue"),
+ ("session_summaries", "Session Summaries"),
+ ("posthog_ai", "PostHog AI"),
+ ("experiments", "Experiments"),
+ ("signal_report", "Signal Report"),
+ ("signals_scout", "Signals Scout"),
+ ("support_reply", "Support Reply"),
+ ("hogdesk", "HogDesk"),
+ ("review_hog", "ReviewHog"),
+ ("image_builder", "Image Builder"),
+ ("loop", "Loop"),
+ ("mcp_analytics", "MCP Analytics"),
+ ("signals_chat", "Signals Chat"),
+ ],
+ help_text="Task origin at provision time, denormalized for per-origin aggregation",
+ max_length=20,
+ null=True,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="task",
+ name="origin_product",
+ field=models.CharField(
+ choices=[
+ ("onboarding", "Onboarding"),
+ ("error_tracking", "Error Tracking"),
+ ("eval_clusters", "Eval Clusters"),
+ ("user_created", "User Created"),
+ ("slack", "Slack"),
+ ("support_queue", "Support Queue"),
+ ("session_summaries", "Session Summaries"),
+ ("posthog_ai", "PostHog AI"),
+ ("experiments", "Experiments"),
+ ("signal_report", "Signal Report"),
+ ("signals_scout", "Signals Scout"),
+ ("support_reply", "Support Reply"),
+ ("hogdesk", "HogDesk"),
+ ("review_hog", "ReviewHog"),
+ ("image_builder", "Image Builder"),
+ ("loop", "Loop"),
+ ("mcp_analytics", "MCP Analytics"),
+ ("signals_chat", "Signals Chat"),
+ ],
+ max_length=20,
+ ),
+ ),
+ # State-only removal; a later migration drops the table. The FKs go now: once the model
+ # is out of Django state nothing cascades into the orphaned table, so a leftover FK would
+ # block deleting any task that had an automation and the TRUNCATE in TransactionTestCase
+ # teardown on posthog_task / posthog_taskrun.
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.DeleteModel(
+ name="TaskAutomation",
+ ),
+ ],
+ database_operations=[
+ migrations.RunSQL(
+ sql=DROP_TASK_AUTOMATION_FKS,
+ reverse_sql=migrations.RunSQL.noop,
+ ),
+ ],
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index 97ec158ac7b2..8debbe3d6cd7 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0094_task_last_activity_indexes
+0095_remove_task_automation
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index b0d0cd764920..9e585d30e974 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -178,7 +178,6 @@ class Task(DeletedMetaFields, models.Model):
ERROR_TRACKING = "error_tracking", "Error Tracking"
EVAL_CLUSTERS = "eval_clusters", "Eval Clusters"
USER_CREATED = "user_created", "User Created"
- AUTOMATION = "automation", "Automation"
SLACK = "slack", "Slack"
SUPPORT_QUEUE = "support_queue", "Support Queue"
SESSION_SUMMARIES = "session_summaries", "Session Summaries"
@@ -1388,7 +1387,7 @@ def bump_task_activity_on_thread_message(sender, instance: "TaskThreadMessage",
@receiver(post_save, sender=Task)
def project_task_created_activity(sender, instance: Task, created: bool, **kwargs) -> None:
"""Seed the creator's activity row. A signal rather than a facade call because tasks are
- created from several paths (API, automations, the sandbox warm path) and every one of them
+ created from several paths (API, loops, the sandbox warm path) and every one of them
should show up in its creator's feed."""
if created and instance.created_by_id is not None:
TaskActivity.record(
@@ -1523,118 +1522,6 @@ class ChannelStar(TeamScopedRootMixin):
]
-class TaskAutomationManager(models.Manager):
- def get_queryset(self):
- return (
- super()
- .get_queryset()
- .select_related(
- "task",
- "task__team",
- "task__created_by",
- "task__github_integration",
- "task__github_user_integration",
- "last_task_run",
- "last_task_run__task",
- )
- )
-
-
-class TaskAutomationQuerySet(models.QuerySet):
- def with_task_context(self):
- return self.select_related(
- "task",
- "task__team",
- "task__created_by",
- "task__github_integration",
- "task__github_user_integration",
- "last_task_run",
- "last_task_run__task",
- )
-
-
-class TaskAutomation(models.Model):
- class RunStatus(models.TextChoices):
- SUCCESS = "success", "Success"
- FAILED = "failed", "Failed"
- RUNNING = "running", "Running"
-
- # nosemgrep: prefer-uuid7-django-pk -- TODO: migrate to uuid7 or clarify intent
- id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
- cron_expression = models.CharField(max_length=100)
- timezone = models.CharField(max_length=128, default="UTC")
- template_id = models.CharField(max_length=255, null=True, blank=True)
- enabled = models.BooleanField(default=True)
- task = models.OneToOneField(Task, on_delete=models.CASCADE, related_name="automation")
- last_task_run = models.ForeignKey("TaskRun", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
- last_error = models.TextField(null=True, blank=True)
- created_at = models.DateTimeField(default=django_timezone.now)
- updated_at = models.DateTimeField(auto_now=True)
-
- objects = TaskAutomationManager()
-
- class Meta:
- db_table = "posthog_task_automation"
- ordering = ["task__title", "-created_at"]
-
- def __str__(self):
- return self.name
-
- @property
- def schedule_id(self) -> str:
- return f"task-automation-{self.id}"
-
- @property
- def team(self) -> Team:
- return self.task.team
-
- @property
- def team_id(self) -> int:
- return self.task.team_id
-
- @property
- def created_by(self) -> User | None:
- return self.task.created_by
-
- @property
- def created_by_id(self) -> int | None:
- return self.task.created_by_id
-
- @property
- def name(self) -> str:
- return self.task.title
-
- @property
- def prompt(self) -> str:
- return self.task.description
-
- @property
- def repository(self) -> str | None:
- return self.task.repository
-
- @property
- def github_integration(self) -> Integration | None:
- return self.task.github_integration
-
- @property
- def github_integration_id(self) -> int | None:
- return self.task.github_integration_id
-
- @property
- def last_run_at(self) -> datetime | None:
- return self.last_task_run.created_at if self.last_task_run else None
-
- @property
- def last_run_status(self) -> str | None:
- if self.last_task_run is None:
- return None
- if self.last_task_run.status == TaskRun.Status.COMPLETED:
- return self.RunStatus.SUCCESS
- if self.last_task_run.status in [TaskRun.Status.FAILED, TaskRun.Status.CANCELLED]:
- return self.RunStatus.FAILED
- return self.RunStatus.RUNNING
-
-
class Loop(ModelActivityMixin, TeamScopedRootMixin):
"""A named, cloud-executed agent automation: instructions plus model config,
fired by schedule/GitHub/API triggers. Each firing spawns an internal Task
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index db433b2433fb..521c6887780c 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -5,12 +5,10 @@ import logging
import binascii
from datetime import datetime, timedelta
from typing import Any, cast
-from zoneinfo import available_timezones
from django.utils import timezone as django_timezone
import posthoganalytics
-from croniter import croniter
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field
from rest_framework import serializers
@@ -33,7 +31,6 @@ from products.tasks.backend.facade.contracts import (
SlackThreadReferenceDTO,
TaskActivityDTO,
TaskActivityPageDTO,
- TaskAutomationDTO,
TaskDetailDTO,
TaskMentionDTO,
TaskRunDetailDTO,
@@ -3214,94 +3211,6 @@ class TaskRunSessionLogsQuerySerializer(serializers.Serializer):
)
-class TaskAutomationSerializer(DataclassSerializer):
- """Detail/create/update/run response for a task automation."""
-
- class Meta:
- dataclass = TaskAutomationDTO
- fields = [
- "id",
- "name",
- "prompt",
- "repository",
- "github_integration",
- "cron_expression",
- "timezone",
- "template_id",
- "enabled",
- "last_run_at",
- "last_run_status",
- "last_task_id",
- "last_task_run_id",
- "last_error",
- "created_at",
- "updated_at",
- ]
-
-
-class TaskAutomationWriteSerializer(serializers.Serializer):
- """Request body for creating or updating a task automation."""
-
- name = serializers.CharField(max_length=255, help_text="Display name (stored as the backing task's title).")
- prompt = serializers.CharField(help_text="The automation prompt (stored as the backing task's description).")
- repository = serializers.CharField(
- max_length=255, help_text="Target repository in the format organization/repository."
- )
- github_integration = TeamScopedPrimaryKeyRelatedField(
- queryset=Integration.objects.filter(kind="github"),
- required=False,
- allow_null=True,
- help_text="GitHub integration to run as. Defaults to the team's GitHub integration when omitted.",
- )
- cron_expression = serializers.CharField(
- max_length=100, help_text="Standard 5-field cron expression (minute hour day month weekday)."
- )
- timezone = serializers.CharField(
- max_length=128, required=False, default="UTC", help_text="IANA timezone the schedule runs in."
- )
- template_id = serializers.CharField(
- max_length=255,
- required=False,
- allow_null=True,
- allow_blank=True,
- help_text="Optional template identifier this automation was created from.",
- )
- enabled = serializers.BooleanField(
- required=False, default=True, help_text="Whether the schedule is active; paused when false."
- )
-
- def validate_github_integration(self, value):
- if value and value.team_id != self.context["team"].id:
- raise serializers.ValidationError("Integration must belong to the same team")
- return value
-
- def validate_repository(self, value: str) -> str:
- normalized = value.strip().lower()
- parts = normalized.split("/")
- if len(parts) != 2 or not parts[0] or not parts[1]:
- raise serializers.ValidationError("Repository must be in the format organization/repository")
- return normalized
-
- def validate_cron_expression(self, value: str) -> str:
- normalized = value.strip()
- parts = normalized.split()
- if len(parts) != 5:
- raise serializers.ValidationError(
- "Only standard 5-field cron expressions are supported "
- "(minute hour day month weekday). Example: '0 9 * * 1-5'."
- )
- if not croniter.is_valid(normalized):
- raise serializers.ValidationError(
- "Invalid cron expression. Use standard 5-field cron syntax (e.g., '0 9 * * 1-5')."
- )
- return normalized
-
- def validate_timezone(self, value: str) -> str:
- if value not in available_timezones():
- raise serializers.ValidationError(f"'{value}' is not a valid IANA timezone.")
- return value
-
-
class SandboxEnvironmentSerializer(DataclassSerializer):
"""Detail/create/update response for a sandbox environment."""
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 9e43ca559d80..b3eaa8c88844 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -43,12 +43,7 @@ from posthog.api.utils import ServerTimingsGathered
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
from posthog.event_usage import groups
from posthog.models import User
-from posthog.permissions import (
- APIScopePermission,
- DenyMCPBuiltInAgentOAuth,
- get_authenticator_scoped_team_ids,
- get_authenticator_scopes,
-)
+from posthog.permissions import APIScopePermission, get_authenticator_scoped_team_ids, get_authenticator_scopes
from posthog.rate_limit import CodeInviteThrottle, TaskRunChartRenderThrottle
from posthog.renderers import ServerSentEventRenderer
from posthog.schema_migrations.upgrade import upgrade
@@ -110,8 +105,6 @@ from products.tasks.backend.presentation.serializers import (
SlackThreadContextResponseSerializer,
StreamReadTokenResponseSerializer,
TaskArtifactsResponseSerializer,
- TaskAutomationSerializer,
- TaskAutomationWriteSerializer,
TaskCommentDetailQuerySerializer,
TaskCommentDetailSerializer,
TaskCommentsQuerySerializer,
@@ -1056,122 +1049,6 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return Response(status=status.HTTP_204_NO_CONTENT)
-class DenyBuiltInAgentTaskAutomations(DenyMCPBuiltInAgentOAuth):
- """Automations schedule future runs that resolve a member's credentials, so a
- built-in agent's sandbox token must not create or trigger them."""
-
- message = "Built-in agents cannot manage task automations."
-
-
-@extend_schema(tags=["task-automations"])
-class TaskAutomationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
- """API for managing scheduled task automations."""
-
- authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
- permission_classes = [IsAuthenticated, APIScopePermission, DenyBuiltInAgentTaskAutomations]
- scope_object = "task"
- http_method_names = ["get", "post", "patch", "delete", "head", "options"]
-
- def _write_serializer(self, data, *, partial: bool = False) -> TaskAutomationWriteSerializer:
- serializer = TaskAutomationWriteSerializer(
- data=data, partial=partial, context={"team": self.team, "team_id": self.team.id}
- )
- serializer.is_valid(raise_exception=True)
- return serializer
-
- @staticmethod
- def _facade_kwargs(validated_data: dict) -> dict:
- """Translate the resolved ``github_integration`` instance to its id for the facade."""
- kwargs = dict(validated_data)
- if "github_integration" in kwargs:
- integration = kwargs.pop("github_integration")
- kwargs["github_integration_id"] = integration.id if integration is not None else None
- return kwargs
-
- @extend_schema(responses={200: TaskAutomationSerializer(many=True)})
- def list(self, request, **kwargs):
- automations = tasks_facade.list_task_automations(self.team_id, getattr(request.user, "id", None))
- page = self.paginate_queryset(automations)
- if page is not None:
- return self.get_paginated_response(TaskAutomationSerializer(page, many=True).data)
- return Response(TaskAutomationSerializer(automations, many=True).data)
-
- @extend_schema(responses={200: TaskAutomationSerializer})
- def retrieve(self, request, pk=None, **kwargs):
- automation = tasks_facade.get_task_automation(pk, self.team_id, getattr(request.user, "id", None))
- if automation is None:
- raise NotFound()
- return Response(TaskAutomationSerializer(automation).data)
-
- @extend_schema(
- request=TaskAutomationWriteSerializer,
- responses={
- 201: TaskAutomationSerializer,
- 403: OpenApiResponse(
- response=TaskRunErrorResponseSerializer,
- description="PostHog Desktop access is required",
- ),
- },
- )
- def create(self, request, **kwargs):
- # Automations schedule cloud runs, so creating one needs the same Desktop access as
- # running a task. No Inbox surface creates automations, so no exemption applies.
- if access_response := code_access_required_response(request.user):
- return access_response
- serializer = self._write_serializer(request.data)
- automation = tasks_facade.create_task_automation(
- self.team_id, getattr(request.user, "id", None), **self._facade_kwargs(serializer.validated_data)
- )
- return Response(TaskAutomationSerializer(automation).data, status=status.HTTP_201_CREATED)
-
- @extend_schema(
- request=TaskAutomationWriteSerializer,
- responses={
- 200: TaskAutomationSerializer,
- 403: OpenApiResponse(
- response=TaskRunErrorResponseSerializer,
- description="PostHog Desktop access is required",
- ),
- },
- )
- def partial_update(self, request, pk=None, **kwargs):
- serializer = self._write_serializer(request.data, partial=True)
- if serializer.validated_data.get("enabled") is True:
- if access_response := code_access_required_response(request.user):
- return access_response
- automation = tasks_facade.update_task_automation(
- pk, self.team_id, getattr(request.user, "id", None), **self._facade_kwargs(serializer.validated_data)
- )
- if automation is None:
- raise NotFound()
- return Response(TaskAutomationSerializer(automation).data)
-
- @extend_schema(responses={204: None})
- def destroy(self, request, pk=None, **kwargs):
- if not tasks_facade.delete_task_automation(pk, self.team_id, getattr(request.user, "id", None)):
- raise NotFound()
- return Response(status=status.HTTP_204_NO_CONTENT)
-
- @extend_schema(
- request=None,
- responses={
- 200: TaskAutomationSerializer,
- 403: OpenApiResponse(
- response=TaskRunErrorResponseSerializer,
- description="PostHog Desktop access is required",
- ),
- },
- )
- @action(detail=True, methods=["post"], url_path="run", required_scopes=["task:write"])
- def run(self, request, pk=None, **kwargs):
- if access_response := code_access_required_response(request.user):
- return access_response
- automation = tasks_facade.run_task_automation_now(pk, self.team_id, getattr(request.user, "id", None))
- if automation is None:
- raise NotFound()
- return Response(TaskAutomationSerializer(automation).data)
-
-
@extend_schema(tags=["task-runs", "tasks"])
def is_sandbox_agent_request(request, task_id: str) -> bool:
"""True only for the task-bound sandbox OAuth identity, never a human session or key."""
diff --git a/products/tasks/backend/routes.py b/products/tasks/backend/routes.py
index e031ac8188a2..3a50ec103b1b 100644
--- a/products/tasks/backend/routes.py
+++ b/products/tasks/backend/routes.py
@@ -33,7 +33,6 @@ def register_routes(routers: RouterRegistry) -> None:
)
routers.projects.register(r"task_mentions", channels.TaskMentionViewSet, "project_task_mentions", ["team_id"])
routers.projects.register(r"task_activity", channels.TaskActivityViewSet, "project_task_activity", ["team_id"])
- routers.projects.register(r"task_automations", tasks.TaskAutomationViewSet, "project_task_automations", ["team_id"])
routers.projects.register(r"loops", loops.LoopViewSet, "project_loops", ["team_id"])
routers.projects.register(
r"sandbox_environments", tasks.SandboxEnvironmentViewSet, "project_sandbox_environments", ["team_id"]
diff --git a/products/tasks/backend/temporal/__init__.py b/products/tasks/backend/temporal/__init__.py
index 4c0f6a10f15e..48752e79a678 100644
--- a/products/tasks/backend/temporal/__init__.py
+++ b/products/tasks/backend/temporal/__init__.py
@@ -1,4 +1,3 @@
-from .automation import RunTaskAutomationWorkflow, run_task_automation_activity
from .bake_dev_stack_image.activities import bake_and_publish_dev_stack_image
from .bake_dev_stack_image.workflow import BakeDevStackImageWorkflow
from .build_image.activities import build_and_publish_image, mark_image_build_failed, scan_image_spec
@@ -63,7 +62,6 @@ WORKFLOWS = [
SlackAgentDesignRelayWorkflow,
CreateSnapshotForRepositoryWorkflow,
PostHogCodeAgentRelayWorkflow,
- RunTaskAutomationWorkflow,
RunLoopWorkflow,
BuildSandboxImageWorkflow,
BakeDevStackImageWorkflow,
@@ -109,7 +107,6 @@ ACTIVITIES = [
start_slack_agent_design_stream,
append_slack_agent_design_steps,
stop_slack_agent_design_stream,
- run_task_automation_activity,
run_loop_trigger_activity,
# create_snapshot activities
get_snapshot_context,
diff --git a/products/tasks/backend/temporal/automation/__init__.py b/products/tasks/backend/temporal/automation/__init__.py
deleted file mode 100644
index abd7ad668b94..000000000000
--- a/products/tasks/backend/temporal/automation/__init__.py
+++ /dev/null
@@ -1,4 +0,0 @@
-from .activities import run_task_automation_activity
-from .workflow import RunTaskAutomationWorkflow
-
-__all__ = ["run_task_automation_activity", "RunTaskAutomationWorkflow"]
diff --git a/products/tasks/backend/temporal/automation/activities.py b/products/tasks/backend/temporal/automation/activities.py
deleted file mode 100644
index 8fb2285f0e26..000000000000
--- a/products/tasks/backend/temporal/automation/activities.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from django.core.exceptions import PermissionDenied
-
-from temporalio import activity
-from temporalio.exceptions import ApplicationError
-
-from posthog.temporal.common.utils import asyncify
-
-
-@asyncify
-def run_task_automation_activity(automation_id: str) -> None:
- from ...automation_service import run_task_automation
-
- try:
- run_task_automation(automation_id, trigger_workflow_id=activity.info().workflow_id)
- except PermissionDenied as e:
- raise ApplicationError(str(e), type="AutomationAccessRevoked", non_retryable=True) from e
diff --git a/products/tasks/backend/temporal/automation/workflow.py b/products/tasks/backend/temporal/automation/workflow.py
deleted file mode 100644
index 4a84ac1cef4f..000000000000
--- a/products/tasks/backend/temporal/automation/workflow.py
+++ /dev/null
@@ -1,24 +0,0 @@
-from datetime import timedelta
-
-import temporalio
-from temporalio.common import RetryPolicy
-
-from posthog.temporal.common.base import PostHogWorkflow
-
-from .activities import run_task_automation_activity
-
-
[email protected](name="run-task-automation")
-class RunTaskAutomationWorkflow(PostHogWorkflow):
- @staticmethod
- def parse_inputs(inputs: list[str]) -> str:
- return inputs[0]
-
- @temporalio.workflow.run
- async def run(self, automation_id: str) -> None:
- await temporalio.workflow.execute_activity(
- run_task_automation_activity,
- automation_id,
- start_to_close_timeout=timedelta(minutes=2),
- retry_policy=RetryPolicy(maximum_attempts=3),
- )
diff --git a/products/tasks/backend/temporal/process_task/README.md b/products/tasks/backend/temporal/process_task/README.md
index 20f93dcd575c..daa26f8b326b 100644
--- a/products/tasks/backend/temporal/process_task/README.md
+++ b/products/tasks/backend/temporal/process_task/README.md
@@ -52,7 +52,7 @@ User ─────────────────────────
### PostHog API
-`backend/presentation/views/api.py` (thin viewsets) over `backend/facade/api.py` (behavior) — every user-triggered cloud launch path, including prewarming and task automations, checks server-side PostHog Desktop access before provisioning or activating a run. Composer prewarming carries the complete ordered repository selection, so single- and multi-repository submissions can reuse only a matching sandbox. Runtime, model, branch, and sandbox configuration must match; reasoning effort may change and is applied before the warmed agent's first turn. Scheduled automations repeat the entitlement check at execution time so revoked access cannot launch later. `TaskViewSet.run` creates a `TaskRun` (status=QUEUED) and starts the Temporal workflow. `TaskRunViewSet.partial_update` handles status transitions and signals the Temporal workflow on terminal statuses via `signal_workflow_completion`. `TaskRunViewSet.cancel` (`POST .../runs/{id}/cancel/`) is the user-facing kill switch: `cancel_task_run` interrupts the in-flight agent turn, signals `complete_task("cancelled")` so the workflow snapshots the session and tears down the sandbox, and falls back to finalizing the run directly when no workflow is running.
+`backend/presentation/views/api.py` (thin viewsets) over `backend/facade/api.py` (behavior) — every user-triggered cloud launch path, including prewarming, checks server-side PostHog Desktop access before provisioning or activating a run. Composer prewarming carries the complete ordered repository selection, so single- and multi-repository submissions can reuse only a matching sandbox. Runtime, model, branch, and sandbox configuration must match; reasoning effort may change and is applied before the warmed agent's first turn. `TaskViewSet.run` creates a `TaskRun` (status=QUEUED) and starts the Temporal workflow. `TaskRunViewSet.partial_update` handles status transitions and signals the Temporal workflow on terminal statuses via `signal_workflow_completion`. `TaskRunViewSet.cancel` (`POST .../runs/{id}/cancel/`) is the user-facing kill switch: `cancel_task_run` interrupts the in-flight agent turn, signals `complete_task("cancelled")` so the workflow snapshots the session and tears down the sandbox, and falls back to finalizing the run directly when no workflow is running.
### Temporal workflow
diff --git a/products/tasks/backend/temporal/process_task/tests/test_max_run_duration.py b/products/tasks/backend/temporal/process_task/tests/test_max_run_duration.py
index c83a1a1c3bbe..cfc3ecba5524 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_max_run_duration.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_max_run_duration.py
@@ -12,7 +12,7 @@ DEFAULT_CAP_SECONDS = 3 * 60 * 60
def _context(
- state: dict | None, *, origin_product: str | None = Task.OriginProduct.AUTOMATION.value
+ state: dict | None, *, origin_product: str | None = Task.OriginProduct.LOOP.value
) -> TaskProcessingContext:
return TaskProcessingContext(
task_id="task-id",
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 29d579f3cbc7..8bf92880170f 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -73,7 +73,6 @@ from products.tasks.backend.models import (
SandboxSession,
Task,
TaskArtifact,
- TaskAutomation,
TaskClientProvenance,
TaskPin,
TaskRun,
@@ -230,29 +229,6 @@ class BaseTaskAPITest(TestCase):
self.organization.members.add(user)
return user
- def create_automation(
- self,
- name="Daily PRs",
- prompt="Check my GitHub PRs",
- repository="posthog/posthog",
- team=None,
- user=None,
- ):
- task = Task.objects.create(
- team=team or self.team,
- created_by=user or self.user,
- title=name,
- description=prompt,
- origin_product=Task.OriginProduct.AUTOMATION,
- repository=repository,
- )
- return TaskAutomation.objects.create(
- task=task,
- cron_expression="0 9 * * *",
- timezone="Europe/London",
- enabled=True,
- )
-
class TestBuiltInAgentTaskAccess(BaseTaskAPITest):
def _built_in_agent_client(self) -> APIClient:
@@ -290,30 +266,6 @@ class TestBuiltInAgentTaskAccess(BaseTaskAPITest):
assert response.status_code == status.HTTP_201_CREATED
assert Task.objects.filter(title="Child task").exists()
- def test_cannot_create_or_run_task_automations(self) -> None:
- automation = self.create_automation()
- client = self._built_in_agent_client()
-
- assert (
- client.post(
- "/api/projects/@current/task_automations/",
- {
- "name": "Scheduled child",
- "prompt": "Escape agent grants later",
- "repository": "posthog/posthog",
- "cron_expression": "0 9 * * *",
- "timezone": "UTC",
- },
- format="json",
- ).status_code
- == status.HTTP_403_FORBIDDEN
- )
- assert (
- client.post(f"/api/projects/@current/task_automations/{automation.id}/run/").status_code
- == status.HTTP_403_FORBIDDEN
- )
- assert not TaskAutomation.objects.filter(task__title="Scheduled child").exists()
-
class TestTaskCreatorScoping(BaseTaskAPITest):
def _create_legacy_task(self, title: str = "Legacy") -> Task:
@@ -660,48 +612,6 @@ class TestTaskCreatorScoping(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["id"], str(run.id))
- def test_retrieve_signal_report_automation_owned_by_another_user_succeeds(self):
- # TaskAutomationViewSet filters with task_run_visibility_q (task FK traversal).
- other_user = self.create_organization_user("signal-owner")
- task = Task.objects.create(
- team=self.team,
- created_by=other_user,
- title="Signal Report Task",
- description="Generated by signals",
- origin_product=Task.OriginProduct.SIGNAL_REPORT,
- internal=True,
- )
- automation = TaskAutomation.objects.create(
- task=task,
- cron_expression="0 9 * * *",
- timezone="Europe/London",
- enabled=True,
- )
-
- response = self.client.get(f"/api/projects/@current/task_automations/{automation.id}/")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json()["id"], str(automation.id))
-
- def test_retrieve_other_user_internal_non_signal_automation_returns_404(self):
- other_user = self.create_organization_user("victim")
- task = Task.objects.create(
- team=self.team,
- created_by=other_user,
- title="Their internal",
- description="",
- origin_product=Task.OriginProduct.USER_CREATED,
- internal=True,
- )
- automation = TaskAutomation.objects.create(
- task=task,
- cron_expression="0 9 * * *",
- timezone="Europe/London",
- enabled=True,
- )
-
- response = self.client.get(f"/api/projects/@current/task_automations/{automation.id}/")
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
-
def test_repositories_excludes_other_user_repos(self):
other_user = self.create_organization_user("victim")
mine = self.create_task("Mine", created_by=self.user)
@@ -826,26 +736,6 @@ class TestTaskCreatorScoping(BaseTaskAPITest):
)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
- def test_run_automation_for_other_user_task_returns_404(self):
- other_user = self.create_organization_user("victim")
- task = Task.objects.create(
- team=self.team,
- created_by=other_user,
- title="Their automation task",
- description="prompt",
- origin_product=Task.OriginProduct.AUTOMATION,
- repository="victim/repo",
- )
- automation = TaskAutomation.objects.create(
- task=task,
- cron_expression="0 9 * * *",
- timezone="Europe/London",
- enabled=True,
- )
-
- response = self.client.post(f"/api/projects/@current/task_automations/{automation.id}/run/")
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
-
@override_settings(CLOUD_DEPLOYMENT="US")
class TestTaskVisibilityProductionDebugGuard(BaseTaskAPITest):
@@ -4828,268 +4718,6 @@ class TestTaskSummariesAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
-class TestTaskAutomationAPI(BaseTaskAPITest):
- @patch("products.tasks.backend.automation_service.sync_automation_schedule")
- def test_create_automation(self, mock_sync_schedule):
- response = self.client.post(
- "/api/projects/@current/task_automations/",
- {
- "name": "Daily PRs",
- "prompt": "Check my GitHub PRs",
- "repository": "posthog/posthog",
- "cron_expression": "0 9 * * *",
- "timezone": "Europe/London",
- },
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- payload = response.json()
- self.assertEqual(payload["name"], "Daily PRs")
- self.assertEqual(payload["repository"], "posthog/posthog")
- self.assertEqual(payload["cron_expression"], "0 9 * * *")
- self.assertEqual(payload["timezone"], "Europe/London")
- self.assertTrue(payload["enabled"])
-
- automation = TaskAutomation.objects.get(id=payload["id"])
- self.assertEqual(automation.task.title, "Daily PRs")
- self.assertEqual(automation.task.description, "Check my GitHub PRs")
- self.assertEqual(automation.task.repository, "posthog/posthog")
- self.assertEqual(automation.cron_expression, "0 9 * * *")
- mock_sync_schedule.assert_called_once_with(automation)
-
- @patch("products.tasks.backend.automation_service.sync_automation_schedule")
- def test_create_automation_requires_code_access(self, mock_sync_schedule):
- self.set_tasks_feature_flag(False)
-
- response = self.client.post(
- "/api/projects/@current/task_automations/",
- {
- "name": "Daily PRs",
- "prompt": "Check my GitHub PRs",
- "repository": "posthog/posthog",
- "cron_expression": "0 9 * * *",
- "timezone": "Europe/London",
- },
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
- self.assertEqual(response.json()["code"], "code_access_required")
- self.assertFalse(TaskAutomation.objects.exists())
- mock_sync_schedule.assert_not_called()
-
- def test_list_automations(self):
- automation = self.create_automation()
-
- response = self.client.get("/api/projects/@current/task_automations/")
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- payload = response.json()
- self.assertEqual(len(payload["results"]), 1)
- self.assertEqual(payload["results"][0]["id"], str(automation.id))
- self.assertEqual(payload["results"][0]["cron_expression"], "0 9 * * *")
-
- def test_soft_deleted_task_hides_automation(self):
- automation = self.create_automation()
- automation.task.soft_delete()
-
- response = self.client.get("/api/projects/@current/task_automations/")
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json()["results"], [])
- self.assertEqual(
- self.client.get(f"/api/projects/@current/task_automations/{automation.id}/").status_code,
- status.HTTP_404_NOT_FOUND,
- )
-
- def test_create_automation_rejects_invalid_timezone(self):
- response = self.client.post(
- "/api/projects/@current/task_automations/",
- {
- "name": "Daily PRs",
- "prompt": "Check my GitHub PRs",
- "repository": "posthog/posthog",
- "cron_expression": "0 9 * * *",
- "timezone": "UTC+99",
- },
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(
- response.json(),
- {
- "type": "validation_error",
- "code": "invalid_input",
- "detail": "'UTC+99' is not a valid IANA timezone.",
- "attr": "timezone",
- },
- )
-
- def test_create_automation_rejects_invalid_cron_expression(self):
- response = self.client.post(
- "/api/projects/@current/task_automations/",
- {
- "name": "Daily PRs",
- "prompt": "Check my GitHub PRs",
- "repository": "posthog/posthog",
- "cron_expression": "not a cron",
- "timezone": "Europe/London",
- },
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(
- response.json(),
- {
- "type": "validation_error",
- "code": "invalid_input",
- "detail": "Only standard 5-field cron expressions are supported "
- "(minute hour day month weekday). Example: '0 9 * * 1-5'.",
- "attr": "cron_expression",
- },
- )
-
- @patch("products.tasks.backend.facade.api._sync_automation_schedule")
- def test_create_automation_rolls_back_task_when_automation_create_fails(self, mock_sync_schedule):
- with patch(
- "products.tasks.backend.facade.api.TaskAutomation.objects.create",
- side_effect=RuntimeError("automation create failed"),
- ):
- with self.assertRaises(RuntimeError):
- tasks_facade.create_task_automation(
- self.team.id,
- self.user.id,
- name="Daily PRs",
- prompt="Check my GitHub PRs",
- repository="posthog/posthog",
- cron_expression="0 9 * * *",
- timezone="Europe/London",
- )
-
- self.assertFalse(
- Task.objects.filter(
- team=self.team,
- title="Daily PRs",
- origin_product=Task.OriginProduct.AUTOMATION,
- ).exists()
- )
-
- @patch("products.tasks.backend.automation_service.sync_automation_schedule")
- def test_update_automation(self, mock_sync_schedule):
- automation = self.create_automation()
-
- response = self.client.patch(
- f"/api/projects/@current/task_automations/{automation.id}/",
- {
- "name": "Updated PR check",
- "cron_expression": "30 14 * * *",
- "enabled": False,
- },
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- payload = response.json()
- self.assertEqual(payload["name"], "Updated PR check")
- self.assertEqual(payload["cron_expression"], "30 14 * * *")
- self.assertFalse(payload["enabled"])
-
- automation.refresh_from_db()
- automation.task.refresh_from_db()
- self.assertEqual(automation.task.title, "Updated PR check")
- self.assertEqual(automation.cron_expression, "30 14 * * *")
- self.assertFalse(automation.enabled)
- mock_sync_schedule.assert_called_once_with(automation)
-
- @patch("products.tasks.backend.automation_service.sync_automation_schedule")
- def test_update_automation_without_enabling_needs_no_code_access(self, _mock_sync_schedule):
- # The gate only guards turning an automation on; editing or disabling one must stay
- # possible for users without Desktop access, or they couldn't stop their own schedules.
- automation = self.create_automation()
- self.set_tasks_feature_flag(False)
-
- response = self.client.patch(
- f"/api/projects/@current/task_automations/{automation.id}/",
- {"cron_expression": "30 14 * * *"},
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- automation.refresh_from_db()
- self.assertEqual(automation.cron_expression, "30 14 * * *")
-
- @patch("products.tasks.backend.automation_service.sync_automation_schedule")
- def test_enable_automation_requires_code_access(self, mock_sync_schedule):
- automation = self.create_automation()
- automation.enabled = False
- automation.save(update_fields=["enabled", "updated_at"])
- self.set_tasks_feature_flag(False)
-
- response = self.client.patch(
- f"/api/projects/@current/task_automations/{automation.id}/",
- {"enabled": True},
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
- self.assertEqual(response.json()["code"], "code_access_required")
- automation.refresh_from_db()
- self.assertFalse(automation.enabled)
- mock_sync_schedule.assert_not_called()
-
- @patch("products.tasks.backend.facade.api._sync_automation_schedule")
- def test_update_automation_rolls_back_automation_when_task_update_fails(self, mock_sync_schedule):
- automation = self.create_automation()
-
- with patch.object(Task, "save", side_effect=RuntimeError("task update failed")):
- with self.assertRaises(RuntimeError):
- tasks_facade.update_task_automation(
- automation.id,
- self.team.id,
- self.user.id,
- name="Updated PR check",
- cron_expression="30 14 * * *",
- )
-
- automation.refresh_from_db()
- automation.task.refresh_from_db()
- self.assertEqual(automation.cron_expression, "0 9 * * *")
- self.assertEqual(automation.task.title, "Daily PRs")
-
- @patch("products.tasks.backend.automation_service.delete_automation_schedule")
- def test_delete_automation(self, mock_delete_schedule):
- automation = self.create_automation()
-
- response = self.client.delete(f"/api/projects/@current/task_automations/{automation.id}/")
-
- self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
- mock_delete_schedule.assert_called_once()
- self.assertFalse(TaskAutomation.objects.filter(id=automation.id).exists())
-
- @patch("products.tasks.backend.automation_service.run_task_automation")
- def test_run(self, mock_run_task_automation):
- automation = self.create_automation()
-
- response = self.client.post(f"/api/projects/@current/task_automations/{automation.id}/run/")
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- mock_run_task_automation.assert_called_once_with(str(automation.id))
-
- @patch("products.tasks.backend.automation_service.run_task_automation")
- def test_run_requires_code_access(self, mock_run_task_automation):
- self.set_tasks_feature_flag(False)
- automation = self.create_automation()
-
- response = self.client.post(f"/api/projects/@current/task_automations/{automation.id}/run/")
-
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
- self.assertEqual(response.json()["code"], "code_access_required")
- mock_run_task_automation.assert_not_called()
-
-
_PR_URL = "https://github.com/posthog/posthog-js/pull/1"
_OTHER_PR_URL = "https://github.com/posthog/posthog-js/pull/2"
@@ -9150,16 +8778,12 @@ class TestTasksAPIPermissions(BaseTaskAPITest):
def test_authentication_required(self):
task = self.create_task()
- automation = self.create_automation(name="Daily PRs", prompt="Check my PRs")
self.client.force_authenticate(None)
endpoints = [
("/api/projects/@current/tasks/", "GET"),
(f"/api/projects/@current/tasks/{task.id}/", "GET"),
- ("/api/projects/@current/task_automations/", "GET"),
- (f"/api/projects/@current/task_automations/{automation.id}/", "GET"),
- (f"/api/projects/@current/task_automations/{automation.id}/run/", "POST"),
]
for url, method in endpoints:
@@ -9189,32 +8813,10 @@ class TestTasksAPIPermissions(BaseTaskAPITest):
response = self.client.delete(f"/api/projects/@current/tasks/{other_task.id}/")
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
- def test_cross_team_automation_access_forbidden(self):
- other_automation = self.create_automation(
- name="Other Team Automation",
- prompt="Description",
- team=self.other_team,
- user=self.other_user,
- )
-
- response = self.client.get(f"/api/projects/@current/task_automations/{other_automation.id}/")
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
-
- response = self.client.patch(
- f"/api/projects/@current/task_automations/{other_automation.id}/",
- {"name": "Hacked Automation"},
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
-
- response = self.client.delete(f"/api/projects/@current/task_automations/{other_automation.id}/")
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
-
def test_list_endpoints_only_return_team_resources(self):
# Create resources in both teams
my_task = self.create_task("My Task")
- my_automation = self.create_automation(name="My automation", prompt="Mine")
other_task = Task.objects.create(
team=self.other_team,
@@ -9222,12 +8824,6 @@ class TestTasksAPIPermissions(BaseTaskAPITest):
description="Description",
origin_product=Task.OriginProduct.USER_CREATED,
)
- other_automation = self.create_automation(
- name="Other automation",
- prompt="Other",
- team=self.other_team,
- user=self.other_user,
- )
# List tasks should only return my team's tasks
response = self.client.get("/api/projects/@current/tasks/")
@@ -9236,12 +8832,6 @@ class TestTasksAPIPermissions(BaseTaskAPITest):
self.assertIn(str(my_task.id), task_ids)
self.assertNotIn(str(other_task.id), task_ids)
- response = self.client.get("/api/projects/@current/task_automations/")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- automation_ids = [a["id"] for a in response.json()["results"]]
- self.assertIn(str(my_automation.id), automation_ids)
- self.assertNotIn(str(other_automation.id), automation_ids)
-
@parameterized.expand(
[
("task:read", "GET", "/api/projects/@current/tasks/", True),
@@ -9269,13 +8859,10 @@ class TestTasksAPIPermissions(BaseTaskAPITest):
f"/api/projects/@current/tasks/{{task_id}}/runs/{{run_id}}/living_artifacts/{{artifact_id}}/edit/",
False,
),
- ("task:read", "GET", "/api/projects/@current/task_automations/", True),
- ("task:read", "GET", "/api/projects/@current/task_automations/{automation_id}/", True),
("task:read", "POST", "/api/projects/@current/tasks/", False),
("task:read", "PATCH", f"/api/projects/@current/tasks/{{task_id}}/", False),
("task:read", "DELETE", f"/api/projects/@current/tasks/{{task_id}}/", False),
("task:read", "POST", f"/api/projects/@current/tasks/{{task_id}}/run/", False),
- ("task:read", "POST", "/api/projects/@current/task_automations/", False),
("task:write", "GET", "/api/projects/@current/tasks/", True),
("task:write", "POST", "/api/projects/@current/tasks/", True),
("task:write", "PATCH", f"/api/projects/@current/tasks/{{task_id}}/", True),
@@ -9309,12 +8896,6 @@ class TestTasksAPIPermissions(BaseTaskAPITest):
f"/api/projects/@current/tasks/{{task_id}}/runs/{{run_id}}/living_artifacts/{{artifact_id}}/edit/",
True,
),
- ("task:write", "GET", "/api/projects/@current/task_automations/", True),
- ("task:write", "GET", "/api/projects/@current/task_automations/{automation_id}/", True),
- ("task:write", "POST", "/api/projects/@current/task_automations/", True),
- ("task:write", "PATCH", "/api/projects/@current/task_automations/{automation_id}/", True),
- ("task:write", "DELETE", "/api/projects/@current/task_automations/{automation_id}/", True),
- ("task:write", "POST", "/api/projects/@current/task_automations/{automation_id}/run/", True),
("other_scope:read", "GET", "/api/projects/@current/tasks/", False),
("other_scope:write", "POST", "/api/projects/@current/tasks/", False),
("*", "GET", "/api/projects/@current/tasks/", True),
@@ -9337,15 +8918,10 @@ class TestTasksAPIPermissions(BaseTaskAPITest):
f"/api/projects/@current/tasks/{{task_id}}/runs/{{run_id}}/living_artifacts/{{artifact_id}}/edit/",
True,
),
- ("*", "GET", "/api/projects/@current/task_automations/", True),
- ("*", "GET", "/api/projects/@current/task_automations/{automation_id}/", True),
- ("*", "POST", "/api/projects/@current/task_automations/", True),
- ("*", "POST", "/api/projects/@current/task_automations/{automation_id}/run/", True),
]
)
def test_scoped_api_key_permissions(self, scope, method, url_template, should_have_access):
task = self.create_task()
- automation = self.create_automation(name="Scoped automation", prompt="Check my PRs")
run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)
api_key_value = generate_random_token_personal()
@@ -9360,7 +8936,6 @@ class TestTasksAPIPermissions(BaseTaskAPITest):
url = url_template.format(
task_id=task.id,
run_id=run.id,
- automation_id=automation.id,
artifact_id=uuid.uuid4(),
)
@@ -9373,16 +8948,6 @@ class TestTasksAPIPermissions(BaseTaskAPITest):
"description": "Description",
"origin_product": Task.OriginProduct.USER_CREATED,
}
- elif method == "POST" and url == "/api/projects/@current/task_automations/":
- data = {
- "name": "New Automation",
- "prompt": "Check my PRs",
- "repository": "posthog/posthog",
- "cron_expression": "0 9 * * *",
- "timezone": "Europe/London",
- }
- elif method == "PATCH" and "/task_automations/" in url:
- data = {"name": "Updated Automation"}
elif method == "PATCH" and "/tasks/" in url:
data = {"title": "Updated Task"}
elif method == "POST" and "/living_artifacts/" in url and url.endswith("/edit/"):
diff --git a/products/tasks/backend/tests/test_automation_service.py b/products/tasks/backend/tests/test_automation_service.py
deleted file mode 100644
index a0978474bbdc..000000000000
--- a/products/tasks/backend/tests/test_automation_service.py
+++ /dev/null
@@ -1,161 +0,0 @@
-from unittest.mock import patch
-
-from django.core.exceptions import PermissionDenied
-from django.test import TestCase
-
-from posthog.models import Organization, Team, User
-
-from products.tasks.backend.automation_service import run_task_automation, update_automation_run_result
-from products.tasks.backend.models import Task, TaskAutomation, TaskRun
-
-
-class TestAutomationService(TestCase):
- def setUp(self):
- self.organization = Organization.objects.create(name="Test Org")
- self.team = Team.objects.create(organization=self.organization, name="Test Team")
- self.user = User.objects.create_user(email="[email protected]", first_name="Test", password="password")
- access_patcher = patch("products.tasks.backend.automation_service.has_tasks_access", return_value=True)
- access_patcher.start()
- self.addCleanup(access_patcher.stop)
-
- def create_automation(self) -> TaskAutomation:
- task = Task.objects.create(
- team=self.team,
- created_by=self.user,
- title="Daily PRs",
- description="Check my GitHub PRs",
- origin_product=Task.OriginProduct.AUTOMATION,
- repository="posthog/posthog",
- )
- return TaskAutomation.objects.create(
- task=task,
- cron_expression="0 9 * * *",
- timezone="Europe/London",
- enabled=True,
- )
-
- @patch("products.tasks.backend.automation_service.execute_task_processing_workflow_for_automation")
- def test_run_task_automation_is_idempotent_per_trigger_workflow(self, mock_execute_workflow):
- automation = self.create_automation()
-
- with self.captureOnCommitCallbacks(execute=True):
- first_task, first_run = run_task_automation(
- str(automation.id), trigger_workflow_id="automation-workflow-123"
- )
- with self.captureOnCommitCallbacks(execute=True):
- second_task, second_run = run_task_automation(
- str(automation.id), trigger_workflow_id="automation-workflow-123"
- )
-
- self.assertEqual(first_task.id, second_task.id)
- self.assertEqual(first_run.id, second_run.id)
- self.assertEqual(Task.objects.filter(origin_product=Task.OriginProduct.AUTOMATION).count(), 1)
- self.assertEqual(TaskRun.objects.filter(task__origin_product=Task.OriginProduct.AUTOMATION).count(), 1)
- self.assertEqual(first_run.state["automation_id"], str(automation.id))
- self.assertEqual(first_run.state["automation_trigger_workflow_id"], "automation-workflow-123")
- self.assertEqual(mock_execute_workflow.call_count, 2)
-
- @patch("products.tasks.backend.automation_service.execute_task_processing_workflow_for_automation")
- def test_run_task_automation_does_not_reuse_run_from_another_team(self, mock_execute_workflow):
- automation = self.create_automation()
- other_team = Team.objects.create(organization=self.organization, name="Other Team")
- other_task = Task.objects.create(
- team=other_team,
- created_by=self.user,
- title="Other automation",
- description="Should not be reused",
- origin_product=Task.OriginProduct.AUTOMATION,
- repository="posthog/posthog",
- )
- other_run = other_task.create_run(
- mode="background",
- extra_state={
- "automation_id": str(automation.id),
- "automation_trigger_workflow_id": "automation-workflow-123",
- },
- )
-
- with self.captureOnCommitCallbacks(execute=True):
- task, task_run = run_task_automation(str(automation.id), trigger_workflow_id="automation-workflow-123")
-
- self.assertNotEqual(task_run.id, other_run.id)
- self.assertEqual(task.team_id, self.team.id)
- self.assertEqual(task_run.task_id, task.id)
- self.assertEqual(mock_execute_workflow.call_count, 1)
-
- @patch("products.tasks.backend.automation_service.execute_task_processing_workflow_for_automation")
- def test_run_task_automation_reuses_task_and_creates_new_runs(self, mock_execute_workflow):
- automation = self.create_automation()
-
- with self.captureOnCommitCallbacks(execute=True):
- first_task, first_run = run_task_automation(str(automation.id))
- with self.captureOnCommitCallbacks(execute=True):
- second_task, second_run = run_task_automation(str(automation.id))
-
- automation.refresh_from_db()
- self.assertEqual(first_task.id, second_task.id)
- self.assertEqual(automation.task_id, first_task.id)
- self.assertEqual(automation.last_run_at, second_run.created_at)
- self.assertEqual(automation.last_run_status, TaskAutomation.RunStatus.RUNNING)
- self.assertNotEqual(first_run.id, second_run.id)
- self.assertEqual(Task.objects.filter(origin_product=Task.OriginProduct.AUTOMATION).count(), 1)
- self.assertEqual(TaskRun.objects.filter(task=first_task).count(), 2)
- self.assertEqual(mock_execute_workflow.call_count, 2)
-
- @patch("products.tasks.backend.automation_service.has_tasks_access", return_value=False)
- @patch("products.tasks.backend.automation_service.execute_task_processing_workflow_for_automation")
- def test_run_task_automation_requires_code_access(self, mock_execute_workflow, _mock_access):
- automation = self.create_automation()
-
- with self.assertRaises(PermissionDenied):
- run_task_automation(str(automation.id))
-
- self.assertFalse(TaskRun.objects.filter(task=automation.task).exists())
- mock_execute_workflow.assert_not_called()
- automation.refresh_from_db()
- self.assertIsNotNone(automation.last_error)
-
- @patch("products.tasks.backend.automation_service.execute_task_processing_workflow_for_automation")
- def test_run_task_automation_fails_closed_without_creator(self, mock_execute_workflow):
- # created_by is SET_NULL on user deletion; with no user there is no entitlement and
- # no way to mint the run's sandbox OAuth token, so the fire must stop, not skip the check.
- automation = self.create_automation()
- automation.task.created_by = None
- automation.task.save(update_fields=["created_by", "updated_at"])
-
- with self.assertRaises(PermissionDenied):
- run_task_automation(str(automation.id))
-
- self.assertFalse(TaskRun.objects.filter(task=automation.task).exists())
- mock_execute_workflow.assert_not_called()
-
- def test_automation_last_run_properties_come_from_last_task_run(self):
- automation = self.create_automation()
- task_run = automation.task.create_run(mode="background", extra_state={"automation_id": str(automation.id)})
- task_run.status = TaskRun.Status.COMPLETED
- task_run.save(update_fields=["status", "updated_at"])
-
- automation.last_task_run = task_run
- automation.save(update_fields=["last_task_run", "updated_at"])
-
- automation.refresh_from_db()
- self.assertEqual(automation.last_run_at, task_run.created_at)
- self.assertEqual(automation.last_run_status, TaskAutomation.RunStatus.SUCCESS)
-
- def test_update_automation_run_result_records_failure_from_previous_run(self):
- automation = self.create_automation()
- first_run = automation.task.create_run(mode="background", extra_state={"automation_id": str(automation.id)})
- second_run = automation.task.create_run(mode="background", extra_state={"automation_id": str(automation.id)})
-
- automation.last_task_run = second_run
- automation.save(update_fields=["last_task_run", "updated_at"])
-
- first_run.status = TaskRun.Status.FAILED
- first_run.error_message = "Automation failed after a newer run started"
- first_run.save(update_fields=["status", "error_message", "updated_at"])
-
- update_automation_run_result(first_run)
-
- automation.refresh_from_db()
- self.assertEqual(automation.last_task_run_id, second_run.id)
- self.assertEqual(automation.last_error, "Automation failed after a newer run started")
diff --git a/products/tasks/backend/tests/test_run_log_mirror.py b/products/tasks/backend/tests/test_run_log_mirror.py
index b07bea4f240c..aa505582bc6a 100644
--- a/products/tasks/backend/tests/test_run_log_mirror.py
+++ b/products/tasks/backend/tests/test_run_log_mirror.py
@@ -285,7 +285,7 @@ class TestAppendLogMirroring(TestCase):
[
(Task.OriginProduct.SIGNALS_SCOUT, True),
(Task.OriginProduct.USER_CREATED, True),
- (Task.OriginProduct.AUTOMATION, False),
+ (Task.OriginProduct.LOOP, False),
]
)
@patch("products.tasks.backend.logic.services.run_log_mirror.logger")
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index f3618f62c93f..ecc3b4c3aa09 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -1061,126 +1061,6 @@ export interface TaskActivityMarkReadResponseApi {
unread_count: number
}
-/**
- * Detail/create/update/run response for a task automation.
- */
-export interface TaskAutomationDTOApi {
- id: string
- name: string
- prompt: string
- /** @nullable */
- repository: string | null
- /** @nullable */
- github_integration: number | null
- cron_expression: string
- timezone: string
- /** @nullable */
- template_id: string | null
- enabled: boolean
- /** @nullable */
- last_run_at: string | null
- /** @nullable */
- last_run_status: string | null
- last_task_id: string
- /** @nullable */
- last_task_run_id: string | null
- /** @nullable */
- last_error: string | null
- created_at: string
- updated_at: string
-}
-
-export interface PaginatedTaskAutomationDTOListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: TaskAutomationDTOApi[]
-}
-
-/**
- * Request body for creating or updating a task automation.
- */
-export interface TaskAutomationWriteApi {
- /**
- * Display name (stored as the backing task's title).
- * @maxLength 255
- */
- name: string
- /** The automation prompt (stored as the backing task's description). */
- prompt: string
- /**
- * Target repository in the format organization/repository.
- * @maxLength 255
- */
- repository: string
- /**
- * GitHub integration to run as. Defaults to the team's GitHub integration when omitted.
- * @nullable
- */
- github_integration?: number | null
- /**
- * Standard 5-field cron expression (minute hour day month weekday).
- * @maxLength 100
- */
- cron_expression: string
- /**
- * IANA timezone the schedule runs in.
- * @maxLength 128
- */
- timezone?: string
- /**
- * Optional template identifier this automation was created from.
- * @maxLength 255
- * @nullable
- */
- template_id?: string | null
- /** Whether the schedule is active; paused when false. */
- enabled?: boolean
-}
-
-/**
- * Request body for creating or updating a task automation.
- */
-export interface PatchedTaskAutomationWriteApi {
- /**
- * Display name (stored as the backing task's title).
- * @maxLength 255
- */
- name?: string
- /** The automation prompt (stored as the backing task's description). */
- prompt?: string
- /**
- * Target repository in the format organization/repository.
- * @maxLength 255
- */
- repository?: string
- /**
- * GitHub integration to run as. Defaults to the team's GitHub integration when omitted.
- * @nullable
- */
- github_integration?: number | null
- /**
- * Standard 5-field cron expression (minute hour day month weekday).
- * @maxLength 100
- */
- cron_expression?: string
- /**
- * IANA timezone the schedule runs in.
- * @maxLength 128
- */
- timezone?: string
- /**
- * Optional template identifier this automation was created from.
- * @maxLength 255
- * @nullable
- */
- template_id?: string | null
- /** Whether the schedule is active; paused when false. */
- enabled?: boolean
-}
-
/**
* Response shape for a task channel, read from a frozen ``ChannelDTO``.
*/
@@ -1656,7 +1536,6 @@ export interface PaginatedTaskDetailDTOListApi {
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
- * * `automation` - Automation
* * `slack` - Slack
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
@@ -1679,7 +1558,6 @@ export const OriginProductEnumApi = {
ErrorTracking: 'error_tracking',
EvalClusters: 'eval_clusters',
UserCreated: 'user_created',
- Automation: 'automation',
Slack: 'slack',
SupportQueue: 'support_queue',
SessionSummaries: 'session_summaries',
@@ -1719,7 +1597,6 @@ export interface TaskCreateApi {
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
- * * `automation` - Automation
* * `slack` - Slack
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
@@ -1863,7 +1740,6 @@ export interface TaskWriteApi {
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
- * * `automation` - Automation
* * `slack` - Slack
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
@@ -1992,7 +1868,6 @@ export interface PatchedTaskWriteApi {
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
- * * `automation` - Automation
* * `slack` - Slack
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
@@ -4262,17 +4137,6 @@ export type TaskActivityListParams = {
limit?: number
}
-export type TaskAutomationsListParams = {
- /**
- * Number of results to return per page.
- */
- limit?: number
- /**
- * The initial index from which to return the results.
- */
- offset?: number
-}
-
export type TaskChannelsListParams = {
/**
* Number of results to return per page.
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index 6d9077a4611f..4ca8144efeeb 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -38,7 +38,6 @@ import type {
PaginatedLoopDTOListApi,
PaginatedSandboxCustomImageDTOListApi,
PaginatedSandboxEnvironmentDTOListApi,
- PaginatedTaskAutomationDTOListApi,
PaginatedTaskDetailDTOListApi,
PaginatedTaskMentionDTOListApi,
PaginatedTaskRunDetailDTOListApi,
@@ -49,7 +48,6 @@ import type {
PatchedLoopWriteApi,
PatchedSandboxCustomImageUpdateApi,
PatchedSandboxEnvironmentWriteApi,
- PatchedTaskAutomationWriteApi,
PatchedTaskRunSetOutputRequestApi,
PatchedTaskRunUpdateApi,
PatchedTaskWriteApi,
@@ -70,9 +68,6 @@ import type {
TaskActivityMarkReadResponseApi,
TaskActivityPageDTOApi,
TaskArtifactsResponseApi,
- TaskAutomationDTOApi,
- TaskAutomationWriteApi,
- TaskAutomationsListParams,
TaskChannelsFeedListParams,
TaskChannelsListParams,
TaskCommentDetailApi,
@@ -721,127 +716,6 @@ export const taskActivityMarkReadCreate = async (
})
}
-export const getTaskAutomationsListUrl = (projectId: string, params?: TaskAutomationsListParams) => {
- const normalizedParams = new URLSearchParams()
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : String(value))
- }
- })
-
- const stringifiedParams = normalizedParams.toString()
-
- return stringifiedParams.length > 0
- ? `/api/projects/${projectId}/task_automations/?${stringifiedParams}`
- : `/api/projects/${projectId}/task_automations/`
-}
-
-/**
- * API for managing scheduled task automations.
- */
-export const taskAutomationsList = async (
- projectId: string,
- params?: TaskAutomationsListParams,
- options?: RequestInit
-): Promise<PaginatedTaskAutomationDTOListApi> => {
- return apiMutator<PaginatedTaskAutomationDTOListApi>(getTaskAutomationsListUrl(projectId, params), {
- ...options,
- method: 'GET',
- })
-}
-
-export const getTaskAutomationsCreateUrl = (projectId: string) => {
- return `/api/projects/${projectId}/task_automations/`
-}
-
-/**
- * API for managing scheduled task automations.
- */
-export const taskAutomationsCreate = async (
- projectId: string,
- taskAutomationWriteApi: TaskAutomationWriteApi,
- options?: RequestInit
-): Promise<TaskAutomationDTOApi> => {
- return apiMutator<TaskAutomationDTOApi>(getTaskAutomationsCreateUrl(projectId), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(taskAutomationWriteApi),
- })
-}
-
-export const getTaskAutomationsRetrieveUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/task_automations/${id}/`
-}
-
-/**
- * API for managing scheduled task automations.
- */
-export const taskAutomationsRetrieve = async (
- projectId: string,
- id: string,
- options?: RequestInit
-): Promise<TaskAutomationDTOApi> => {
- return apiMutator<TaskAutomationDTOApi>(getTaskAutomationsRetrieveUrl(projectId, id), {
- ...options,
- method: 'GET',
- })
-}
-
-export const getTaskAutomationsPartialUpdateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/task_automations/${id}/`
-}
-
-/**
- * API for managing scheduled task automations.
- */
-export const taskAutomationsPartialUpdate = async (
- projectId: string,
- id: string,
- patchedTaskAutomationWriteApi?: PatchedTaskAutomationWriteApi,
- options?: RequestInit
-): Promise<TaskAutomationDTOApi> => {
- return apiMutator<TaskAutomationDTOApi>(getTaskAutomationsPartialUpdateUrl(projectId, id), {
- ...options,
- method: 'PATCH',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(patchedTaskAutomationWriteApi),
- })
-}
-
-export const getTaskAutomationsDestroyUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/task_automations/${id}/`
-}
-
-/**
- * API for managing scheduled task automations.
- */
-export const taskAutomationsDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {
- return apiMutator<void>(getTaskAutomationsDestroyUrl(projectId, id), {
- ...options,
- method: 'DELETE',
- })
-}
-
-export const getTaskAutomationsRunCreateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/task_automations/${id}/run/`
-}
-
-/**
- * API for managing scheduled task automations.
- */
-export const taskAutomationsRunCreate = async (
- projectId: string,
- id: string,
- options?: RequestInit
-): Promise<TaskAutomationDTOApi> => {
- return apiMutator<TaskAutomationDTOApi>(getTaskAutomationsRunCreateUrl(projectId, id), {
- ...options,
- method: 'POST',
- })
-}
-
export const getTaskChannelsListUrl = (projectId: string, params?: TaskChannelsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index 06eeb2db49d8..616b6e18cac6 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -900,113 +900,6 @@ export const TaskActivityMarkReadCreateBody = /* @__PURE__ */ zod
})
.describe('Request body for clearing the unread flag on specific tasks.')
-/**
- * API for managing scheduled task automations.
- */
-export const taskAutomationsCreateBodyNameMax = 255
-
-export const taskAutomationsCreateBodyRepositoryMax = 255
-
-export const taskAutomationsCreateBodyCronExpressionMax = 100
-
-export const taskAutomationsCreateBodyTimezoneDefault = `UTC`
-export const taskAutomationsCreateBodyTimezoneMax = 128
-
-export const taskAutomationsCreateBodyTemplateIdMax = 255
-
-export const taskAutomationsCreateBodyEnabledDefault = true
-
-export const TaskAutomationsCreateBody = /* @__PURE__ */ zod
- .object({
- name: zod
- .string()
- .max(taskAutomationsCreateBodyNameMax)
- .describe("Display name (stored as the backing task's title)."),
- prompt: zod.string().describe("The automation prompt (stored as the backing task's description)."),
- repository: zod
- .string()
- .max(taskAutomationsCreateBodyRepositoryMax)
- .describe('Target repository in the format organization\/repository.'),
- github_integration: zod
- .number()
- .nullish()
- .describe("GitHub integration to run as. Defaults to the team's GitHub integration when omitted."),
- cron_expression: zod
- .string()
- .max(taskAutomationsCreateBodyCronExpressionMax)
- .describe('Standard 5-field cron expression (minute hour day month weekday).'),
- timezone: zod
- .string()
- .max(taskAutomationsCreateBodyTimezoneMax)
- .default(taskAutomationsCreateBodyTimezoneDefault)
- .describe('IANA timezone the schedule runs in.'),
- template_id: zod
- .string()
- .max(taskAutomationsCreateBodyTemplateIdMax)
- .nullish()
- .describe('Optional template identifier this automation was created from.'),
- enabled: zod
- .boolean()
- .default(taskAutomationsCreateBodyEnabledDefault)
- .describe('Whether the schedule is active; paused when false.'),
- })
- .describe('Request body for creating or updating a task automation.')
-
-/**
- * API for managing scheduled task automations.
- */
-export const taskAutomationsPartialUpdateBodyNameMax = 255
-
-export const taskAutomationsPartialUpdateBodyRepositoryMax = 255
-
-export const taskAutomationsPartialUpdateBodyCronExpressionMax = 100
-
-export const taskAutomationsPartialUpdateBodyTimezoneDefault = `UTC`
-export const taskAutomationsPartialUpdateBodyTimezoneMax = 128
-
-export const taskAutomationsPartialUpdateBodyTemplateIdMax = 255
-
-export const taskAutomationsPartialUpdateBodyEnabledDefault = true
-
-export const TaskAutomationsPartialUpdateBody = /* @__PURE__ */ zod
- .object({
- name: zod
- .string()
- .max(taskAutomationsPartialUpdateBodyNameMax)
- .optional()
- .describe("Display name (stored as the backing task's title)."),
- prompt: zod.string().optional().describe("The automation prompt (stored as the backing task's description)."),
- repository: zod
- .string()
- .max(taskAutomationsPartialUpdateBodyRepositoryMax)
- .optional()
- .describe('Target repository in the format organization\/repository.'),
- github_integration: zod
- .number()
- .nullish()
- .describe("GitHub integration to run as. Defaults to the team's GitHub integration when omitted."),
- cron_expression: zod
- .string()
- .max(taskAutomationsPartialUpdateBodyCronExpressionMax)
- .optional()
- .describe('Standard 5-field cron expression (minute hour day month weekday).'),
- timezone: zod
- .string()
- .max(taskAutomationsPartialUpdateBodyTimezoneMax)
- .default(taskAutomationsPartialUpdateBodyTimezoneDefault)
- .describe('IANA timezone the schedule runs in.'),
- template_id: zod
- .string()
- .max(taskAutomationsPartialUpdateBodyTemplateIdMax)
- .nullish()
- .describe('Optional template identifier this automation was created from.'),
- enabled: zod
- .boolean()
- .default(taskAutomationsPartialUpdateBodyEnabledDefault)
- .describe('Whether the schedule is active; paused when false.'),
- })
- .describe('Request body for creating or updating a task automation.')
-
/**
* Returns the existing public channel with the (normalized) name, creating it if needed. A channel created here is starred for the requester unless star is false.
* @summary Resolve or create a public channel
@@ -1197,7 +1090,6 @@ export const TasksCreateBody = /* @__PURE__ */ zod
'error_tracking',
'eval_clusters',
'user_created',
- 'automation',
'slack',
'support_queue',
'session_summaries',
@@ -1214,11 +1106,11 @@ export const TasksCreateBody = /* @__PURE__ */ zod
'signals_chat',
])
.describe(
- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'
+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'
)
.optional()
.describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'
),
repository: zod
.string()
@@ -1362,7 +1254,6 @@ export const TasksUpdateBody = /* @__PURE__ */ zod
'error_tracking',
'eval_clusters',
'user_created',
- 'automation',
'slack',
'support_queue',
'session_summaries',
@@ -1379,11 +1270,11 @@ export const TasksUpdateBody = /* @__PURE__ */ zod
'signals_chat',
])
.describe(
- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'
+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'
)
.optional()
.describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'
),
repository: zod
.string()
@@ -1512,7 +1403,6 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod
'error_tracking',
'eval_clusters',
'user_created',
- 'automation',
'slack',
'support_queue',
'session_summaries',
@@ -1529,11 +1419,11 @@ export const TasksPartialUpdateBody = /* @__PURE__ */ zod
'signals_chat',
])
.describe(
- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'
+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'
)
.optional()
.describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'
),
repository: zod
.string()
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index e5b7e850e70b..e1442ab0d3ef 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -279,24 +279,6 @@ tools:
task-activity-mark-read-create:
operation: task_activity_mark_read_create
enabled: false
- task-automations-create:
- operation: task_automations_create
- enabled: false
- task-automations-destroy:
- operation: task_automations_destroy
- enabled: false
- task-automations-list:
- operation: task_automations_list
- enabled: false
- task-automations-partial-update:
- operation: task_automations_partial_update
- enabled: false
- task-automations-retrieve:
- operation: task_automations_retrieve
- enabled: false
- task-automations-run-create:
- operation: task_automations_run_create
- enabled: false
task-channels-context-generation-retrieve:
operation: task_channels_context_generation_retrieve
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 43653ca9cba3..d8c3e166fa48 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -49477,7 +49477,6 @@ export namespace Schemas {
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
- * * `automation` - Automation
* * `slack` - Slack
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
@@ -49501,7 +49500,6 @@ export namespace Schemas {
ErrorTracking: 'error_tracking',
EvalClusters: 'eval_clusters',
UserCreated: 'user_created',
- Automation: 'automation',
Slack: 'slack',
SupportQueue: 'support_queue',
SessionSummaries: 'session_summaries',
@@ -53971,44 +53969,6 @@ export namespace Schemas {
results: Tagger[];
}
- /**
- * Detail/create/update/run response for a task automation.
- */
- export interface TaskAutomationDTO {
- id: string;
- name: string;
- prompt: string;
- /** @nullable */
- repository: string | null;
- /** @nullable */
- github_integration: number | null;
- cron_expression: string;
- timezone: string;
- /** @nullable */
- template_id: string | null;
- enabled: boolean;
- /** @nullable */
- last_run_at: string | null;
- /** @nullable */
- last_run_status: string | null;
- last_task_id: string;
- /** @nullable */
- last_task_run_id: string | null;
- /** @nullable */
- last_error: string | null;
- created_at: string;
- updated_at: string;
- }
-
- export interface PaginatedTaskAutomationDTOList {
- count: number;
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
- results: TaskAutomationDTO[];
- }
-
/**
* * `anthropic` - anthropic
* * `openai` - openai
@@ -62848,47 +62808,6 @@ export namespace Schemas {
deleted?: boolean;
}
- /**
- * Request body for creating or updating a task automation.
- */
- export interface PatchedTaskAutomationWrite {
- /**
- * Display name (stored as the backing task's title).
- * @maxLength 255
- */
- name?: string;
- /** The automation prompt (stored as the backing task's description). */
- prompt?: string;
- /**
- * Target repository in the format organization/repository.
- * @maxLength 255
- */
- repository?: string;
- /**
- * GitHub integration to run as. Defaults to the team's GitHub integration when omitted.
- * @nullable
- */
- github_integration?: number | null;
- /**
- * Standard 5-field cron expression (minute hour day month weekday).
- * @maxLength 100
- */
- cron_expression?: string;
- /**
- * IANA timezone the schedule runs in.
- * @maxLength 128
- */
- timezone?: string;
- /**
- * Optional template identifier this automation was created from.
- * @maxLength 255
- * @nullable
- */
- template_id?: string | null;
- /** Whether the schedule is active; paused when false. */
- enabled?: boolean;
- }
-
export interface PatchedTaskRunSetOutputRequest {
/** Output data from the run. Validated against the task's json_schema if one is set. */
output?: unknown;
@@ -62964,7 +62883,6 @@ export namespace Schemas {
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
- * * `automation` - Automation
* * `slack` - Slack
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
@@ -78501,47 +78419,6 @@ export namespace Schemas {
artifacts: TaskArtifact[];
}
- /**
- * Request body for creating or updating a task automation.
- */
- export interface TaskAutomationWrite {
- /**
- * Display name (stored as the backing task's title).
- * @maxLength 255
- */
- name: string;
- /** The automation prompt (stored as the backing task's description). */
- prompt: string;
- /**
- * Target repository in the format organization/repository.
- * @maxLength 255
- */
- repository: string;
- /**
- * GitHub integration to run as. Defaults to the team's GitHub integration when omitted.
- * @nullable
- */
- github_integration?: number | null;
- /**
- * Standard 5-field cron expression (minute hour day month weekday).
- * @maxLength 100
- */
- cron_expression: string;
- /**
- * IANA timezone the schedule runs in.
- * @maxLength 128
- */
- timezone?: string;
- /**
- * Optional template identifier this automation was created from.
- * @maxLength 255
- * @nullable
- */
- template_id?: string | null;
- /** Whether the schedule is active; paused when false. */
- enabled?: boolean;
- }
-
export interface TaskCommentAnchor {
/** Anchor kind. */
kind?: string;
@@ -78695,7 +78572,6 @@ export namespace Schemas {
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
- * * `automation` - Automation
* * `slack` - Slack
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
@@ -79859,7 +79735,6 @@ export namespace Schemas {
* * `error_tracking` - Error Tracking
* * `eval_clusters` - Eval Clusters
* * `user_created` - User Created
- * * `automation` - Automation
* * `slack` - Slack
* * `support_queue` - Support Queue
* * `session_summaries` - Session Summaries
@@ -92335,17 +92210,6 @@ export namespace Schemas {
limit?: number;
};
- export type TaskAutomationsListParams = {
- /**
- * Number of results to return per page.
- */
- limit?: number;
- /**
- * The initial index from which to return the results.
- */
- offset?: number;
- };
-
export type TaskChannelsListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.ts
index 421654c62f4a..3bd8a573b0af 100644
--- a/services/mcp/src/generated/tasks/api.ts
+++ b/services/mcp/src/generated/tasks/api.ts
@@ -982,7 +982,6 @@ export const TasksCreateBody = /* @__PURE__ */ zod
'error_tracking',
'eval_clusters',
'user_created',
- 'automation',
'slack',
'support_queue',
'session_summaries',
@@ -999,11 +998,11 @@ export const TasksCreateBody = /* @__PURE__ */ zod
'signals_chat',
])
.describe(
- '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'
+ '\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'
)
.optional()
.describe(
- 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `automation` - Automation\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'
+ 'PostHog product or surface that created this task (e.g. error_tracking, slack, user_created). Origins reserved for server-created agents cannot be set through this API.\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat'
),
repository: zod
.string()