: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): hand off a task to a colleague from the row menus (#84646)
Shy Alter5b14650ef8bf
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex c7a6976b7b98..8aee967cea28 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -2547,6 +2547,25 @@ export class PostHogAPIClient {return data.pinned;}+ // Handoff is absent from the Desktop-generated client, so use the same raw-fetch path as pin.+ async handoffTask(taskId: string, userId: number): Promise<Task> {+ const teamId = await this.getTeamId();+ const urlPath = `/api/projects/${teamId}/tasks/${taskId}/handoff/`;+ const response = await this.api.fetcher.fetch({+ method: "post",+ url: new URL(`${this.api.baseUrl}${urlPath}`),+ path: urlPath,+ overrides: { body: JSON.stringify({ user: userId }) },+ });+ if (!response.ok) {+ throw new Error(`Failed to hand off task: ${response.statusText}`);+ }+ const data = (await response.json()) as Parameters<+ typeof normalizeTaskResponse+ >[0];+ return normalizeTaskResponse(data, { teamId });+ }+async createTask(options: Pick<Task, "description"> &Partial<diff --git a/products/desktop/packages/core/src/canvas/activityEvents.ts b/products/desktop/packages/core/src/canvas/activityEvents.tsindex 80c552e1a7b3..4b7cf3c460e2 100644--- a/products/desktop/packages/core/src/canvas/activityEvents.ts+++ b/products/desktop/packages/core/src/canvas/activityEvents.ts@@ -20,6 +20,7 @@ export const ACTIVITY_EVENTS = ["pr_merged","pr_closed","message_forwarded",+ "task_handed_off",] as const;export type ActivityEventKind = (typeof ACTIVITY_EVENTS)[number];@@ -88,6 +89,14 @@ export interface MessageForwardedPayload {runId: string;}+export interface TaskHandedOffPayload {+ fromUserId: number | null;+ toUserId: number;+ /** Rendered names, so the row can read without a member lookup. */+ fromDisplayName: string | null;+ toDisplayName: string;+}+/** Identity only: the thread body, quote, and replies are fetched when the row opens. */export interface CommentEventPayload {commentId: string;@@ -115,7 +124,8 @@ export type ActivityEvent =| { kind: "pr_created"; payload: PrPayload }| { kind: "pr_merged"; payload: PrPayload }| { kind: "pr_closed"; payload: PrPayload }- | { kind: "message_forwarded"; payload: MessageForwardedPayload };+ | { kind: "message_forwarded"; payload: MessageForwardedPayload }+ | { kind: "task_handed_off"; payload: TaskHandedOffPayload };function str(value: unknown, fallback = ""): string {return typeof value === "string" ? value : fallback;@@ -255,6 +265,24 @@ export function parseActivityEvent(message: {// A PR row with no url can't be labelled or opened, so it isn't a row.return parsed.prUrl ? { kind: event, payload: parsed } : null;}+ case "task_handed_off": {+ // Older rows only carry user ids; a row with neither name can't say who+ // took over, so fall back to undrawn rather than label it wrong.+ const toDisplayName = optionalStr(payload.to_display_name);+ if (!toDisplayName) return null;+ return {+ kind: event,+ payload: {+ fromUserId:+ typeof payload.from_user_id === "number"+ ? payload.from_user_id+ : null,+ toUserId: num(payload.to_user_id, 0),+ fromDisplayName: optionalStr(payload.from_display_name),+ toDisplayName,+ },+ };+ }case "message_forwarded":return {kind: event,diff --git a/products/desktop/packages/core/src/canvas/activityTimeline.ts b/products/desktop/packages/core/src/canvas/activityTimeline.tsindex 6032c0ff2a9d..fa1bf34376db 100644--- a/products/desktop/packages/core/src/canvas/activityTimeline.ts+++ b/products/desktop/packages/core/src/canvas/activityTimeline.ts@@ -242,5 +242,8 @@ function eventIdentity(return event.payload.prUrl;case "message_forwarded":return event.payload.messageId;+ case "task_handed_off":+ // Each handoff is its own row; only a duplicate write of the same one collapses.+ return message.id;}}diff --git a/products/desktop/packages/core/src/context-menu/context-menu.test.ts b/products/desktop/packages/core/src/context-menu/context-menu.test.tsindex 925f41188e47..732dc7d3cd32 100644--- a/products/desktop/packages/core/src/context-menu/context-menu.test.ts+++ b/products/desktop/packages/core/src/context-menu/context-menu.test.ts@@ -152,6 +152,23 @@ describe("ContextMenuService.showTaskContextMenu", () => {);});+ it("offers Hand off only to callers that mark it available", async () => {+ // The API 404s a non-owner's handoff, so the item must stay hidden from one.+ const owner = new FakeContextMenu();+ const handedOff = makeService(owner).showTaskContextMenu({+ ...baseTask,+ canHandoff: true,+ });+ await owner.shown;+ findItem(owner.lastItems, "Hand off…").click();+ expect(await handedOff).toEqual({ action: { type: "handoff" } });++ const viewer = new FakeContextMenu();+ makeService(viewer).showTaskContextMenu(baseTask);+ await viewer.shown;+ expect(labels(viewer.lastItems)).not.toContain("Hand off…");+ });+it("can hide Archive prior tasks for task lists without that action", async () => {const menu = new FakeContextMenu();makeService(menu).showTaskContextMenu({diff --git a/products/desktop/packages/core/src/context-menu/context-menu.ts b/products/desktop/packages/core/src/context-menu/context-menu.tsindex 5bb16aaf36af..6867a01af9b1 100644--- a/products/desktop/packages/core/src/context-menu/context-menu.ts+++ b/products/desktop/packages/core/src/context-menu/context-menu.ts@@ -123,6 +123,7 @@ export class ContextMenuService {isInCommandCenter,hasEmptyCommandCenterCell,showArchivePrior = true,+ canHandoff,channels,} = input;const { apps, lastUsedAppId } = await this.getExternalAppsData();@@ -176,6 +177,12 @@ export class ContextMenuService {]: []),...fileToItems,+ ...(canHandoff+ ? [+ this.separator(),+ this.item("Hand off…", { type: "handoff" as const }),+ ]+ : []),this.separator(),this.item("Archive", { type: "archive" }),...(showArchivePriordiff --git a/products/desktop/packages/core/src/context-menu/schemas.ts b/products/desktop/packages/core/src/context-menu/schemas.tsindex 2667f78404c7..057a6a158320 100644--- a/products/desktop/packages/core/src/context-menu/schemas.ts+++ b/products/desktop/packages/core/src/context-menu/schemas.ts@@ -18,6 +18,8 @@ export const taskContextMenuInput = z.object({isInCommandCenter: z.boolean().optional(),hasEmptyCommandCenterCell: z.boolean().optional(),showArchivePrior: z.boolean().optional(),+ // Only the task's owner may hand it off; callers omit the item otherwise.+ canHandoff: z.boolean().optional(),// The project's channels available as "File to…" targets.// Omit (or pass empty) to hide the submenu entirely.channels: z.array(fileToChannel).optional(),@@ -68,6 +70,7 @@ const taskAction = z.discriminatedUnion("type", [z.object({ type: z.literal("archive-prior") }),z.object({ type: z.literal("delete") }),z.object({ type: z.literal("add-to-command-center") }),+ z.object({ type: z.literal("handoff") }),z.object({ type: z.literal("external-app"), action: externalAppAction }),z.object({ type: z.literal("file-to-channel"), channelId: z.string() }),]);diff --git a/products/desktop/packages/core/src/tasks/contextMenuActions.test.ts b/products/desktop/packages/core/src/tasks/contextMenuActions.test.tsindex 3ef8773661b8..6282e01f7754 100644--- a/products/desktop/packages/core/src/tasks/contextMenuActions.test.ts+++ b/products/desktop/packages/core/src/tasks/contextMenuActions.test.ts@@ -25,6 +25,9 @@ describe("resolveTaskContextMenuIntent", () => {expect(resolveTaskContextMenuIntent({ type: "stop" }, {})).toEqual({type: "stop",});+ expect(resolveTaskContextMenuIntent({ type: "handoff" }, {})).toEqual({+ type: "handoff",+ });expect(resolveTaskContextMenuIntent({ type: "delete" }, {})).toEqual({type: "delete",});diff --git a/products/desktop/packages/core/src/tasks/contextMenuActions.ts b/products/desktop/packages/core/src/tasks/contextMenuActions.tsindex dd4280397f19..c4b28ab3b87e 100644--- a/products/desktop/packages/core/src/tasks/contextMenuActions.ts+++ b/products/desktop/packages/core/src/tasks/contextMenuActions.ts@@ -14,6 +14,7 @@ export type TaskContextMenuIntent =| { type: "archive-prior" }| { type: "delete" }| { type: "add-to-command-center" }+ | { type: "handoff" }| { type: "file-to-channel"; channelId: string }| { type: "external-app"; action: ExternalAppAction };@@ -38,6 +39,8 @@ export function resolveTaskContextMenuIntent(return { type: "delete" };case "add-to-command-center":return { type: "add-to-command-center" };+ case "handoff":+ return { type: "handoff" };case "file-to-channel":return { type: "file-to-channel", channelId: action.channelId };case "external-app":diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsxindex cf66f17a5c1d..345f5787f215 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx@@ -7,7 +7,7 @@ import {} from "@posthog/ui/features/sidebar/taskDrag";import { useTaskSelectionStore } from "@posthog/ui/features/sidebar/taskSelectionStore";import { Theme } from "@radix-ui/themes";-import { fireEvent, render, screen } from "@testing-library/react";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import type { ReactNode } from "react";import { beforeEach, describe, expect, it, vi } from "vitest";@@ -15,11 +15,18 @@ import { beforeEach, describe, expect, it, vi } from "vitest";// The row's status comes from live session/workspace state and a per-task tRPC// query, none of which a unit test has. Stubbed at the module boundary, as// ChannelSidebar.test.tsx does for the same reason.-const mocks = vi.hoisted(() => ({ status: null as TaskStatusInput | null }));+const mocks = vi.hoisted(() => ({+ status: null as TaskStatusInput | null,+ currentUserId: 999 as number | undefined,+}));+vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({+ useCurrentUser: () => ({ data: { id: mocks.currentUserId } }),+}));vi.mock("@posthog/ui/features/canvas/hooks/useChannelTaskStatus", () => ({useChannelTaskStatus: () => mocks.status,}));-// The row menu's spaces list and filing mutation are tRPC-backed.+// The row menu's spaces list and filing mutation are tRPC-backed. The+// handoff dialog's channels lookup rides the same mock.vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({useChannels: () => ({ channels: [{ id: "channel-1", name: "code" }] }),}));@@ -29,6 +36,13 @@ vi.mock("@posthog/ui/features/canvas/hooks/useFileTaskToChannel", () => ({vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({useFeatureFlag: () => true,}));+// The handoff dialog is tested on its own; here it only opens.+vi.mock(+ "@posthog/ui/features/task-detail/components/HandoffTaskDialog",+ () => ({+ HandoffTaskDialog: () => null,+ }),+);import { usePendingCanvasDeleteStore } from "@posthog/ui/features/canvas/stores/pendingCanvasDeleteStore";import { ChannelItemPreviewCardProvider } from "./ChannelItemHoverCard";@@ -365,6 +379,42 @@ describe("ChannelItemRow", () => {}});+ it("offers Hand off… only to the task's owner", async () => {+ // The API 404s a non-owner's handoff, so the menu must not offer it to one.+ const ownerItem = item({+ authorUser: { id: 999, uuid: "u-1", email: "[email protected]" },+ task: {+ id: "task-1",+ task_number: 1,+ slug: "task-1",+ title: "Investigate signup drop-off",+ description: "",+ created_at: "2026-07-16T12:00:00.000Z",+ updated_at: "2026-07-16T12:00:00.000Z",+ origin_product: "user_created",+ created_by: { id: 999, uuid: "u-1", email: "[email protected]" },+ channel: "channel-1",+ },+ });++ renderInList(+ <ChannelItemRow actions={actions} isActive={false} item={ownerItem} />,+ );+ await openCard();+ expect(screen.getByRole("button", { name: "Hand off…" })).not.toBeNull();++ cleanup();++ mocks.currentUserId = 7;+ renderInList(+ <ChannelItemRow actions={actions} isActive={false} item={ownerItem} />,+ );+ await userEvent.hover(screen.getByText("Investigate signup drop-off"));+ await screen.findByRole("button", { name: "Pin" }, { timeout: 2000 });+ expect(screen.queryByRole("button", { name: "Hand off…" })).toBeNull();+ mocks.currentUserId = 999;+ });+it("disables Add to Command Center when there is nowhere to put the task", async () => {renderWithMenu({ onAddToCommandCenter: undefined });diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsxindex 8bc5941de337..80c0b858bbc2 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx@@ -16,6 +16,7 @@ import {TooltipTrigger,} from "@posthog/quill";import { formatRelativeTimeShort } from "@posthog/shared";+import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";import { ChannelItemHoverCard } from "@posthog/ui/features/canvas/components/ChannelItemHoverCard";import { iconForTemplate } from "@posthog/ui/features/canvas/components/canvasTemplateIcon";import {@@ -40,6 +41,7 @@ import {import { SidebarItem } from "@posthog/ui/features/sidebar/components/SidebarItem";import { writeTaskDragData } from "@posthog/ui/features/sidebar/taskDrag";import { SESSION_ROW_ATTRIBUTE } from "@posthog/ui/features/sidebar/useMarqueeSelection";+import { HandoffTaskDialog } from "@posthog/ui/features/task-detail/components/HandoffTaskDialog";import {type DragEvent,type ReactNode,@@ -281,6 +283,13 @@ export function ChannelItemRow({}) {const status = useChannelTaskStatus(item);const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);+ const [handoffOpen, setHandoffOpen] = useState(false);+ const currentUser = useCurrentUser();+ const canHandoff =+ item.kind === "task" &&+ item.task != null &&+ item.authorUser?.id != null &&+ currentUser.data?.id === item.authorUser.id;const handleDragStart = useCallback((event: DragEvent) => {if (item.kind !== "task") return;@@ -324,8 +333,11 @@ export function ChannelItemRow({onRename,onTogglePin: () => actions.togglePin(item),onArchive: () => actions.archive(item),+ ...(canHandoff ? { onHandoff: () => setHandoffOpen(true) } : {}),},- [item, channelId, actions, onAddToCommandCenter, onRename],+ // canHandoff rides on the currentUser query, so it belongs in deps for a+ // sign-in refresh to re-evaluate.+ [item, channelId, actions, onAddToCommandCenter, onRename, canHandoff],);if (isEditing) {@@ -405,6 +417,13 @@ export function ChannelItemRow({</AlertDialogFooter></AlertDialogContent></AlertDialog>+ {canHandoff && item.task ? (+ <HandoffTaskDialog+ task={item.task}+ open={handoffOpen}+ onOpenChange={setHandoffOpen}+ />+ ) : null}</>);}diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.test.tsxindex bb6d1f2db7c3..de23ea9bf854 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.test.tsx@@ -44,6 +44,9 @@ vi.mock("@posthog/ui/features/canvas/components/ChannelsFab", () => ({vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({useChannels: () => ({ channels: [] }),}));+vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({+ useCurrentUser: () => ({ data: { id: 1, email: "[email protected]" } }),+}));vi.mock("@posthog/ui/features/tasks/useTaskMutations", () => ({useRenameTask: () => ({ renameTask: vi.fn() }),}));diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsxindex 93d0fd233e82..7bb323799a36 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx@@ -1,5 +1,11 @@import { Theme } from "@radix-ui/themes";-import { act, render, screen, waitFor } from "@testing-library/react";+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";@@ -17,7 +23,9 @@ const mocks = vi.hoisted(() => ({title: string;channel: string;updated_at: string;+ authorId?: number;}[],+ currentUserId: 999 as number | undefined,totals: {} as Record<string, number>,unreadSessions: {} as Record<string, number>,blockedSessions: {} as Record<string, number>,@@ -57,6 +65,23 @@ vi.mock("@posthog/ui/features/canvas/hooks/useBlockedSessionCount", () => ({useBlockedSessionCount: () => (channelId: string | undefined) =>mocks.blockedSessions[channelId ?? ""] ?? 0,}));+vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({+ useCurrentUser: () => ({ data: { id: mocks.currentUserId } }),+}));+// The row menu's spaces list and filing mutation are tRPC-backed; the flag+// lookup sits behind a service provider that isn't mounted here.+vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({+ useFeatureFlag: () => true,+}));+vi.mock("@posthog/ui/features/canvas/hooks/useFileTaskToChannel", () => ({+ useFileTaskToChannel: () => ({ fileTask: vi.fn() }),+}));+vi.mock(+ "@posthog/ui/features/task-detail/components/HandoffTaskDialog",+ () => ({+ HandoffTaskDialog: () => null,+ }),+);vi.mock("@posthog/ui/features/canvas/hooks/useRecentSpaceTasks", () => ({NO_TASKS: { items: [], total: 0 },usePrefetchSpaceTasks: () => () => undefined,@@ -73,10 +98,17 @@ vi.mock("@posthog/ui/features/canvas/hooks/useRecentSpaceTasks", () => ({ts: Date.parse(task.updated_at),pinned: false,rawStatus: null,- authorUser: null,+ authorUser:+ task.authorId != null+ ? {+ id: task.authorId,+ uuid: `u-${task.authorId}`,+ email: "[email protected]",+ }+ : null,authorName: null,authorUuid: null,- task: null,+ task: task.authorId != null ? { id: task.id } : null,}));// `total` is what the space holds, not what the tree shows — the tests// that exercise "View all" set it above the row count.@@ -440,6 +472,28 @@ describe("ChannelsList", () => {expect(screen.queryByText("Ship the tree")).toBeNull();});+ it("offers Hand off… on an owned task's context menu only", async () => {+ // The API 404s a non-owner's handoff, so the menu must not offer it to one.+ mocks.tasks[0] = { ...mocks.tasks[0], authorId: 999 };+ mocks.tasks[1] = { ...mocks.tasks[1], authorId: 7 };+ const user = userEvent.setup();+ renderList();++ await user.click(screen.getByLabelText("Expand engineering"));+ fireEvent.contextMenu(screen.getByText("Ship the tree"));+ expect(+ await screen.findByRole("menuitem", { name: "Hand off…" }),+ ).toBeTruthy();+ await user.keyboard("{Escape}");++ fireEvent.contextMenu(screen.getByText("Write the tests"));+ await waitFor(() =>+ expect(+ screen.queryByRole("menuitem", { name: "Hand off…" }),+ ).toBeNull(),+ );+ });+// Picking a session out of the tree is browsing across spaces, not a// request to go into one — sliding into the space would take the tree the// reader is working through off the screen.diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsxindex 7a446d9ee370..9ec23f52b7e2 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx@@ -47,6 +47,7 @@ import {TooltipTrigger,} from "@posthog/quill";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";+import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";import {ChannelItemHoverCard,SpaceHoverCard,@@ -111,6 +112,7 @@ import {taskDot,} from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";+import { HandoffTaskDialog } from "@posthog/ui/features/task-detail/components/HandoffTaskDialog";import {OverflowTickerText,useOverflowTickerReveal,@@ -466,6 +468,15 @@ const SpaceTaskRow = memo(function SpaceTaskRow({(s) => s.highlightedValue === item.key,);+ const [handoffOpen, setHandoffOpen] = useState(false);+ // Only the owner may hand a task off; the API 404s it for anyone else.+ const currentUser = useCurrentUser();+ const canHandoff =+ item.kind === "task" &&+ item.task != null &&+ item.authorUser?.id != null &&+ currentUser.data?.id === item.authorUser.id;+// The tree only lists sessions, so this is always the task menu. Rename is// the one item the space's own list has and this doesn't, because it edits in// place and there is no inline editor on a row the keyboard is walking.@@ -483,8 +494,11 @@ const SpaceTaskRow = memo(function SpaceTaskRow({onAddToCommandCenter: actions.commandCenterAssigner(item.id),onTogglePin: () => actions.togglePin(item),onArchive: () => actions.archive(item),+ ...(canHandoff ? { onHandoff: () => setHandoffOpen(true) } : {}),}),- [item, spaceId, actions],+ // canHandoff rides on the currentUser query, so it belongs in deps for a+ // sign-in refresh to re-evaluate.+ [item, spaceId, actions, canHandoff],);const row = (@@ -533,6 +547,13 @@ const SpaceTaskRow = memo(function SpaceTaskRow({>{row}</ChannelItemHoverCard>+ {canHandoff && item.task ? (+ <HandoffTaskDialog+ task={item.task}+ open={handoffOpen}+ onOpenChange={setHandoffOpen}+ />+ ) : null}</TaskStatusTooltips></TaskRowContextMenu>);diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsxindex 5bf80777ff55..2fa5fb1f326c 100644--- a/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx@@ -9,6 +9,7 @@ import {SquaresFourIcon,StopCircle,TrashIcon,+ UserSwitchIcon,} from "@phosphor-icons/react";import { sessionsLabel } from "@posthog/core/sidebar/selection";import {@@ -64,6 +65,8 @@ export interface TaskRowMenuProps {/** Tasks are archived; canvases are deleted (with an undo window). */onArchive?: () => void;onDelete?: () => void;+ /** Owner-only: handing a task to a colleague needs a confirm dialog. */+ onHandoff?: () => void;}// The two menus differ only in which primitives draw them, so the item list is@@ -171,6 +174,12 @@ function TaskRowMenuItems({</MenuSubFlyout></Sub>)}+ {isTask && menu.onHandoff && (+ <Item onClick={menu.onHandoff}>+ <UserSwitchIcon size={14} />+ Hand off…+ </Item>+ )}{menu.onArchive && (<Item onClick={menu.onArchive}><ArchiveIcon size={14} />diff --git a/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsx b/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsxindex 9d04001d22da..55af3416d976 100644--- a/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/activityRows.tsx@@ -18,6 +18,7 @@ import {ProhibitIcon,QuestionIcon,SquaresFourIcon,+ UserSwitchIcon,XIcon,} from "@phosphor-icons/react";import type { CommentScope } from "@posthog/api-client/posthog-client";@@ -253,6 +254,7 @@ const EVENT_TONES: Record<ActivityEvent["kind"], BeadTone> = {pr_merged: "violet",pr_closed: "red",message_forwarded: "neutral",+ task_handed_off: "blue",};/** No glyph here is itself a circle: a ring inside a ring reads as a mistake at this size,@@ -271,6 +273,7 @@ const EVENT_ICONS: Record<ActivityEvent["kind"], ReactNode> = {pr_merged: <GitMergeIcon size={11} />,pr_closed: <ProhibitIcon size={11} />,message_forwarded: <PaperPlaneTiltIcon size={9} weight="fill" />,+ task_handed_off: <UserSwitchIcon size={11} />,};function eventLabel(@@ -355,6 +358,17 @@ function eventLabel(: "Comment thread reopened";case "message_forwarded":return "Message sent to the agent";+ case "task_handed_off": {+ const { fromDisplayName, toDisplayName } = event.payload;+ return (+ <>+ {fromDisplayName+ ? `${fromDisplayName} handed the task off to `+ : "Task handed off to "}+ <span className="font-medium">{toDisplayName}</span>+ </>+ );+ }}}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsxindex 590aabefff57..7bc4a836fa87 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx@@ -14,6 +14,8 @@ import {useArchiveCacheKeys,useArchiveTask,} from "@posthog/ui/features/archive/useArchiveTask";+import { useAuthStateValue } from "@posthog/ui/features/auth/store";+import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";import { useCommandCenterStore } from "@posthog/ui/features/command-center/commandCenterStore";import { placeTaskInCommandCenter } from "@posthog/ui/features/command-center/placeTaskInCommandCenter";import { useExternalAppAction } from "@posthog/ui/features/external-apps/useExternalAppAction";@@ -29,6 +31,7 @@ import { usePinnedTasks } from "@posthog/ui/features/sidebar/usePinnedTasks";import { useSidebarBulkActions } from "@posthog/ui/features/sidebar/useSidebarBulkActions";import { useSidebarData } from "@posthog/ui/features/sidebar/useSidebarData";import { useTaskViewed } from "@posthog/ui/features/sidebar/useTaskViewed";+import { HandoffTaskDialog } from "@posthog/ui/features/task-detail/components/HandoffTaskDialog";import { useTaskContextMenu } from "@posthog/ui/features/tasks/useTaskContextMenu";import { useRenameTask } from "@posthog/ui/features/tasks/useTaskMutations";import { useTasks } from "@posthog/ui/features/tasks/useTasks";@@ -70,6 +73,8 @@ function SidebarMenuComponent() {const { showContextMenu, editingTaskId, setEditingTaskId } =useTaskContextMenu();+ const authStatus = useAuthStateValue((s) => s.status);+ const currentUser = useCurrentUser();const { archiveTask } = useArchiveTask();const { renameTask } = useRenameTask();const { togglePin, setPinnedMany } = usePinnedTasks();@@ -117,6 +122,8 @@ function SidebarMenuComponent() {taskTitle: string;runId?: string;} | null>(null);+ const [handoffTaskId, setHandoffTaskId] = useState<string | null>(null);+ const handoffTask = handoffTaskId ? taskMap.get(handoffTaskId) : undefined;useClearSelectionOnEscape();const listAnchorRef = useRef<HTMLDivElement | null>(null);@@ -322,6 +329,14 @@ function SidebarMenuComponent() {(id) => id === taskId && taskMap.has(id),);+ // The menu mirrors the header's rule: only the owner sees Hand off.+ // Read through the full task map: the sidebar's summary rows don't+ // always carry `created_by`.+ const canHandoff =+ authStatus === "authenticated" &&+ currentUser.data?.id != null &&+ taskMap.get(taskId)?.created_by?.id === currentUser.data.id;+showContextMenu(task, e, {worktreePath: workspace?.worktreePath ?? undefined,folderPath: workspace?.folderPath ?? undefined,@@ -333,6 +348,8 @@ function SidebarMenuComponent() {runId,isInCommandCenter,hasEmptyCommandCenterCell: true,+ canHandoff,+ onHandoff: () => setHandoffTaskId(task.id),onTogglePin: () => handleTaskTogglePin(taskId),onStop: (stopTaskId, taskTitle, stopRunId) =>setStopConfirm({@@ -549,6 +566,15 @@ function SidebarMenuComponent() {onConfirm={handleConfirmArchive}onCancel={() => setArchiveConfirm(null)}/>+ {handoffTask ? (+ <HandoffTaskDialog+ task={handoffTask}+ open+ onOpenChange={(open) => {+ if (!open) setHandoffTaskId(null);+ }}+ />+ ) : null}{stopConfirm ? (<StopCloudRunDialogopendiff --git a/products/desktop/packages/ui/src/features/task-detail/components/HandoffTaskDialog.test.tsx b/products/desktop/packages/ui/src/features/task-detail/components/HandoffTaskDialog.test.tsxnew file mode 100644index 000000000000..ee9c6508b334--- /dev/null+++ b/products/desktop/packages/ui/src/features/task-detail/components/HandoffTaskDialog.test.tsx@@ -0,0 +1,153 @@+import type { Task } from "@posthog/shared/domain-types";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { render, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import type { ReactNode } from "react";+import { describe, expect, it, vi } from "vitest";++const currentUserId = vi.hoisted(() => ({ id: 1 as number | undefined }));+const mockHandoffMutate = vi.hoisted(() => vi.fn());+const mockMembers = vi.hoisted(() => ({+ members: [+ { id: 1, uuid: "u-1", email: "[email protected]", first_name: "Owner" },+ { id: 2, uuid: "u-2", email: "[email protected]", first_name: "Col" },+ { id: 3, uuid: "u-3", email: "[email protected]", first_name: "Pepper" },+ ],+}));+const mockChannels = vi.hoisted(() => ({+ channels: [] as Array<{ id: string; channelType: string }>,+}));++vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({+ useCurrentUser: () => ({ data: { id: currentUserId.id } }),+}));+vi.mock("@posthog/ui/features/canvas/hooks/useOrgMembers", () => ({+ useOrgMembers: () => ({ members: mockMembers.members, isLoading: false }),+}));+vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({+ useChannels: () => ({ channels: mockChannels.channels }),+}));+vi.mock("@posthog/ui/features/tasks/useTaskMutations", () => ({+ useHandoffTask: () => ({ mutate: mockHandoffMutate, isPending: false }),+}));+vi.mock("../../../primitives/toast", () => ({+ toast: { success: vi.fn(), error: vi.fn() },+}));++import { HandoffTaskDialog } from "./HandoffTaskDialog";++function createTask(overrides: Partial<Task> = {}): Task {+ return {+ id: "task-1",+ task_number: 1,+ slug: "task-1",+ title: "Fix the thing",+ description: "",+ created_at: "2026-05-28T00:00:00.000Z",+ updated_at: "2026-05-28T00:00:00.000Z",+ origin_product: "user_created",+ created_by: { id: 1, uuid: "u-1", email: "[email protected]" },+ channel: null,+ ...overrides,+ };+}++function renderDialog(task: Task, open = true) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+ return render(+ <HandoffTaskDialog task={task} open={open} onOpenChange={() => {}} />,+ { wrapper },+ );+}++describe("HandoffTaskDialog", () => {+ it("keeps the confirm disabled until a person is picked", async () => {+ // Only the recipient can undo a handoff, so a confirm with no pick must not fire.+ mockHandoffMutate.mockClear();+ const user = userEvent.setup();+ renderDialog(createTask());++ const dialog = await screen.findByRole("alertdialog");+ expect(+ within(dialog).getByRole("button", { name: "Hand off" }),+ ).toHaveAttribute("aria-disabled", "true");+ await user.keyboard("{Enter}");+ expect(mockHandoffMutate).not.toHaveBeenCalled();+ });++ it("explains that a personal-space task moves to the recipient", async () => {+ renderDialog(createTask({ channel: null }));++ const dialog = await screen.findByRole("alertdialog");+ expect(+ within(dialog).getByText(/moves into their personal space/i),+ ).toBeInTheDocument();+ expect(+ within(dialog).getByText(/only they can hand it back/i),+ ).toBeInTheDocument();+ });++ it("filters people by name or email as you type in the field", async () => {+ const user = userEvent.setup();+ renderDialog(createTask());+ await screen.findByRole("alertdialog");++ await user.click(screen.getByRole("combobox", { name: /hand off to/i }));+ expect(await screen.findByText("Col")).toBeInTheDocument();+ await user.keyboard("pepp");++ expect(await screen.findByText("Pepper")).toBeInTheDocument();+ expect(screen.queryByText("Col")).not.toBeInTheDocument();+ });++ it("does not offer the current owner as a handoff target", async () => {+ const user = userEvent.setup();+ renderDialog(createTask());+ await screen.findByRole("alertdialog");++ await user.click(screen.getByRole("combobox", { name: /hand off to/i }));+ expect(await screen.findByText("Col")).toBeInTheDocument();+ expect(screen.queryByText("[email protected]")).not.toBeInTheDocument();+ });++ it("shows the picked person in the field", async () => {+ const user = userEvent.setup();+ renderDialog(createTask());+ await screen.findByRole("alertdialog");++ await user.click(screen.getByRole("combobox", { name: /hand off to/i }));+ await user.click(await screen.findByText("Col"));++ expect(screen.getByRole("combobox", { name: /hand off to/i })).toHaveValue(+ "Col",+ );+ });++ it("hands off to the selected member only after the acknowledge checkbox", async () => {+ mockHandoffMutate.mockClear();+ const user = userEvent.setup();+ renderDialog(createTask());+ const dialog = await screen.findByRole("alertdialog");++ await user.click(screen.getByRole("combobox", { name: /hand off to/i }));+ await user.click(await screen.findByText("Col"));+ // A pick alone isn't enough: the checkbox is what says they really read it.+ expect(+ within(dialog).getByRole("button", { name: "Hand off" }),+ ).toHaveAttribute("aria-disabled", "true");+ await user.click(+ within(dialog).getByRole("checkbox", { name: /can't undo this/i }),+ );+ await user.click(within(dialog).getByRole("button", { name: "Hand off" }));++ expect(mockHandoffMutate).toHaveBeenCalledWith(+ { taskId: "task-1", userId: 2 },+ expect.objectContaining({ onSuccess: expect.any(Function) }),+ );+ });+});diff --git a/products/desktop/packages/ui/src/features/task-detail/components/HandoffTaskDialog.tsx b/products/desktop/packages/ui/src/features/task-detail/components/HandoffTaskDialog.tsxnew file mode 100644index 000000000000..8a5f35f539d1--- /dev/null+++ b/products/desktop/packages/ui/src/features/task-detail/components/HandoffTaskDialog.tsx@@ -0,0 +1,245 @@+import {+ AlertDialog,+ AlertDialogClose,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ Button,+ Checkbox,+ Combobox,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxItem,+ ComboboxList,+ DialogBody,+ Field,+ FieldLabel,+ InputGroupAddon,+} from "@posthog/quill";+import type { Task, UserBasic } from "@posthog/shared/domain-types";+import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";+import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";+import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";+import { useOrgMembers } from "@posthog/ui/features/canvas/hooks/useOrgMembers";+import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";+import { useHandoffTask } from "@posthog/ui/features/tasks/useTaskMutations";+import { useMemo, useState } from "react";+import { toast } from "../../../primitives/toast";+import { logger } from "../../../shell/logger";++const log = logger.scope("task-detail");++interface PersonItem {+ id: string;+ label: string;+ member: UserBasic;+}++/**+ * The confirm step of a handoff. The field is the search box: clicking it+ * opens the roster, typing narrows it. The commit stays locked until a+ * colleague is picked AND the acknowledge box is checked. Only the recipient can reverse a+ * handoff, so the menu item that opens this carries an ellipsis.+ */+export function HandoffTaskDialog({+ task,+ open,+ onOpenChange,+}: {+ task: Task;+ open: boolean;+ onOpenChange: (open: boolean) => void;+}) {+ const currentUser = useCurrentUser();+ const { mutate: handoffTask, isPending } = useHandoffTask();+ const [selectedId, setSelectedId] = useState<string | null>(null);+ const [acknowledged, setAcknowledged] = useState(false);++ const { members, isLoading: membersLoading } = useOrgMembers();+ const { channels } = useChannels();+ // A personal-space task moves into the recipient's personal space on handoff,+ // so the warning has to cover losing access, not just control.+ const movesToTheRecipient =+ !task.channel ||+ channels.find((channel) => channel.id === task.channel)?.channelType ===+ "personal";++ // Same reset rhythm as other dialogs: opening starts fresh. Adjusted during+ // render, not in an effect, because an effect would commit a frame of the+ // stale state first.+ const [wasOpen, setWasOpen] = useState(open);+ if (open !== wasOpen) {+ setWasOpen(open);+ if (open) {+ setSelectedId(null);+ setAcknowledged(false);+ }+ }++ // ids as values: the members query repolls and rebuilds its objects, so a+ // selected object stops matching the list by identity and the combobox+ // silently drops the selection. Ids compare by value.+ const items = useMemo<PersonItem[]>(+ () =>+ members.flatMap((member) =>+ member.id === currentUser.data?.id+ ? []+ : [+ {+ id: String(member.id),+ label: userDisplayName(member),+ member,+ },+ ],+ ),+ [members, currentUser.data?.id],+ );+ const byId = useMemo(+ () => new Map(items.map((item) => [item.id, item])),+ [items],+ );+ const itemIds = useMemo(() => items.map((item) => item.id), [items]);+ const selected = selectedId ? byId.get(selectedId) : undefined;+ const canHandOff = selected !== undefined && acknowledged;++ const handleConfirm = () => {+ if (!selected) return;+ const name = userDisplayName(selected.member);+ handoffTask(+ { taskId: task.id, userId: selected.member.id },+ {+ onSuccess: () => {+ toast.success(`Handed "${task.title}" off to ${name}`);+ onOpenChange(false);+ },+ onError: (error) => {+ log.error("Failed to hand off task", error);+ toast.error("Couldn't hand off the task. Try again.");+ },+ },+ );+ };++ return (+ <AlertDialog+ open={open}+ onOpenChange={(next) => {+ // Hold the dialog while the request is in flight; closing mid-flight+ // would look like a cancel while the handoff still goes through.+ if (!next && isPending) return;+ onOpenChange(next);+ }}+ >+ <AlertDialogContent className="max-w-md">+ <AlertDialogHeader>+ <AlertDialogTitle>Hand off task</AlertDialogTitle>+ <AlertDialogDescription render={<div />}>+ <p>+ <span className="font-medium text-foreground">{task.title}</span>{" "}+ goes to the person you pick.+ </p>+ <p>They steer it and get its notifications.</p>+ {movesToTheRecipient ? (+ <p>It moves into their personal space, so you lose access.</p>+ ) : null}+ <p>Only they can hand it back.</p>+ </AlertDialogDescription>+ </AlertDialogHeader>+ <DialogBody viewportClassName="flex flex-col gap-3 px-4 pb-3">+ <Field>+ <FieldLabel htmlFor="handoff-person">Hand off to</FieldLabel>+ <Combobox<string>+ items={itemIds}+ value={selectedId}+ onValueChange={(value) => setSelectedId(value)}+ itemToStringLabel={(id) => byId.get(id)?.label ?? ""}+ // Name or email substring, so searching by handle works even+ // when the roster shows full names.+ filter={(id, query) => {+ const needle = query.trim().toLowerCase();+ if (!needle) return true;+ const item = byId.get(id);+ if (!item) return false;+ return (+ item.label.toLowerCase().includes(needle) ||+ (item.member.email ?? "").toLowerCase().includes(needle)+ );+ }}+ autoHighlight+ disabled={isPending}+ >+ <ComboboxInput+ id="handoff-person"+ placeholder="Search people…"+ disabled={isPending}+ className="w-full"+ >+ {selected ? (+ <InputGroupAddon align="inline-start">+ <UserAvatar user={selected.member} size="xs" />+ </InputGroupAddon>+ ) : null}+ </ComboboxInput>+ <ComboboxContent className="w-[var(--anchor-width)] min-w-[240px]">+ <ComboboxEmpty>+ {membersLoading ? "Loading people…" : "No people match."}+ </ComboboxEmpty>+ <ComboboxList className="max-h-[min(18rem,calc(var(--available-height,18rem)-2rem))]">+ {(itemId: string) => {+ const item = byId.get(itemId);+ if (!item) return null;+ return (+ <ComboboxItem key={item.id} value={item.id}>+ <UserAvatar+ user={item.member}+ size="xs"+ className="shrink-0"+ />+ <span className="min-w-0 truncate">{item.label}</span>+ <span className="ml-auto shrink-0 truncate text-muted-foreground text-xs">+ {item.member.email}+ </span>+ </ComboboxItem>+ );+ }}+ </ComboboxList>+ </ComboboxContent>+ </Combobox>+ </Field>+ <Field orientation="horizontal" className="items-center gap-2">+ <Checkbox+ id="handoff-acknowledge"+ checked={acknowledged}+ onCheckedChange={(checked) => setAcknowledged(checked === true)}+ disabled={isPending}+ />+ <FieldLabel htmlFor="handoff-acknowledge" className="font-normal">+ I understand I can't undo this myself.+ </FieldLabel>+ </Field>+ </DialogBody>+ <AlertDialogFooter>+ <AlertDialogClose+ render={+ <Button variant="outline" size="sm" disabled={isPending}>+ Cancel+ </Button>+ }+ />+ <Button+ variant="primary"+ size="sm"+ disabled={!canHandOff}+ loading={isPending}+ onClick={handleConfirm}+ >+ Hand off+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}diff --git a/products/desktop/packages/ui/src/features/tasks/useTaskContextMenu.ts b/products/desktop/packages/ui/src/features/tasks/useTaskContextMenu.tsindex ee4b8c858946..af45f6627938 100644--- a/products/desktop/packages/ui/src/features/tasks/useTaskContextMenu.ts+++ b/products/desktop/packages/ui/src/features/tasks/useTaskContextMenu.ts@@ -50,7 +50,9 @@ export function useTaskContextMenu() {isInCommandCenter?: boolean;hasEmptyCommandCenterCell?: boolean;showArchivePrior?: boolean;+ canHandoff?: boolean;onTogglePin?: () => void;+ onHandoff?: () => void;onStop?: (taskId: string, taskTitle: string, runId?: string) => void;onArchive?: (taskId: string) => void;onArchivePrior?: (taskId: string) => void;@@ -70,7 +72,9 @@ export function useTaskContextMenu() {isInCommandCenter,hasEmptyCommandCenterCell,showArchivePrior,+ canHandoff,onTogglePin,+ onHandoff,onStop,onArchive,onArchivePrior,@@ -88,6 +92,7 @@ export function useTaskContextMenu() {isInCommandCenter,hasEmptyCommandCenterCell,showArchivePrior,+ canHandoff,channels: channels.map(({ id, name, channelType, starred }) => ({id,name,@@ -139,6 +144,10 @@ export function useTaskContextMenu() {case "add-to-command-center":onAddToCommandCenter?.();break;+ case "handoff":+ // The dialog lives with the caller; the hook can't own a modal.+ onHandoff?.();+ break;case "file-to-channel":try {await fileTask(intent.channelId, task.id);diff --git a/products/desktop/packages/ui/src/features/tasks/useTaskMutations.test.tsx b/products/desktop/packages/ui/src/features/tasks/useTaskMutations.test.tsxindex 7d3855ea40ae..eb8b26968f4d 100644--- a/products/desktop/packages/ui/src/features/tasks/useTaskMutations.test.tsx+++ b/products/desktop/packages/ui/src/features/tasks/useTaskMutations.test.tsx@@ -1,10 +1,14 @@import type { Schemas } from "@posthog/api-client";import type { Task } from "@posthog/shared/domain-types";-import { channelFeedQueryKey } from "@posthog/ui/features/canvas/hooks/useChannelFeed";+import {+ channelFeedQueryKey,+ channelFeedQueryRoot,+} from "@posthog/ui/features/canvas/hooks/useChannelFeed";import {type SpaceTaskPage,spaceTreeTasksQueryRoot,} from "@posthog/ui/features/canvas/hooks/useRecentSpaceTasks";+import { TASK_CHANNELS_QUERY_KEY } from "@posthog/ui/features/canvas/hooks/useTaskChannels";import { taskFeedResultsQueryKey } from "@posthog/ui/features/canvas/hooks/useTaskFeedResults";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { renderHook, waitFor } from "@testing-library/react";@@ -12,7 +16,11 @@ import { act, type ReactNode } from "react";import { beforeEach, describe, expect, it, vi } from "vitest";const mockUpdateTask = vi.hoisted(() => vi.fn());-const mockClient = vi.hoisted(() => ({ updateTask: mockUpdateTask }));+const mockHandoffTask = vi.hoisted(() => vi.fn());+const mockClient = vi.hoisted(() => ({+ updateTask: mockUpdateTask,+ handoffTask: mockHandoffTask,+}));const mockUpdateSessionTaskTitle = vi.hoisted(() => vi.fn());vi.mock("@posthog/ui/features/auth/authClient", () => ({@@ -26,7 +34,7 @@ vi.mock("@posthog/di/react", () => ({}));import { taskKeys } from "./taskKeys";-import { useRenameTask } from "./useTaskMutations";+import { useHandoffTask, useRenameTask } from "./useTaskMutations";const TASK_ID = "task-1";const OTHER_TASK_ID = "task-2";@@ -365,3 +373,39 @@ describe("useRenameTask", () => {);});});++describe("useHandoffTask", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("forwards the recipient id and invalidates the views a handoff redraws", async () => {+ mockHandoffTask.mockResolvedValue(createTask({ created_by: null }));+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ });+ const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries");+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+ const { result } = renderHook(() => useHandoffTask(), { wrapper });++ await act(async () => {+ await result.current.mutateAsync({ taskId: TASK_ID, userId: 7 });+ });++ expect(mockHandoffTask).toHaveBeenCalledWith(TASK_ID, 7);+ // Skipping these would leave the old owner staring at a task (and a channel)+ // the backend already moved to the recipient's space.+ const invalidatedKeys = invalidateSpy.mock.calls.map(+ ([options]) => options?.queryKey,+ );+ expect(invalidatedKeys).toContainEqual(taskKeys.lists());+ expect(invalidatedKeys).toContainEqual(taskKeys.detail(TASK_ID));+ expect(invalidatedKeys).toContainEqual(TASK_CHANNELS_QUERY_KEY);+ expect(invalidatedKeys).toContainEqual(channelFeedQueryRoot);+ });+});diff --git a/products/desktop/packages/ui/src/features/tasks/useTaskMutations.ts b/products/desktop/packages/ui/src/features/tasks/useTaskMutations.tsindex cb40821be851..ca83d508ba62 100644--- a/products/desktop/packages/ui/src/features/tasks/useTaskMutations.ts+++ b/products/desktop/packages/ui/src/features/tasks/useTaskMutations.ts@@ -22,6 +22,7 @@ import {type SpaceTaskPage,spaceTreeTasksQueryRoot,} from "@posthog/ui/features/canvas/hooks/useRecentSpaceTasks";+import { TASK_CHANNELS_QUERY_KEY } from "@posthog/ui/features/canvas/hooks/useTaskChannels";import { taskFeedResultsQueryRoot } from "@posthog/ui/features/canvas/hooks/useTaskFeedResults";import { taskKeys } from "@posthog/ui/features/tasks/taskKeys";import { useAuthenticatedMutation } from "@posthog/ui/hooks/useAuthenticatedMutation";@@ -61,6 +62,32 @@ export function useUpdateTask() {);}+/**+ * Hand a task off to a colleague: the backend makes them the owner, moves a+ * private-space task into the recipient's private space, and announces the+ * handoff in the task's thread. The next refresh may drop the task from the+ * requester's own lists, so nothing here is seeded optimistically.+ */+export function useHandoffTask() {+ const queryClient = useQueryClient();++ return useAuthenticatedMutation(+ (client, { taskId, userId }: { taskId: string; userId: number }) =>+ client.handoffTask(taskId, userId),+ {+ onSuccess: (_, { taskId }) => {+ queryClient.invalidateQueries({ queryKey: taskKeys.lists() });+ queryClient.invalidateQueries({ queryKey: taskKeys.detail(taskId) });+ queryClient.invalidateQueries({ queryKey: taskKeys.allSummaries() });+ queryClient.invalidateQueries({ queryKey: channelFeedQueryRoot });+ // A recipient's private channel may be created by the handoff, and the+ // task's channel can change (private space moves to the recipient's).+ queryClient.invalidateQueries({ queryKey: TASK_CHANNELS_QUERY_KEY });+ },+ },+ );+}+export function useRenameTask() {const queryClient = useQueryClient();const updateTask = useUpdateTask();