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): keep pinned and recently active tasks in the work list (#117550)

Paul D'Ambrab1cf9b678aa2
diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.ts
index c1d7258c8ffb..7223b6779b8a 100644
--- a/products/desktop/packages/api-client/src/posthog-client.test.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts
@@ -718,6 +718,34 @@ describe("PostHogAPIClient", () => {
});
});
+ it.each([
+ {
+ sources: ["posthog_desktop", "slack"],
+ sent: ["posthog_desktop", "slack"],
+ },
+ { sources: [], sent: [] },
+ ])("sends task list sources $sources as $sent", async ({ sources, sent }) => {
+ const fetch = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ results: [], count: 0 }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ const client = new PostHogAPIClient(
+ "https://app.posthog.test",
+ async () => "token",
+ async () => "token",
+ 42,
+ { fetch },
+ );
+
+ await client.getTasksPage({ sources });
+
+ const url = fetch.mock.calls[0][0] as URL;
+ expect(url.pathname).toBe("/api/projects/42/tasks/");
+ expect(url.searchParams.getAll("sources")).toEqual(sent);
+ });
+
it("fetches later task pages before reporting complete results", async () => {
const client = new PostHogAPIClient(
"https://app.posthog.test",
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index beda4c356b53..35cbda229ff7 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -339,6 +339,11 @@ export interface TaskListOptions {
ciStatus?: string;
/** List only tasks the requesting user has pinned. */
pinned?: boolean;
+ /**
+ * List only tasks from any of these sources, in the desktop source filter's words. Filtering on
+ * the server keeps sources the user hid, such as scheduled runs, from filling the page.
+ */
+ sources?: readonly string[];
/** Filter to tasks with a thread comment from this user ID. */
commentedBy?: number;
/** Filter to tasks whose thread mentions this user ID. */
@@ -3303,7 +3308,7 @@ export class PostHogAPIClient {
options?: TaskListOptions,
): Promise<{ tasks: Task[]; count: number }> {
const teamId = await this.getTeamId();
- const params: Record<string, string | number | boolean> = {
+ const params: Record<string, string | number | boolean | string[]> = {
limit: options?.limit ?? 500,
};
@@ -3351,6 +3356,10 @@ export class PostHogAPIClient {
params.pinned = true;
}
+ if (options?.sources?.length) {
+ params.sources = [...options.sources];
+ }
+
if (options?.commentedBy) {
params.commented_by = options.commentedBy;
}
diff --git a/products/desktop/packages/core/src/canvas/channelItems.ts b/products/desktop/packages/core/src/canvas/channelItems.ts
index 672854d71cc5..bff21baee8fe 100644
--- a/products/desktop/packages/core/src/canvas/channelItems.ts
+++ b/products/desktop/packages/core/src/canvas/channelItems.ts
@@ -134,7 +134,7 @@ function environmentOf(
return mode === "cloud" ? "cloud" : "local";
}
-function sourceOf(task: Task): string | null {
+export function sourceOf(task: Task): string | null {
if (task.origin_product === "posthog_ai") {
return WEB_SOURCE;
}
@@ -336,6 +336,14 @@ export function migrateLegacySources(sources: SourceFilter): string[] {
);
}
+function uniqueSources(sources: Iterable<string | null>): string[] {
+ const unique = new Set<string>();
+ for (const source of sources) {
+ if (source) unique.add(source);
+ }
+ return [...unique].sort();
+}
+
/**
* The sources present in a list, so the menu only offers the ones that can
* actually match. Keyed by `origin_product`; sorted so the menu is stable
@@ -344,11 +352,12 @@ export function migrateLegacySources(sources: SourceFilter): string[] {
export function channelItemSources(
items: readonly ChannelItemModel[],
): string[] {
- const sources = new Set<string>();
- for (const item of items) {
- if (item.source) sources.add(item.source);
- }
- return [...sources].sort();
+ return uniqueSources(items.map((item) => item.source));
+}
+
+/** The sources of a task list, in the source filter's words. Sorted so the menu is stable. */
+export function taskSources(tasks: readonly Task[]): string[] {
+ return uniqueSources(tasks.map(sourceOf));
}
export function filterChannelItems(
diff --git a/products/desktop/packages/ui/src/features/canvas/components/work/WorkColumn.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/work/WorkColumn.test.tsx
index 28271847b84e..30c45c81858f 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/work/WorkColumn.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/work/WorkColumn.test.tsx
@@ -1,6 +1,7 @@
import {
type ChannelItemModel,
DESKTOP_SOURCE,
+ FIRST_PARTY_CLIENT_SOURCES,
} from "@posthog/core/canvas/channelItems";
import { ChannelItemPreviewCardProvider } from "@posthog/ui/features/canvas/components/ChannelItemHoverCard";
import { Theme } from "@radix-ui/themes";
@@ -10,6 +11,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
items: [] as { item: ChannelItemModel; channelId: string | undefined }[],
+ recentWorkArgs: undefined as unknown,
+ taskSources: [] as string[],
navigate: {
toChannelTask: vi.fn(),
toChannelDashboard: vi.fn(),
@@ -28,7 +31,18 @@ vi.mock("@posthog/ui/router/navigationBridge", () => ({
}));
vi.mock("@posthog/ui/features/canvas/hooks/useRecentWorkItems", () => ({
- useRecentWorkItems: () => ({ items: mocks.items, isLoading: false }),
+ useRecentWorkItems: (args: unknown) => {
+ mocks.recentWorkArgs = args;
+ return { items: mocks.items, isLoading: false };
+ },
+}));
+vi.mock("@posthog/ui/features/canvas/hooks/useTaskSources", () => ({
+ useTaskSources: () => mocks.taskSources,
+}));
+vi.mock("@posthog/ui/features/canvas/components/ChannelFilterMenu", () => ({
+ ChannelFilterMenu: ({ sources }: { sources: readonly string[] }) => (
+ <div data-testid="filter-sources">{sources.join(",")}</div>
+ ),
}));
vi.mock("@posthog/ui/features/canvas/hooks/useChannelItems", () => ({
useChannelItemActions: ({
@@ -112,6 +126,7 @@ vi.mock("@posthog/ui/features/canvas/hooks/useFileTaskToChannel", () => ({
useFileTaskToChannel: () => vi.fn(),
}));
+import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";
import { useTaskSelectionStore } from "@posthog/ui/features/sidebar/taskSelectionStore";
import { WorkColumn } from "./WorkColumn";
@@ -169,12 +184,28 @@ const navigate = mocks.navigate;
beforeEach(() => {
for (const spy of Object.values(mocks.navigate)) spy.mockClear();
mocks.items = [1, 2, 3, 4, 5].map(entry);
+ mocks.taskSources = [];
+ useSidebarStore.setState({ pickedChannelItemSources: [] });
useTaskSelectionStore.setState({ selectedTaskIds: [], lastClickedId: null });
});
afterEach(cleanup);
describe("WorkColumn", () => {
+ it("asks for the selected sources and still offers the ones it hides", () => {
+ mocks.taskSources = ["signals_scout", "slack"];
+ useSidebarStore.setState({ pickedChannelItemSources: ["hogdesk"] });
+
+ renderColumn();
+
+ expect(mocks.recentWorkArgs).toEqual({
+ sources: FIRST_PARTY_CLIENT_SOURCES,
+ });
+ expect(
+ screen.getByTestId("filter-sources").textContent?.split(","),
+ ).toEqual(expect.arrayContaining(["hogdesk", "signals_scout", "slack"]));
+ });
+
it("opens a session on a plain click", () => {
renderColumn();
diff --git a/products/desktop/packages/ui/src/features/canvas/components/work/WorkColumn.tsx b/products/desktop/packages/ui/src/features/canvas/components/work/WorkColumn.tsx
index 424131c1e9fc..86509ad1c0ed 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/work/WorkColumn.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/work/WorkColumn.tsx
@@ -61,6 +61,7 @@ import {
useSpacePresence,
} from "@posthog/ui/features/canvas/hooks/useRecentSpaceTasks";
import { useRecentWorkItems } from "@posthog/ui/features/canvas/hooks/useRecentWorkItems";
+import { useTaskSources } from "@posthog/ui/features/canvas/hooks/useTaskSources";
import { useIsChannelUnread } from "@posthog/ui/features/canvas/hooks/useUnreadChannels";
import { useUnreadSessionCount } from "@posthog/ui/features/canvas/hooks/useUnreadSessionCount";
import { useWorkSectionLayout } from "@posthog/ui/features/canvas/hooks/useWorkSectionLayout";
@@ -280,7 +281,14 @@ export function WorkColumn() {
const columnRef = useRef<HTMLDivElement | null>(null);
const [createOpen, setCreateOpen] = useState(false);
- const { items, isLoading } = useRecentWorkItems();
+ const filters = useSidebarStore((state) => state.channelItemFilters);
+ const pickedSources = useSidebarStore(
+ (state) => state.pickedChannelItemSources,
+ );
+ const { items, isLoading } = useRecentWorkItems({
+ sources: filters.sources,
+ });
+ const taskSources = useTaskSources();
const { channels } = useChannels();
const currentChannelId = useCurrentChannelStore((s) => s.currentChannelId);
const isChannelUnread = useIsChannelUnread();
@@ -296,7 +304,6 @@ export function WorkColumn() {
: null;
const needle = query.trim().toLowerCase();
- const filters = useSidebarStore((state) => state.channelItemFilters);
const setFilters = useSidebarStore((state) => state.setChannelItemFilters);
const sort = useSidebarStore((state) => state.channelItemSort);
const setSort = useSidebarStore((state) => state.setChannelItemSort);
@@ -314,9 +321,20 @@ export function WorkColumn() {
const { data: currentUser } = useCurrentUser({ client });
const meUuid = currentUser?.uuid ?? null;
const me = useMemo(() => ({ uuid: meUuid }), [meUuid]);
+ // The server returns only the selected sources, so the menu also offers the sources of the
+ // user's other tasks and every source they picked before. Otherwise a hidden source could
+ // never be turned back on.
const sources = useMemo(
- () => channelItemSources(items.map((entry) => entry.item)),
- [items],
+ () =>
+ Array.from(
+ new Set([
+ ...channelItemSources(items.map((entry) => entry.item)),
+ ...taskSources,
+ ...filters.sources,
+ ...pickedSources,
+ ]),
+ ).sort(),
+ [items, taskSources, filters.sources, pickedSources],
);
const dayStart = useLocalDayStart();
const pinnedItems = useMemo(
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentWorkItems.test.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentWorkItems.test.ts
index 115667b5a575..01640aba2fc3 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentWorkItems.test.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentWorkItems.test.ts
@@ -2,7 +2,7 @@ import type { ChannelSessionFacts } from "@posthog/core/canvas/channelItems";
import type { DashboardRecord } from "@posthog/core/canvas/dashboardSchemas";
import type { Task } from "@posthog/shared/domain-types";
import { describe, expect, it } from "vitest";
-import { selectRecentWorkItems } from "./useRecentWorkItems";
+import { RECENT_WORK_CAP, selectRecentWorkItems } from "./useRecentWorkItems";
const ME = "me-uuid";
const OLD = 1_000;
@@ -46,6 +46,7 @@ function select(
return selectRecentWorkItems({
dashboards: [],
tasks: [],
+ pinnedTasks: [],
lastViewedByCanvasId: {},
meUuid: ME,
archivedTaskIds: new Set(),
@@ -100,10 +101,48 @@ describe("selectRecentWorkItems", () => {
over: { dashboards: [canvas({ createdByUuid: "other-uuid" })] },
expected: [],
},
+ {
+ case: "lists a pinned task the recent fetch did not return",
+ over: {
+ pinnedTasks: [task({ id: "task-pinned" })],
+ pinnedTaskIds: new Set(["task-pinned"]),
+ },
+ expected: ["task:task-pinned"],
+ },
+ {
+ case: "lists a pinned task once when both fetches return it",
+ over: {
+ tasks: [task()],
+ pinnedTasks: [task()],
+ pinnedTaskIds: new Set(["task-new"]),
+ },
+ expected: ["task:task-new"],
+ },
])("$case", ({ over, expected }) => {
expect(keys(over)).toEqual(expected);
});
+ it("caps only the unpinned work, so newer pins cannot empty Recent", () => {
+ const pins = Array.from({ length: RECENT_WORK_CAP }, (_, index) =>
+ task({
+ id: `pin-${index}`,
+ last_activity_at: new Date(NEW + index).toISOString(),
+ }),
+ );
+ const recent = task({
+ id: "recent",
+ last_activity_at: new Date(OLD).toISOString(),
+ });
+
+ expect(
+ keys({
+ tasks: [recent],
+ pinnedTasks: pins,
+ pinnedTaskIds: new Set(pins.map((pin) => pin.id)),
+ }),
+ ).toContain("task:recent");
+ });
+
it("carries each item's own channel", () => {
expect(
select({
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentWorkItems.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentWorkItems.ts
index 0643b8a09b94..97b550893c76 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentWorkItems.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentWorkItems.ts
@@ -12,7 +12,10 @@ import { useChannelSessionFacts } from "@posthog/ui/features/canvas/hooks/useCha
import { useAllCanvases } from "@posthog/ui/features/canvas/hooks/useDashboards";
import { useCanvasViewedStore } from "@posthog/ui/features/canvas/stores/canvasViewedStore";
import { usePinnedTasks } from "@posthog/ui/features/sidebar/usePinnedTasks";
-import { useTasks } from "@posthog/ui/features/tasks/useTasks";
+import {
+ usePinnedTaskRecords,
+ useTasks,
+} from "@posthog/ui/features/tasks/useTasks";
import { useMemo } from "react";
export const RECENT_WORK_CAP = 50;
@@ -22,9 +25,22 @@ export interface RecentWorkItem {
channelId: string | undefined;
}
+// Pins always stay. The cap counts only the rest, so pins with newer activity cannot take the
+// places of the recent work they sit beside.
+function keepPinsAndCapRecent(
+ items: readonly ChannelItemModel[],
+): ChannelItemModel[] {
+ let recent = 0;
+ return items.filter(
+ (item) =>
+ (item.kind === "task" && item.pinned) || recent++ < RECENT_WORK_CAP,
+ );
+}
+
export function selectRecentWorkItems({
dashboards,
tasks,
+ pinnedTasks,
lastViewedByCanvasId,
meUuid,
archivedTaskIds,
@@ -33,6 +49,7 @@ export function selectRecentWorkItems({
}: {
dashboards: readonly DashboardRecord[];
tasks: readonly Task[];
+ pinnedTasks: readonly Task[];
lastViewedByCanvasId: Record<string, number>;
meUuid: string | null;
archivedTaskIds: ReadonlySet<string>;
@@ -45,39 +62,51 @@ export function selectRecentWorkItems({
(meUuid != null && canvas.createdByUuid === meUuid),
);
const canvasChannelId = new Map(mine.map((c) => [c.id, c.channelId]));
+ const taskIds = new Set(tasks.map((task) => task.id));
// The order is the items' own activity time. Opening an item is not activity,
// so the local "viewed" time stays out of it and only says which canvases
// belong to this list.
- return buildChannelItems({
+ const items = buildChannelItems({
dashboards: mine,
- feedTasks: tasks,
+ feedTasks: [
+ ...tasks,
+ ...pinnedTasks.filter((task) => !taskIds.has(task.id)),
+ ],
archivedTaskIds,
pinnedTaskIds,
ownedBy: null,
sessionFacts,
- })
- .sort((a, b) => b.ts - a.ts)
- .filter(
- (item, index) =>
- index < RECENT_WORK_CAP || (item.kind === "task" && item.pinned),
- )
- .map((item) => ({
- item,
- channelId: item.task?.channel ?? canvasChannelId.get(item.id),
- }));
+ }).sort((a, b) => b.ts - a.ts);
+ return keepPinsAndCapRecent(items).map((item) => ({
+ item,
+ channelId: item.task?.channel ?? canvasChannelId.get(item.id),
+ }));
}
-export function useRecentWorkItems(): {
+export function useRecentWorkItems({
+ sources,
+}: {
+ sources: readonly string[];
+}): {
items: RecentWorkItem[];
isLoading: boolean;
} {
- const { data: tasks = [], isLoading: tasksLoading } = useTasks();
+ // Nothing past the cap shows, so the page asks for no more than that. The server cuts the page
+ // from the newest activity: by creation date, a session started last week and still in use is
+ // already off the page when scheduled runs create many tasks.
+ const { data: tasks = [], isLoading: tasksLoading } = useTasks({
+ sources,
+ limit: RECENT_WORK_CAP,
+ ordering: "-last_activity_at",
+ });
+ const { data: pinnedTasks = [], isLoading: pinnedLoading } =
+ usePinnedTaskRecords();
const { dashboards, isLoading: canvasesLoading } = useAllCanvases();
const lastViewedByCanvasId = useCanvasViewedStore(
(state) => state.lastViewedAtByCanvasId,
);
const archivedTaskIds = useArchivedTaskIds();
- const { pinnedTaskIds } = usePinnedTasks();
+ const { pinnedTaskIds, isLoading: pinIdsLoading } = usePinnedTasks();
const sessionFacts = useChannelSessionFacts();
const client = useOptionalAuthenticatedClient();
const { data: currentUser } = useCurrentUser({ client });
@@ -88,6 +117,7 @@ export function useRecentWorkItems(): {
selectRecentWorkItems({
dashboards,
tasks,
+ pinnedTasks,
lastViewedByCanvasId,
meUuid,
archivedTaskIds,
@@ -99,11 +129,16 @@ export function useRecentWorkItems(): {
lastViewedByCanvasId,
meUuid,
tasks,
+ pinnedTasks,
archivedTaskIds,
pinnedTaskIds,
sessionFacts,
],
);
- return { items, isLoading: tasksLoading || canvasesLoading };
+ return {
+ items,
+ isLoading:
+ tasksLoading || canvasesLoading || pinnedLoading || pinIdsLoading,
+ };
}
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskSources.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskSources.ts
new file mode 100644
index 000000000000..b39dfb7f49d6
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskSources.ts
@@ -0,0 +1,9 @@
+import { taskSources } from "@posthog/core/canvas/channelItems";
+import { useTasks } from "@posthog/ui/features/tasks/useTasks";
+import { useMemo } from "react";
+
+/** The sources of the user's recent tasks, so a source filter can offer the sources it hides. */
+export function useTaskSources(): string[] {
+ const { data: tasks = [] } = useTasks();
+ return useMemo(() => taskSources(tasks), [tasks]);
+}
diff --git a/products/desktop/packages/ui/src/features/sidebar/sidebarStore.test.ts b/products/desktop/packages/ui/src/features/sidebar/sidebarStore.test.ts
index d7bb366cfa19..526dcc8992ea 100644
--- a/products/desktop/packages/ui/src/features/sidebar/sidebarStore.test.ts
+++ b/products/desktop/packages/ui/src/features/sidebar/sidebarStore.test.ts
@@ -19,6 +19,22 @@ describe("sidebarStore", () => {
]);
});
+ it("keeps offering a source after the user unchecks it", () => {
+ const { setChannelItemFilters } = useSidebarStore.getState();
+ setChannelItemFilters({
+ ...DEFAULT_SIDEBAR_CHANNEL_ITEM_FILTERS,
+ sources: [DESKTOP_SOURCE, "slack"],
+ });
+ setChannelItemFilters({
+ ...DEFAULT_SIDEBAR_CHANNEL_ITEM_FILTERS,
+ sources: [DESKTOP_SOURCE],
+ });
+
+ expect(useSidebarStore.getState().pickedChannelItemSources).toEqual(
+ expect.arrayContaining(["slack"]),
+ );
+ });
+
it("rehydration sanitizes list item metadata fields", async () => {
localStorage.setItem(
"sidebar-storage",
diff --git a/products/desktop/packages/ui/src/features/sidebar/sidebarStore.ts b/products/desktop/packages/ui/src/features/sidebar/sidebarStore.ts
index cae5a3cd8f8a..7721de7df04c 100644
--- a/products/desktop/packages/ui/src/features/sidebar/sidebarStore.ts
+++ b/products/desktop/packages/ui/src/features/sidebar/sidebarStore.ts
@@ -37,6 +37,9 @@ interface SidebarStoreState {
// The space session list's narrowing. Held here rather than in the list so a
// space switch, which remounts the list, keeps what the user chose.
channelItemFilters: ChannelItemFilters;
+ // Every source the user has selected, so the filter menu keeps offering a
+ // source after it is unchecked, even when no loaded task comes from it.
+ pickedChannelItemSources: string[];
channelItemSort: ChannelItemSort;
channelItemGrouping: ChannelItemGrouping;
workSectionHeights: PreferredWorkSectionHeights;
@@ -101,6 +104,7 @@ export const useSidebarStore = create<SidebarStore>()(
showInternal: false,
taskTypeFilter: [...ALL_WORKSPACE_MODES],
channelItemFilters: DEFAULT_SIDEBAR_CHANNEL_ITEM_FILTERS,
+ pickedChannelItemSources: [],
channelItemSort: DEFAULT_CHANNEL_ITEM_SORT,
channelItemGrouping: DEFAULT_CHANNEL_ITEM_GROUPING,
workSectionHeights: {},
@@ -165,7 +169,16 @@ export const useSidebarStore = create<SidebarStore>()(
})),
setChannelsEnabled: (channelsEnabled) => set({ channelsEnabled }),
setChannelItemFilters: (channelItemFilters) =>
- set({ channelItemFilters }),
+ set((state) => ({
+ channelItemFilters,
+ pickedChannelItemSources: Array.from(
+ new Set([
+ ...state.pickedChannelItemSources,
+ ...state.channelItemFilters.sources,
+ ...channelItemFilters.sources,
+ ]),
+ ),
+ })),
setChannelItemSort: (channelItemSort) => set({ channelItemSort }),
setChannelItemGrouping: (channelItemGrouping) =>
set({ channelItemGrouping }),
@@ -214,6 +227,7 @@ export const useSidebarStore = create<SidebarStore>()(
showInternal: state.showInternal,
taskTypeFilter: state.taskTypeFilter,
channelItemFilters: state.channelItemFilters,
+ pickedChannelItemSources: state.pickedChannelItemSources,
channelItemSort: state.channelItemSort,
channelItemGrouping: state.channelItemGrouping,
workSectionHeights: state.workSectionHeights,
@@ -234,6 +248,7 @@ export const useSidebarStore = create<SidebarStore>()(
showInternal?: boolean;
taskTypeFilter?: WorkspaceMode[];
channelItemFilters?: Partial<ChannelItemFilters>;
+ pickedChannelItemSources?: string[];
channelItemSort?: ChannelItemSort;
channelItemGrouping?: ChannelItemGrouping;
workSectionHeights?: PreferredWorkSectionHeights;
@@ -267,6 +282,9 @@ export const useSidebarStore = create<SidebarStore>()(
...current.channelItemFilters,
...persistedState.channelItemFilters,
},
+ pickedChannelItemSources:
+ persistedState.pickedChannelItemSources ??
+ current.pickedChannelItemSources,
channelItemSort:
persistedState.channelItemSort ?? current.channelItemSort,
channelItemGrouping:
diff --git a/products/desktop/packages/ui/src/features/sidebar/usePinnedTasks.ts b/products/desktop/packages/ui/src/features/sidebar/usePinnedTasks.ts
index e50be8e1d529..f7e56d3d69e1 100644
--- a/products/desktop/packages/ui/src/features/sidebar/usePinnedTasks.ts
+++ b/products/desktop/packages/ui/src/features/sidebar/usePinnedTasks.ts
@@ -1,9 +1,11 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useCallback, useMemo, useRef } from "react";
import { useAuthenticatedQuery } from "../../hooks/useAuthenticatedQuery";
+import { taskKeys } from "../tasks/taskKeys";
import { pinnedTasksApi } from "./taskMetaApi";
const PINNED_TASKS_QUERY_KEY = ["task-pins"] as const;
+const PINNED_TASK_RECORDS_QUERY_KEY = taskKeys.list({ pinned: true });
export function usePinnedTasks() {
const queryClient = useQueryClient();
@@ -17,6 +19,14 @@ export function usePinnedTasks() {
const pinnedSet = useMemo(() => new Set(pinnedTaskIds), [pinnedTaskIds]);
+ const refetchPinnedTaskRecords = useCallback(
+ () =>
+ queryClient.invalidateQueries({
+ queryKey: PINNED_TASK_RECORDS_QUERY_KEY,
+ }),
+ [queryClient],
+ );
+
const togglePinMutation = useMutation({
scope: { id: "task-pins" },
mutationFn: ({ taskId, pinned }: { taskId: string; pinned: boolean }) =>
@@ -45,6 +55,7 @@ export function usePinnedTasks() {
return result.isPinned ? [...filtered, taskId] : filtered;
});
},
+ onSettled: refetchPinnedTaskRecords,
});
const togglePinMutationRef = useRef(togglePinMutation);
@@ -103,6 +114,7 @@ export function usePinnedTasks() {
return pinned ? rest : [...rest, ...failed];
});
},
+ onSettled: refetchPinnedTaskRecords,
});
const setPinnedManyMutationRef = useRef(setPinnedManyMutation);
@@ -128,8 +140,9 @@ export function usePinnedTasks() {
queryClient.setQueryData<string[]>(pinnedQueryKey, (old) =>
old?.filter((id) => id !== taskId),
);
+ await refetchPinnedTaskRecords();
},
- [queryClient, pinnedQueryKey],
+ [queryClient, pinnedQueryKey, refetchPinnedTaskRecords],
);
const isPinned = useCallback(
diff --git a/products/desktop/packages/ui/src/features/tasks/taskKeys.ts b/products/desktop/packages/ui/src/features/tasks/taskKeys.ts
index fef10e25b35b..5904eeab50d0 100644
--- a/products/desktop/packages/ui/src/features/tasks/taskKeys.ts
+++ b/products/desktop/packages/ui/src/features/tasks/taskKeys.ts
@@ -3,6 +3,10 @@ interface TaskListFilters {
createdBy?: number;
originProduct?: string;
internal?: boolean;
+ pinned?: boolean;
+ sources?: readonly string[];
+ limit?: number;
+ ordering?: string;
}
export const taskKeys = {
diff --git a/products/desktop/packages/ui/src/features/tasks/useTaskCrudMutations.test.tsx b/products/desktop/packages/ui/src/features/tasks/useTaskCrudMutations.test.tsx
index 76bde2513e41..72d893a11f9e 100644
--- a/products/desktop/packages/ui/src/features/tasks/useTaskCrudMutations.test.tsx
+++ b/products/desktop/packages/ui/src/features/tasks/useTaskCrudMutations.test.tsx
@@ -210,6 +210,17 @@ describe("useCreateTask.invalidateTasks", () => {
filters: { originProduct: "slack" },
expectedLength: 0,
},
+ { name: "pinned list", filters: { pinned: true }, expectedLength: 0 },
+ {
+ name: "list showing desktop sources",
+ filters: { sources: ["posthog_desktop", "posthog_mobile"] },
+ expectedLength: 1,
+ },
+ {
+ name: "list hiding desktop sources",
+ filters: { sources: ["slack"] },
+ expectedLength: 0,
+ },
])(
"seeds the $name with the new task ($expectedLength entr(y/ies))",
({ filters, expectedLength }) => {
diff --git a/products/desktop/packages/ui/src/features/tasks/useTaskCrudMutations.ts b/products/desktop/packages/ui/src/features/tasks/useTaskCrudMutations.ts
index 628dde456f1d..9e1d93201b6a 100644
--- a/products/desktop/packages/ui/src/features/tasks/useTaskCrudMutations.ts
+++ b/products/desktop/packages/ui/src/features/tasks/useTaskCrudMutations.ts
@@ -1,3 +1,4 @@
+import { sourceOf } from "@posthog/core/canvas/channelItems";
import {
SESSION_SERVICE,
type SessionService,
@@ -49,15 +50,19 @@ export function useCreateTask() {
// is read by the sidebar to brand a task's icon by id membership, so
// seeding a freshly created, non-slack task into it would make that task
// briefly render as a Slack task until the list refetches. Origin-less
- // lists, by contrast, should mirror every new task.
+ // lists, by contrast, should mirror every new task. A new task is never
+ // pinned, so the pinned list is skipped too, and a source-filtered list
+ // takes it only when it shows the new task's source.
queryClient.setQueriesData<Task[]>(
{
queryKey: taskKeys.lists(),
predicate: (query) => {
- const isOriginScopedList = Boolean(
- taskKeys.filtersOf(query.queryKey)?.originProduct,
- );
- return !isOriginScopedList;
+ const filters = taskKeys.filtersOf(query.queryKey);
+ if (filters?.originProduct || filters?.pinned) return false;
+ const { sources } = filters ?? {};
+ if (!sources) return true;
+ const source = sourceOf(newTask);
+ return source !== null && sources.includes(source);
},
},
(old) => insertTaskDedup(old, newTask),
diff --git a/products/desktop/packages/ui/src/features/tasks/useTasks.ts b/products/desktop/packages/ui/src/features/tasks/useTasks.ts
index e61954dab91b..149745d9c83a 100644
--- a/products/desktop/packages/ui/src/features/tasks/useTasks.ts
+++ b/products/desktop/packages/ui/src/features/tasks/useTasks.ts
@@ -24,20 +24,36 @@ export function useTasks(
repository?: string;
showAllUsers?: boolean;
showInternal?: boolean;
+ sources?: readonly string[];
+ limit?: number;
+ ordering?: "-last_activity_at" | "-created_at";
},
options?: { enabled?: boolean; subscribed?: boolean },
) {
const { data: currentUser } = useMeQuery();
const createdBy = filters?.showAllUsers ? undefined : currentUser?.id;
const internal = filters?.showInternal ? true : undefined;
+ const sources = filters?.sources?.length
+ ? [...filters.sources].sort()
+ : undefined;
return useAuthenticatedQuery(
- taskKeys.list({ repository: filters?.repository, createdBy, internal }),
+ taskKeys.list({
+ repository: filters?.repository,
+ createdBy,
+ internal,
+ sources,
+ limit: filters?.limit,
+ ordering: filters?.ordering,
+ }),
(client) =>
client.getTasks({
repository: filters?.repository,
createdBy,
internal,
+ sources,
+ limit: filters?.limit,
+ ordering: filters?.ordering,
// The sidebar and every other full-list consumer narrow the task before use
// and never read its description, so ask for the basic payload without it.
basic: true,
@@ -50,6 +66,25 @@ export function useTasks(
);
}
+// A pin can be on any task the user can see, also one older than the recent list reaches. The
+// server cuts each page at 100 rows, so this reads every page to keep every pin. It polls like the
+// other task lists: a pin on another user's task, or from a source the work list hides, has no
+// other path to a fresh status. It goes stale as fast as the pin IDs in usePinnedTasks, so a
+// window focus reloads both and a pin made on another device shows up.
+export function usePinnedTaskRecords() {
+ return useAuthenticatedQuery(
+ taskKeys.list({ pinned: true }),
+ async (client) =>
+ (
+ await client.getTasksWithStatus(
+ { pinned: true, basic: true },
+ { fetchAll: true },
+ )
+ ).tasks as unknown as Task[],
+ { staleTime: 30_000, refetchInterval: TASK_LIST_POLL_INTERVAL_MS },
+ );
+}
+
export function useTaskSummaries(
ids: string[],
options?: { enabled?: boolean },