:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(desktop): do not reorder a space's sessions when one is opened (#105066)
posthog[bot]a89caab769f1
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.test.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.test.tsindex be62a63a46b7..b4eae2d5bf0f 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.test.ts+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.test.ts@@ -1,6 +1,37 @@-import type { UserBasic } from "@posthog/shared/domain-types";-import { describe, expect, it } from "vitest";-import { spacePeople } from "./useRecentSpaceTasks";+import type { Task, UserBasic } from "@posthog/shared/domain-types";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { renderHook, waitFor } from "@testing-library/react";+import { createElement, type ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ getTasksPage: vi.fn(),+ timestamps: {} as Record<string, { lastViewedAt: number | null }>,+}));++vi.mock("@posthog/ui/features/auth/authClient", () => ({+ useOptionalAuthenticatedClient: () => ({ getTasksPage: mocks.getTasksPage }),+}));+vi.mock("@posthog/ui/features/archive/useArchivedTaskIds", () => ({+ useArchivedTaskIds: () => EMPTY_IDS,+}));+vi.mock("@posthog/ui/features/sidebar/usePinnedTasks", () => ({+ usePinnedTasks: () => ({ pinnedTaskIds: EMPTY_IDS }),+}));+vi.mock("@posthog/ui/features/sidebar/useTaskViewed", () => ({+ useTaskViewed: () => ({ timestamps: mocks.timestamps }),+}));+vi.mock("@posthog/ui/features/canvas/hooks/useBlockedSessionCount", () => ({+ useBlockedTaskIds: () => EMPTY_IDS,+}));++const EMPTY_IDS: ReadonlySet<string> = new Set();++import {+ type SpaceTasks,+ spacePeople,+ useRecentSpaceTasks,+} from "./useRecentSpaceTasks";function user(name: string): UserBasic {return {@@ -51,3 +82,87 @@ describe("spacePeople", () => {expect(spacePeople(tasks, createdBy, limit)).toEqual(expected);});});++const OPENED_AT = Date.UTC(2026, 0, 2);++function spaceTask(id: string, activityAt: number): Task {+ return {+ id,+ title: id,+ created_at: new Date(Date.UTC(2026, 0, 1)).toISOString(),+ last_activity_at: new Date(activityAt).toISOString(),+ } as Task;+}++// Newest first, the order the server pages a space in.+const FRESH = spaceTask("fresh", Date.UTC(2026, 0, 3));+const UNREAD = spaceTask("unread", Date.UTC(2026, 0, 2) - 1);++let queryClient: QueryClient;+function wrapper({ children }: { children: ReactNode }) {+ return createElement(QueryClientProvider, { client: queryClient }, children);+}++function rowsOf(view: { result: { current: Map<string, SpaceTasks> } }) {+ return view.result.current.get("space-1")?.items.map((item) => item.id);+}++/** The tree with one space open, once its first page has arrived. */+async function openSpace() {+ const view = renderHook(() => useRecentSpaceTasks(["space-1"]), { wrapper });+ await waitFor(() => expect(rowsOf(view)).toEqual(["unread", "fresh"]));+ return view;+}++describe("useRecentSpaceTasks", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ mocks.timestamps = {+ fresh: { lastViewedAt: Date.UTC(2026, 0, 4) },+ unread: { lastViewedAt: Date.UTC(2026, 0, 1) },+ };+ mocks.getTasksPage.mockResolvedValue({+ tasks: [FRESH, UNREAD],+ count: 2,+ });+ });++ it("keeps a row where it is when the reader opens it", async () => {+ const view = await openSpace();++ // Opening the unread session marks it viewed. Its dot clears, but the row+ // must not drop below the quiet one under the reader's pointer.+ mocks.timestamps = {+ ...mocks.timestamps,+ unread: { lastViewedAt: OPENED_AT },+ };+ view.rerender();++ expect(rowsOf(view)).toEqual(["unread", "fresh"]);+ });++ it.each([+ { name: "unchanged", freshTask: FRESH },+ { name: "updated", freshTask: spaceTask("fresh", Date.UTC(2026, 0, 5)) },+ ])(+ "takes the viewed state again after an $name page is fetched",+ async ({ freshTask }) => {+ const view = await openSpace();++ mocks.timestamps = {+ ...mocks.timestamps,+ unread: { lastViewedAt: OPENED_AT },+ };+ mocks.getTasksPage.mockResolvedValue({+ tasks: [freshTask, UNREAD],+ count: 2,+ });+ await queryClient.refetchQueries();++ await waitFor(() => expect(rowsOf(view)).toEqual(["fresh", "unread"]));+ },+ );+});diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.tsindex b724641355cd..9c010d66ca03 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.ts+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.ts@@ -101,9 +101,9 @@ export const NO_TASKS: SpaceTasks = { items: [], total: 0 };/** What a space's rows were built from, so they can be reused unchanged. */interface CachedSpaceTasks {page: SpaceTaskPage;+ dataUpdatedAt: number;archivedTaskIds: ReadonlySet<string>;pinnedTaskIds: ReadonlySet<string>;- viewedAt: TaskTimestamps;blockedTaskIds: ReadonlySet<string>;built: SpaceTasks;}@@ -162,9 +162,12 @@ function spaceTreeOrder(* them the item models and every row's props.*/function combineTaskPages(- queries: { data?: SpaceTaskPage }[],-): SpaceTaskPage[] {- return queries.map((query) => query.data ?? NO_PAGE);+ queries: { data?: SpaceTaskPage; dataUpdatedAt: number }[],+): { page: SpaceTaskPage; dataUpdatedAt: number }[] {+ return queries.map((query) => ({+ page: query.data ?? NO_PAGE,+ dataUpdatedAt: query.dataUpdatedAt,+ }));}// Slower than the open channel's own feed (5s): the tree is a glance at what's@@ -204,18 +207,26 @@ export function useRecentSpaceTasks(// already-open row a new array — enough to re-render every session row in the// tree on every expand.const cache = useRef(new Map<string, CachedSpaceTasks>());+ // Out of the reuse key below, and read through a ref so it is not a+ // dependency either. Opening a session marks it viewed, and ordering on that+ // the moment it changes moves the row the reader just clicked — down a tier,+ // and sometimes off the five the space shows.+ const viewedAtRef = useRef(viewedAt);+ viewedAtRef.current = viewedAt;return useMemo(() => {const bySpace = new Map<string, SpaceTasks>();spaceIds.forEach((spaceId, index) => {- const page = pagePerSpace[index] ?? NO_PAGE;+ const page = pagePerSpace[index]?.page ?? NO_PAGE;+ const dataUpdatedAt = pagePerSpace[index]?.dataUpdatedAt ?? 0;const cached = cache.current.get(spaceId);if (cached &&cached.page === page &&+ // A successful poll can keep the same page reference.+ cached.dataUpdatedAt === dataUpdatedAt &&cached.archivedTaskIds === archivedTaskIds &&cached.pinnedTaskIds === pinnedTaskIds &&- cached.viewedAt === viewedAt &&cached.blockedTaskIds === blockedTaskIds) {bySpace.set(spaceId, cached.built);@@ -236,32 +247,26 @@ export function useRecentSpaceTasks(// archived and not yet mirrored, which `useServerArchiveSync` is working// through.const built: SpaceTasks = {- items: spaceTreeOrder(available, viewedAt, blockedTaskIds).slice(- 0,- RECENT_TASKS_PER_SPACE,- ),+ items: spaceTreeOrder(+ available,+ viewedAtRef.current,+ blockedTaskIds,+ ).slice(0, RECENT_TASKS_PER_SPACE),total:page.tasks.length < TREE_FETCH_LIMIT ? available.length : page.count,};cache.current.set(spaceId, {page,+ dataUpdatedAt,archivedTaskIds,pinnedTaskIds,- viewedAt,blockedTaskIds,built,});bySpace.set(spaceId, built);});return bySpace;- }, [- spaceIds,- pagePerSpace,- archivedTaskIds,- pinnedTaskIds,- viewedAt,- blockedTaskIds,- ]);+ }, [spaceIds, pagePerSpace, archivedTaskIds, pinnedTaskIds, blockedTaskIds]);}/**