:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): mobile hand off a task to a colleague (#87026)
Tom Owers63dfa306a8cb
diff --git a/products/desktop/apps/mobile/src/app/task/[id].tsx b/products/desktop/apps/mobile/src/app/task/[id].tsxindex a48884d98812..3ec20f3ac73f 100644--- a/products/desktop/apps/mobile/src/app/task/[id].tsx+++ b/products/desktop/apps/mobile/src/app/task/[id].tsx@@ -24,6 +24,7 @@ import {import { useQueryClient } from "@tanstack/react-query";import * as Haptics from "expo-haptics";import { useLocalSearchParams, useRouter } from "expo-router";+import { UserSwitch } from "phosphor-react-native";import { useFeatureFlag } from "posthog-react-native";import { useCallback, useEffect, useRef, useState } from "react";import {@@ -36,9 +37,11 @@ import {import { useReanimatedKeyboardAnimation } from "react-native-keyboard-controller";import Animated, { useAnimatedStyle } from "react-native-reanimated";import { FloatingBackButton } from "@/components/FloatingBackButton";+import { useUserQuery } from "@/features/auth";import { usePreferencesStore } from "@/features/preferences/stores/preferencesStore";import { CustomImageBadge } from "@/features/tasks/components/CustomImageBadge";import { FloatingTaskHeader } from "@/features/tasks/components/FloatingTaskHeader";+import { HandoffTaskSheet } from "@/features/tasks/components/HandoffTaskSheet";import { PrDiffStatsBadge } from "@/features/tasks/components/PrDiffStatsBadge";import { PrStatusBadge } from "@/features/tasks/components/PrStatusBadge";import { StopRunButton } from "@/features/tasks/components/StopRunButton";@@ -104,6 +107,8 @@ export default function TaskDetailScreen() {const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);const [retrying, setRetrying] = useState(false);+ const [handoffOpen, setHandoffOpen] = useState(false);+ const { data: currentUser } = useUserQuery();const {connectToTask,@@ -732,6 +737,10 @@ export default function TaskDetailScreen() {[router],);+ // Only the owner may hand a task off, matching the desktop menu gate.+ const canHandoff =+ !!task && currentUser != null && task.created_by?.id === currentUser.id;+const prUrl = readPrUrls(task?.latest_run?.output)[0];const activityPhase = getSessionActivityPhase({ retrying, session });@@ -789,6 +798,17 @@ export default function TaskDetailScreen() {rightSlot={<>{task ? <CustomImageBadge task={task} /> : null}+ {canHandoff ? (+ <Pressable+ onPress={() => setHandoffOpen(true)}+ hitSlop={8}+ className="h-9 w-9 items-center justify-center rounded-full active:bg-gray-3"+ accessibilityRole="button"+ accessibilityLabel="Hand off task"+ >+ <UserSwitch size={20} color={themeColors.gray[12]} />+ </Pressable>+ ) : null}{canStopRun ? (<StopRunButton onPress={handleStopRun} />) : prUrl ? (@@ -910,6 +930,17 @@ export default function TaskDetailScreen() {/></Animated.View></Animated.View>+ {task ? (+ <HandoffTaskSheet+ visible={handoffOpen}+ task={task}+ onClose={() => setHandoffOpen(false)}+ onHandedOff={() => {+ setHandoffOpen(false);+ if (router.canGoBack()) router.back();+ }}+ />+ ) : null}</View>);}diff --git a/products/desktop/apps/mobile/src/features/tasks/components/HandoffTaskSheet.test.tsx b/products/desktop/apps/mobile/src/features/tasks/components/HandoffTaskSheet.test.tsxnew file mode 100644index 000000000000..3a79384e9c89--- /dev/null+++ b/products/desktop/apps/mobile/src/features/tasks/components/HandoffTaskSheet.test.tsx@@ -0,0 +1,190 @@+import type { Task } from "@posthog/shared";+import type { UserBasic } from "@posthog/shared/domain-types";+import { createElement, type ReactElement } from "react";+import { Pressable } from "react-native";+import { act, create, type ReactTestRenderer } from "react-test-renderer";+import { beforeEach, describe, expect, it, vi } from "vitest";++const { handoffMutate, onHandedOff, membersRef, currentUserRef } = vi.hoisted(+ () => ({+ handoffMutate: vi.fn(),+ onHandedOff: vi.fn(),+ membersRef: { current: [] as UserBasic[] },+ currentUserRef: { current: { id: 1 } as { id: number } | undefined },+ }),+);++// The global react-native mock renders Modal through a DOM portal that is a+// no-op under the node test env, so its children never mount. Substitute plain+// host elements for the components the sheet uses so the body is inspectable.+vi.mock("react-native", () => {+ const host = (name: string) => (props: Record<string, unknown>) =>+ createElement(name, props);+ return {+ ActivityIndicator: host("ActivityIndicator"),+ Alert: { alert: vi.fn() },+ FlatList: <T,>({+ data,+ renderItem,+ keyExtractor,+ }: {+ data: readonly T[];+ renderItem: (info: { item: T; index: number }) => ReactElement;+ keyExtractor?: (item: T, index: number) => string;+ }) =>+ createElement(+ "FlatList",+ {},+ (data ?? []).map((item, index) =>+ createElement(+ "FlatListItem",+ { key: keyExtractor?.(item, index) ?? index },+ renderItem({ item, index }),+ ),+ ),+ ),+ Modal: host("Modal"),+ Pressable: host("Pressable"),+ TextInput: host("TextInput"),+ View: host("View"),+ };+});++vi.mock("../hooks/useOrgMembers", () => ({+ useOrgMembers: () => ({ members: membersRef.current, isLoading: false }),+}));++vi.mock("../hooks/useTasks", () => ({+ useHandoffTask: () => ({ mutate: handoffMutate, isPending: false }),+}));++vi.mock("@/features/auth", () => ({+ useUserQuery: () => ({ data: currentUserRef.current }),+}));++vi.mock("@/hooks/useDebouncedValue", () => ({+ useDebouncedValue: (value: unknown) => value,+}));++vi.mock("@/hooks/useScreenInsets", () => ({+ useScreenInsets: () => ({ bottom: () => 0, sheetContentTop: () => 0 }),+}));++vi.mock("@/lib/theme", () => ({+ useThemeColors: () => ({ gray: {}, accent: {} }),+}));++vi.mock("@components/text", () => ({+ Text: (props: Record<string, unknown>) => createElement("Text", props),+}));++vi.mock("expo-haptics", () => ({+ impactAsync: vi.fn(),+ ImpactFeedbackStyle: { Medium: "medium" },+}));++vi.mock("phosphor-react-native", () => ({+ Check: (props: Record<string, unknown>) => createElement("Check", props),+ MagnifyingGlass: (props: Record<string, unknown>) =>+ createElement("MagnifyingGlass", props),+}));++function member(id: number, email: string, firstName?: string): UserBasic {+ return { id, uuid: `u-${id}`, email, first_name: firstName };+}++const TASK: Task = {+ id: "task-1",+ task_number: 1,+ slug: "task-1",+ title: "Fix the thing",+ description: "",+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ origin_product: "code",+};++function textOf(node: { props: { children?: unknown } }): string {+ const children = node.props.children;+ return Array.isArray(children) ? children.join("") : String(children ?? "");+}++function pressableWithText(tree: ReactTestRenderer, text: string) {+ return tree.root+ .findAllByType(Pressable)+ .find((pressable) =>+ pressable+ .findAll((n) => String(n.type) === "Text")+ .some((t) => textOf(t).includes(text)),+ );+}++function render(task: Task = TASK): ReactTestRenderer {+ let tree!: ReactTestRenderer;+ act(() => {+ tree = create(+ createElement(HandoffTaskSheet, {+ visible: true,+ task,+ onClose: vi.fn(),+ onHandedOff,+ }),+ );+ });+ return tree;+}++let HandoffTaskSheet: typeof import("./HandoffTaskSheet").HandoffTaskSheet;++describe("HandoffTaskSheet", () => {+ beforeEach(async () => {+ handoffMutate.mockReset();+ handoffMutate.mockImplementation(+ (_vars, opts?: { onSuccess?: () => void }) => opts?.onSuccess?.(),+ );+ onHandedOff.mockReset();+ membersRef.current = [+ member(1, "[email protected]", "Me"),+ member(2, "[email protected]", "Alice"),+ ];+ currentUserRef.current = { id: 1 };+ ({ HandoffTaskSheet } = await import("./HandoffTaskSheet"));+ });++ it("excludes the current user from the roster", () => {+ const tree = render();+ const emails = tree.root+ .findAll((n) => String(n.type) === "Text")+ .map(textOf);+ expect(emails).toContain("[email protected]");+ expect(emails).not.toContain("[email protected]");+ });++ it("locks the commit until a colleague is picked and acknowledged", () => {+ const tree = render();+ expect(pressableWithText(tree, "Hand off")?.props.disabled).toBe(true);++ act(() => pressableWithText(tree, "[email protected]")?.props.onPress());+ expect(pressableWithText(tree, "Hand off")?.props.disabled).toBe(true);++ act(() => pressableWithText(tree, "I understand")?.props.onPress());+ const button = pressableWithText(tree, "Hand off");+ expect(button?.props.disabled).toBe(false);++ act(() => button?.props.onPress());+ expect(handoffMutate).toHaveBeenCalledWith(+ { taskId: "task-1", userId: 2 },+ expect.anything(),+ );+ expect(onHandedOff).toHaveBeenCalled();+ });++ it("warns that the requester can lose access", () => {+ const tree = render();+ const copy = tree.root+ .findAll((n) => String(n.type) === "Text")+ .map(textOf)+ .join(" ");+ expect(copy).toContain("you lose access");+ });+});diff --git a/products/desktop/apps/mobile/src/features/tasks/components/HandoffTaskSheet.tsx b/products/desktop/apps/mobile/src/features/tasks/components/HandoffTaskSheet.tsxnew file mode 100644index 000000000000..8a85eb0520ec--- /dev/null+++ b/products/desktop/apps/mobile/src/features/tasks/components/HandoffTaskSheet.tsx@@ -0,0 +1,252 @@+import { Text } from "@components/text";+import { getUserInitials } from "@posthog/core/auth/userInitials";+import type { Task } from "@posthog/shared";+import type { UserBasic } from "@posthog/shared/domain-types";+import * as Haptics from "expo-haptics";+import { Check, MagnifyingGlass } from "phosphor-react-native";+import { useMemo, useState } from "react";+import {+ ActivityIndicator,+ Alert,+ FlatList,+ Modal,+ Pressable,+ TextInput,+ View,+} from "react-native";+import { useUserQuery } from "@/features/auth";+import { useDebouncedValue } from "@/hooks/useDebouncedValue";+import { useScreenInsets } from "@/hooks/useScreenInsets";+import { useThemeColors } from "@/lib/theme";+import { useOrgMembers } from "../hooks/useOrgMembers";+import { useHandoffTask } from "../hooks/useTasks";+import { userDisplayName } from "../utils/userDisplayName";++interface HandoffTaskSheetProps {+ visible: boolean;+ task: Task;+ onClose: () => void;+ // The detail screen holds its own task/session state that a handoff makes+ // stale (and may revoke access to), so the host leaves the screen on success.+ onHandedOff: () => void;+}++function MemberRow({+ member,+ selected,+ onPress,+}: {+ member: UserBasic;+ selected: boolean;+ onPress: () => void;+}) {+ const themeColors = useThemeColors();+ return (+ <Pressable+ onPress={onPress}+ className="flex-row items-center justify-between rounded-md px-2 py-2.5 active:bg-gray-3"+ >+ <View className="min-w-0 flex-1 flex-row items-center gap-2.5">+ <View className="h-6 w-6 items-center justify-center rounded-full bg-gray-4">+ <Text className="text-[11px] text-gray-10">+ {getUserInitials(member)}+ </Text>+ </View>+ <View className="min-w-0 flex-1">+ <Text className="text-[14px] text-gray-12" numberOfLines={1}>+ {userDisplayName(member)}+ </Text>+ <Text className="text-[12px] text-gray-9" numberOfLines={1}>+ {member.email}+ </Text>+ </View>+ </View>+ {selected && <Check size={16} color={themeColors.gray[12]} />}+ </Pressable>+ );+}++export function HandoffTaskSheet({+ visible,+ task,+ onClose,+ onHandedOff,+}: HandoffTaskSheetProps) {+ const { bottom, sheetContentTop } = useScreenInsets();+ const themeColors = useThemeColors();+ const { data: currentUser } = useUserQuery();+ const { mutate: handoffTask, isPending } = useHandoffTask();+ const { members, isLoading } = useOrgMembers({ enabled: visible });++ const [query, setQuery] = useState("");+ const debouncedQuery = useDebouncedValue(query, 250);+ const [selectedId, setSelectedId] = useState<number | null>(null);+ const [acknowledged, setAcknowledged] = useState(false);++ const [wasVisible, setWasVisible] = useState(visible);+ if (visible !== wasVisible) {+ setWasVisible(visible);+ if (visible) {+ setQuery("");+ setSelectedId(null);+ setAcknowledged(false);+ }+ }++ const options = useMemo(() => {+ const needle = debouncedQuery.trim().toLowerCase();+ return members.filter((member) => {+ if (member.id === currentUser?.id) return false;+ if (!needle) return true;+ return (+ userDisplayName(member).toLowerCase().includes(needle) ||+ member.email.toLowerCase().includes(needle)+ );+ });+ }, [members, currentUser?.id, debouncedQuery]);++ const selected = options.find((member) => member.id === selectedId);+ const canSubmit = selected !== undefined && acknowledged && !isPending;++ const handleConfirm = () => {+ if (!selected) return;+ Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);+ handoffTask(+ { taskId: task.id, userId: selected.id },+ {+ onSuccess: onHandedOff,+ onError: () => {+ Alert.alert(+ "Couldn't hand off",+ "The task could not be handed off. Please try again.",+ );+ },+ },+ );+ };++ return (+ <Modal+ visible={visible}+ animationType="slide"+ presentationStyle="pageSheet"+ onRequestClose={isPending ? undefined : onClose}+ >+ <View+ className="flex-1 bg-background"+ style={{ paddingTop: sheetContentTop() }}+ >+ <View className="flex-row items-center justify-between border-gray-6 border-b px-4 pb-3">+ <Text className="font-semibold text-[18px] text-gray-12">+ Hand off task+ </Text>+ <Pressable onPress={onClose} disabled={isPending}>+ <Text className="font-semibold text-[14px] text-accent-9">+ Cancel+ </Text>+ </Pressable>+ </View>++ <View className="gap-1 px-4 pt-3">+ <Text className="text-[13px] text-gray-11">+ <Text className="font-medium text-gray-12">{task.title}</Text> goes+ to the person you pick. They steer it and get its notifications.+ </Text>+ <Text className="text-[13px] text-gray-11">+ If it's in your personal space, it moves to theirs and you lose+ access. Only they can hand it back.+ </Text>+ </View>++ <View className="px-4 pt-3">+ <View className="flex-row items-center gap-2 rounded-lg bg-gray-2 px-3 py-2">+ <MagnifyingGlass size={16} color={themeColors.gray[9]} />+ <TextInput+ value={query}+ onChangeText={setQuery}+ placeholder="Search people…"+ placeholderTextColor={themeColors.gray[9]}+ autoCapitalize="none"+ autoCorrect={false}+ className="min-w-0 flex-1 text-[14px] text-gray-12"+ />+ </View>+ </View>++ {options.length === 0 ? (+ isLoading ? (+ <View className="flex-1 items-center justify-center">+ <ActivityIndicator size="large" color={themeColors.accent[9]} />+ </View>+ ) : (+ <View className="flex-1 items-center justify-center p-6">+ <Text className="text-[14px] text-gray-10">No people found</Text>+ </View>+ )+ ) : (+ <FlatList+ className="flex-1"+ data={options}+ keyExtractor={(member) => String(member.id)}+ keyboardShouldPersistTaps="handled"+ contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 12 }}+ renderItem={({ item }) => (+ <MemberRow+ member={item}+ selected={item.id === selectedId}+ onPress={() => setSelectedId(item.id)}+ />+ )}+ />+ )}++ <View+ className="gap-3 border-gray-6 border-t px-4 pt-3"+ style={{ paddingBottom: bottom("roomy") }}+ >+ <Pressable+ onPress={() => setAcknowledged((prev) => !prev)}+ disabled={isPending}+ className="flex-row items-center gap-2.5 active:opacity-70"+ >+ <View+ className={`h-5 w-5 items-center justify-center rounded border ${acknowledged ? "border-transparent" : "border-gray-7"}`}+ style={+ acknowledged ? { backgroundColor: themeColors.accent[9] } : null+ }+ >+ {acknowledged ? (+ <Check size={12} color="#fff" weight="bold" />+ ) : null}+ </View>+ <Text className="flex-1 text-[13px] text-gray-11">+ I understand I can't undo this myself.+ </Text>+ </Pressable>++ <Pressable+ onPress={handleConfirm}+ disabled={!canSubmit}+ className="h-11 flex-row items-center justify-center rounded-lg active:opacity-80"+ style={{+ backgroundColor: canSubmit+ ? themeColors.accent[9]+ : themeColors.gray[4],+ }}+ >+ {isPending ? (+ <ActivityIndicator color="#fff" />+ ) : (+ <Text+ className="font-semibold text-[15px]"+ style={{ color: canSubmit ? "#fff" : themeColors.gray[9] }}+ >+ Hand off+ </Text>+ )}+ </Pressable>+ </View>+ </View>+ </Modal>+ );+}diff --git a/products/desktop/apps/mobile/src/features/tasks/hooks/useOrgMembers.ts b/products/desktop/apps/mobile/src/features/tasks/hooks/useOrgMembers.tsnew file mode 100644index 000000000000..6fd6f4aae242--- /dev/null+++ b/products/desktop/apps/mobile/src/features/tasks/hooks/useOrgMembers.ts@@ -0,0 +1,33 @@+import type { UserBasic } from "@posthog/shared/domain-types";+import { useQuery } from "@tanstack/react-query";+import { useMemo } from "react";+import { useAuthStore } from "@/features/auth";+import { getPostHogApiClient } from "@/lib/posthogApiClient";+import { userDisplayName } from "../utils/userDisplayName";++// Membership churn is slow; one fetch per session window is plenty.+const ORG_MEMBERS_STALE_MS = 5 * 60_000;++export function useOrgMembers(options?: { enabled?: boolean }): {+ members: UserBasic[];+ isLoading: boolean;+} {+ const { projectId, oauthAccessToken } = useAuthStore();++ const query = useQuery({+ queryKey: ["org-members"],+ queryFn: () => getPostHogApiClient().listOrganizationMembersWithStatus(),+ enabled: (options?.enabled ?? true) && !!projectId && !!oauthAccessToken,+ staleTime: ORG_MEMBERS_STALE_MS,+ });++ const members = useMemo(+ () =>+ (query.data?.members ?? [])+ .flatMap((member) => (member.user?.email ? [member.user] : []))+ .sort((a, b) => userDisplayName(a).localeCompare(userDisplayName(b))),+ [query.data],+ );++ return { members, isLoading: query.isLoading };+}diff --git a/products/desktop/apps/mobile/src/features/tasks/hooks/useTasks.ts b/products/desktop/apps/mobile/src/features/tasks/hooks/useTasks.tsindex 862459708e96..c80804e9762b 100644--- a/products/desktop/apps/mobile/src/features/tasks/hooks/useTasks.ts+++ b/products/desktop/apps/mobile/src/features/tasks/hooks/useTasks.ts@@ -169,6 +169,23 @@ export function useDeleteTask() {});}+export function useHandoffTask() {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: ({ taskId, userId }: { taskId: string; userId: number }) =>+ getPostHogApiClient().handoffTask(taskId, userId),+ // The task may leave the requester's own list, so nothing is seeded.+ onSuccess: (_, { taskId }) => {+ queryClient.invalidateQueries({ queryKey: taskKeys.lists() });+ queryClient.invalidateQueries({ queryKey: taskKeys.detail(taskId) });+ },+ onError: (error) => {+ log.error("Failed to hand off task", error.message);+ },+ });+}+export function useRunTask() {const queryClient = useQueryClient();diff --git a/products/desktop/apps/mobile/src/features/tasks/utils/userDisplayName.ts b/products/desktop/apps/mobile/src/features/tasks/utils/userDisplayName.tsnew file mode 100644index 000000000000..939a296cdb25--- /dev/null+++ b/products/desktop/apps/mobile/src/features/tasks/utils/userDisplayName.ts@@ -0,0 +1,6 @@+import type { UserBasic } from "@posthog/shared/domain-types";++export function userDisplayName(user: UserBasic): string {+ const name = [user.first_name, user.last_name].filter(Boolean).join(" ");+ return name || user.email;+}