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): filter and sort the sessions list from one menu (#81128)

Adam Leithb7546a6ac090
diff --git a/products/desktop/packages/core/src/canvas/channelItems.test.ts b/products/desktop/packages/core/src/canvas/channelItems.test.ts
index bbb4a9a6a2f7..64339cf8ae44 100644
--- a/products/desktop/packages/core/src/canvas/channelItems.test.ts
+++ b/products/desktop/packages/core/src/canvas/channelItems.test.ts
@@ -2,8 +2,12 @@ import type { Task, UserBasic } from "@posthog/shared/domain-types";
import { describe, expect, it } from "vitest";
import {
buildChannelItems,
+ type ChannelItemFilters,
type ChannelItemModel,
+ channelItemSources,
+ DEFAULT_CHANNEL_ITEM_FILTERS,
filterChannelItems,
+ sortChannelItems,
} from "./channelItems";
import type { DashboardRecord } from "./dashboardSchemas";
@@ -104,6 +108,86 @@ describe("buildChannelItems", () => {
expect(item.ts).toBe(0);
});
+ // The filters ask about facts that only exist once the renderer's state is
+ // folded in, so each has to survive the build rather than being read off the
+ // task alone.
+ it.each([
+ {
+ what: "a worktree, which is a local checkout",
+ mode: "worktree" as const,
+ runEnvironment: null,
+ expected: "local",
+ },
+ {
+ what: "a workspace we can see, over the run's own claim",
+ mode: "local" as const,
+ runEnvironment: "cloud" as const,
+ expected: "local",
+ },
+ {
+ what: "the run, when there is no workspace",
+ mode: undefined,
+ runEnvironment: "cloud" as const,
+ expected: "cloud",
+ },
+ {
+ what: "neither, which leaves the session unplaced",
+ mode: undefined,
+ runEnvironment: null,
+ expected: null,
+ },
+ ])("places a session by $what", ({ mode, runEnvironment, expected }) => {
+ const [item] = build({
+ feedTasks: [
+ task({
+ latest_run: runEnvironment
+ ? ({ environment: runEnvironment } as Task["latest_run"])
+ : undefined,
+ }),
+ ],
+ sessionFacts: {
+ needsInputTaskIds: NONE,
+ viewedTimestamps: {},
+ workspaceModeByTaskId: new Map(mode ? [["t1", mode]] : []),
+ },
+ });
+ expect(item.environment).toBe(expected);
+ });
+
+ it("reads a filed session's source, and none for one started here", () => {
+ const items = build({
+ feedTasks: [
+ task({ id: "filed", origin_product: "slack" }),
+ task({ id: "own", origin_product: "user_created" }),
+ ],
+ });
+ expect(items.map((i) => i.source)).toEqual(["slack", null]);
+ });
+
+ it("marks the sessions asking for input and the ones you haven't read", () => {
+ const items = build({
+ feedTasks: [
+ task({ id: "asking" }),
+ task({ id: "unread" }),
+ task({ id: "quiet" }),
+ ],
+ sessionFacts: {
+ needsInputTaskIds: new Set(["asking"]),
+ // Read before it last moved, so only this one counts as unread. A task
+ // never opened has no timestamp and is not unread.
+ viewedTimestamps: {
+ unread: { lastViewedAt: 1_000, lastActivityAt: null },
+ },
+ workspaceModeByTaskId: new Map(),
+ },
+ });
+ expect(items.map((i) => [i.id, i.needsInput, i.unread])).toEqual([
+ ["asking", true, false],
+ ["unread", false, true],
+ ["quiet", false, false],
+ ]);
+ });
+
it("returns everything when the owner is unknown", () => {
const items = build({
dashboards: [canvas({ createdBy: "Grace Hopper" })],
@@ -152,8 +236,13 @@ function model(over: Partial<ChannelItemModel> = {}): ChannelItemModel {
id: "t1",
title: "Ship the thing",
ts: 0,
+ createdAt: 0,
pinned: false,
rawStatus: null,
+ environment: null,
+ source: null,
+ needsInput: false,
+ unread: false,
authorUser: ME,
authorName: null,
authorUuid: ME.uuid,
@@ -163,6 +252,10 @@ function model(over: Partial<ChannelItemModel> = {}): ChannelItemModel {
};
}
+function filters(over: Partial<ChannelItemFilters> = {}): ChannelItemFilters {
+ return { ...DEFAULT_CHANNEL_ITEM_FILTERS, ...over };
+}
+
describe("filterChannelItems", () => {
const me = { uuid: ME.uuid };
@@ -170,8 +263,7 @@ describe("filterChannelItems", () => {
const items = [model({ title: "Ship IT" }), model({ title: "Other" })];
const result = filterChannelItems(items, {
query: " ship ",
- createdBy: "anyone",
- status: null,
+ filters: filters(),
me,
});
expect(result.map((i) => i.title)).toEqual(["Ship IT"]);
@@ -188,8 +280,7 @@ describe("filterChannelItems", () => {
];
const result = filterChannelItems(items, {
query: "",
- createdBy,
- status: null,
+ filters: filters({ createdBy }),
me,
});
expect(result.map((i) => i.id)).toEqual(expected);
@@ -205,36 +296,94 @@ describe("filterChannelItems", () => {
];
const result = filterChannelItems(items, {
query: "",
- createdBy,
- status: null,
+ filters: filters({ createdBy }),
me,
});
expect(result).toEqual([]);
},
);
- it("filters by run status, including not_started", () => {
- const items = [
- model({ id: "fresh", rawStatus: "not_started" }),
- model({ id: "done", rawStatus: "completed" }),
- ];
- const result = filterChannelItems(items, {
+ const CANDIDATES = [
+ model({ id: "asking", needsInput: true }),
+ model({ id: "unread", unread: true }),
+ model({ id: "pinned", pinned: true }),
+ model({ id: "local", environment: "local" }),
+ model({ id: "cloud", environment: "cloud" }),
+ model({ id: "from-slack", source: "slack" }),
+ model({ id: "quiet" }),
+ ];
+
+ it.each([
+ { filter: { attention: "needs_input" }, kept: ["asking"] },
+ { filter: { attention: "unread" }, kept: ["unread"] },
+ { filter: { pinned: "pinned" }, kept: ["pinned"] },
+ { filter: { environment: "local" }, kept: ["local"] },
+ { filter: { environment: "cloud" }, kept: ["cloud"] },
+ { filter: { source: "slack" }, kept: ["from-slack"] },
+ ] as const)("keeps only $kept for $filter", ({ filter, kept }) => {
+ const result = filterChannelItems(CANDIDATES, {
query: "",
- createdBy: "anyone",
- status: "not_started",
+ filters: filters(filter),
me,
});
- expect(result.map((i) => i.id)).toEqual(["fresh"]);
+ expect(result.map((i) => i.id)).toEqual(kept);
});
- it("excludes canvases when a run status is selected", () => {
- const items = [model({ kind: "canvas", rawStatus: null })];
+ it("narrows on every filter at once", () => {
+ const items = [
+ model({ id: "match", unread: true, environment: "cloud", pinned: true }),
+ model({ id: "not-pinned", unread: true, environment: "cloud" }),
+ model({ id: "wrong-place", unread: true, environment: "local" }),
+ ];
const result = filterChannelItems(items, {
query: "",
- createdBy: "anyone",
- status: "completed",
+ filters: filters({
+ attention: "unread",
+ environment: "cloud",
+ pinned: "pinned",
+ }),
me,
});
- expect(result).toEqual([]);
+ expect(result.map((i) => i.id)).toEqual(["match"]);
+ });
+});
+
+describe("channelItemSources", () => {
+ it("offers each source once, and nothing for sessions started here", () => {
+ const items = [
+ model({ id: "a", source: "slack" }),
+ model({ id: "b", source: "slack" }),
+ model({ id: "c", source: "error_tracking" }),
+ model({ id: "d", source: null }),
+ ];
+ expect(channelItemSources(items)).toEqual(["error_tracking", "slack"]);
+ });
+});
+
+describe("sortChannelItems", () => {
+ const items = [
+ model({ id: "middle", title: "B", ts: 2, createdAt: 3 }),
+ model({ id: "newest", title: "C", ts: 3, createdAt: 1 }),
+ model({ id: "oldest", title: "A", ts: 1, createdAt: 2 }),
+ ];
+
+ it.each([
+ { sort: "recent", order: ["newest", "middle", "oldest"] },
+ { sort: "created", order: ["middle", "oldest", "newest"] },
+ { sort: "alpha", order: ["oldest", "middle", "newest"] },
+ ] as const)("orders by $sort", ({ sort, order }) => {
+ expect(sortChannelItems(items, sort).map((i) => i.id)).toEqual(order);
+ });
+
+ // A pin is a request not to lose the thing, and the list is capped — under any
+ // sort a pinned session that fell in with the rest could drop off the end.
+ it("leads with pins whatever the sort", () => {
+ const pinnedLast = [
+ ...items,
+ model({ id: "pin", title: "Z", ts: 0, createdAt: 0, pinned: true }),
+ ];
+ for (const sort of ["recent", "created", "alpha"] as const) {
+ expect(sortChannelItems(pinnedLast, sort)[0]?.id).toBe("pin");
+ }
});
});
diff --git a/products/desktop/packages/core/src/canvas/channelItems.ts b/products/desktop/packages/core/src/canvas/channelItems.ts
index 2f30acda8a88..2cda8065efb8 100644
--- a/products/desktop/packages/core/src/canvas/channelItems.ts
+++ b/products/desktop/packages/core/src/canvas/channelItems.ts
@@ -1,18 +1,37 @@
+import type { WorkspaceMode } from "@posthog/shared";
import type {
Task,
TaskRunStatus,
UserBasic,
} from "@posthog/shared/domain-types";
+import { isTaskUnread, type TaskTimestamp } from "../sidebar/buildSidebarData";
import type { DashboardRecord } from "./dashboardSchemas";
+/** Where a session runs. `worktree` is a local checkout, so it reads as local. */
+export type ChannelItemEnvironment = "local" | "cloud";
+
export interface ChannelItemModel {
key: string;
kind: "task" | "canvas";
id: string;
title: string;
ts: number;
+ /** When it was first made, for the created-first sort. */
+ createdAt: number;
pinned: boolean;
rawStatus: TaskRunStatus | null;
+ /**
+ * The three session facts the filters ask about. A canvas has no run, so it
+ * carries the empty answer to all three and drops out of any filter that
+ * names one.
+ */
+ environment: ChannelItemEnvironment | null;
+ /** The product that filed it (`origin_product`), or null if it started here. */
+ source: string | null;
+ /** The agent is blocked on an answer from you. */
+ needsInput: boolean;
+ /** There is activity here you haven't seen. */
+ unread: boolean;
authorUser: UserBasic | null;
authorName: string | null;
authorUuid: string | null;
@@ -44,18 +63,65 @@ function isOwnedBy(
return item.authorUuid != null && item.authorUuid === owner.uuid;
}
+/**
+ * The per-session state the item list can't read off a task on its own: what the
+ * live session is asking for, when you last looked, and where the session's
+ * workspace actually is. All three live in the renderer, so they are handed in
+ * rather than fetched — and each one defaults to "nothing known", which reads as
+ * a quiet, unplaced session rather than a wrong claim about one.
+ */
+export interface ChannelSessionFacts {
+ needsInputTaskIds: ReadonlySet<string>;
+ viewedTimestamps: Readonly<Record<string, TaskTimestamp>>;
+ workspaceModeByTaskId: ReadonlyMap<string, WorkspaceMode>;
+}
+
+const NO_SESSION_FACTS: ChannelSessionFacts = {
+ needsInputTaskIds: new Set(),
+ viewedTimestamps: {},
+ workspaceModeByTaskId: new Map(),
+};
+
+/**
+ * Where a session runs, preferring the workspace we can see over the run's own
+ * claim — the same precedence `deriveTaskData` uses, so a row and this filter
+ * can't disagree. A session with neither is unplaced, not local.
+ */
+function environmentOf(
+ task: Task,
+ workspaceMode: WorkspaceMode | undefined,
+): ChannelItemEnvironment | null {
+ const mode = workspaceMode ?? task.latest_run?.environment ?? null;
+ if (mode === null) return null;
+ return mode === "cloud" ? "cloud" : "local";
+}
+
+/**
+ * `origin_product` for a session someone started here rather than one filed by
+ * another product. It is the default the backend stamps on, so it is an absence
+ * of a source, not one of the sources to choose between.
+ */
+const SELF_ORIGIN = "user_created";
+
+function sourceOf(task: Task): string | null {
+ const origin = task.origin_product;
+ return origin && origin !== SELF_ORIGIN ? origin : null;
+}
+
export function buildChannelItems({
dashboards,
feedTasks,
archivedTaskIds,
pinnedTaskIds,
ownedBy,
+ sessionFacts = NO_SESSION_FACTS,
}: {
dashboards: readonly DashboardRecord[];
feedTasks: readonly Task[];
archivedTaskIds: ReadonlySet<string>;
pinnedTaskIds: ReadonlySet<string>;
ownedBy: ChannelItemOwner | null;
+ sessionFacts?: ChannelSessionFacts;
}): ChannelItemModel[] {
const canvasItems: ChannelItemModel[] = dashboards.map((d) => ({
key: `canvas:${d.id}`,
@@ -63,8 +129,13 @@ export function buildChannelItems({
id: d.id,
title: d.name,
ts: d.updatedAt,
+ createdAt: d.createdAt,
pinned: d.pinnedAt != null,
rawStatus: null,
+ environment: null,
+ source: null,
+ needsInput: false,
+ unread: false,
authorUser: null,
authorName: d.createdBy ?? null,
authorUuid: d.createdByUuid ?? null,
@@ -82,8 +153,19 @@ export function buildChannelItems({
id: task.id,
title: task.title || "Untitled task",
ts: Date.parse(task.updated_at) || 0,
+ createdAt: Date.parse(task.created_at) || 0,
pinned: pinnedTaskIds.has(task.id),
rawStatus: task.latest_run?.status ?? null,
+ environment: environmentOf(
+ task,
+ sessionFacts.workspaceModeByTaskId.get(task.id),
+ ),
+ source: sourceOf(task),
+ needsInput: sessionFacts.needsInputTaskIds.has(task.id),
+ unread: isTaskUnread(
+ task.updated_at,
+ sessionFacts.viewedTimestamps[task.id],
+ ),
authorUser: task.created_by ?? null,
authorName: null,
authorUuid: task.created_by?.uuid ?? null,
@@ -98,18 +180,76 @@ export function buildChannelItems({
}
export type CreatedByFilter = "anyone" | "me" | "others";
+/** What a session wants from you, in the row dot's vocabulary. */
+export type AttentionFilter = "any" | "needs_input" | "unread";
+export type PinnedFilter = "any" | "pinned";
+export type EnvironmentFilter = "any" | ChannelItemEnvironment;
+/** `ANY_SOURCE`, or an `origin_product` key like `slack`. */
+export type SourceFilter = string;
+export type ChannelItemSort = "recent" | "created" | "alpha";
+
+export const ANY_SOURCE = "any";
+
+export interface ChannelItemFilters {
+ createdBy: CreatedByFilter;
+ attention: AttentionFilter;
+ pinned: PinnedFilter;
+ environment: EnvironmentFilter;
+ source: SourceFilter;
+}
+
+export const DEFAULT_CHANNEL_ITEM_FILTERS: ChannelItemFilters = {
+ createdBy: "anyone",
+ attention: "any",
+ pinned: "any",
+ environment: "any",
+ source: ANY_SOURCE,
+};
+
+/** Newest activity first, which is what a session list is for. */
+export const DEFAULT_CHANNEL_ITEM_SORT: ChannelItemSort = "recent";
+
+/**
+ * Whether the list is narrowed — what lights the filter button up. The search
+ * box is excluded: it says so itself, visibly, while a filter left on in a
+ * closed menu is the state nothing else on screen explains.
+ */
+export function hasActiveChannelItemFilters(
+ filters: ChannelItemFilters,
+): boolean {
+ return (
+ filters.createdBy !== "anyone" ||
+ filters.attention !== "any" ||
+ filters.pinned !== "any" ||
+ filters.environment !== "any" ||
+ filters.source !== ANY_SOURCE
+ );
+}
+
+/**
+ * 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
+ * between renders.
+ */
+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();
+}
export function filterChannelItems(
items: readonly ChannelItemModel[],
{
query,
- createdBy,
- status,
+ filters,
me,
}: {
query: string;
- createdBy: CreatedByFilter;
- status: TaskRunStatus | null;
+ filters: ChannelItemFilters;
me: ChannelItemOwner;
},
): ChannelItemModel[] {
@@ -121,15 +261,58 @@ export function filterChannelItems(
) {
return false;
}
- if (createdBy !== "anyone") {
+ if (filters.createdBy !== "anyone") {
// An item with no creator uuid (e.g. the backend returns `created_by:
// null` once a creator is deleted) belongs to neither bucket: it isn't
// mine, but "others" means a *known* other person, not "unknown".
if (item.authorUuid == null) return false;
const mine = isOwnedBy(item, me);
- if (createdBy === "me" ? !mine : mine) return false;
+ if (filters.createdBy === "me" ? !mine : mine) return false;
+ }
+ if (filters.attention === "needs_input" && !item.needsInput) return false;
+ if (filters.attention === "unread" && !item.unread) return false;
+ if (filters.pinned === "pinned" && !item.pinned) return false;
+ // An unplaced session (no workspace, no run) matches neither environment:
+ // naming one is a question about where the work happens, and "we don't
+ // know" is not an answer to it.
+ if (
+ filters.environment !== "any" &&
+ item.environment !== filters.environment
+ ) {
+ return false;
+ }
+ if (filters.source !== ANY_SOURCE && item.source !== filters.source) {
+ return false;
}
- if (status && item.rawStatus !== status) return false;
return true;
});
}
+
+function compareChannelItems(
+ a: ChannelItemModel,
+ b: ChannelItemModel,
+ sort: ChannelItemSort,
+): number {
+ if (sort === "alpha") return a.title.localeCompare(b.title);
+ if (sort === "created") return b.createdAt - a.createdAt;
+ return b.ts - a.ts;
+}
+
+/**
+ * The list in the order the reader asked for, pins first.
+ *
+ * Pins lead whatever the sort is: a pin is a request not to lose the thing, and
+ * below the sort it would fall off the end of the list's cap. The order inside
+ * each half is the one that was chosen.
+ */
+export function sortChannelItems(
+ items: readonly ChannelItemModel[],
+ sort: ChannelItemSort,
+): ChannelItemModel[] {
+ const pinned = items.filter((item) => item.pinned);
+ const rest = items.filter((item) => !item.pinned);
+ return [
+ ...pinned.sort((a, b) => compareChannelItems(a, b, sort)),
+ ...rest.sort((a, b) => compareChannelItems(a, b, sort)),
+ ];
+}
diff --git a/products/desktop/packages/core/src/canvas/runStatus.test.ts b/products/desktop/packages/core/src/canvas/runStatus.test.ts
index 7c19dd9715ab..fbf05ffc6ea5 100644
--- a/products/desktop/packages/core/src/canvas/runStatus.test.ts
+++ b/products/desktop/packages/core/src/canvas/runStatus.test.ts
@@ -1,20 +1,5 @@
-import type { TaskRunStatus } from "@posthog/shared/domain-types";
import { describe, expect, it } from "vitest";
-import {
- RUN_STATUS_FILTER_OPTIONS,
- RUN_STATUS_LABELS,
- runStatusLabel,
- runStatusVariant,
-} from "./runStatus";
-
-const ALL_STATUSES: TaskRunStatus[] = [
- "not_started",
- "queued",
- "in_progress",
- "completed",
- "failed",
- "cancelled",
-];
+import { runStatusLabel, runStatusVariant } from "./runStatus";
describe("runStatusLabel", () => {
it.each([
@@ -49,27 +34,3 @@ describe("runStatusVariant", () => {
expect(runStatusVariant(null)).toBe("default");
});
});
-
-describe("RUN_STATUS_FILTER_OPTIONS", () => {
- it("leads with the any-status option", () => {
- expect(RUN_STATUS_FILTER_OPTIONS[0]).toEqual({
- value: null,
- label: "Any status",
- });
- });
-
- it("offers every run status, so none is silently unfilterable", () => {
- const offered = RUN_STATUS_FILTER_OPTIONS.map((o) => o.value).filter(
- (v) => v !== null,
- );
- expect(new Set(offered)).toEqual(new Set(ALL_STATUSES));
- });
-
- it("reuses the shared labels rather than restating them", () => {
- for (const option of RUN_STATUS_FILTER_OPTIONS) {
- if (option.value) {
- expect(option.label).toBe(RUN_STATUS_LABELS[option.value]);
- }
- }
- });
-});
diff --git a/products/desktop/packages/core/src/canvas/runStatus.ts b/products/desktop/packages/core/src/canvas/runStatus.ts
index 90917af05d7b..312283271691 100644
--- a/products/desktop/packages/core/src/canvas/runStatus.ts
+++ b/products/desktop/packages/core/src/canvas/runStatus.ts
@@ -47,20 +47,3 @@ export function isRunStatusActive(
): boolean {
return status === "queued" || status === "in_progress";
}
-
-export const RUN_STATUS_FILTER_OPTIONS: readonly {
- value: TaskRunStatus | null;
- label: string;
-}[] = [
- { value: null, label: "Any status" },
- ...(
- [
- "not_started",
- "queued",
- "in_progress",
- "completed",
- "failed",
- "cancelled",
- ] as const
- ).map((value) => ({ value, label: RUN_STATUS_LABELS[value] })),
-];
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelFilterMenu.stories.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelFilterMenu.stories.tsx
new file mode 100644
index 000000000000..9dbcb52e38d8
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelFilterMenu.stories.tsx
@@ -0,0 +1,82 @@
+import {
+ type ChannelItemFilters,
+ type ChannelItemSort,
+ DEFAULT_CHANNEL_ITEM_FILTERS,
+ DEFAULT_CHANNEL_ITEM_SORT,
+ hasActiveChannelItemFilters,
+} from "@posthog/core/canvas/channelItems";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { useState } from "react";
+import { ChannelFilterMenu } from "./ChannelFilterMenu";
+
+/**
+ * The menu owns nothing — the sessions list holds the filters — so the story
+ * supplies the state the sidebar would, and the picks stick the way they do
+ * there.
+ */
+function Harness({
+ initialFilters,
+ initialSort,
+ sources,
+ showCreatedBy,
+}: {
+ initialFilters: ChannelItemFilters;
+ initialSort: ChannelItemSort;
+ sources: string[];
+ showCreatedBy: boolean;
+}) {
+ const [filters, setFilters] = useState(initialFilters);
+ const [sort, setSort] = useState(initialSort);
+ return (
+ <div className="flex justify-end p-2">
+ <ChannelFilterMenu
+ filters={filters}
+ onFiltersChange={setFilters}
+ sort={sort}
+ onSortChange={setSort}
+ sources={sources}
+ showCreatedBy={showCreatedBy}
+ active={hasActiveChannelItemFilters(filters)}
+ />
+ </div>
+ );
+}
+
+const meta: Meta<typeof Harness> = {
+ title: "Spaces/ChannelFilterMenu",
+ component: Harness,
+ args: {
+ initialFilters: DEFAULT_CHANNEL_ITEM_FILTERS,
+ initialSort: DEFAULT_CHANNEL_ITEM_SORT,
+ sources: ["slack", "error_tracking", "support_queue"],
+ showCreatedBy: true,
+ },
+ decorators: [
+ (Story) => (
+ <div className="w-64 border border-border">
+ <Story />
+ </div>
+ ),
+ ],
+};
+
+export default meta;
+type Story = StoryObj<typeof Harness>;
+
+export const Default: Story = {};
+
+/** A filter is on, so the button is lit and the menu offers a way out. */
+export const Filtered: Story = {
+ args: {
+ initialFilters: {
+ ...DEFAULT_CHANNEL_ITEM_FILTERS,
+ attention: "needs_input",
+ environment: "cloud",
+ },
+ },
+};
+
+/** #me, where every session is yours: no "created by", and no filed sources. */
+export const PersonalSpace: Story = {
+ args: { showCreatedBy: false, sources: [] },
+};
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelFilterMenu.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelFilterMenu.tsx
new file mode 100644
index 000000000000..d454db6bfc39
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelFilterMenu.tsx
@@ -0,0 +1,269 @@
+import { FunnelSimple as FunnelSimpleIcon } from "@phosphor-icons/react";
+import {
+ ANY_SOURCE,
+ type AttentionFilter,
+ type ChannelItemFilters,
+ type ChannelItemSort,
+ type CreatedByFilter,
+ DEFAULT_CHANNEL_ITEM_FILTERS,
+ type EnvironmentFilter,
+ type PinnedFilter,
+} from "@posthog/core/canvas/channelItems";
+import {
+ Button,
+ cn,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from "@posthog/quill";
+import { cnHeaderButton } from "@posthog/ui/features/canvas/components/channelHeaderButton";
+import { getOriginProductMeta } from "@posthog/ui/features/sidebar/components/items/TaskIcon";
+import {
+ DOT_TONE_VAR,
+ type DotTone,
+} from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";
+
+interface Option<T extends string> {
+ value: T;
+ label: string;
+ /** Drawn before the label, in the list's own dot colours. */
+ tone?: DotTone;
+}
+
+// The two states a session can be in that are yours to clear, in the list's own
+// vocabulary: blue is blocked on you, the brand yellow is output you haven't
+// read. Everything settled is what's left, and has nothing to filter for.
+const ATTENTION_OPTIONS: readonly Option<AttentionFilter>[] = [
+ { value: "any", label: "Any status" },
+ { value: "needs_input", label: "Needs input", tone: "blue" },
+ { value: "unread", label: "Unread", tone: "yellow" },
+];
+
+const CREATED_BY_OPTIONS: readonly Option<CreatedByFilter>[] = [
+ { value: "anyone", label: "Anyone" },
+ { value: "me", label: "Me" },
+ { value: "others", label: "Other people" },
+];
+
+const PINNED_OPTIONS: readonly Option<PinnedFilter>[] = [
+ { value: "any", label: "All sessions" },
+ { value: "pinned", label: "Pinned only" },
+];
+
+const ENVIRONMENT_OPTIONS: readonly Option<EnvironmentFilter>[] = [
+ { value: "any", label: "Anywhere" },
+ { value: "local", label: "Local" },
+ { value: "cloud", label: "Cloud" },
+];
+
+const SORT_OPTIONS: readonly Option<ChannelItemSort>[] = [
+ { value: "recent", label: "Recent activity" },
+ { value: "created", label: "Date created" },
+ { value: "alpha", label: "Name" },
+];
+
+function labelOf<T extends string>(
+ options: readonly Option<T>[],
+ value: T,
+): string {
+ return options.find((option) => option.value === value)?.label ?? "";
+}
+
+/**
+ * A status option's dot, drawn from the same tone tokens a row's dot uses so the
+ * menu names the marks in the list rather than a second colour vocabulary. No
+ * tooltip: the label is right beside it.
+ */
+function OptionDot({ tone }: { tone: DotTone }) {
+ return (
+ <span
+ aria-hidden
+ className="size-2 shrink-0 rounded-full"
+ style={{ backgroundColor: DOT_TONE_VAR[tone] }}
+ />
+ );
+}
+
+/**
+ * One filter as a submenu: its name, the choice currently in force, and the
+ * radio group behind it. A group per submenu keeps the top level a list of
+ * questions rather than a wall of every answer to all of them.
+ */
+function FilterSubmenu<T extends string>({
+ label,
+ options,
+ value,
+ onChange,
+}: {
+ label: string;
+ options: readonly Option<T>[];
+ value: T;
+ onChange: (value: T) => void;
+}) {
+ // Every list leads with its own "everything" option, so a value that isn't the
+ // first one is a choice someone made, and the trigger says so.
+ const narrowed = value !== options[0]?.value;
+
+ return (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger className="pr-1">
+ <span>{label}</span>
+ <span
+ className={`flex-1 pl-4 text-right ${narrowed ? "text-primary" : "text-muted-foreground/80"}`}
+ >
+ {labelOf(options, value)}
+ </span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ <DropdownMenuRadioGroup
+ value={value}
+ onValueChange={(next) => onChange(next as T)}
+ >
+ {options.map((option) => (
+ <DropdownMenuRadioItem key={option.value} value={option.value}>
+ <span className="flex items-center gap-2">
+ {option.tone ? <OptionDot tone={option.tone} /> : null}
+ {option.label}
+ </span>
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+}
+
+/**
+ * The sessions list's filters and sort order, behind the funnel button.
+ *
+ * Sources are the ones the list actually holds rather than every product that
+ * can file a session: an option that can only ever empty the list is a worse
+ * answer than not offering it.
+ */
+export function ChannelFilterMenu({
+ filters,
+ onFiltersChange,
+ sort,
+ onSortChange,
+ sources,
+ showCreatedBy,
+ active,
+}: {
+ filters: ChannelItemFilters;
+ onFiltersChange: (filters: ChannelItemFilters) => void;
+ sort: ChannelItemSort;
+ onSortChange: (sort: ChannelItemSort) => void;
+ /** `origin_product` keys present in the list. */
+ sources: readonly string[];
+ /** False in #me, where every session is yours and the filter says nothing. */
+ showCreatedBy: boolean;
+ /** A filter is narrowing the list, so the button says so. */
+ active: boolean;
+}) {
+ const sourceOptions: Option<string>[] = [
+ { value: ANY_SOURCE, label: "Any source" },
+ ...sources.map((source) => ({
+ value: source,
+ // A source we have no name for still filters — the raw key is a worse
+ // label than "Slack", but a missing option would be a worse answer.
+ label: getOriginProductMeta(source)?.label ?? source,
+ })),
+ ];
+
+ const set = <K extends keyof ChannelItemFilters>(
+ key: K,
+ value: ChannelItemFilters[K],
+ ) => onFiltersChange({ ...filters, [key]: value });
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="default"
+ size="icon-xs"
+ aria-label="Filter"
+ className={cn("relative", cnHeaderButton(active))}
+ >
+ <FunnelSimpleIcon size={12} />
+ {active && (
+ <span
+ aria-hidden
+ className="absolute top-0 right-0 size-1.5 rounded-full bg-primary"
+ />
+ )}
+ </Button>
+ }
+ />
+ <DropdownMenuContent
+ align="end"
+ side="bottom"
+ sideOffset={6}
+ className="min-w-fit"
+ >
+ <FilterSubmenu
+ label="Status"
+ options={ATTENTION_OPTIONS}
+ value={filters.attention}
+ onChange={(value) => set("attention", value)}
+ />
+ {/* #me holds only your own sessions, so "created by" can only ever
+ answer "you" — the whole group is dropped rather than shown with two
+ options that empty the list. */}
+ {showCreatedBy && (
+ <FilterSubmenu
+ label="Created by"
+ options={CREATED_BY_OPTIONS}
+ value={filters.createdBy}
+ onChange={(value) => set("createdBy", value)}
+ />
+ )}
+ <FilterSubmenu
+ label="Pinned"
+ options={PINNED_OPTIONS}
+ value={filters.pinned}
+ onChange={(value) => set("pinned", value)}
+ />
+ <FilterSubmenu
+ label="Environment"
+ options={ENVIRONMENT_OPTIONS}
+ value={filters.environment}
+ onChange={(value) => set("environment", value)}
+ />
+ <FilterSubmenu
+ label="Source"
+ options={sourceOptions}
+ value={filters.source}
+ onChange={(value) => set("source", value)}
+ />
+ <DropdownMenuSeparator />
+ <FilterSubmenu
+ label="Sort by"
+ options={SORT_OPTIONS}
+ value={sort}
+ onChange={onSortChange}
+ />
+ {active && (
+ <>
+ <DropdownMenuSeparator />
+ {/* The empty state tells you to clear the filters; with five of them
+ behind submenus, this is where that instruction is carried out. */}
+ <DropdownMenuItem
+ onClick={() => onFiltersChange(DEFAULT_CHANNEL_ITEM_FILTERS)}
+ variant="destructive"
+ >
+ Clear filters
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx
index 426504cb923e..9be41f4fee5f 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx
@@ -41,8 +41,13 @@ function item(overrides: Partial<ChannelItemModel> = {}): ChannelItemModel {
id: "task-1",
title: "Investigate signup drop-off",
ts: Date.parse("2026-07-17T12:00:00.000Z"),
+ createdAt: Date.parse("2026-07-16T12:00:00.000Z"),
pinned: false,
rawStatus: null,
+ environment: null,
+ source: null,
+ needsInput: false,
+ unread: false,
authorUser: null,
authorName: null,
authorUuid: "user-uuid",
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.test.tsx
index bcd735dcc70c..3dc85e226331 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.test.tsx
@@ -1,6 +1,6 @@
import type { ChannelItemModel } from "@posthog/core/canvas/channelItems";
import { Theme } from "@radix-ui/themes";
-import { render, screen } from "@testing-library/react";
+import { fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -62,8 +62,13 @@ function item(overrides: Partial<ChannelItemModel> = {}): ChannelItemModel {
id: "task-1",
title: "Investigate signup drop-off",
ts: Date.parse("2026-07-17T12:00:00.000Z"),
+ createdAt: Date.parse("2026-07-16T12:00:00.000Z"),
pinned: false,
rawStatus: null,
+ environment: null,
+ source: null,
+ needsInput: false,
+ unread: false,
authorUser: null,
authorName: "Someone else",
// Not the viewer, so filtering to "Me" leaves nothing.
@@ -131,15 +136,23 @@ describe("ChannelSidebar", () => {
});
it("doesn't call a cold load 'no matches' while a filter is active", async () => {
- const user = userEvent.setup();
+ // A submenu is `pointer-events: none` until Base UI settles it, which never
+ // happens under jsdom's layout — the same setup the other menu suites use.
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
mocks.items = [item()];
const { rerender } = renderSidebar();
// Filter down to the viewer's own items; this one is someone else's, so the
// settled list really has no matches.
await user.click(screen.getByRole("button", { name: "Filter" }));
- await user.click(await screen.findByRole("menuitemradio", { name: "Me" }));
- expect(screen.getByText("No matches")).toBeInTheDocument();
+ await user.click(
+ await screen.findByRole("menuitem", { name: /Created by/ }),
+ );
+ // A pointer sequence inside an unsettled submenu never reaches Base UI's
+ // handler under jsdom; the reasoning-menu suite picks its radios this way
+ // for the same reason.
+ fireEvent.click(await screen.findByRole("menuitemradio", { name: "Me" }));
+ expect(await screen.findByText("No matches")).toBeInTheDocument();
// Reloading the space empties the list again — that isn't a verdict.
mocks.items = [];
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx
index 5c59fd06d2dc..649b4c74ad55 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx
@@ -1,21 +1,20 @@
import {
ChatsCircleIcon,
- FunnelSimple as FunnelSimpleIcon,
MagnifyingGlass,
PackageIcon,
} from "@phosphor-icons/react";
-import type { CreatedByFilter } from "@posthog/core/canvas/channelItems";
-import { filterChannelItems } from "@posthog/core/canvas/channelItems";
-import { RUN_STATUS_FILTER_OPTIONS } from "@posthog/core/canvas/runStatus";
+import {
+ type ChannelItemFilters,
+ type ChannelItemSort,
+ channelItemSources,
+ DEFAULT_CHANNEL_ITEM_FILTERS,
+ DEFAULT_CHANNEL_ITEM_SORT,
+ filterChannelItems,
+ hasActiveChannelItemFilters,
+ sortChannelItems,
+} from "@posthog/core/canvas/channelItems";
import {
Button,
- cn,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuRadioGroup,
- DropdownMenuRadioItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
Empty,
EmptyDescription,
EmptyHeader,
@@ -27,10 +26,11 @@ import {
SkeletonText,
} from "@posthog/quill";
import { LOOPS_FLAG } from "@posthog/shared";
-import type { TaskRunStatus } from "@posthog/shared/domain-types";
import { ChannelBackRow } from "@posthog/ui/features/canvas/components/ChannelBackRow";
+import { ChannelFilterMenu } from "@posthog/ui/features/canvas/components/ChannelFilterMenu";
import { ChannelItemRow } from "@posthog/ui/features/canvas/components/ChannelItemRow";
import { ChannelsFab } from "@posthog/ui/features/canvas/components/ChannelsFab";
+import { cnHeaderButton } from "@posthog/ui/features/canvas/components/channelHeaderButton";
import {
type ChannelPageKey,
channelPageLabel,
@@ -47,19 +47,6 @@ import { logger } from "@posthog/ui/shell/logger";
import { useNavigate, useRouterState } from "@tanstack/react-router";
import { useMemo, useState } from "react";
-const CREATED_BY_OPTIONS: readonly { value: CreatedByFilter; label: string }[] =
- [
- { value: "anyone", label: "Anyone" },
- { value: "me", label: "Me" },
- { value: "others", label: "Other people" },
- ] as const;
-
-// The header's icon buttons are quill's ghost button at the 20px scale; only the
-// sticky state is ours, because quill styles the transient open state (hover,
-// popup) but has no notion of "search is showing" or "a filter is applied".
-const cnHeaderButton = (active: boolean) =>
- cn("text-muted-foreground", active && "bg-fill-selected text-foreground");
-
const RECENTS_CAP = 30;
const log = logger.scope("channel-sidebar");
@@ -68,23 +55,25 @@ function RecentSectionHeader({
onToggleSearch,
query,
onQueryChange,
- createdByFilter,
- onCreatedByChange,
+ filters,
+ onFiltersChange,
+ sort,
+ onSortChange,
+ sources,
showCreatedBy,
- statusFilter,
- onStatusChange,
filtersActive,
}: {
searchOpen: boolean;
onToggleSearch: () => void;
query: string;
onQueryChange: (value: string) => void;
- createdByFilter: CreatedByFilter;
- onCreatedByChange: (value: CreatedByFilter) => void;
+ filters: ChannelItemFilters;
+ onFiltersChange: (filters: ChannelItemFilters) => void;
+ sort: ChannelItemSort;
+ onSortChange: (sort: ChannelItemSort) => void;
+ sources: readonly string[];
/** False in #me, where every session is yours and the filter says nothing. */
showCreatedBy: boolean;
- statusFilter: TaskRunStatus | null;
- onStatusChange: (value: TaskRunStatus | null) => void;
filtersActive: boolean;
}) {
return (
@@ -103,69 +92,15 @@ function RecentSectionHeader({
>
<MagnifyingGlass size={12} />
</Button>
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <Button
- variant="default"
- size="icon-xs"
- aria-label="Filter"
- className={cnHeaderButton(filtersActive)}
- >
- <FunnelSimpleIcon size={12} />
- </Button>
- }
- />
- <DropdownMenuContent
- align="end"
- side="bottom"
- sideOffset={6}
- className="min-w-fit"
- >
- {/* #me holds only your own sessions, so "created by" can only ever
- answer "you" — the whole group is dropped rather than shown with
- two options that empty the list. */}
- {showCreatedBy && (
- <>
- <MenuLabel>Created by</MenuLabel>
- <DropdownMenuRadioGroup
- value={createdByFilter}
- onValueChange={(value) =>
- onCreatedByChange(value as CreatedByFilter)
- }
- >
- {CREATED_BY_OPTIONS.map((option) => (
- <DropdownMenuRadioItem
- key={option.value}
- value={option.value}
- >
- {option.label}
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- <DropdownMenuSeparator />
- </>
- )}
- <MenuLabel>Status</MenuLabel>
- <DropdownMenuRadioGroup
- value={statusFilter ?? "any"}
- onValueChange={(value) =>
- onStatusChange(
- value === "any" ? null : (value as TaskRunStatus),
- )
- }
- >
- {RUN_STATUS_FILTER_OPTIONS.map((option) => (
- <DropdownMenuRadioItem
- key={option.value ?? "any"}
- value={option.value ?? "any"}
- >
- {option.label}
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
+ <ChannelFilterMenu
+ filters={filters}
+ onFiltersChange={onFiltersChange}
+ sort={sort}
+ onSortChange={onSortChange}
+ sources={sources}
+ showCreatedBy={showCreatedBy}
+ active={filtersActive}
+ />
</div>
{searchOpen && (
<div className="px-1 pb-1">
@@ -261,9 +196,10 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {
const [searchOpen, setSearchOpen] = useState(false);
const [query, setQuery] = useState("");
- const [createdByFilter, setCreatedByFilter] =
- useState<CreatedByFilter>("anyone");
- const [statusFilter, setStatusFilter] = useState<TaskRunStatus | null>(null);
+ const [rawFilters, setFilters] = useState<ChannelItemFilters>(
+ DEFAULT_CHANNEL_ITEM_FILTERS,
+ );
+ const [sort, setSort] = useState<ChannelItemSort>(DEFAULT_CHANNEL_ITEM_SORT);
// Every session in #me is yours, so the author filter has nothing to sort by.
// The state survives a space switch, so the value is neutralised here as well
// as hidden — otherwise "Other people" carried in from a shared space would
@@ -271,10 +207,16 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {
const { channels } = useChannels();
const isPersonalChannel =
channels.find((c) => c.id === channelId)?.name === PERSONAL_CHANNEL_NAME;
- const createdBy: CreatedByFilter = isPersonalChannel
- ? "anyone"
- : createdByFilter;
- const filtersActive = createdBy !== "anyone" || statusFilter !== null;
+ const filters = useMemo<ChannelItemFilters>(
+ () =>
+ isPersonalChannel ? { ...rawFilters, createdBy: "anyone" } : rawFilters,
+ [isPersonalChannel, rawFilters],
+ );
+ const filtersActive = hasActiveChannelItemFilters(filters);
+ // The menu only offers sources the list holds, so it is built from everything
+ // in the space rather than from what the current filters left behind — picking
+ // one source must not be what removes the others from the menu.
+ const sources = useMemo(() => channelItemSources(items), [items]);
const base = `/website/${channelId}`;
// Activeness is a key comparison rather than a flag baked into each item, so
@@ -288,20 +230,16 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {
// One list, pins included — a pin is a mark on a session, not a different kind
// of thing, and the row's own badge says so. They sort to the top because a pin
- // is a request not to lose the thing: below the recency order it would fall off
+ // is a request not to lose the thing: below the chosen order it would fall off
// the end of the cap.
- const recentItems = useMemo(() => {
- const matching = filterChannelItems(items, {
- query,
- createdBy,
- status: statusFilter,
- me,
- });
- return [
- ...matching.filter((i) => i.pinned),
- ...matching.filter((i) => !i.pinned),
- ].slice(0, RECENTS_CAP);
- }, [items, query, createdBy, statusFilter, me]);
+ const recentItems = useMemo(
+ () =>
+ sortChannelItems(
+ filterChannelItems(items, { query, filters, me }),
+ sort,
+ ).slice(0, RECENTS_CAP),
+ [items, query, filters, sort, me],
+ );
const narrowed = filtersActive || searchOpen;
const listState = listStateOf({
@@ -459,11 +397,12 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {
}}
query={query}
onQueryChange={setQuery}
- createdByFilter={createdBy}
- onCreatedByChange={setCreatedByFilter}
+ filters={filters}
+ onFiltersChange={setFilters}
+ sort={sort}
+ onSortChange={setSort}
+ sources={sources}
showCreatedBy={!isPersonalChannel}
- statusFilter={statusFilter}
- onStatusChange={setStatusFilter}
filtersActive={filtersActive}
/>
{recentItems.length > 0 ? (
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsFab.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsFab.tsx
index cb654896f4d4..b5db0874a358 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsFab.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsFab.tsx
@@ -81,7 +81,7 @@ export function ChannelsFab({ channelId }: { channelId?: string }) {
variant="primary"
size="icon-lg"
aria-label="Create"
- className="absolute right-3 bottom-3 z-10 rounded-full shadow-lg"
+ className="absolute right-3 bottom-3 z-10"
>
<PlusIcon size={20} weight="bold" />
{channelsLayout && hasDraft && (
diff --git a/products/desktop/packages/ui/src/features/canvas/components/channelHeaderButton.ts b/products/desktop/packages/ui/src/features/canvas/components/channelHeaderButton.ts
new file mode 100644
index 000000000000..9a9797d2ff14
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/channelHeaderButton.ts
@@ -0,0 +1,10 @@
+import { cn } from "@posthog/quill";
+
+/**
+ * The sessions header's icon buttons: quill's ghost button at the 20px scale.
+ * Only the sticky state is ours, because quill styles the transient open state
+ * (hover, popup) but has no notion of "search is showing" or "a filter is
+ * applied".
+ */
+export const cnHeaderButton = (active: boolean): string =>
+ cn("text-muted-foreground", active && "bg-fill-selected text-foreground");
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.test.tsx b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.test.tsx
index 0d5e923d8a7b..ab652e06d336 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.test.tsx
@@ -58,6 +58,18 @@ vi.mock("@posthog/ui/features/sidebar/usePinnedTasks", () => ({
togglePin: mocks.togglePin,
}),
}));
+// The session facts behind the status and environment filters. All three reach
+// the host — for live sessions, viewed timestamps and workspaces — and this
+// suite is about which items the hook builds, not what they say.
+vi.mock("@posthog/ui/features/sidebar/useSidebarSessionMap", () => ({
+ useSidebarSessionMap: () => new Map(),
+}));
+vi.mock("@posthog/ui/features/sidebar/useTaskViewed", () => ({
+ useTaskViewed: () => ({ timestamps: {} }),
+}));
+vi.mock("@posthog/ui/features/workspace/useWorkspace", () => ({
+ useWorkspaces: () => ({ data: undefined, isFetched: true }),
+}));
vi.mock("@posthog/ui/features/auth/authClient", () => ({
useOptionalAuthenticatedClient: () => undefined,
}));
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx
index 790a4adb9fd4..4a7422954c97 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx
@@ -2,7 +2,9 @@ import {
buildChannelItems,
type ChannelItemModel,
type ChannelItemOwner,
+ type ChannelSessionFacts,
} from "@posthog/core/canvas/channelItems";
+import type { WorkspaceMode } from "@posthog/shared";
import { useArchivedTaskIds } from "@posthog/ui/features/archive/useArchivedTaskIds";
import { useArchiveTask } from "@posthog/ui/features/archive/useArchiveTask";
import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
@@ -17,7 +19,10 @@ import {
useDashboards,
} from "@posthog/ui/features/canvas/hooks/useDashboards";
import { usePinnedTasks } from "@posthog/ui/features/sidebar/usePinnedTasks";
+import { useSidebarSessionMap } from "@posthog/ui/features/sidebar/useSidebarSessionMap";
+import { useTaskViewed } from "@posthog/ui/features/sidebar/useTaskViewed";
import { useTasks } from "@posthog/ui/features/tasks/useTasks";
+import { useWorkspaces } from "@posthog/ui/features/workspace/useWorkspace";
import { toast } from "@posthog/ui/primitives/toast";
import { useNavigate } from "@tanstack/react-router";
import { useMemo } from "react";
@@ -65,6 +70,31 @@ export function useChannelItems(channelId: string): {
client,
});
+ // What the filters ask about beyond the task itself: a live session's
+ // permission prompt, when you last looked, and where the workspace is. The
+ // session map is the sidebar's own subscription, which ignores the streamed
+ // events a turn fires and only wakes on the fields a row reads.
+ const sessions = useSidebarSessionMap();
+ const { timestamps } = useTaskViewed();
+ const { data: workspaces } = useWorkspaces();
+ const sessionFacts = useMemo<ChannelSessionFacts>(() => {
+ const needsInputTaskIds = new Set<string>();
+ for (const [taskId, session] of sessions) {
+ if ((session.pendingPermissions?.size ?? 0) > 0) {
+ needsInputTaskIds.add(taskId);
+ }
+ }
+ const workspaceModeByTaskId = new Map<string, WorkspaceMode>();
+ for (const [taskId, workspace] of Object.entries(workspaces ?? {})) {
+ if (workspace.mode) workspaceModeByTaskId.set(taskId, workspace.mode);
+ }
+ return {
+ needsInputTaskIds,
+ viewedTimestamps: timestamps,
+ workspaceModeByTaskId,
+ };
+ }, [sessions, timestamps, workspaces]);
+
const meUuid = currentUser?.uuid ?? null;
const me = useMemo<ChannelItemOwner>(() => ({ uuid: meUuid }), [meUuid]);
// Only a uuid establishes identity — ownership compares uuids, so a viewer
@@ -93,9 +123,11 @@ export function useChannelItems(channelId: string): {
// The personal channel is yours — but don't filter until we know
// who you are, or #me flashes everyone's items on a cold load.
ownedBy: isPersonal && viewerKnown ? me : null,
+ sessionFacts,
});
}, [
identityKnown,
+ sessionFacts,
dashboards,
feedTasks,
filedTaskRecords,