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.

feat(desktop): add task feed actions (#85357)

Shy Alter95007183c9c1
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.test.tsx
index ad8644ca0b29..a7e67a290a6c 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.test.tsx
@@ -1,6 +1,6 @@
import type { Task } from "@posthog/shared/domain-types";
import { Theme } from "@radix-ui/themes";
-import { render, screen } from "@testing-library/react";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -23,15 +23,73 @@ vi.mock("@tanstack/react-router", () => ({
</a>
),
}));
+const { channelTaskData } = vi.hoisted(() => ({
+ channelTaskData: { current: undefined as unknown },
+}));
vi.mock("@posthog/ui/features/canvas/hooks/useChannelTaskData", () => ({
- useChannelTaskData: () => undefined,
+ useChannelTaskData: () => channelTaskData.current,
}));
vi.mock("@posthog/ui/features/sidebar/useTaskPrStatus", () => ({
useTaskPrStatus: () => ({ prState: null }),
}));
+vi.mock("@posthog/ui/features/canvas/hooks/useTaskThread", () => ({
+ useTaskThread: () => ({ messages: [] }),
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useMarkTaskActivityRead", () => ({
+ useMarkTaskActivityRead: () => ({ mutate: vi.fn() }),
+}));
+vi.mock("@posthog/ui/features/sidebar/usePinnedTasks", () => ({
+ usePinnedTasks: () => ({ togglePin: vi.fn() }),
+}));
+const { archiveTask } = vi.hoisted(() => ({ archiveTask: vi.fn() }));
+vi.mock("@posthog/ui/features/archive/useArchiveTask", () => ({
+ useArchiveTask: () => ({ archiveTask }),
+}));
+vi.mock(
+ "@posthog/ui/features/sidebar/components/ArchiveRunningTaskDialog",
+ () => ({
+ ArchiveRunningTaskDialog: ({ open }: { open: boolean }) =>
+ open ? <div>Archive running task?</div> : null,
+ }),
+);
+vi.mock("@posthog/ui/features/sessions/components/StopCloudRunDialog", () => ({
+ StopCloudRunDialog: ({ open, title }: { open: boolean; title: string }) =>
+ open ? <div>{title}</div> : null,
+}));
+const { archivedTaskIds } = vi.hoisted(() => ({
+ archivedTaskIds: { current: new Set<string>() },
+}));
+vi.mock("@posthog/ui/features/archive/useArchivedTaskIds", () => ({
+ useArchivedTaskIds: () => archivedTaskIds.current,
+}));
+vi.mock("@posthog/ui/features/tasks/useTaskMutations", () => ({
+ useRenameTask: () => ({ renameTask: vi.fn() }),
+}));
+vi.mock("@posthog/ui/features/command-center/commandCenterStore", () => ({
+ useCommandCenterStore: (
+ selector: (state: { cells: (string | null)[] }) => unknown,
+ ) => selector({ cells: [null] }),
+}));
+vi.mock("@posthog/ui/features/command-center/placeTaskInCommandCenter", () => ({
+ placeTaskInCommandCenter: vi.fn(),
+}));
+vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({
+ useFeatureFlag: () => true,
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({
+ useChannels: () => ({
+ channels: [{ id: "channel-1", name: "Personal space", starred: false }],
+ }),
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useFileTaskToChannel", () => ({
+ useFileTaskToChannel: () => vi.fn(),
+}));
vi.mock("@posthog/ui/features/browser-tabs/TaskTabIcon", () => ({
TaskTabIcon: () => <span />,
}));
+vi.mock("@posthog/ui/primitives/hooks/useInView", () => ({
+ useInView: () => [vi.fn(), true],
+}));
import { ChannelFeedView, ExpandablePrompt, TaskCard } from "./ChannelFeedView";
import { mergeFeedEntries, stripContextBlocks } from "./channelFeedDisplay";
@@ -56,6 +114,9 @@ const task = {
afterEach(() => {
vi.restoreAllMocks();
+ archivedTaskIds.current = new Set<string>();
+ archiveTask.mockReset();
+ channelTaskData.current = undefined;
});
// ExpandablePrompt measures how the prompt wraps to decide where to cut and
@@ -98,6 +159,164 @@ describe("ChannelFeedView", () => {
expect(screen.getByRole("status")).toHaveTextContent("Loading tasks");
});
+ it("hides archived tasks from the feed", () => {
+ const archived = {
+ ...task,
+ id: "task-archived",
+ title: "Already archived",
+ } satisfies Task;
+ archivedTaskIds.current = new Set([archived.id]);
+ render(
+ <Theme>
+ <ChannelFeedView
+ channelId="channel-1"
+ tasks={[task, archived]}
+ isLoading={false}
+ onOpenTask={vi.fn()}
+ onOpenThread={vi.fn()}
+ />
+ </Theme>,
+ );
+
+ expect(screen.queryByText("Already archived")).not.toBeInTheDocument();
+ expect(screen.getByText(task.title)).toBeInTheDocument();
+ });
+
+ it.each([
+ {
+ name: "options menu",
+ open: async () => {
+ fireEvent.mouseDown(
+ screen.getByLabelText(`Options for ${task.title}`),
+ { button: 0 },
+ );
+ },
+ },
+ {
+ name: "context menu",
+ open: async () => {
+ fireEvent.contextMenu(screen.getByText(task.title));
+ },
+ },
+ ])("offers every task action from the $name", async ({ open }) => {
+ render(
+ <Theme>
+ <ChannelFeedView
+ channelId="channel-1"
+ tasks={[task]}
+ isLoading={false}
+ onOpenTask={vi.fn()}
+ onOpenThread={vi.fn()}
+ />
+ </Theme>,
+ );
+
+ await open();
+
+ await waitFor(() => expect(screen.getByText("Pin")).toBeInTheDocument());
+ for (const label of [
+ "Pin",
+ "Rename",
+ "Add to Command Center",
+ "File to…",
+ "Archive",
+ ]) {
+ expect(screen.getByText(label)).toBeInTheDocument();
+ }
+ });
+
+ it("closes the options menu when its trigger is pressed again", async () => {
+ render(
+ <Theme>
+ <ChannelFeedView
+ channelId="channel-1"
+ tasks={[task]}
+ isLoading={false}
+ onOpenTask={vi.fn()}
+ onOpenThread={vi.fn()}
+ />
+ </Theme>,
+ );
+
+ const trigger = screen.getByLabelText(`Options for ${task.title}`);
+ fireEvent.mouseDown(trigger, { button: 0 });
+ await waitFor(() => expect(screen.getByText("Pin")).toBeInTheDocument());
+
+ fireEvent.mouseDown(trigger, { button: 0 });
+ await waitFor(() =>
+ expect(screen.queryByText("Pin")).not.toBeInTheDocument(),
+ );
+ });
+
+ it("opens the archive confirmation for an active task", async () => {
+ channelTaskData.current = {
+ cloudPrUrl: null,
+ isGenerating: true,
+ isPinned: false,
+ needsPermission: false,
+ taskRunEnvironment: "cloud",
+ taskRunStatus: "in_progress",
+ };
+ const user = userEvent.setup();
+ render(
+ <Theme>
+ <ChannelFeedView
+ channelId="channel-1"
+ tasks={[task]}
+ isLoading={false}
+ onOpenTask={vi.fn()}
+ onOpenThread={vi.fn()}
+ />
+ </Theme>,
+ );
+
+ fireEvent.mouseDown(screen.getByLabelText(`Options for ${task.title}`), {
+ button: 0,
+ });
+ await waitFor(() =>
+ expect(screen.getByText("Archive")).toBeInTheDocument(),
+ );
+
+ await user.click(screen.getByText("Archive"));
+
+ expect(screen.getByText("Archive running task?")).toBeInTheDocument();
+ expect(archiveTask).not.toHaveBeenCalled();
+ });
+
+ it("opens the stop confirmation for an active cloud task", async () => {
+ channelTaskData.current = {
+ cloudPrUrl: null,
+ isGenerating: true,
+ isPinned: false,
+ needsPermission: false,
+ taskRunEnvironment: "cloud",
+ taskRunStatus: "in_progress",
+ };
+ const user = userEvent.setup();
+ render(
+ <Theme>
+ <ChannelFeedView
+ channelId="channel-1"
+ tasks={[task]}
+ isLoading={false}
+ onOpenTask={vi.fn()}
+ onOpenThread={vi.fn()}
+ />
+ </Theme>,
+ );
+
+ fireEvent.mouseDown(screen.getByLabelText(`Options for ${task.title}`), {
+ button: 0,
+ });
+ await waitFor(() =>
+ expect(screen.getByText("Stop task")).toBeInTheDocument(),
+ );
+
+ await user.click(screen.getByText("Stop task"));
+
+ expect(screen.getByText(`Stop "${task.title}"?`)).toBeInTheDocument();
+ });
+
it("reports when its task is opened", async () => {
const user = userEvent.setup();
const onOpen = vi.fn();
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx
index 300adcbbe23b..a0115d10879b 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelFeedView.tsx
@@ -16,12 +16,14 @@ import { buildThreadTimeline } from "@posthog/core/canvas/threadTimeline";
import type { PrCheck } from "@posthog/core/git/router-schemas";
import { parsePrNumber } from "@posthog/core/git-interaction/prStatus";
import { xmlToPlainText } from "@posthog/core/message-editor/content";
+import { isTaskActivelyRunning } from "@posthog/core/sidebar/taskRunning";
import {
AvatarGroup,
Badge,
Card,
CardContent,
cn,
+ Input,
Popover,
PopoverContent,
PopoverTrigger,
@@ -38,6 +40,8 @@ import type {
TaskRunStatus,
UserBasic,
} from "@posthog/shared/domain-types";
+import { useArchivedTaskIds } from "@posthog/ui/features/archive/useArchivedTaskIds";
+import { useArchiveTask } from "@posthog/ui/features/archive/useArchiveTask";
import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";
import { TaskTabIcon } from "@posthog/ui/features/browser-tabs/TaskTabIcon";
import {
@@ -45,6 +49,11 @@ import {
mergeFeedEntries,
stripContextBlocks,
} from "@posthog/ui/features/canvas/components/channelFeedDisplay";
+import {
+ TaskRowContextMenu,
+ TaskRowDropdownMenu,
+ type TaskRowMenuProps,
+} from "@posthog/ui/features/canvas/components/TaskRowMenu";
import { buildRows } from "@posthog/ui/features/canvas/components/taskArtifactRows";
import type { ChannelFeedSystemMessage } from "@posthog/ui/features/canvas/hooks/useChannelFeedMessages";
import { useChannelTaskData } from "@posthog/ui/features/canvas/hooks/useChannelTaskData";
@@ -54,17 +63,24 @@ import type { ThreadPanelTab } from "@posthog/ui/features/canvas/stores/threadPa
import { taskCardNavigation } from "@posthog/ui/features/canvas/taskCardNavigation";
import { canvasArtifactOpenHandler } from "@posthog/ui/features/canvas/utils/canvasArtifactNavigation";
import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";
+import { useCommandCenterStore } from "@posthog/ui/features/command-center/commandCenterStore";
+import { placeTaskInCommandCenter } from "@posthog/ui/features/command-center/placeTaskInCommandCenter";
import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";
import { usePrArtifact } from "@posthog/ui/features/git-interaction/usePrArtifact";
import { usePrTitles } from "@posthog/ui/features/git-interaction/usePrDetails";
import { usePanelLayoutStore } from "@posthog/ui/features/panels/panelLayoutStore";
import { usePrChecks } from "@posthog/ui/features/pr-review/usePrChecks";
+import { StopCloudRunDialog } from "@posthog/ui/features/sessions/components/StopCloudRunDialog";
+import { ArchiveRunningTaskDialog } from "@posthog/ui/features/sidebar/components/ArchiveRunningTaskDialog";
+import { usePinnedTasks } from "@posthog/ui/features/sidebar/usePinnedTasks";
import {
type SidebarPrState,
useTaskPrStatus,
} from "@posthog/ui/features/sidebar/useTaskPrStatus";
+import { useRenameTask } from "@posthog/ui/features/tasks/useTaskMutations";
import { FileIcon } from "@posthog/ui/primitives/FileIcon";
import { useInView } from "@posthog/ui/primitives/hooks/useInView";
+import { toast } from "@posthog/ui/primitives/toast";
import { openExternalUrl } from "@posthog/ui/shell/openExternal";
import { parseHttpsUrl } from "@posthog/ui/utils/posthogLinks";
import { Text } from "@radix-ui/themes";
@@ -709,6 +725,17 @@ const FeedItem = memo(function FeedItem({
const { mutate: markTasksRead } = useMarkTaskActivityRead();
const statusDisplay = useTaskStatusDisplay(task);
const taskData = useChannelTaskData(task);
+ const { togglePin } = usePinnedTasks();
+ const { archiveTask } = useArchiveTask({ navigateSpace: "website" });
+ const { renameTask } = useRenameTask();
+ const commandCenterCells = useCommandCenterStore((state) => state.cells);
+ const [editingTitle, setEditingTitle] = useState(false);
+ const [titleValue, setTitleValue] = useState(task.title);
+ const [isSavingTitle, setIsSavingTitle] = useState(false);
+ const [archiveConfirmOpen, setArchiveConfirmOpen] = useState(false);
+ const [stopConfirmOpen, setStopConfirmOpen] = useState(false);
+ const isActive = taskData ? isTaskActivelyRunning(taskData) : false;
+ const canStop = taskData?.taskRunEnvironment === "cloud" && isActive;
const starter = channelTaskStarter(task);
const prompt = useMemo(
() => stripContextBlocks(xmlToPlainText(task.description ?? "")),
@@ -768,6 +795,79 @@ const FeedItem = memo(function FeedItem({
markRead();
onOpenTask(task);
}, [markRead, onOpenTask, task]);
+ const beginTitleEdit = useCallback(() => {
+ setTitleValue(task.title);
+ setEditingTitle(true);
+ }, [task.title]);
+ const saveTitle = useCallback(() => {
+ if (isSavingTitle) return;
+ const newTitle = titleValue.trim();
+ if (!newTitle || newTitle === task.title) {
+ setEditingTitle(false);
+ return;
+ }
+ setIsSavingTitle(true);
+ void renameTask({
+ taskId: task.id,
+ currentTitle: task.title,
+ newTitle,
+ })
+ .then(() => setEditingTitle(false))
+ .catch(() => {
+ toast.error("Couldn't rename task", { description: "Try again." });
+ })
+ .finally(() => setIsSavingTitle(false));
+ }, [isSavingTitle, renameTask, task.id, task.title, titleValue]);
+ const runArchive = useCallback(async () => {
+ try {
+ await archiveTask({ taskId: task.id });
+ } catch (error) {
+ toast.error("Couldn't archive task", { description: "Try again." });
+ throw error;
+ }
+ }, [archiveTask, task.id]);
+ const archiveTaskFromFeed = useCallback(() => {
+ if (isActive) {
+ setArchiveConfirmOpen(true);
+ return;
+ }
+ void runArchive().catch(() => undefined);
+ }, [isActive, runArchive]);
+ const confirmArchive = useCallback(async () => {
+ await runArchive();
+ setArchiveConfirmOpen(false);
+ }, [runArchive]);
+ const menu: TaskRowMenuProps = useMemo(
+ () => ({
+ kind: "task",
+ id: task.id,
+ title: task.title,
+ isPinned: taskData?.isPinned ?? false,
+ channelId: task.channel ?? undefined,
+ onAddToCommandCenter: commandCenterCells.includes(task.id)
+ ? undefined
+ : () => placeTaskInCommandCenter(task.id, task.title),
+ onRename: beginTitleEdit,
+ onStop: canStop ? () => setStopConfirmOpen(true) : undefined,
+ onTogglePin: () => {
+ void togglePin(task.id).catch(() => {
+ toast.error("Couldn't update pin", { description: "Try again." });
+ });
+ },
+ onArchive: archiveTaskFromFeed,
+ }),
+ [
+ archiveTaskFromFeed,
+ beginTitleEdit,
+ canStop,
+ commandCenterCells,
+ task.channel,
+ task.id,
+ task.title,
+ taskData?.isPinned,
+ togglePin,
+ ],
+ );
// A chip opens its artifact directly: canvases navigate to the canvas, files
// open as a tab in the task view (the tab is staged in the layout store, then
// the task view is opened to show it). Anything unopenable falls back to the
@@ -803,193 +903,242 @@ const FeedItem = memo(function FeedItem({
const visiblePrCount = prUrls.length >= 5 ? 1 : 2;
return (
- <Card
- size="sm"
- role="button"
- tabIndex={0}
- className="mx-auto my-1.5 w-full max-w-[660px] cursor-pointer rounded-xl bg-(--gray-2) py-0 transition-colors hover:border-(--gray-7) hover:bg-(--gray-3)"
- onClick={() => {
- markRead();
- onOpenThread(task);
- }}
- onKeyDown={(event) => {
- // Only when the card itself has focus: descendant buttons (title, PR
- // and comment chips, the prompt toggle) bubble their key events here,
- // and preventDefault would swallow their own Enter/Space activation.
- if (event.target !== event.currentTarget) return;
- if (event.key === "Enter" || event.key === " ") {
- event.preventDefault();
+ <TaskRowContextMenu menu={menu}>
+ <Card
+ size="sm"
+ role="button"
+ tabIndex={0}
+ className="mx-auto my-1.5 w-full max-w-[660px] cursor-pointer rounded-xl bg-(--gray-2) py-0 transition-colors hover:border-(--gray-7) hover:bg-(--gray-3)"
+ onClick={(event) => {
+ if (
+ event.target instanceof Element &&
+ event.target.closest('[data-slot="dropdown-menu-trigger"]')
+ ) {
+ return;
+ }
markRead();
onOpenThread(task);
- }
- }}
- >
- <CardContent className="flex flex-col px-4 pt-3.5 pb-3">
- <div className="flex items-center gap-3">
- <div className="flex min-w-0 flex-1 items-baseline gap-1.5">
- <button
- type="button"
- className="min-w-0 truncate text-left font-semibold text-sm leading-snug"
- onClick={(event) => {
- event.stopPropagation();
- openTask();
- }}
- >
- {task.title || "Untitled task"}
- </button>
- <span className="shrink-0 text-(--gray-9) text-xs">
- · {formatRelativeTimeShort(task.updated_at)}
- </span>
- </div>
- <TaskStatusBadge display={statusDisplay} />
- </div>
- <div className="mt-1.5 text-(--gray-9) text-xs leading-normal">
- <ExpandablePrompt
- lines={2}
- expandedContent={
- <div className="whitespace-normal text-(--gray-11) [&_pre]:my-1.5">
- <MarkdownRenderer content={prompt} />
- </div>
- }
- >
- {prompt || "A new task was started"}
- </ExpandablePrompt>
- </div>
- <div className="mt-3 flex flex-wrap items-center gap-1.5">
- {showRepo && task.repository && (
- <span
- className={cn(CHIP_CLASS, "border-transparent bg-transparent")}
- >
- <GitBranchIcon size={12} />
- {task.repository}
- </span>
- )}
- {prUrls.slice(0, visiblePrCount).map((url) => (
- <PrChip key={url} url={url} />
- ))}
- {prUrls.length > visiblePrCount && (
- <OverflowChip
- label={`+${prUrls.length - visiblePrCount} ${
- prUrls.length - visiblePrCount === 1 ? "PR" : "PRs"
- }`}
- >
- {prUrls.slice(visiblePrCount).map((url) => (
- <PrPopoverRow key={url} url={url} />
- ))}
- </OverflowChip>
- )}
- {artifacts.slice(0, 2).map((artifact) => (
- <button
- key={artifact.key}
- type="button"
- className={CHIP_CLASS}
- onClick={(event) => {
- event.stopPropagation();
- openArtifact(artifact);
- }}
- >
- {artifact.kind === "canvas" ? (
- <AppWindowIcon size={12} />
+ }}
+ onKeyDown={(event) => {
+ // Only when the card itself has focus: descendant buttons (title, PR
+ // and comment chips, the prompt toggle) bubble their key events here,
+ // and preventDefault would swallow their own Enter/Space activation.
+ if (event.target !== event.currentTarget) return;
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ markRead();
+ onOpenThread(task);
+ }
+ }}
+ >
+ <CardContent className="flex flex-col px-4 pt-3.5 pb-3">
+ <div className="flex items-center gap-3">
+ <div className="flex min-w-0 flex-1 items-baseline gap-1.5">
+ {editingTitle ? (
+ <Input
+ autoFocus
+ aria-label="Task title"
+ value={titleValue}
+ disabled={isSavingTitle}
+ className="h-6 min-w-0 font-semibold text-sm"
+ onClick={(event) => event.stopPropagation()}
+ onChange={(event) => setTitleValue(event.target.value)}
+ onBlur={saveTitle}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ saveTitle();
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ setEditingTitle(false);
+ }
+ }}
+ />
) : (
- <FileIcon filename={artifact.name} size={12} />
- )}
- <span className="max-w-40 truncate">{artifact.name}</span>
- </button>
- ))}
- {artifacts.length > 2 && (
- <OverflowChip
- label={`+${artifacts.length - 2} ${
- artifacts.length - 2 === 1 ? "file" : "files"
- }`}
- >
- {artifacts.slice(2).map((artifact) => (
<button
- key={artifact.key}
type="button"
- className={cn(CHIP_CLASS, "w-full")}
+ className="min-w-0 truncate text-left font-semibold text-sm leading-snug"
onClick={(event) => {
event.stopPropagation();
- openArtifact(artifact);
+ openTask();
}}
>
- {artifact.kind === "canvas" ? (
- <AppWindowIcon size={12} />
- ) : (
- <FileIcon filename={artifact.name} size={12} />
- )}
- <span className="truncate">{artifact.name}</span>
+ {task.title || "Untitled task"}
</button>
- ))}
- </OverflowChip>
- )}
- {humanMessages.length > 0 ? (
- <button
- type="button"
- className={CHIP_CLASS}
- onClick={(event) => {
- event.stopPropagation();
- onOpenThread(task, "comments");
- }}
- >
- <ChatCircleIcon size={12} />
- <span className="font-semibold text-(--gray-9)">
- {humanMessages.length}
+ )}
+ <span className="shrink-0 text-(--gray-9) text-xs">
+ · {formatRelativeTimeShort(task.updated_at)}
</span>
- </button>
- ) : (
- <button
- type="button"
- className={CHIP_CLASS}
- onClick={(event) => {
- event.stopPropagation();
- onOpenThread(task, "comments");
- }}
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ <TaskStatusBadge display={statusDisplay} />
+ <TaskRowDropdownMenu menu={menu} />
+ </div>
+ </div>
+ <div className="mt-1.5 text-(--gray-9) text-xs leading-normal">
+ <ExpandablePrompt
+ lines={2}
+ expandedContent={
+ <div className="whitespace-normal text-(--gray-11) [&_pre]:my-1.5">
+ <MarkdownRenderer content={prompt} />
+ </div>
+ }
>
- <PlusIcon size={12} />
- Comment
- </button>
- )}
- <span className="flex-1" />
- {authors.length > 0 && (
- <HoverPopover
- trigger={
- // A real button: the popover trigger expects native button
- // semantics, and it gives keyboard users a way to open the
- // participant list.
- <button
- type="button"
- aria-label="Participants"
- className="inline-flex cursor-default"
- onClick={(event) => event.stopPropagation()}
- >
- {/* reverse: the stack sits at the card's right edge, so the
+ {prompt || "A new task was started"}
+ </ExpandablePrompt>
+ </div>
+ <div className="mt-3 flex flex-wrap items-center gap-1.5">
+ {showRepo && task.repository && (
+ <span
+ className={cn(CHIP_CLASS, "border-transparent bg-transparent")}
+ >
+ <GitBranchIcon size={12} />
+ {task.repository}
+ </span>
+ )}
+ {prUrls.slice(0, visiblePrCount).map((url) => (
+ <PrChip key={url} url={url} />
+ ))}
+ {prUrls.length > visiblePrCount && (
+ <OverflowChip
+ label={`+${prUrls.length - visiblePrCount} ${
+ prUrls.length - visiblePrCount === 1 ? "PR" : "PRs"
+ }`}
+ >
+ {prUrls.slice(visiblePrCount).map((url) => (
+ <PrPopoverRow key={url} url={url} />
+ ))}
+ </OverflowChip>
+ )}
+ {artifacts.slice(0, 2).map((artifact) => (
+ <button
+ key={artifact.key}
+ type="button"
+ className={CHIP_CLASS}
+ onClick={(event) => {
+ event.stopPropagation();
+ openArtifact(artifact);
+ }}
+ >
+ {artifact.kind === "canvas" ? (
+ <AppWindowIcon size={12} />
+ ) : (
+ <FileIcon filename={artifact.name} size={12} />
+ )}
+ <span className="max-w-40 truncate">{artifact.name}</span>
+ </button>
+ ))}
+ {artifacts.length > 2 && (
+ <OverflowChip
+ label={`+${artifacts.length - 2} ${
+ artifacts.length - 2 === 1 ? "file" : "files"
+ }`}
+ >
+ {artifacts.slice(2).map((artifact) => (
+ <button
+ key={artifact.key}
+ type="button"
+ className={cn(CHIP_CLASS, "w-full")}
+ onClick={(event) => {
+ event.stopPropagation();
+ openArtifact(artifact);
+ }}
+ >
+ {artifact.kind === "canvas" ? (
+ <AppWindowIcon size={12} />
+ ) : (
+ <FileIcon filename={artifact.name} size={12} />
+ )}
+ <span className="truncate">{artifact.name}</span>
+ </button>
+ ))}
+ </OverflowChip>
+ )}
+ {humanMessages.length > 0 ? (
+ <button
+ type="button"
+ className={CHIP_CLASS}
+ onClick={(event) => {
+ event.stopPropagation();
+ onOpenThread(task, "comments");
+ }}
+ >
+ <ChatCircleIcon size={12} />
+ <span className="font-semibold text-(--gray-9)">
+ {humanMessages.length}
+ </span>
+ </button>
+ ) : (
+ <button
+ type="button"
+ className={CHIP_CLASS}
+ onClick={(event) => {
+ event.stopPropagation();
+ onOpenThread(task, "comments");
+ }}
+ >
+ <PlusIcon size={12} />
+ Comment
+ </button>
+ )}
+ <span className="flex-1" />
+ {authors.length > 0 && (
+ <HoverPopover
+ trigger={
+ // A real button: the popover trigger expects native button
+ // semantics, and it gives keyboard users a way to open the
+ // participant list.
+ <button
+ type="button"
+ aria-label="Participants"
+ className="inline-flex cursor-default"
+ onClick={(event) => event.stopPropagation()}
+ >
+ {/* reverse: the stack sits at the card's right edge, so the
hover expansion must spread left, into the card — the
default spreads right, off the edge and clipped. */}
- <AvatarGroup size="xs" stacked reverse>
+ <AvatarGroup size="xs" stacked reverse>
+ {authors.map((author) => (
+ <UserAvatar key={author.uuid} user={author} size="xs" />
+ ))}
+ </AvatarGroup>
+ </button>
+ }
+ content={
+ <div className="flex flex-col gap-1.5">
{authors.map((author) => (
- <UserAvatar key={author.uuid} user={author} size="xs" />
+ <div
+ key={author.uuid}
+ className="flex items-center gap-2 text-xs"
+ >
+ <UserAvatar user={author} size="xs" />
+ {userDisplayName(author)}
+ </div>
))}
- </AvatarGroup>
- </button>
- }
- content={
- <div className="flex flex-col gap-1.5">
- {authors.map((author) => (
- <div
- key={author.uuid}
- className="flex items-center gap-2 text-xs"
- >
- <UserAvatar user={author} size="xs" />
- {userDisplayName(author)}
- </div>
- ))}
- </div>
- }
- />
- )}
- </div>
- </CardContent>
- </Card>
+ </div>
+ }
+ />
+ )}
+ </div>
+ </CardContent>
+ </Card>
+ <ArchiveRunningTaskDialog
+ open={archiveConfirmOpen}
+ taskTitle={task.title}
+ stopsCloudSandbox={taskData?.taskRunEnvironment === "cloud"}
+ onConfirm={confirmArchive}
+ onCancel={() => setArchiveConfirmOpen(false)}
+ />
+ <StopCloudRunDialog
+ open={stopConfirmOpen}
+ taskId={task.id}
+ runId={task.latest_run?.id}
+ title={`Stop "${task.title}"?`}
+ buttonLabel="Stop task"
+ onOpenChange={setStopConfirmOpen}
+ onStopped={() => toast.success("Stop requested")}
+ />
+ </TaskRowContextMenu>
);
});
@@ -1203,9 +1352,18 @@ export function ChannelFeedView({
onOpenTask: (task: Task) => void;
onOpenThread: (task: Task, tab?: ThreadPanelTab) => void;
}) {
+ // Archiving is local-only host state the server task list doesn't know about,
+ // so a just-archived card would otherwise reappear on the next poll. Drop
+ // archived tasks here, the same way the sidebar tree does via useChannelItems.
+ const archivedTaskIds = useArchivedTaskIds();
+ const visibleTasks = useMemo(
+ () => tasks.filter((task) => !archivedTaskIds.has(task.id)),
+ [tasks, archivedTaskIds],
+ );
+
const entries = useMemo<FeedEntry[]>(
- () => mergeFeedEntries(tasks, systemMessages ?? []),
- [tasks, systemMessages],
+ () => mergeFeedEntries(visibleTasks, systemMessages ?? []),
+ [visibleTasks, systemMessages],
);
// The channel's dominant repo: on a single-repo channel every card would
@@ -1213,7 +1371,7 @@ export function ChannelFeedView({
// different repo than most of the channel.
const dominantRepo = useMemo(() => {
const counts = new Map<string, number>();
- for (const task of tasks) {
+ for (const task of visibleTasks) {
if (!task.repository) continue;
counts.set(task.repository, (counts.get(task.repository) ?? 0) + 1);
}
@@ -1226,7 +1384,7 @@ export function ChannelFeedView({
}
}
return best;
- }, [tasks]);
+ }, [visibleTasks]);
const viewportRef = useRef<HTMLDivElement>(null);
// biome-ignore lint/correctness/useExhaustiveDependencies: channelId is a trigger — switching channels or finishing the initial load swaps/completes the rows without a remount, so re-land at the latest cards
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx
index 44773cc8e37a..5bf80777ff55 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskRowMenu.tsx
@@ -1,11 +1,13 @@
import {
ArchiveIcon,
CaretRightIcon,
+ DotsThreeIcon,
FolderSimpleIcon,
PencilSimpleIcon,
PushPinIcon,
PushPinSlashIcon,
SquaresFourIcon,
+ StopCircle,
TrashIcon,
} from "@phosphor-icons/react";
import { sessionsLabel } from "@posthog/core/sidebar/selection";
@@ -18,6 +20,10 @@ import {
ContextMenuSubTrigger,
ContextMenuTrigger,
DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSub,
+ DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@posthog/quill";
import { PROJECT_BLUEBIRD_FLAG } from "@posthog/shared";
@@ -30,7 +36,7 @@ import {
MenuSubFlyout,
SearchableMenuFlyout,
} from "@posthog/ui/primitives/SearchableMenuFlyout";
-import { type ComponentType, type ReactNode, useMemo } from "react";
+import { type ComponentType, type ReactNode, useMemo, useState } from "react";
/**
* What a row's menu can do. The row owns the handlers because they're the same
@@ -53,6 +59,7 @@ export interface TaskRowMenuProps {
onAddToCommandCenter?: () => void;
/** Absent where there's no inline rename to open — canvases, for now. */
onRename?: () => void;
+ onStop?: () => void;
onTogglePin: () => void;
/** Tasks are archived; canvases are deleted (with an undo window). */
onArchive?: () => void;
@@ -80,6 +87,12 @@ const CONTEXT_PARTS: MenuParts = {
SubTrigger: ContextMenuSubTrigger,
};
+const DROPDOWN_PARTS: MenuParts = {
+ Item: DropdownMenuItem,
+ Sub: DropdownMenuSub,
+ SubTrigger: DropdownMenuSubTrigger,
+};
+
/**
* The row's actions, in the order the native menu used: the edits, then the
* places a task can be sent, then the destructive one last.
@@ -125,6 +138,12 @@ function TaskRowMenuItems({
Rename
</Item>
)}
+ {menu.onStop && (
+ <Item onClick={menu.onStop}>
+ <StopCircle size={14} />
+ Stop task
+ </Item>
+ )}
{isTask && (
<Item
disabled={!menu.onAddToCommandCenter}
@@ -254,6 +273,30 @@ function TaskRowBulkMenuItems({
* `onSubmenuOpenChange` reports the one thing that *is* a popup ("File to…"), so
* a hover surface can stay open while the pointer is inside it.
*/
+export function TaskRowDropdownMenu({ menu }: { menu: TaskRowMenuProps }) {
+ const [open, setOpen] = useState(false);
+
+ return (
+ <DropdownMenu open={open} onOpenChange={setOpen}>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="default"
+ size="icon-xs"
+ aria-label={`Options for ${menu.title || "task"}`}
+ onClick={(event) => event.stopPropagation()}
+ />
+ }
+ >
+ <DotsThreeIcon size={14} weight="bold" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-56">
+ <TaskRowMenuItems parts={DROPDOWN_PARTS} menu={menu} />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
export function TaskRowMenuList({
menu,
onAction,
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskFeedResults.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskFeedResults.ts
index 290e60056a21..eccf034bac1b 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskFeedResults.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskFeedResults.ts
@@ -19,6 +19,7 @@ import {
const TASK_FEED_POLL_INTERVAL_MS = 15_000;
const TASK_FEED_MAX_PAGES = 5;
+export const taskFeedResultsQueryRoot = ["task-feed-results"] as const;
function isPersonToken(token: FeedQueryToken): boolean {
return (
@@ -35,7 +36,7 @@ function isCurrentUserToken(token: FeedQueryToken): boolean {
}
export function taskFeedResultsQueryKey(query: string) {
- return ["task-feed-results", query] as const;
+ return [...taskFeedResultsQueryRoot, query] as const;
}
export function useFeedQueryPlan(query: string | undefined): {
diff --git a/products/desktop/packages/ui/src/features/tasks/useTaskMutations.test.tsx b/products/desktop/packages/ui/src/features/tasks/useTaskMutations.test.tsx
index 128899468290..7d3855ea40ae 100644
--- a/products/desktop/packages/ui/src/features/tasks/useTaskMutations.test.tsx
+++ b/products/desktop/packages/ui/src/features/tasks/useTaskMutations.test.tsx
@@ -5,6 +5,7 @@ import {
type SpaceTaskPage,
spaceTreeTasksQueryRoot,
} from "@posthog/ui/features/canvas/hooks/useRecentSpaceTasks";
+import { taskFeedResultsQueryKey } from "@posthog/ui/features/canvas/hooks/useTaskFeedResults";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
import { act, type ReactNode } from "react";
@@ -45,6 +46,8 @@ function createTask(overrides: Partial<Task> = {}): Task {
};
}
+type TaskFeedResults = { tasks: Task[]; isComplete: boolean };
+
function createSummary(overrides: Partial<Schemas.TaskSummary> = {}) {
return {
id: TASK_ID,
@@ -77,6 +80,7 @@ describe("useRenameTask", () => {
const summaryKey = taskKeys.summaries([TASK_ID]);
const detailKey = taskKeys.detail(TASK_ID);
const channelFeedKey = channelFeedQueryKey("channel-1");
+ const taskFeedKey = taskFeedResultsQueryKey("created-by:@me");
queryClient.setQueryData<Task[]>(listKey, [
createTask(),
createTask({ id: OTHER_TASK_ID, title: "Other" }),
@@ -91,6 +95,10 @@ describe("useRenameTask", () => {
tasks: [createTask()],
count: 7,
});
+ queryClient.setQueryData<TaskFeedResults>(taskFeedKey, {
+ tasks: [createTask()],
+ isComplete: true,
+ });
await act(async () => {
await result.current.renameTask({
@@ -131,6 +139,12 @@ describe("useRenameTask", () => {
tasks: [{ title: "Renamed", title_manually_set: true }],
count: 7,
});
+ expect(
+ queryClient.getQueryData<TaskFeedResults>(taskFeedKey)?.tasks[0],
+ ).toMatchObject({
+ title: "Renamed",
+ title_manually_set: true,
+ });
expect(mockUpdateTask).toHaveBeenCalledWith(TASK_ID, {
title: "Renamed",
@@ -148,6 +162,7 @@ describe("useRenameTask", () => {
const summaryKey = taskKeys.summaries([TASK_ID]);
const detailKey = taskKeys.detail(TASK_ID);
const channelFeedKey = channelFeedQueryKey("channel-1");
+ const taskFeedKey = taskFeedResultsQueryKey("created-by:@me");
queryClient.setQueryData<Task[]>(listKey, [createTask()]);
queryClient.setQueryData<Schemas.TaskSummary[]>(summaryKey, [
createSummary(),
@@ -158,6 +173,10 @@ describe("useRenameTask", () => {
tasks: [createTask()],
count: 7,
});
+ queryClient.setQueryData<TaskFeedResults>(taskFeedKey, {
+ tasks: [createTask()],
+ isComplete: true,
+ });
let caught: unknown;
await act(async () => {
@@ -191,6 +210,9 @@ describe("useRenameTask", () => {
expect(
queryClient.getQueryData<SpaceTaskPage>(SPACE_TREE_KEY)?.tasks[0].title,
).toBe("Original title");
+ expect(
+ queryClient.getQueryData<TaskFeedResults>(taskFeedKey)?.tasks[0].title,
+ ).toBe("Original title");
expect(mockUpdateSessionTaskTitle).toHaveBeenNthCalledWith(
1,
diff --git a/products/desktop/packages/ui/src/features/tasks/useTaskMutations.ts b/products/desktop/packages/ui/src/features/tasks/useTaskMutations.ts
index c389a1f0674e..cb40821be851 100644
--- a/products/desktop/packages/ui/src/features/tasks/useTaskMutations.ts
+++ b/products/desktop/packages/ui/src/features/tasks/useTaskMutations.ts
@@ -22,11 +22,14 @@ import {
type SpaceTaskPage,
spaceTreeTasksQueryRoot,
} from "@posthog/ui/features/canvas/hooks/useRecentSpaceTasks";
+import { taskFeedResultsQueryRoot } from "@posthog/ui/features/canvas/hooks/useTaskFeedResults";
import { taskKeys } from "@posthog/ui/features/tasks/taskKeys";
import { useAuthenticatedMutation } from "@posthog/ui/hooks/useAuthenticatedMutation";
import { useQueryClient } from "@tanstack/react-query";
import { useCallback } from "react";
+type TaskFeedResults = { tasks: Task[]; isComplete: boolean };
+
export function useUpdateTask() {
const queryClient = useQueryClient();
@@ -52,6 +55,7 @@ export function useUpdateTask() {
queryClient.invalidateQueries({ queryKey: taskKeys.allSummaries() });
queryClient.invalidateQueries({ queryKey: spaceTreeTasksQueryRoot });
queryClient.invalidateQueries({ queryKey: channelFeedQueryRoot });
+ queryClient.invalidateQueries({ queryKey: taskFeedResultsQueryRoot });
},
},
);
@@ -84,6 +88,7 @@ export function useRenameTask() {
channelFeedQueryRoot,
taskKeys.allSummaries(),
spaceTreeTasksQueryRoot,
+ taskFeedResultsQueryRoot,
taskKeys.detail(taskId),
].map((queryKey) => queryClient.cancelQueries({ queryKey })),
);
@@ -94,6 +99,10 @@ export function useRenameTask() {
const previousChannelFeedQueries = queryClient.getQueriesData<Task[]>({
queryKey: channelFeedQueryRoot,
});
+ const previousTaskFeedQueries =
+ queryClient.getQueriesData<TaskFeedResults>({
+ queryKey: taskFeedResultsQueryRoot,
+ });
const previousSummaryQueries = queryClient.getQueriesData<
Schemas.TaskSummary[]
>({
@@ -123,6 +132,17 @@ export function useRenameTask() {
{ queryKey: spaceTreeTasksQueryRoot },
(old) => applyRenameToPage(old, taskId, newTitle),
);
+ queryClient.setQueriesData<TaskFeedResults>(
+ { queryKey: taskFeedResultsQueryRoot },
+ (old) =>
+ old
+ ? {
+ ...old,
+ tasks:
+ applyRenameToList(old.tasks, taskId, newTitle) ?? old.tasks,
+ }
+ : old,
+ );
if (previousDetail) {
queryClient.setQueryData<Task>(
@@ -148,10 +168,20 @@ export function useRenameTask() {
const spaceTreeTitles = queryClient
.getQueriesData<SpaceTaskPage>({ queryKey: spaceTreeTasksQueryRoot })
.map(([, page]) => getTaskTitle(page?.tasks, taskId));
+ const taskFeedTitles = queryClient
+ .getQueriesData<TaskFeedResults>({
+ queryKey: taskFeedResultsQueryRoot,
+ })
+ .map(([, result]) => getTaskTitle(result?.tasks, taskId));
const rollbackSession = shouldRollbackSessionTitle({
detailTitle: queryClient.getQueryData<Task>(taskKeys.detail(taskId))
?.title,
- listTitles: [...listTitles, ...channelFeedTitles, ...spaceTreeTitles],
+ listTitles: [
+ ...listTitles,
+ ...channelFeedTitles,
+ ...spaceTreeTitles,
+ ...taskFeedTitles,
+ ],
newTitle,
});
@@ -180,6 +210,24 @@ export function useRenameTask() {
rollbackPageData<SpaceTaskPage>(current, data, taskId, newTitle),
);
}
+ for (const [queryKey, data] of previousTaskFeedQueries) {
+ queryClient.setQueryData<TaskFeedResults | undefined>(
+ queryKey,
+ (current) =>
+ current
+ ? {
+ ...current,
+ tasks:
+ rollbackListData(
+ current.tasks,
+ data?.tasks ?? [],
+ taskId,
+ newTitle,
+ ) ?? current.tasks,
+ }
+ : current,
+ );
+ }
if (previousDetail) {
queryClient.setQueryData<Task | undefined>(
taskKeys.detail(taskId),