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.

fix(desktop): avoid idle task list observers (#93126)

Alessandro Pogliaghi2be1f23b624d
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index ea34eead82fb..4422c02701bd 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -4853,6 +4853,7 @@ export namespace Schemas {
goalLines: Array<GoalLine> | null;
heatmap: HeatmapSettings | null;
leftYAxisSettings: YAxisSettings | null;
+ legendPosition: LegendPosition | null;
pie: PieChartSettings | null;
resultCustomizations: Record<string, ResultCustomizationByValue> | null;
rightYAxisSettings: YAxisSettings | null;
@@ -6492,6 +6493,7 @@ export namespace Schemas {
| "apns"
| "postgresql"
| "aws-s3"
+ | "aws-redshift"
| "s3-compatible"
| "snowflake"
| "youtube-analytics";
@@ -11252,6 +11254,10 @@ export namespace Schemas {
* * `Anvil` - Anvil
* * `Coolify` - Coolify
* * `SocialPilot` - SocialPilot
+ * * `Strato` - Strato
+ * * `Medusa` - Medusa
+ * * `Membrain` - Membrain
+ * * `RecallAI` - RecallAI
*/
export type ExternalDataSourceTypeEnum =
| "Ashby"
@@ -12578,7 +12584,11 @@ export namespace Schemas {
| "Lovable"
| "Anvil"
| "Coolify"
- | "SocialPilot";
+ | "SocialPilot"
+ | "Strato"
+ | "Medusa"
+ | "Membrain"
+ | "RecallAI";
/**
* * `web` - web
* * `api` - api
@@ -13914,6 +13924,10 @@ export namespace Schemas {
* * `Anvil` - Anvil
* * `Coolify` - Coolify
* * `SocialPilot` - SocialPilot
+ * * `Strato` - Strato
+ * * `Medusa` - Medusa
+ * * `Membrain` - Membrain
+ * * `RecallAI` - RecallAI
*/
source_type: ExternalDataSourceTypeEnum;
/**
@@ -13929,6 +13943,7 @@ export namespace Schemas {
| (ExternalDataSourceCreateCreatedViaEnum & unknown)
| undefined;
direct_query_enabled?: boolean | undefined;
+ destination_ids?: Array<string> | undefined;
};
export type ExternalDataSourceCreateResponse = {
/**
@@ -16180,6 +16195,10 @@ export namespace Schemas {
*/
export type TaskRunEnvironmentEnum = "local" | "cloud";
export type TaskRunSummary = {
+ /**
+ * ID of the latest run.
+ */
+ id: string;
status: TaskRunStatusEnum | NullEnum;
environment: TaskRunEnvironmentEnum | NullEnum;
};
@@ -16190,6 +16209,10 @@ export namespace Schemas {
id: string;
title: string;
repository: string | null;
+ /**
+ * ID of the user who created the task, or null for system-created tasks.
+ */
+ created_by_id: number | null;
created_at: string;
updated_at: string;
/**
@@ -18698,6 +18721,59 @@ export namespace Schemas {
_create_in_folder?: string | undefined;
form_content?: unknown | undefined;
};
+ export type SurveySerializerCreateUpdateOnlySchema = {
+ id: string;
+ /**
+ * Survey name. Anyone can read it. In-app surveys send it to every visitor's browser alongside the questions and appearance text, and a hosted survey shows it on its public page. Keep customer names and other private details out of it.
+ */
+ name: string;
+ description?: string | undefined;
+ /**
+ * Survey type.
+ *
+ * * `popover` - popover
+ * * `widget` - widget
+ * * `external_survey` - external survey
+ * * `api` - api
+ */
+ type: SurveyTypeEnum;
+ schedule?: (SurveyScheduleEnum | NullEnum) | undefined;
+ linked_flag: MinimalFeatureFlag & unknown;
+ linked_flag_id?: (number | null) | undefined;
+ linked_insight_id?: (number | null) | undefined;
+ targeting_flag_id?: number | undefined;
+ targeting_flag: MinimalFeatureFlag & unknown;
+ internal_targeting_flag: MinimalFeatureFlag & unknown;
+ targeting_flag_filters?: (FeatureFlagFiltersSchema | null) | undefined;
+ remove_targeting_flag?: (boolean | null) | undefined;
+ questions?: (Array<SurveyQuestionInputSchema> | null) | undefined;
+ conditions?: (SurveyConditionsSchema | null) | undefined;
+ appearance?: (SurveyAppearanceSchema | null) | undefined;
+ created_at: string;
+ created_by: UserBasic & unknown;
+ start_date?: (string | null) | undefined;
+ end_date?: (string | null) | undefined;
+ archived?: boolean | undefined;
+ responses_limit?: (number | null) | undefined;
+ iteration_count?: (number | null) | undefined;
+ iteration_frequency_days?: (number | null) | undefined;
+ iteration_start_dates?: (Array<string | null> | null) | undefined;
+ current_iteration?: (number | null) | undefined;
+ current_iteration_start_date?: (string | null) | undefined;
+ response_sampling_start_date?: (string | null) | undefined;
+ response_sampling_interval_type?:
+ | (SurveySamplingIntervalTypeEnum | BlankEnum | NullEnum)
+ | undefined;
+ response_sampling_interval?: (number | null) | undefined;
+ response_sampling_limit?: (number | null) | undefined;
+ response_sampling_daily_limits?: unknown | undefined;
+ enable_partial_responses?: (boolean | null) | undefined;
+ enable_iframe_embedding?: (boolean | null) | undefined;
+ base_language?: string | undefined;
+ translations?: unknown | undefined;
+ _create_in_folder?: string | undefined;
+ form_content?: unknown | undefined;
+ };
export type SurveyStatsResponse = {
/**
* The survey ID these stats belong to.
@@ -20215,9 +20291,9 @@ export namespace Endpoints {
parameters: {
path: { id: string; project_id: string };
- body: Schemas.Survey;
+ body: Schemas.SurveySerializerCreateUpdateOnlySchema;
};
- responses: { 200: Schemas.Survey };
+ responses: { 200: Schemas.SurveySerializerCreateUpdateOnly };
};
export type patch_Surveys_partial_update = {
method: "PATCH";
diff --git a/products/desktop/packages/core/src/sidebar/buildSidebarData.test.ts b/products/desktop/packages/core/src/sidebar/buildSidebarData.test.ts
index 1e4ac2cb0db8..27099bc979ec 100644
--- a/products/desktop/packages/core/src/sidebar/buildSidebarData.test.ts
+++ b/products/desktop/packages/core/src/sidebar/buildSidebarData.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
import {
+ deriveTaskData,
limitTasksPerGroup,
+ narrowFullTask,
readRunMode,
sliceVisibleTasks,
} from "./buildSidebarData";
@@ -94,3 +96,34 @@ describe("readRunMode", () => {
expect(readRunMode(state)).toBe(expected);
});
});
+
+describe("sidebar action metadata", () => {
+ it("preserves creator and run IDs from a full task", () => {
+ const task = narrowFullTask({
+ id: "task-1",
+ title: "Investigate slow startup",
+ repository: null,
+ created_at: "2026-09-02T09:00:00Z",
+ updated_at: "2026-09-02T09:00:00Z",
+ created_by: { id: 7 },
+ latest_run: {
+ id: "run-1",
+ status: "in_progress",
+ environment: "cloud",
+ },
+ });
+
+ const result = deriveTaskData(task, {
+ session: undefined,
+ workspace: undefined,
+ timestamp: undefined,
+ pinnedIds: new Set(),
+ suspendedIds: new Set(),
+ slackTaskIds: new Set(),
+ slackThreadUrlByTaskId: new Map(),
+ });
+
+ expect(result.createdById).toBe(7);
+ expect(result.taskRunId).toBe("run-1");
+ });
+});
diff --git a/products/desktop/packages/core/src/sidebar/buildSidebarData.ts b/products/desktop/packages/core/src/sidebar/buildSidebarData.ts
index 44fb5c77b6ed..0e1a58d049a4 100644
--- a/products/desktop/packages/core/src/sidebar/buildSidebarData.ts
+++ b/products/desktop/packages/core/src/sidebar/buildSidebarData.ts
@@ -13,7 +13,9 @@ export interface FullTask {
updated_at: string;
last_activity_at?: string | null;
origin_product?: string;
+ created_by?: { id: number } | null;
latest_run?: {
+ id?: string;
status?: TaskRunStatus | null;
environment?: "local" | "cloud" | null;
output?: { pr_url?: unknown } | null;
@@ -30,7 +32,9 @@ export interface SidebarTask {
last_activity_at?: string | null;
origin_product?: string;
slack_thread_url?: string;
+ created_by_id?: number | null;
latest_run?: {
+ id?: string;
status?: TaskRunStatus | null;
environment?: "local" | "cloud" | null;
output?: { pr_url?: unknown } | null;
@@ -72,8 +76,10 @@ export function narrowFullTask(task: FullTask | Task): SidebarTask {
created_at: task.created_at,
updated_at: task.updated_at,
last_activity_at: task.last_activity_at ?? null,
+ created_by_id: task.created_by?.id ?? null,
latest_run: task.latest_run
? {
+ id: task.latest_run.id,
status: task.latest_run.status,
environment: task.latest_run.environment ?? null,
output: task.latest_run.output ?? null,
@@ -203,11 +209,12 @@ export function deriveTaskRunState(
session: TaskSession | undefined,
): Pick<
TaskData,
- "id" | "isGenerating" | "taskRunStatus" | "taskRunEnvironment"
+ "id" | "isGenerating" | "taskRunId" | "taskRunStatus" | "taskRunEnvironment"
> {
return {
id: task.id,
isGenerating: session?.isPromptPending ?? false,
+ taskRunId: task.latest_run?.id ?? undefined,
taskRunStatus: session?.cloudStatus ?? task.latest_run?.status ?? undefined,
taskRunEnvironment: task.latest_run?.environment ?? undefined,
};
@@ -237,6 +244,7 @@ export function deriveTaskData(
return {
...deriveTaskRunState(task, session),
title: task.title,
+ createdById: task.created_by_id ?? undefined,
createdAt,
lastActivityAt,
isUnread,
diff --git a/products/desktop/packages/core/src/sidebar/selection.test.ts b/products/desktop/packages/core/src/sidebar/selection.test.ts
index 4306b50a2eeb..bd8fed3c0521 100644
--- a/products/desktop/packages/core/src/sidebar/selection.test.ts
+++ b/products/desktop/packages/core/src/sidebar/selection.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
computeBulkPinDirection,
computeOrderedVisibleTaskIds,
+ computeOrderedVisibleTasks,
computePriorTaskIds,
computeRangeSelection,
dedupeTaskIds,
@@ -107,6 +108,35 @@ describe("computeOrderedVisibleTaskIds", () => {
);
expect(ids).toEqual(["a"]);
});
+
+ it("uses every rendered project row instead of the flat slice", () => {
+ const tasks = computeOrderedVisibleTasks(
+ {
+ pinnedTasks: [makeTaskData("p1")],
+ flatTasks: [makeTaskData("first-project-only")],
+ groupedTasks: [
+ {
+ id: "g1",
+ name: "g1",
+ tasks: [makeTaskData("first-project-only")],
+ },
+ {
+ id: "g2",
+ name: "g2",
+ tasks: [makeTaskData("second-project")],
+ },
+ ],
+ },
+ "by-project",
+ new Set(),
+ );
+
+ expect(tasks.map((task) => task.id)).toEqual([
+ "p1",
+ "first-project-only",
+ "second-project",
+ ]);
+ });
});
describe("computePriorTaskIds", () => {
diff --git a/products/desktop/packages/core/src/sidebar/selection.ts b/products/desktop/packages/core/src/sidebar/selection.ts
index bd6f40727443..d87cf418764e 100644
--- a/products/desktop/packages/core/src/sidebar/selection.ts
+++ b/products/desktop/packages/core/src/sidebar/selection.ts
@@ -1,22 +1,33 @@
-import type { SidebarData } from "./sidebarData.types";
+import type { SidebarData, TaskData } from "./sidebarData.types";
export type OrganizeMode = "by-project" | "chronological";
-export function computeOrderedVisibleTaskIds(
+export function computeOrderedVisibleTasks(
sidebarData: Pick<SidebarData, "pinnedTasks" | "flatTasks" | "groupedTasks">,
organizeMode: OrganizeMode,
collapsedSections: ReadonlySet<string>,
-): string[] {
- const ids: string[] = sidebarData.pinnedTasks.map((task) => task.id);
+): TaskData[] {
+ const tasks = [...sidebarData.pinnedTasks];
if (organizeMode === "by-project") {
for (const group of sidebarData.groupedTasks) {
- if (collapsedSections.has(group.id)) continue;
- for (const task of group.tasks) ids.push(task.id);
+ if (!collapsedSections.has(group.id)) tasks.push(...group.tasks);
}
} else {
- for (const task of sidebarData.flatTasks) ids.push(task.id);
+ tasks.push(...sidebarData.flatTasks);
}
- return ids;
+ return tasks;
+}
+
+export function computeOrderedVisibleTaskIds(
+ sidebarData: Pick<SidebarData, "pinnedTasks" | "flatTasks" | "groupedTasks">,
+ organizeMode: OrganizeMode,
+ collapsedSections: ReadonlySet<string>,
+): string[] {
+ return computeOrderedVisibleTasks(
+ sidebarData,
+ organizeMode,
+ collapsedSections,
+ ).map((task) => task.id);
}
export interface RangeSelection {
diff --git a/products/desktop/packages/core/src/sidebar/sidebarData.types.ts b/products/desktop/packages/core/src/sidebar/sidebarData.types.ts
index 21c0f2cf7f14..a5ce3647a6b7 100644
--- a/products/desktop/packages/core/src/sidebar/sidebarData.types.ts
+++ b/products/desktop/packages/core/src/sidebar/sidebarData.types.ts
@@ -18,6 +18,8 @@ export interface TaskData {
repository: TaskRepositoryInfo | null;
isSuspended: boolean;
folderId?: string;
+ createdById?: number;
+ taskRunId?: string;
taskRunStatus?: TaskRunStatus;
taskRunEnvironment?: "local" | "cloud";
runMode?: RunMode;
diff --git a/products/desktop/packages/ui/src/features/archive/useArchiveTask.test.ts b/products/desktop/packages/ui/src/features/archive/useArchiveTask.test.ts
index efbe1e0acc0e..8b0c956c2b35 100644
--- a/products/desktop/packages/ui/src/features/archive/useArchiveTask.test.ts
+++ b/products/desktop/packages/ui/src/features/archive/useArchiveTask.test.ts
@@ -11,6 +11,7 @@ describe("getCachedArchiveTask", () => {
id: "task-1",
title: "Archived from sidebar",
repository: "posthog/code",
+ created_by_id: 7,
created_at: "2026-07-23T10:00:00.000Z",
updated_at: "2026-07-23T11:00:00.000Z",
latest_run: null,
diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx
index 384e96029fa5..32182e44915a 100644
--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx
@@ -1,6 +1,6 @@
import { findGroupFolder } from "@posthog/core/sidebar/groupTasks";
import {
- computeOrderedVisibleTaskIds,
+ computeOrderedVisibleTasks,
computePriorTaskIds,
formatArchiveResult,
formatBulkResult,
@@ -24,6 +24,10 @@ import { StopCloudRunDialog } from "@posthog/ui/features/sessions/components/Sto
import { useArchivingTasksStore } from "@posthog/ui/features/sidebar/archivingTasksStore";
import { withSidebarPeekHeld } from "@posthog/ui/features/sidebar/sidebarPeekStore";
import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";
+import {
+ openSidebarTask,
+ resolveSidebarTask,
+} from "@posthog/ui/features/sidebar/sidebarTaskInteractions";
import { useTaskSelectionStore } from "@posthog/ui/features/sidebar/taskSelectionStore";
import { useBulkArchiveConfirm } from "@posthog/ui/features/sidebar/useBulkArchiveConfirm";
import { useClearSelectionOnEscape } from "@posthog/ui/features/sidebar/useClearSelectionOnEscape";
@@ -39,9 +43,7 @@ import { useTasks } from "@posthog/ui/features/tasks/useTasks";
import { useWorkspaces } from "@posthog/ui/features/workspace/useWorkspace";
import { DotsCircleSpinner } from "@posthog/ui/primitives/DotsCircleSpinner";
import { toast } from "@posthog/ui/primitives/toast";
-import { navigateToTaskDetail } from "@posthog/ui/router/navigationBridge";
import { useAppView } from "@posthog/ui/router/useAppView";
-import { openTask } from "@posthog/ui/router/useOpenTask";
import { logger } from "@posthog/ui/shell/logger";
import { Box, Flex } from "@radix-ui/themes";
import { useQueryClient } from "@tanstack/react-query";
@@ -68,11 +70,16 @@ function SidebarMenuComponent() {
const archiveCacheKeys = useArchiveCacheKeys();
const view = useAppView();
- // Must mirror useSidebarData's filters so taskMap covers every rendered
- // task — otherwise handleTaskClick silently bails for tasks not in the map.
const showAllUsers = useSidebarStore((s) => s.showAllUsers);
const showInternal = useSidebarStore((s) => s.showInternal);
- const { data: allTasks = [] } = useTasks({ showAllUsers, showInternal });
+ const showCreator = useSidebarStore((s) =>
+ s.listItemMetadataFields.includes("creator"),
+ );
+ const observeFullTasks = showAllUsers || showCreator;
+ const { data: allTasks = [] } = useTasks(
+ { showAllUsers, showInternal },
+ { enabled: observeFullTasks, subscribed: observeFullTasks },
+ );
const { data: workspaces = {} } = useWorkspaces();
const { markAsViewed } = useTaskViewed();
@@ -93,19 +100,6 @@ function SidebarMenuComponent() {
activeView: view,
});
- const taskMap = useMemo(
- () => new Map<string, Task>(allTasks.map((task) => [task.id, task])),
- [allTasks],
- );
- const creatorNameByTaskId = useMemo(() => {
- const names = new Map<string, string>();
- for (const task of allTasks) {
- const name = creatorName(task.created_by);
- if (name) names.set(task.id, name);
- }
- return names;
- }, [allTasks]);
-
const commandCenterCells = useCommandCenterStore((s) => s.cells);
const previousTaskIdRef = useRef<string | null>(null);
@@ -140,8 +134,7 @@ function SidebarMenuComponent() {
taskTitle: string;
runId?: string;
} | null>(null);
- const [handoffTaskId, setHandoffTaskId] = useState<string | null>(null);
- const handoffTask = handoffTaskId ? taskMap.get(handoffTaskId) : undefined;
+ const [handoffTask, setHandoffTask] = useState<Task | null>(null);
useClearSelectionOnEscape();
const listAnchorRef = useRef<HTMLDivElement | null>(null);
@@ -159,24 +152,8 @@ function SidebarMenuComponent() {
const collapsedSections = useSidebarStore((s) => s.collapsedSections);
const allSidebarTasks = useMemo(
- () => [...sidebarData.pinnedTasks, ...sidebarData.flatTasks],
- [sidebarData.pinnedTasks, sidebarData.flatTasks],
- );
-
- const allSidebarTaskIds = useMemo(
- () => allSidebarTasks.map((t) => t.id),
- [allSidebarTasks],
- );
-
- // Ordered list of currently visible task IDs in display order. Used as the
- // index for shift-click range selection so it matches what the user sees —
- // in by-project mode the chronological flat order would span across project
- // groups and pull in unrelated tasks.
- // Depends on the three list fields rather than `sidebarData` itself, which
- // useSidebarData rebuilds as a fresh object every render.
- const orderedVisibleTaskIds = useMemo(
() =>
- computeOrderedVisibleTaskIds(
+ computeOrderedVisibleTasks(
{
pinnedTasks: sidebarData.pinnedTasks,
flatTasks: sidebarData.flatTasks,
@@ -194,6 +171,20 @@ function SidebarMenuComponent() {
],
);
+ const allSidebarTaskIds = useMemo(
+ () => allSidebarTasks.map((t) => t.id),
+ [allSidebarTasks],
+ );
+
+ const creatorNameByTaskId = useMemo(() => {
+ const names = new Map<string, string>();
+ for (const task of allTasks) {
+ const name = creatorName(task.created_by);
+ if (name) names.set(task.id, name);
+ }
+ return names;
+ }, [allTasks]);
+
useEffect(() => {
pruneSelection(allSidebarTaskIds);
}, [allSidebarTaskIds, pruneSelection]);
@@ -214,7 +205,7 @@ function SidebarMenuComponent() {
}
if (e.shiftKey) {
e.preventDefault();
- selectRange(taskId, orderedVisibleTaskIds, activeTaskId);
+ selectRange(taskId, allSidebarTaskIds, activeTaskId);
return;
}
if (e.metaKey || e.ctrlKey) {
@@ -224,15 +215,7 @@ function SidebarMenuComponent() {
}
clearSelection();
- const task = taskMap.get(taskId);
- if (task) {
- void openTask(task);
- } else {
- // Sidebar rows come from the summaries path, which can include tasks the
- // full-list query (taskMap) doesn't carry. Don't silently bail — navigate
- // by id; the task-detail route resolves the task from its own query.
- navigateToTaskDetail(taskId);
- }
+ void openSidebarTask(queryClient, taskId);
};
const handleBulkContextMenu = useCallback(
@@ -316,14 +299,16 @@ function SidebarMenuComponent() {
[folders, removeFolder, hostClient, openExternalApp],
);
- const handleTaskContextMenu = (
+ const handleTaskContextMenu = async (
taskId: string,
e: React.MouseEvent,
isPinned: boolean,
) => {
+ e.preventDefault();
+ e.stopPropagation();
+
// Right-clicking a row that's mid-archive is a no-op.
if (useArchivingTasksStore.getState().isArchiving(taskId)) {
- e.preventDefault();
return;
}
@@ -341,24 +326,17 @@ function SidebarMenuComponent() {
}
const taskData = allSidebarTasks.find((t) => t.id === taskId);
- const task = taskMap.get(taskId) ?? taskData;
- if (task) {
- const runId = taskMap.get(taskId)?.latest_run?.id;
+ if (taskData) {
const workspace = workspaces[taskId];
- const isInCommandCenter = commandCenterCells.some(
- (id) => id === taskId && taskMap.has(id),
- );
+ const isInCommandCenter = commandCenterCells.includes(taskId);
- // 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;
+ taskData.createdById === currentUser.data.id;
void withSidebarPeekHeld(() =>
- showContextMenu(task, e, {
+ showContextMenu(taskData, e, {
worktreePath: workspace?.worktreePath ?? undefined,
folderPath: workspace?.folderPath ?? undefined,
isPinned,
@@ -366,11 +344,14 @@ function SidebarMenuComponent() {
canStop:
taskData?.taskRunEnvironment === "cloud" &&
isTaskActivelyRunning(taskData),
- runId,
+ runId: taskData.taskRunId,
isInCommandCenter,
hasEmptyCommandCenterCell: true,
canHandoff,
- onHandoff: () => setHandoffTaskId(task.id),
+ onHandoff: async () => {
+ const task = await resolveSidebarTask(queryClient, taskId);
+ if (task) setHandoffTask(task);
+ },
onTogglePin: () => handleTaskTogglePin(taskId),
onStop: (stopTaskId, taskTitle, stopRunId) =>
setStopConfirm({
@@ -381,7 +362,7 @@ function SidebarMenuComponent() {
onArchive: handleTaskArchive,
onArchivePrior: handleArchivePrior,
onAddToCommandCenter: () => {
- placeTaskInCommandCenter(taskId, task.title);
+ placeTaskInCommandCenter(taskId, taskData.title);
},
}),
);
@@ -594,7 +575,7 @@ function SidebarMenuComponent() {
task={handoffTask}
open
onOpenChange={(open) => {
- if (!open) setHandoffTaskId(null);
+ if (!open) setHandoffTask(null);
}}
/>
) : null}
diff --git a/products/desktop/packages/ui/src/features/sidebar/sidebarTaskInteractions.test.ts b/products/desktop/packages/ui/src/features/sidebar/sidebarTaskInteractions.test.ts
new file mode 100644
index 000000000000..a00f216ec716
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sidebar/sidebarTaskInteractions.test.ts
@@ -0,0 +1,81 @@
+import type { Task } from "@posthog/shared/domain-types";
+import { QueryClient } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ getAuthenticatedClient: vi.fn(),
+ getTask: vi.fn(),
+ navigateToTaskDetail: vi.fn(),
+ openTask: vi.fn(),
+}));
+
+vi.mock("@posthog/ui/features/auth/authClientImperative", () => ({
+ getAuthenticatedClient: mocks.getAuthenticatedClient,
+}));
+
+vi.mock("@posthog/ui/router/navigationBridge", () => ({
+ navigateToTaskDetail: mocks.navigateToTaskDetail,
+}));
+
+vi.mock("@posthog/ui/router/useOpenTask", () => ({
+ openTask: mocks.openTask,
+}));
+
+import { openSidebarTask, resolveSidebarTask } from "./sidebarTaskInteractions";
+
+const task = {
+ id: "task-1",
+ title: "Investigate slow startup",
+ created_at: "2026-09-02T09:00:00Z",
+ updated_at: "2026-09-02T09:00:00Z",
+} as Task;
+
+function createQueryClient(): QueryClient {
+ return new QueryClient({
+ defaultOptions: { queries: { gcTime: Infinity, retry: false } },
+ });
+}
+
+describe("sidebar task interactions", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getAuthenticatedClient.mockResolvedValue({ getTask: mocks.getTask });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("opens a cold task through the full task workflow", async () => {
+ mocks.getTask.mockResolvedValue(task);
+
+ await openSidebarTask(createQueryClient(), task.id);
+
+ expect(mocks.openTask).toHaveBeenCalledWith(task);
+ expect(mocks.navigateToTaskDetail).not.toHaveBeenCalled();
+ });
+
+ it("resolves the full task for a deferred menu action", async () => {
+ mocks.getTask.mockResolvedValue(task);
+
+ await expect(
+ resolveSidebarTask(createQueryClient(), task.id),
+ ).resolves.toBe(task);
+ });
+
+ it("does not drop a deferred menu action when task loading is slow", async () => {
+ vi.useFakeTimers();
+ let resolveTask: (value: Task) => void = () => undefined;
+ mocks.getTask.mockReturnValue(
+ new Promise<Task>((resolve) => {
+ resolveTask = resolve;
+ }),
+ );
+ const result = resolveSidebarTask(createQueryClient(), task.id);
+
+ await vi.advanceTimersByTimeAsync(5_000);
+
+ resolveTask(task);
+ await expect(result).resolves.toBe(task);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/sidebar/sidebarTaskInteractions.ts b/products/desktop/packages/ui/src/features/sidebar/sidebarTaskInteractions.ts
new file mode 100644
index 000000000000..460fc3d82745
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sidebar/sidebarTaskInteractions.ts
@@ -0,0 +1,57 @@
+import type { Task } from "@posthog/shared/domain-types";
+import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";
+import { taskKeys } from "@posthog/ui/features/tasks/taskKeys";
+import { navigateToTaskDetail } from "@posthog/ui/router/navigationBridge";
+import { openTask } from "@posthog/ui/router/useOpenTask";
+import type { QueryClient } from "@tanstack/react-query";
+
+function getCachedTask(queryClient: QueryClient, taskId: string): Task | null {
+ const detail = queryClient.getQueryData<Task>(
+ taskDetailQuery(taskId).queryKey,
+ );
+ if (detail) return detail;
+
+ for (const [, tasks] of queryClient.getQueriesData<Task[]>({
+ queryKey: taskKeys.lists(),
+ })) {
+ const task = tasks?.find((candidate) => candidate.id === taskId);
+ if (task) return task;
+ }
+ return null;
+}
+
+async function fetchTask(
+ queryClient: QueryClient,
+ taskId: string,
+): Promise<Task> {
+ return queryClient.fetchQuery({
+ ...taskDetailQuery(taskId),
+ retry: false,
+ });
+}
+
+export async function openSidebarTask(
+ queryClient: QueryClient,
+ taskId: string,
+): Promise<void> {
+ const task = await resolveSidebarTask(queryClient, taskId);
+ if (!task) {
+ navigateToTaskDetail(taskId);
+ return;
+ }
+ await openTask(task);
+}
+
+export async function resolveSidebarTask(
+ queryClient: QueryClient,
+ taskId: string,
+): Promise<Task | null> {
+ const cached = getCachedTask(queryClient, taskId);
+ if (cached) return cached;
+
+ try {
+ return await fetchTask(queryClient, taskId);
+ } catch {
+ return null;
+ }
+}
diff --git a/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.test.tsx b/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.test.tsx
index 5498f874e7ae..a64f9c63dc79 100644
--- a/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.test.tsx
+++ b/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.test.tsx
@@ -115,6 +115,25 @@ describe("useSidebarBulkActions", () => {
});
});
+ it("observes live task ids only while sessions are selected", () => {
+ const { rerender } = renderHook(
+ ({ taskIds }) => useSidebarBulkActions(taskIds, TASKS),
+ { initialProps: { taskIds: [] as string[] } },
+ );
+
+ expect(hoisted.useTasks).toHaveBeenLastCalledWith(undefined, {
+ enabled: false,
+ subscribed: false,
+ });
+
+ rerender({ taskIds: ["t1"] });
+
+ expect(hoisted.useTasks).toHaveBeenLastCalledWith(undefined, {
+ enabled: true,
+ subscribed: true,
+ });
+ });
+
it.each([
{
name: "none pinned",
diff --git a/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.ts b/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.ts
index f515eabfca8d..dfd38755dd22 100644
--- a/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.ts
+++ b/products/desktop/packages/ui/src/features/sidebar/useSidebarBulkActions.ts
@@ -73,6 +73,7 @@ export function useSidebarBulkActions(
taskIds: string[],
tasks: BulkSessionInfo[],
): SidebarBulkActions {
+ const selectedCount = taskIds.length;
const queryClient = useQueryClient();
const archiveCacheKeys = useArchiveCacheKeys();
const clearSelection = useTaskSelectionStore((s) => s.clearSelection);
@@ -93,13 +94,11 @@ export function useSidebarBulkActions(
const channels = bluebirdEnabled ? fetchedChannels : EMPTY_CHANNELS;
const { fileTask } = useChannelTaskMutations();
- const liveTaskIds = useLiveTaskIds();
+ const liveTaskIds = useLiveTaskIds(selectedCount > 0);
const [isArchiving, setIsArchiving] = useState(false);
const [isFiling, setIsFiling] = useState(false);
- const selectedCount = taskIds.length;
-
const selectedTasks = useMemo(() => {
const ids = new Set(taskIds);
return tasks.filter((task) => ids.has(task.id));
diff --git a/products/desktop/packages/ui/src/features/sidebar/useSidebarData.ts b/products/desktop/packages/ui/src/features/sidebar/useSidebarData.ts
index 92161e839433..5cdc362e8b14 100644
--- a/products/desktop/packages/ui/src/features/sidebar/useSidebarData.ts
+++ b/products/desktop/packages/ui/src/features/sidebar/useSidebarData.ts
@@ -77,7 +77,7 @@ export function useSidebarData({
useTaskSummaries(summaryIds, { enabled: !showAllUsers });
const { data: fullTasks = [], isLoading: isTasksLoading } = useTasks(
{ showAllUsers, showInternal },
- { enabled: showAllUsers },
+ { enabled: showAllUsers, subscribed: showAllUsers },
);
const { data: slackTasks = [] } = useSlackTasks({
enabled: !showAllUsers,
diff --git a/products/desktop/packages/ui/src/features/tasks/useLiveTaskIds.ts b/products/desktop/packages/ui/src/features/tasks/useLiveTaskIds.ts
index 3d2f1d71f6cd..b7f860fca06f 100644
--- a/products/desktop/packages/ui/src/features/tasks/useLiveTaskIds.ts
+++ b/products/desktop/packages/ui/src/features/tasks/useLiveTaskIds.ts
@@ -10,8 +10,11 @@ import { useMemo } from "react";
* empty tile the user does. `null` while the list is unknown, which callers
* read as "hold every non-empty cell" rather than guessing the other way.
*/
-export function useLiveTaskIds(): ReadonlySet<string> | null {
- const { data: liveTasks } = useTasks();
+export function useLiveTaskIds(enabled = true): ReadonlySet<string> | null {
+ const { data: liveTasks } = useTasks(undefined, {
+ enabled,
+ subscribed: enabled,
+ });
return useMemo(
() => (liveTasks ? new Set(liveTasks.map((task) => task.id)) : null),
[liveTasks],
diff --git a/products/desktop/packages/ui/src/features/tasks/useTaskContextMenu.ts b/products/desktop/packages/ui/src/features/tasks/useTaskContextMenu.ts
index af45f6627938..b3890d7811f2 100644
--- a/products/desktop/packages/ui/src/features/tasks/useTaskContextMenu.ts
+++ b/products/desktop/packages/ui/src/features/tasks/useTaskContextMenu.ts
@@ -52,7 +52,7 @@ export function useTaskContextMenu() {
showArchivePrior?: boolean;
canHandoff?: boolean;
onTogglePin?: () => void;
- onHandoff?: () => void;
+ onHandoff?: () => Promise<void> | void;
onStop?: (taskId: string, taskTitle: string, runId?: string) => void;
onArchive?: (taskId: string) => void;
onArchivePrior?: (taskId: string) => void;
@@ -146,7 +146,7 @@ export function useTaskContextMenu() {
break;
case "handoff":
// The dialog lives with the caller; the hook can't own a modal.
- onHandoff?.();
+ await onHandoff?.();
break;
case "file-to-channel":
try {
diff --git a/products/desktop/packages/ui/src/features/tasks/useTasks.test.tsx b/products/desktop/packages/ui/src/features/tasks/useTasks.test.tsx
new file mode 100644
index 000000000000..e87dda5caace
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/tasks/useTasks.test.tsx
@@ -0,0 +1,49 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook } from "@testing-library/react";
+import type { PropsWithChildren } from "react";
+import { describe, expect, it, vi } from "vitest";
+import { taskKeys } from "./taskKeys";
+import { useTasks } from "./useTasks";
+
+vi.mock("@posthog/ui/features/auth/authClient", () => ({
+ useOptionalAuthenticatedClient: () => ({ getTasks: vi.fn() }),
+}));
+
+vi.mock("@posthog/ui/features/auth/useMeQuery", () => ({
+ useMeQuery: () => ({ data: { id: 42 } }),
+}));
+
+describe("useTasks", () => {
+ it("does not observe shared cache updates when unsubscribed", () => {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const wrapper = ({ children }: PropsWithChildren) => (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ let renderCount = 0;
+ const { result } = renderHook(
+ () => {
+ renderCount += 1;
+ return useTasks(undefined, { enabled: false, subscribed: false });
+ },
+ { wrapper },
+ );
+ const queryKey = taskKeys.list({
+ repository: undefined,
+ createdBy: 42,
+ internal: undefined,
+ });
+
+ expect(
+ queryClient.getQueryCache().find({ queryKey })?.getObserversCount(),
+ ).toBe(0);
+
+ act(() => {
+ queryClient.setQueryData(queryKey, [{ id: "task-1" }]);
+ });
+
+ expect(renderCount).toBe(1);
+ expect(result.current.data).toBeUndefined();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/tasks/useTasks.ts b/products/desktop/packages/ui/src/features/tasks/useTasks.ts
index 9b029cf0c140..d22e830cf456 100644
--- a/products/desktop/packages/ui/src/features/tasks/useTasks.ts
+++ b/products/desktop/packages/ui/src/features/tasks/useTasks.ts
@@ -25,7 +25,7 @@ export function useTasks(
showAllUsers?: boolean;
showInternal?: boolean;
},
- options?: { enabled?: boolean },
+ options?: { enabled?: boolean; subscribed?: boolean },
) {
const { data: currentUser } = useMeQuery();
const createdBy = filters?.showAllUsers ? undefined : currentUser?.id;
@@ -41,6 +41,7 @@ export function useTasks(
}) as unknown as Promise<Task[]>,
{
enabled: (options?.enabled ?? true) && !!currentUser?.id,
+ subscribed: options?.subscribed,
refetchInterval: TASK_LIST_POLL_INTERVAL_MS,
},
);
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index c5137c740b84..c8703c0e9214 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -5529,7 +5529,7 @@ def get_task_summaries(team_id: int, user_id: int | None, *, ids: list) -> list[
latest_run = (
TaskRun.objects.filter(task=OuterRef("pk"), team_id=team_id)
.order_by("-created_at", "-id")
- .annotate(_data=JSONObject(status="status", environment="environment"))
+ .annotate(_data=JSONObject(id="id", status="status", environment="environment"))
)
tasks = (
Task.objects.filter(team_id=team_id, deleted=False, id__in=ids)
@@ -5541,7 +5541,9 @@ def get_task_summaries(team_id: int, user_id: int | None, *, ids: list) -> list[
for task in tasks:
raw = getattr(task, "_latest_run", None)
latest = (
- contracts.TaskLatestRunSummaryDTO(status=raw.get("status"), environment=raw.get("environment"))
+ contracts.TaskLatestRunSummaryDTO(
+ id=raw["id"], status=raw.get("status"), environment=raw.get("environment")
+ )
if isinstance(raw, dict)
else None
)
@@ -5550,6 +5552,7 @@ def get_task_summaries(team_id: int, user_id: int | None, *, ids: list) -> list[
id=task.id,
title=task.title,
repository=task.repository,
+ created_by_id=task.created_by_id,
created_at=task.created_at,
updated_at=task.updated_at,
origin_product=task.origin_product,
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index 2595a9e53a21..bae5d0ffe219 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -374,6 +374,7 @@ class TaskCommentDetailDTO:
class TaskLatestRunSummaryDTO:
"""The latest-run status/environment pair nested in a task summary response."""
+ id: UUID
status: str | None
environment: str | None
@@ -389,6 +390,7 @@ class TaskSummaryDTO:
id: UUID
title: str
repository: str | None
+ created_by_id: int | None
created_at: datetime
updated_at: datetime
origin_product: str = ""
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index cf3382cf4b2d..116b89320dc6 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -1911,6 +1911,7 @@ class TaskSummariesRequestSerializer(serializers.Serializer):
class TaskRunSummarySerializer(serializers.Serializer):
+ id = serializers.UUIDField(help_text="ID of the latest run.")
status = serializers.ChoiceField(choices=tasks_facade.TaskRunStatus.choices, allow_null=True)
environment = serializers.ChoiceField(choices=tasks_facade.TaskRunEnvironment.choices, allow_null=True)
@@ -1918,11 +1919,24 @@ class TaskRunSummarySerializer(serializers.Serializer):
class TaskSummarySerializer(DataclassSerializer):
"""Summary response for a task — reads from a frozen ``TaskSummaryDTO``."""
+ created_by_id = serializers.IntegerField(
+ allow_null=True,
+ help_text="ID of the user who created the task, or null for system-created tasks.",
+ )
latest_run = TaskRunSummarySerializer(allow_null=True, required=False)
class Meta:
dataclass = TaskSummaryDTO
- fields = ["id", "title", "repository", "created_at", "updated_at", "origin_product", "latest_run"]
+ fields = [
+ "id",
+ "title",
+ "repository",
+ "created_by_id",
+ "created_at",
+ "updated_at",
+ "origin_product",
+ "latest_run",
+ ]
class TaskListQuerySerializer(serializers.Serializer):
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 5774158f0b4b..8eed18714777 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -829,8 +829,8 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
},
summary="Fetch task summaries by ID",
description=(
- "Returns summary for the requested tasks: `id`, `title`, `repository`, `created_at`, "
- "`updated_at`, and the latest run's `status` and `environment`."
+ "Returns summary for the requested tasks, including the creator ID and the latest run's "
+ "ID, status, and environment."
),
parameters=[
OpenApiParameter(
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 0589cac7e754..510181e97130 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -4974,7 +4974,16 @@ class TestTaskInternalFilterAPI(BaseTaskAPITest):
class TestTaskSummariesAPI(BaseTaskAPITest):
SUMMARIES_URL = "/api/projects/@current/tasks/summaries/"
- SUMMARY_FIELDS = {"id", "title", "repository", "created_at", "updated_at", "origin_product", "latest_run"}
+ SUMMARY_FIELDS = {
+ "id",
+ "title",
+ "repository",
+ "created_by_id",
+ "created_at",
+ "updated_at",
+ "origin_product",
+ "latest_run",
+ }
def post_summaries(self, ids):
return self.client.post(self.SUMMARIES_URL, {"ids": ids}, format="json")
@@ -5034,7 +5043,7 @@ class TestTaskSummariesAPI(BaseTaskAPITest):
[payload] = response.json()["results"]
self.assertEqual(
payload["latest_run"],
- {"status": valid_run.status, "environment": valid_run.environment},
+ {"id": str(valid_run.id), "status": valid_run.status, "environment": valid_run.environment},
)
@parameterized.expand(
@@ -5061,7 +5070,8 @@ class TestTaskSummariesAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
[payload] = response.json()["results"]
self.assertEqual(set(payload.keys()), self.SUMMARY_FIELDS)
- expected_run = {"status": run.status, "environment": run.environment} if run else None
+ self.assertEqual(payload["created_by_id"], self.user.id)
+ expected_run = {"id": str(run.id), "status": run.status, "environment": run.environment} if run else None
self.assertEqual(payload["latest_run"], expected_run)
def test_summaries_paginates_large_id_sets(self):
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 15b0e0e749f7..edbfbbb4d60b 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -4759,6 +4759,8 @@ export const TaskRunEnvironmentEnumApi = {
} as const
export interface TaskRunSummaryApi {
+ /** ID of the latest run. */
+ id: string
status: TaskRunStatusEnumApi | null
environment: TaskRunEnvironmentEnumApi | null
}
@@ -4771,6 +4773,11 @@ export interface TaskSummaryDTOApi {
title: string
/** @nullable */
repository: string | null
+ /**
+ * ID of the user who created the task, or null for system-created tasks.
+ * @nullable
+ */
+ created_by_id: number | null
created_at: string
updated_at: string
origin_product?: string
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index c47dd3defbe0..c9dc5dee657a 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -2909,7 +2909,7 @@ export const getTasksSummariesCreateUrl = (projectId: string, params?: TasksSumm
}
/**
- * Returns summary for the requested tasks: `id`, `title`, `repository`, `created_at`, `updated_at`, and the latest run's `status` and `environment`.
+ * Returns summary for the requested tasks, including the creator ID and the latest run's ID, status, and environment.
* @summary Fetch task summaries by ID
*/
export const tasksSummariesCreate = async (
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index beddea7ef82c..573750f43fb1 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -3459,7 +3459,7 @@ export const TasksConfigCreateBody = /* @__PURE__ */ zod
)
/**
- * Returns summary for the requested tasks: `id`, `title`, `repository`, `created_at`, `updated_at`, and the latest run's `status` and `environment`.
+ * Returns summary for the requested tasks, including the creator ID and the latest run's ID, status, and environment.
* @summary Fetch task summaries by ID
*/
export const tasksSummariesCreateBodyIdsMax = 5000
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 17b490b7242d..b26fa35be280 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -58317,6 +58317,8 @@ export namespace Schemas {
} as const;
export interface TaskRunSummary {
+ /** ID of the latest run. */
+ id: string;
status: TaskRunStatusEnum | null;
environment: TaskRunEnvironmentEnum | null;
}
@@ -58329,6 +58331,11 @@ export namespace Schemas {
title: string;
/** @nullable */
repository: string | null;
+ /**
+ * ID of the user who created the task, or null for system-created tasks.
+ * @nullable
+ */
+ created_by_id: number | null;
created_at: string;
updated_at: string;
origin_product?: string;