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/perf): scope filed-task invalidation to the channels that changed (#85034)

Adam Leith983b86c71f68
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTasks.test.tsx b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTasks.test.tsx
new file mode 100644
index 000000000000..121b26e8aad7
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTasks.test.tsx
@@ -0,0 +1,112 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const LIST_PATH = [["channelTasks", "list"]];
+const listKey = (channelId: string) => [
+ ...LIST_PATH,
+ { input: { channelId }, type: "query" },
+];
+
+const mutations = vi.hoisted(() => ({
+ file: vi.fn().mockResolvedValue({ taskId: "t1", channelId: "dest" }),
+ unfile: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock("@posthog/host-router/react", () => ({
+ useHostTRPC: () => ({
+ channelTasks: {
+ list: {
+ pathFilter: () => ({ queryKey: LIST_PATH }),
+ queryFilter: ({ channelId }: { channelId: string }) => ({
+ queryKey: listKey(channelId),
+ }),
+ },
+ file: {
+ mutationOptions: (options: object) => ({
+ ...options,
+ mutationFn: mutations.file,
+ }),
+ },
+ unfile: {
+ mutationOptions: (options: object) => ({
+ ...options,
+ mutationFn: mutations.unfile,
+ }),
+ },
+ },
+ }),
+}));
+
+import { useChannelTaskMutations } from "./useChannelTasks";
+
+describe("useChannelTaskMutations", () => {
+ let queryClient: QueryClient;
+
+ function wrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ }
+
+ const invalidatedChannels = () =>
+ queryClient
+ .getQueryCache()
+ .getAll()
+ .filter((query) => query.state.isInvalidated)
+ .map(
+ (query) =>
+ (query.queryKey[1] as { input: { channelId: string } }).input
+ .channelId,
+ )
+ .sort();
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ // A user who has browsed around holds a list per channel visited. Only the
+ // ones a filed task actually moves between should be refetched.
+ queryClient.setQueryData(listKey("source"), [{ taskId: "t1" }]);
+ queryClient.setQueryData(listKey("dest"), [{ taskId: "t2" }]);
+ queryClient.setQueryData(listKey("unrelated"), [{ taskId: "t3" }]);
+ });
+
+ it("filing a task invalidates only its old and new channel", async () => {
+ const { result } = renderHook(() => useChannelTaskMutations(), { wrapper });
+
+ await act(async () => {
+ await result.current.fileTask("dest", "t1");
+ });
+
+ expect(invalidatedChannels()).toEqual(["dest", "source"]);
+ });
+
+ it("filing a task invalidates a channel whose list is still loading", async () => {
+ // A first load has no cached membership to check, and its request may have
+ // gone out before the mutation. Skipping it lets the pre-mutation response
+ // land and sit fresh, leaving the task showing in the space it left.
+ queryClient
+ .getQueryCache()
+ .build(queryClient, { queryKey: listKey("loading") });
+ const { result } = renderHook(() => useChannelTaskMutations(), { wrapper });
+
+ await act(async () => {
+ await result.current.fileTask("dest", "t1");
+ });
+
+ expect(invalidatedChannels()).toEqual(["dest", "loading", "source"]);
+ });
+
+ it("unfiling a task invalidates only the channel that listed it", async () => {
+ const { result } = renderHook(() => useChannelTaskMutations(), { wrapper });
+
+ await act(async () => {
+ await result.current.unfileTask("t1");
+ });
+
+ expect(invalidatedChannels()).toEqual(["source"]);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTasks.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTasks.ts
index 41ce31254009..3668b4144c65 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTasks.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTasks.ts
@@ -59,15 +59,40 @@ export function useChannelTaskMutations() {
const trpc = useHostTRPC();
const queryClient = useQueryClient();
- const invalidate = () => {
- void queryClient.invalidateQueries(trpc.channelTasks.list.pathFilter());
+ /**
+ * Filing moves a task, so at most two lists change: the channel it lands in
+ * and whichever one still shows it. Every other cached channel is untouched,
+ * and someone who has browsed a lot of channels holds a lot of those.
+ */
+ const invalidateAffected = (taskId: string, channelId?: string) => {
+ if (channelId) {
+ void queryClient.invalidateQueries(
+ trpc.channelTasks.list.queryFilter({ channelId }),
+ );
+ }
+ void queryClient.invalidateQueries({
+ ...trpc.channelTasks.list.pathFilter(),
+ predicate: (query) => {
+ const tasks = query.state.data as ChannelTaskRecord[] | undefined;
+ // A list still loading has no membership to check, and its in-flight
+ // request may have been sent before this mutation. Refetch rather than
+ // let a pre-mutation response land and sit fresh.
+ if (!tasks) return true;
+ return tasks.some((record) => record.taskId === taskId);
+ },
+ });
};
const file = useMutation(
- trpc.channelTasks.file.mutationOptions({ onSuccess: invalidate }),
+ trpc.channelTasks.file.mutationOptions({
+ onSuccess: (_data, variables) =>
+ invalidateAffected(variables.taskId, variables.channelId),
+ }),
);
const unfile = useMutation(
- trpc.channelTasks.unfile.mutationOptions({ onSuccess: invalidate }),
+ trpc.channelTasks.unfile.mutationOptions({
+ onSuccess: (_data, variables) => invalidateAffected(variables.taskId),
+ }),
);
return {