: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
feat(desktop): customize session list metadata (#86535)
Adam Leith0fa571997f4a
diff --git a/products/desktop/packages/core/src/canvas/channelItems.test.ts b/products/desktop/packages/core/src/canvas/channelItems.test.tsindex ffe4c3415653..e4f85174ad4a 100644--- a/products/desktop/packages/core/src/canvas/channelItems.test.ts+++ b/products/desktop/packages/core/src/canvas/channelItems.test.ts@@ -179,12 +179,46 @@ describe("buildChannelItems", () => {sessionFacts: {needsInputTaskIds: NONE,viewedTimestamps: {},- workspaceModeByTaskId: new Map(mode ? [["t1", mode]] : []),+ workspaceByTaskId: new Map(mode ? [["t1", { mode }]] : []),},});expect(item.environment).toBe(expected);});+ it("resolves a session's repository and branch once, checkout first", () => {+ const [item] = build({+ feedTasks: [task({ id: "t1", repository: "PostHog/code" })],+ sessionFacts: {+ needsInputTaskIds: NONE,+ viewedTimestamps: {},+ workspaceByTaskId: new Map([+ ["t1", { folderPath: "/src/code", branch: "posthog/session-list" }],+ ]),+ },+ });++ expect(item.repository).toEqual({+ key: "posthog/code",+ label: "PostHog/code",+ });+ expect(item.branch).toBe("posthog/session-list");+ });++ it("does not treat a scratch workspace's folder as a repository", () => {+ const [item] = build({+ feedTasks: [task({ id: "t1" })],+ sessionFacts: {+ needsInputTaskIds: NONE,+ viewedTimestamps: {},+ workspaceByTaskId: new Map([+ ["t1", { folderPath: "/scratch/t1", isScratch: true }],+ ]),+ },+ });++ expect(item.repository).toBeNull();+ });+it("reads a filed session's source, and none for one started here", () => {const items = build({feedTasks: [@@ -209,7 +243,7 @@ describe("buildChannelItems", () => {viewedTimestamps: {unread: { lastViewedAt: 1_000, lastActivityAt: null },},- workspaceModeByTaskId: new Map(),+ workspaceByTaskId: new Map(),},});expect(items.map((i) => [i.id, i.needsInput, i.unread])).toEqual([@@ -233,7 +267,7 @@ describe("buildChannelItems", () => {viewedTimestamps: {streamed: { lastViewedAt: 2_000, lastActivityAt: null },},- workspaceModeByTaskId: new Map(),+ workspaceByTaskId: new Map(),},});expect(item.unread).toBe(true);@@ -298,6 +332,8 @@ function model(over: Partial<ChannelItemModel> = {}): ChannelItemModel {authorName: null,authorUuid: ME.uuid,templateId: null,+ repository: null,+ branch: null,task: null,...over,};@@ -450,6 +486,33 @@ describe("groupChannelItems", () => {);}+ it("files rows under their repository, unnamed ones last, when asked to", () => {+ const withRepo = (id: string, key: string | null, label = "") =>+ model({+ id,+ ts: at(29, 9),+ repository: key ? { key, label } : null,+ });++ expect(+ groupChannelItems(+ [+ withRepo("code-1", "posthog/code", "PostHog/code"),+ withRepo("loose", null),+ withRepo("code-2", "posthog/code", "posthog/code"),+ withRepo("web", "posthog/posthog", "PostHog/posthog"),+ ],+ "recent",+ NOW,+ "repository",+ ).map((section) => [section.label, ...section.items.map((i) => i.id)]),+ ).toEqual([+ ["PostHog/code", "code-1", "code-2"],+ ["PostHog/posthog", "web"],+ ["No repository", "loose"],+ ]);+ });+it("runs a day's items under one header", () => {expect(group([diff --git a/products/desktop/packages/core/src/canvas/channelItems.ts b/products/desktop/packages/core/src/canvas/channelItems.tsindex 141033ba0f18..c42ca6562ffb 100644--- a/products/desktop/packages/core/src/canvas/channelItems.ts+++ b/products/desktop/packages/core/src/canvas/channelItems.ts@@ -3,12 +3,14 @@ import {getLocalDayKey,type WorkspaceMode,} from "@posthog/shared";+import type { TaskListGroupingChangedProperties } from "@posthog/shared/analytics-events";import type {Task,TaskRunStatus,UserBasic,} from "@posthog/shared/domain-types";import { isTaskUnread, type TaskTimestamp } from "../sidebar/buildSidebarData";+import { getRepositoryInfo, repositoryLabel } from "../sidebar/groupTasks";import { taskActivityAt, taskActivityTimestamp } from "../tasks/taskActivity";import type { DashboardRecord } from "./dashboardSchemas";@@ -38,6 +40,15 @@ export interface ChannelItemModel {needsInput: boolean;/** There is activity here you haven't seen. */unread: boolean;+ /**+ * Where the session's work sits, resolved once here: the row, its card and+ * the repository grouping all read this, so they cannot answer the question+ * three ways. Null for a canvas, and for a session with no repository and no+ * checkout on this client.+ */+ repository: ChannelItemRepository | null;+ /** The branch its work is on, from the local checkout or the run. */+ branch: string | null;authorUser: UserBasic | null;authorName: string | null;authorUuid: string | null;@@ -53,6 +64,13 @@ export interface ChannelItemModel {task: Task | null;}+/** A repository, as a grouping key and as a reader names it. */+export interface ChannelItemRepository {+ /** Case-folded full path, so two spellings of one repository group together. */+ key: string;+ label: string;+}+export interface ChannelItemOwner {uuid: string | null;}@@ -79,13 +97,27 @@ function isOwnedBy(export interface ChannelSessionFacts {needsInputTaskIds: ReadonlySet<string>;viewedTimestamps: Readonly<Record<string, TaskTimestamp>>;- workspaceModeByTaskId: ReadonlyMap<string, WorkspaceMode>;+ /** The local checkout, where this client has one: where it is, and on what. */+ workspaceByTaskId: ReadonlyMap<string, ChannelWorkspaceFacts>;+}++/** What a session's local checkout says about it. */+export interface ChannelWorkspaceFacts {+ mode?: WorkspaceMode;+ folderPath?: string;+ branch?: string;+ /**+ * A synthetic scratch dir for a repo-less session, not a checkout. Its+ * folderPath is `<scratchBase>/<taskId>`, so resolving a repository from it+ * would label the session by its own id — skip it.+ */+ isScratch?: boolean;}const NO_SESSION_FACTS: ChannelSessionFacts = {needsInputTaskIds: new Set(),viewedTimestamps: {},- workspaceModeByTaskId: new Map(),+ workspaceByTaskId: new Map(),};/**@@ -146,40 +178,50 @@ export function buildChannelItems({authorName: d.createdBy ?? null,authorUuid: d.createdByUuid ?? null,templateId: d.templateId,+ repository: null,+ branch: null,task: null,}));- const taskItems: ChannelItemModel[] = feedTasks.flatMap((task) =>- archivedTaskIds.has(task.id)- ? []- : [- {- key: `task:${task.id}`,- kind: "task" as const,- id: task.id,- title: task.title || "Untitled task",- ts: taskActivityTimestamp(task, "updated") || 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(- taskActivityAt(task),- sessionFacts.viewedTimestamps[task.id],- ),- authorUser: task.created_by ?? null,- authorName: null,- authorUuid: task.created_by?.uuid ?? null,- templateId: null,- task,- },- ],- );+ const taskItems: ChannelItemModel[] = feedTasks.flatMap((task) => {+ if (archivedTaskIds.has(task.id)) return [];+ const workspace = sessionFacts.workspaceByTaskId.get(task.id);+ const repository = getRepositoryInfo(+ task,+ workspace?.isScratch ? undefined : workspace?.folderPath,+ );+ return [+ {+ key: `task:${task.id}`,+ kind: "task" as const,+ id: task.id,+ title: task.title || "Untitled task",+ ts: taskActivityTimestamp(task, "updated") || 0,+ createdAt: Date.parse(task.created_at) || 0,+ pinned: pinnedTaskIds.has(task.id),+ rawStatus: task.latest_run?.status ?? null,+ environment: environmentOf(task, workspace?.mode),+ source: sourceOf(task),+ needsInput: sessionFacts.needsInputTaskIds.has(task.id),+ unread: isTaskUnread(+ taskActivityAt(task),+ sessionFacts.viewedTimestamps[task.id],+ ),+ authorUser: task.created_by ?? null,+ authorName: null,+ authorUuid: task.created_by?.uuid ?? null,+ templateId: null,+ repository: repository+ ? {+ key: repository.fullPath,+ label: repositoryLabel(repository) ?? repository.name,+ }+ : null,+ branch: workspace?.branch ?? task.latest_run?.branch ?? null,+ task,+ },+ ];+ });const all = [...canvasItems, ...taskItems].sort((a, b) => b.ts - a.ts);return ownedBy ? all.filter((item) => isOwnedBy(item, ownedBy)) : all;@@ -215,6 +257,23 @@ export const DEFAULT_CHANNEL_ITEM_FILTERS: ChannelItemFilters = {/** Newest activity first, which is what a session list is for. */export const DEFAULT_CHANNEL_ITEM_SORT: ChannelItemSort = "recent";+/**+ * The space list's sort, in the vocabulary the shared task-list events use:+ * "recent" and the sidebar's "updated" are the same scale under two names, and+ * binding them here is what keeps one property from meaning two things.+ */+export function channelItemSortEvent(+ sort: ChannelItemSort,+): TaskListGroupingChangedProperties["sort_by"] {+ return sort === "recent" ? "updated" : sort;+}++/** What the list's section headers stand for. */+export type ChannelItemGrouping = "date" | "repository";++/** Days, because when something happened is what a session list is scanned by. */+export const DEFAULT_CHANNEL_ITEM_GROUPING: ChannelItemGrouping = "date";+/*** 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@@ -350,6 +409,7 @@ export function groupChannelItems(items: readonly ChannelItemModel[],sort: ChannelItemSort,now: Date = new Date(),+ grouping: ChannelItemGrouping = DEFAULT_CHANNEL_ITEM_GROUPING,): ChannelItemSection[] {const sections: ChannelItemSection[] = [];@@ -360,6 +420,10 @@ export function groupChannelItems(const rest = items.filter((item) => !item.pinned);if (rest.length === 0) return sections;+ if (grouping === "repository") {+ sections.push(...repositorySections(rest));+ return sections;+ }if (sort === "alpha") {sections.push({ key: "all", label: null, items: rest });return sections;@@ -380,3 +444,35 @@ export function groupChannelItems(}return sections;}++/** The repository a row belongs under, or null where it names none. */+const NO_REPOSITORY_KEY = "repo:none";++/**+ * One section per repository, in the order the sorted list first reaches each+ * one — so a repository-grouped list still opens on the most recent work rather+ * than on whichever repository sorts first alphabetically. Sessions with no+ * repository are a run of their own at the end, where they don't interrupt the+ * named ones.+ */+function repositorySections(+ items: readonly ChannelItemModel[],+): ChannelItemSection[] {+ const byRepo = new Map<string, ChannelItemSection>();+ for (const item of items) {+ const key = item.repository+ ? `repo:${item.repository.key}`+ : NO_REPOSITORY_KEY;+ const label = item.repository?.label ?? "No repository";+ const open = byRepo.get(key);+ if (open) {+ open.items.push(item);+ continue;+ }+ byRepo.set(key, { key, label, items: [item] });+ }++ const sections = [...byRepo.values()];+ const unnamed = sections.filter((s) => s.key === NO_REPOSITORY_KEY);+ return [...sections.filter((s) => s.key !== NO_REPOSITORY_KEY), ...unnamed];+}diff --git a/products/desktop/packages/core/src/sidebar/groupTasks.test.ts b/products/desktop/packages/core/src/sidebar/groupTasks.test.tsindex 10d48f1ead8b..650828bd5729 100644--- a/products/desktop/packages/core/src/sidebar/groupTasks.test.ts+++ b/products/desktop/packages/core/src/sidebar/groupTasks.test.ts@@ -32,6 +32,15 @@ function task(}describe("getRepositoryInfo", () => {+ it.each([+ ["/Users/ada/code", "code"],+ ["C:\\Users\\ada\\code", "code"],+ ])("names a checkout at %s after its folder", (folderPath, expected) => {+ expect(+ getRepositoryInfo(makeTask({ repository: null }), folderPath)?.name,+ ).toBe(expected);+ });+it("returns lowercased owner/repo fullPath for a structured repository", () => {const info = getRepositoryInfo(makeTask({ repository: "PostHog/code" }));expect(info).toEqual({diff --git a/products/desktop/packages/core/src/sidebar/groupTasks.ts b/products/desktop/packages/core/src/sidebar/groupTasks.tsindex af674467d147..14fe05438926 100644--- a/products/desktop/packages/core/src/sidebar/groupTasks.ts+++ b/products/desktop/packages/core/src/sidebar/groupTasks.ts@@ -24,6 +24,23 @@ export interface TaskGroup<T extends GroupableTask> {tasks: T[];}+/**+ * A repository as a reader names it: `organization/name`, or the bare name+ * where we never learned the organization. One definition, because a list that+ * groups by repository and a row that prints one have to agree.+ */+export function repositoryLabel(+ repository:+ | Pick<TaskRepositoryInfo, "name" | "organization">+ | null+ | undefined,+): string | undefined {+ if (!repository) return undefined;+ return repository.organization+ ? `${repository.organization}/${repository.name}`+ : repository.name;+}+export function getRepositoryInfo(task: { repository?: string | null },folderPath?: string,@@ -44,7 +61,9 @@ export function getRepositoryInfo(// of colliding with a real owner/repo group.}if (folderPath) {- const name = folderPath.split("/").pop() ?? folderPath;+ // Both separators: a Windows checkout would otherwise take its whole path+ // as the repository's name, which a row then prints in full.+ const name = folderPath.split(/[/\\]/).filter(Boolean).pop() ?? folderPath;return {fullPath: folderPath,name,@@ -127,7 +146,8 @@ export function groupByRepository<T extends GroupableTask>(if ((nameCounts.get(group.name) ?? 0) > 1) {const organization = group.tasks[0]?.repository?.organization;if (organization) {- group.name = `${organization}/${group.name}`;+ group.name =+ repositoryLabel({ name: group.name, organization }) ?? group.name;}}}diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.tsindex 168592a784bd..bf0a30d1b133 100644--- a/products/desktop/packages/shared/src/analytics-events.ts+++ b/products/desktop/packages/shared/src/analytics-events.ts@@ -305,6 +305,20 @@ export interface SidebarReorderedProperties {to_index: number;}+export interface TaskListGroupingChangedProperties {+ group_by: "repository" | "date";+ sort_by: "updated" | "created" | "alpha";+ /** Which list was regrouped: the app sidebar's, or a space's session list. */+ surface: "sidebar" | "space";+}++export interface TaskListAppearanceChangedProperties {+ secondary_fields: ("repository" | "branch" | "creator" | "activity")[];+ secondary_field_count: number;+ /** Which list it was changed from. The setting applies to both. */+ surface: "sidebar" | "space";+}+export interface BrainrotActivatedProperties {/** Grid layout preset, e.g. "2x2". */layout: string;@@ -1397,6 +1411,8 @@ export const ANALYTICS_EVENTS = {SIDEBAR_NAV_ITEM_CLICKED: "Sidebar nav item clicked",SIDEBAR_CUSTOMIZED: "Sidebar customized",SIDEBAR_REORDERED: "Sidebar reordered",+ TASK_LIST_GROUPING_CHANGED: "Task list grouping changed",+ TASK_LIST_APPEARANCE_CHANGED: "Task list appearance changed",// Permission eventsPERMISSION_RESPONDED: "Permission responded",@@ -1583,6 +1599,8 @@ export type EventPropertyMap = {[ANALYTICS_EVENTS.SIDEBAR_NAV_ITEM_CLICKED]: SidebarNavItemClickedProperties;[ANALYTICS_EVENTS.SIDEBAR_CUSTOMIZED]: SidebarCustomizedProperties;[ANALYTICS_EVENTS.SIDEBAR_REORDERED]: SidebarReorderedProperties;+ [ANALYTICS_EVENTS.TASK_LIST_GROUPING_CHANGED]: TaskListGroupingChangedProperties;+ [ANALYTICS_EVENTS.TASK_LIST_APPEARANCE_CHANGED]: TaskListAppearanceChangedProperties;// Permission events[ANALYTICS_EVENTS.PERMISSION_RESPONDED]: PermissionRespondedProperties;diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.tsindex 177679dcb4c0..d18fb8e2a969 100644--- a/products/desktop/packages/shared/src/index.ts+++ b/products/desktop/packages/shared/src/index.ts@@ -355,8 +355,10 @@ export type {TaskCreationOutput,} from "./task-creation-domain";export {+ formatAbsoluteDateTime,formatClockTime,formatDaySeparatorLabel,+ formatRelativeAge,formatRelativeTimeLong,formatRelativeTimeShort,formatShortDayLabel,diff --git a/products/desktop/packages/shared/src/time.ts b/products/desktop/packages/shared/src/time.tsindex 8fd31988ce84..783ac40bac41 100644--- a/products/desktop/packages/shared/src/time.ts+++ b/products/desktop/packages/shared/src/time.ts@@ -32,6 +32,29 @@ export function formatRelativeTimeShort(timestamp: number | string): string {return "now";}+/**+ * How long ago something happened, said as a phrase: "2h ago", "3w ago", or+ * "just now" under a minute. The same scale `formatRelativeTimeShort` uses, so+ * a stamp and a phrase for one timestamp cannot disagree.+ */+export function formatRelativeAge(timestamp: number | string): string {+ const short = formatRelativeTimeShort(timestamp);+ return short === "now" ? "just now" : `${short} ago`;+}++/**+ * The exact moment, in the reader's own locale and zone. What a relative age+ * hides, for the tooltip behind it.+ */+export function formatAbsoluteDateTime(timestamp: number | string): string {+ const ms =+ typeof timestamp === "string" ? new Date(timestamp).getTime() : timestamp;+ return new Date(ms).toLocaleString(undefined, {+ dateStyle: "medium",+ timeStyle: "short",+ });+}+/*** Format a timestamp as a longer relative string (e.g. "3 minutes ago", "1 day ago").* Falls back to a locale date for anything older than a week.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.tsxindex 9dbcb52e38d8..5b888579ff96 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelFilterMenu.stories.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelFilterMenu.stories.tsx@@ -1,10 +1,13 @@import {type ChannelItemFilters,+ type ChannelItemGrouping,type ChannelItemSort,DEFAULT_CHANNEL_ITEM_FILTERS,+ DEFAULT_CHANNEL_ITEM_GROUPING,DEFAULT_CHANNEL_ITEM_SORT,hasActiveChannelItemFilters,} from "@posthog/core/canvas/channelItems";+import { EditListItemAppearanceDialog } from "@posthog/ui/features/sidebar/components/EditListItemAppearanceDialog";import type { Meta, StoryObj } from "@storybook/react-vite";import { useState } from "react";import { ChannelFilterMenu } from "./ChannelFilterMenu";@@ -19,25 +22,45 @@ function Harness({initialSort,sources,showCreatedBy,+ showRunFilters,}: {initialFilters: ChannelItemFilters;initialSort: ChannelItemSort;sources: string[];showCreatedBy: boolean;+ showRunFilters: boolean;}) {const [filters, setFilters] = useState(initialFilters);const [sort, setSort] = useState(initialSort);+ const [grouping, setGrouping] = useState<ChannelItemGrouping>(+ DEFAULT_CHANNEL_ITEM_GROUPING,+ );+ const [appearanceOpen, setAppearanceOpen] = useState(false);return (<div className="flex justify-end p-2"><ChannelFilterMenufilters={filters}- onFiltersChange={setFilters}+ onFilterChange={(key, value) =>+ setFilters((current) => ({ ...current, [key]: value }))+ }+ onClearFilters={() => setFilters(DEFAULT_CHANNEL_ITEM_FILTERS)}sort={sort}onSortChange={setSort}+ grouping={grouping}+ onGroupingChange={setGrouping}+ onEditAppearance={() => setAppearanceOpen(true)}sources={sources}showCreatedBy={showCreatedBy}+ showRunFilters={showRunFilters}active={hasActiveChannelItemFilters(filters)}/>+ {/* The list owns the dialog and the menu only asks for it — so the+ harness renders it too, the way the sidebar does. */}+ <EditListItemAppearanceDialog+ surface="space"+ open={appearanceOpen}+ onOpenChange={setAppearanceOpen}+ /></div>);}@@ -50,6 +73,7 @@ const meta: Meta<typeof Harness> = {initialSort: DEFAULT_CHANNEL_ITEM_SORT,sources: ["slack", "error_tracking", "support_queue"],showCreatedBy: true,+ showRunFilters: true,},decorators: [(Story) => (@@ -76,6 +100,11 @@ export const Filtered: Story = {},};+/** The canvases tab: no run to filter on, and no metadata row to configure. */+export const CanvasesTab: Story = {+ args: { showRunFilters: false },+};+/** #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.tsxindex a30558d6e155..45f43f76e8df 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelFilterMenu.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelFilterMenu.tsx@@ -3,6 +3,7 @@ import {ANY_SOURCE,type AttentionFilter,type ChannelItemFilters,+ type ChannelItemGrouping,type ChannelItemSort,type CreatedByFilter,type EnvironmentFilter,@@ -62,6 +63,11 @@ const ENVIRONMENT_OPTIONS: readonly Option<EnvironmentFilter>[] = [{ value: "cloud", label: "Cloud" },];+const GROUPING_OPTIONS: readonly Option<ChannelItemGrouping>[] = [+ { value: "date", label: "Date" },+ { value: "repository", label: "Repository" },+];+const SORT_OPTIONS: readonly Option<ChannelItemSort>[] = [{ value: "recent", label: "Recent activity" },{ value: "created", label: "Date created" },@@ -152,6 +158,9 @@ export function ChannelFilterMenu({onClearFilters,sort,onSortChange,+ grouping,+ onGroupingChange,+ onEditAppearance,sources,showCreatedBy,showRunFilters,@@ -173,6 +182,11 @@ export function ChannelFilterMenu({onClearFilters: () => void;sort: ChannelItemSort;onSortChange: (sort: ChannelItemSort) => void;+ /** What the list's section headers stand for. */+ grouping: ChannelItemGrouping;+ onGroupingChange: (grouping: ChannelItemGrouping) => void;+ /** Opens the list's appearance dialog, which the list itself renders. */+ onEditAppearance: () => void;/** `origin_product` keys present in the list. */sources: readonly string[];/** False in #me, where every session is yours and the filter says nothing. */@@ -266,6 +280,25 @@ export function ChannelFilterMenu({value={sort}onChange={onSortChange}/>+ {/* A canvas has no repository, and no second row to configure, so the+ tab that lists them is offered neither. */}+ {showRunFilters && (+ <>+ <FilterSubmenu+ label="Group by"+ options={GROUPING_OPTIONS}+ value={grouping}+ onChange={onGroupingChange}+ />+ <DropdownMenuSeparator />+ <DropdownMenuItem+ data-attr="edit-list-item-appearance"+ onClick={onEditAppearance}+ >+ Edit list item appearance…+ </DropdownMenuItem>+ </>+ )}{active && (<><DropdownMenuSeparator />diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.test.tsxindex 42e577b98d52..269b5ca514e0 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemHoverCard.test.tsx@@ -47,6 +47,8 @@ function item(title: string, overrides: Partial<ChannelItemModel> = {}) {authorName: null,authorUuid: "user-uuid",templateId: null,+ repository: null,+ branch: null,task: null,...overrides,} satisfies ChannelItemModel;@@ -130,14 +132,16 @@ describe("ChannelItemHoverCard", () => {expect(screen.queryByText("Ready")).toBeNull();});- it("names what the row's badges mean", async () => {+ it("names what the row's badges mean, with the origin as a stated fact", async () => {mocks.status = { prState: "merged", originProduct: "slack" };renderRows([item("Investigate signup drop-off")]);await openCardOn("Investigate signup drop-off");expect(screen.getByText("Merged")).not.toBeNull();- expect(screen.getByText("Source: Slack")).not.toBeNull();+ // Named by the column it sits in, so the badge drops its own "Source:".+ expect(screen.getByText("Source")).not.toBeNull();+ expect(screen.getByText("Slack")).not.toBeNull();});it("shows the last thing the agent said", async () => {diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemPreview.stories.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemPreview.stories.tsxindex 0062dfe88701..7537f81957ef 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemPreview.stories.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemPreview.stories.tsx@@ -38,7 +38,7 @@ function run(overrides: Partial<TaskRun>): TaskRun {id: "run-1",task: "task-1",team: 1,- branch: null,+ branch: "posthog/importer-cleanup",environment: "cloud",status: "completed",log_url: "",@@ -62,6 +62,7 @@ function task(latestRun: TaskRun, overrides: Partial<Task> = {}): Task {created_at: "2026-07-16T12:00:00.000Z",updated_at: "2026-07-17T12:00:00.000Z",origin_product: "user_created",+ repository: "PostHog/code",latest_run: latestRun,...overrides,};@@ -95,6 +96,8 @@ function item(authorName: null,authorUuid: "user-uuid",templateId: null,+ repository: { key: "posthog/code", label: "PostHog/code" },+ branch: "posthog/importer-cleanup",task: task(latestRun, taskOverrides),...overrides,};diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemPreview.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemPreview.tsxindex 935cc72471e5..967c2d90eba7 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemPreview.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemPreview.tsx@@ -7,7 +7,6 @@ import {Item,ItemActions,ItemContent,- ItemDescription,ItemGroup,ItemSeparator,ItemTitle,@@ -16,16 +15,17 @@ import {TooltipProvider,TooltipTrigger,} from "@posthog/quill";-import { formatRelativeTimeShort } from "@posthog/shared";+import { formatAbsoluteDateTime, formatRelativeAge } from "@posthog/shared";import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";import { iconForTemplate } from "@posthog/ui/features/canvas/components/canvasTemplateIcon";import {TaskRowMenuList,type TaskRowMenuProps,} from "@posthog/ui/features/canvas/components/TaskRowMenu";+import { channelItemAuthor } from "@posthog/ui/features/canvas/hooks/useChannelItemFacts";import { useChannelTaskStatus } from "@posthog/ui/features/canvas/hooks/useChannelTaskStatus";import { useLatestTurnMessage } from "@posthog/ui/features/canvas/hooks/useLatestTurnMessage";-import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";+import { getOriginProductMeta } from "@posthog/ui/features/sidebar/components/items/TaskIcon";import { TaskDotMark } from "@posthog/ui/features/sidebar/components/items/TaskStatusDot";import {type TaskBadge,@@ -34,6 +34,8 @@ import {taskBadges,taskDot,} from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";+import { CopyButton } from "@posthog/ui/primitives/CopyButton";+import { FactLabel, FactList } from "@posthog/ui/primitives/FactList";import { openExternalUrl } from "@posthog/ui/shell/openExternal";import { type ReactNode, useEffect } from "react";@@ -67,18 +69,13 @@ function previewGlyph(item: ChannelItemModel, dot: TaskDot | null): ReactNode {return <TaskDotMark dot={dot} />;}-function authorLabel(item: ChannelItemModel): string | null {- if (item.authorUser) return userDisplayName(item.authorUser);- return item.authorName;-}-/*** Who made it, as the avatar alone. The name is worth a line of the card only* where the avatar can't carry it, so it goes to the label and a tooltip* instead of a row of its own.*/function AuthorAvatar({ item }: { item: ChannelItemModel }) {- const author = authorLabel(item);+ const author = channelItemAuthor(item);if (!author) return null;const label = `Created by ${author}`;return (@@ -159,6 +156,83 @@ function Badge({ badge: { Icon, label, tone, url } }: { badge: TaskBadge }) {);}+/**+ * The branch's value cell: the name, and the one thing a reader wants from a+ * branch name — it, in their clipboard. Truncated rather than wrapped, because+ * the button has to stay at the end of the line.+ */+function BranchLine({ branch }: { branch: string }) {+ return (+ <span className="flex min-w-0 items-center gap-1">+ <span className="truncate" title={branch}>+ {branch}+ </span>+ <CopyButton+ bare+ confirm="tooltip"+ text={branch}+ label="Copy branch name"+ />+ </span>+ );+}++/**+ * What the card can state plainly: where the session's work sits, when it last+ * moved, who filed it, and what it wants. Facts a reader looks up belong in one+ * column rather than scattered between a badge row and a sentence.+ */+function ItemFacts({+ item,+ source,+ status,+}: {+ item: ChannelItemModel;+ /** The origin badge, relabeled: the row's column already says "Source". */+ source: TaskBadge | undefined;+ /** The PR's state, which is what a reader means by a session's status here. */+ status: TaskBadge | undefined;+}) {+ const repository = item.repository?.label;+ return (+ <FactList>+ {repository && (+ <>+ <FactLabel>Repo</FactLabel>+ <span className="truncate" title={repository}>+ {repository}+ </span>+ </>+ )}+ {item.branch && (+ <>+ <FactLabel>Branch</FactLabel>+ <BranchLine branch={item.branch} />+ </>+ )}+ <FactLabel>Updated</FactLabel>+ {/* The exact moment behind the phrase, the same way a row carries it. */}+ <span title={formatAbsoluteDateTime(item.ts)}>+ {formatRelativeAge(item.ts)}+ </span>+ {source && (+ <>+ <FactLabel>Source</FactLabel>+ {/* Still a badge, because Slack's is a link back to the thread. */}+ <Badge badge={source} />+ </>+ )}+ {status && (+ <>+ <FactLabel>Status</FactLabel>+ {/* Still a badge: the PR's state carries its colour, and it opens. */}+ <Badge badge={status} />+ </>+ )}+ </FactList>+ );+}+/*** What the row's marks mean, in words: the dot's own label, the last thing the* agent said, then the badges'.@@ -178,10 +252,13 @@ function ItemSignals({badges,message,}: {- dot: TaskDot;+ dot: TaskDot | null;badges: TaskBadge[];message: string | null;}) {+ // A canvas has no state, nothing said and nothing to link: the separator+ // alone would promise a block that isn't there.+ if (!dot && badges.length === 0 && !message) return null;return (<><ItemSeparator className="my-0" />@@ -190,14 +267,10 @@ function ItemSignals({line of its own and out past the card's edge. */}<Item size="xs" className="flex-nowrap items-start p-2"><ItemContent className="min-w-0 gap-1.5">- <span className="text-xs">{dot.label}</span>- {message && (- // Three lines: enough for the agent's closing sentence, short of- // turning the card into a transcript you have to read.- <p className="line-clamp-3 break-words text-muted-foreground text-xs leading-snug">- {message}- </p>- )}+ {/* What the row's dot says, in words. Above the message, like the+ badges: the agent's own words are the longest thing here, so+ anything under them reads as part of the transcript. */}+ {dot && <span className="text-xs">{dot.label}</span>}{badges.length > 0 && (<div className="flex flex-wrap items-center gap-x-3 gap-y-1">{badges.map((badge) => (@@ -205,6 +278,13 @@ function ItemSignals({))}</div>)}+ {message && (+ // Three lines: enough for the agent's closing sentence, short of+ // turning the card into a transcript you have to read.+ <p className="line-clamp-3 break-words text-muted-foreground text-xs leading-snug">+ {message}+ </p>+ )}</ItemContent></Item></>@@ -239,38 +319,42 @@ export function ChannelItemPreview({const status = useChannelTaskStatus(item);const message = useLatestTurnMessage(item.task);const dot = status ? taskDot(status) : null;+ const badges = status ? taskBadges(status) : [];+ // The origin moves up into the facts, where a labeled column already says+ // what it is; the badge keeps its glyph and its link.+ const origin = badges.find((badge) => badge.key === "origin");+ const originMeta = getOriginProductMeta(status?.originProduct);+ const source =+ origin && originMeta ? { ...origin, label: originMeta.label } : undefined;+ // The PR's state is what "status" means in a labeled column; the dot's own+ // wording is about the session and stays with the agent's words below.+ const pullRequest = badges.find((badge) => badge.key === "pr");return (<ItemGroup className="gap-0!"><Item size="xs" className="flex-nowrap p-2">- <ItemContent className="min-w-0">- {/* No gutter: the mark is one glyph on one line, and a column for it- indents everything under it for the whole height of the card. */}- <ItemTitle className="flex items-baseline gap-2 break-words">- <span className="flex size-4 shrink-0 translate-y-0.5 items-center justify-center">+ <ItemContent className="min-w-0 gap-2">+ <ItemTitle className="wrap-break-word flex items-start gap-2">+ <span className="flex h-[1lh] w-4 shrink-0 items-center justify-center">{previewGlyph(item, dot)}</span>- <span className="min-w-0">{item.title}</span>+ <span className="min-w-0 font-bold">{item.title}</span></ItemTitle>- <ItemDescription>- {item.kind === "canvas" ? "Canvas" : "Task"} · updated{" "}- {formatRelativeTimeShort(item.ts)}- </ItemDescription>+ <div className="pl-6">+ <ItemFacts item={item} source={source} status={pullRequest} />+ </div></ItemContent>- {/* Who made it rides on the identity row rather than taking a row of- its own — the card is a glance, and a line of chrome for a name is- a line the agent's own words could have had. Top-aligned: it belongs- to the title, not to the block of text under it. */}<ItemActions className="self-start"><AuthorAvatar item={item} /></ItemActions></Item>- {dot && status && (- <ItemSignals dot={dot} badges={taskBadges(status)} message={message} />- )}- {/* The row's actions live here now: a row at rest shows its status, and- the card is already the surface you're pointing at when you want to do- something to it. */}+ <ItemSignals+ dot={dot}+ badges={badges.filter(+ (badge) => badge !== origin && badge !== pullRequest,+ )}+ message={message}+ /><ItemSeparator className="my-0" /><div className="p-1"><TaskRowMenuListdiff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsxindex 345f5787f215..157f3db05c3a 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@@ -45,6 +45,7 @@ vi.mock();import { usePendingCanvasDeleteStore } from "@posthog/ui/features/canvas/stores/pendingCanvasDeleteStore";+import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";import { ChannelItemPreviewCardProvider } from "./ChannelItemHoverCard";import { ChannelItemRow } from "./ChannelItemRow";@@ -74,6 +75,8 @@ function item(overrides: Partial<ChannelItemModel> = {}): ChannelItemModel {authorName: null,authorUuid: "user-uuid",templateId: null,+ repository: null,+ branch: null,task: null,...overrides,};@@ -99,6 +102,7 @@ function renderRow(model: ChannelItemModel) {beforeEach(() => {mocks.status = null;+ useSidebarStore.setState({ listItemMetadataFields: [] });usePendingCanvasDeleteStore.setState({ pending: {} });useTaskSelectionStore.setState({selectedTaskIds: [],@@ -505,4 +509,52 @@ describe("ChannelItemRow", () => {expect(remove).toHaveBeenCalledWith(canvas);});++ it("shows the metadata fields the appearance settings ask for, in that order", () => {+ useSidebarStore.setState({+ listItemMetadataFields: ["branch", "repository"],+ });+ renderRow(+ item({+ authorName: "Ada Lovelace",+ repository: { key: "posthog/code", label: "PostHog/code" },+ branch: "posthog/session-list",+ }),+ );++ // Order is the segment builder's job and is tested there; a row's job is+ // to show what the settings asked for.+ expect(screen.getByText("posthog/session-list")).toBeInTheDocument();+ expect(screen.getByText("PostHog/code")).toBeInTheDocument();+ });++ // A session carries its creator as a user, not a name, so reading the name+ // alone left every session row without one.+ it("names the creator of a session, which carries a user rather than a name", () => {+ useSidebarStore.setState({ listItemMetadataFields: ["creator"] });+ renderRow(+ item({+ authorUser: {+ id: 1,+ uuid: "user-uuid",+ first_name: "Ada",+ last_name: "Lovelace",+ email: "[email protected]",+ },+ }),+ );++ expect(screen.getByText("Ada Lovelace")).toBeInTheDocument();+ });++ it("leaves a row single-line when no metadata fields are chosen", () => {+ renderRow(+ item({+ authorName: "Ada Lovelace",+ repository: { key: "posthog/code", label: "PostHog/code" },+ }),+ );++ expect(screen.queryByText(/PostHog\/code/)).not.toBeInTheDocument();+ });});diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsxindex 80c0b858bbc2..6551866fbfac 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx@@ -24,6 +24,7 @@ import {TaskRowContextMenu,type TaskRowMenuProps,} from "@posthog/ui/features/canvas/components/TaskRowMenu";+import { useChannelItemMetadata } from "@posthog/ui/features/canvas/hooks/useChannelItemFacts";import { useChannelTaskStatus } from "@posthog/ui/features/canvas/hooks/useChannelTaskStatus";import { useIsCanvasPendingDelete } from "@posthog/ui/features/canvas/stores/pendingCanvasDeleteStore";import { InlineEditInput } from "@posthog/ui/features/sidebar/components/items/TaskItem";@@ -173,6 +174,7 @@ function ChannelItemDot({export function ChannelItemRowView({item,status,+ subtitle,isActive,isSelected = false,showPinBadge = true,@@ -183,6 +185,8 @@ export function ChannelItemRowView({}: {item: ChannelItemModel;status: TaskStatusInput | null;+ /** The metadata row under the title, when the appearance settings ask for one. */+ subtitle?: ReactNode;isActive: boolean;isSelected?: boolean;showPinBadge?: boolean;@@ -198,6 +202,7 @@ export function ChannelItemRowView({icon={<ChannelItemDot item={item} status={status} />}// A non-string label opts out of SidebarItem's truncation tooltip.label={<span>{item.title}</span>}+ subtitle={subtitle}isActive={isActive}isSelected={isSelected}// Lets a drag-selection find the row and its session; canvases are not@@ -282,6 +287,7 @@ export function ChannelItemRow({onContextMenuOpenChange?: (open: boolean) => void;}) {const status = useChannelTaskStatus(item);+ const subtitle = useChannelItemMetadata(item);const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);const [handoffOpen, setHandoffOpen] = useState(false);const currentUser = useCurrentUser();@@ -360,6 +366,7 @@ export function ChannelItemRow({<ChannelItemRowViewitem={item}status={status}+ subtitle={subtitle}isActive={isActive}isSelected={isSelected}showPinBadge={showPinBadge}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.tsxindex de23ea9bf854..6bb9f000cabd 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@@ -88,6 +88,8 @@ function item(overrides: Partial<ChannelItemModel> = {}): ChannelItemModel {// Not the viewer, so filtering to "Me" leaves nothing.authorUuid: "someone-else-uuid",templateId: null,+ repository: null,+ branch: null,task: null,...overrides,};diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsxindex 1b44310d2776..86e4ff16ebc3 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelSidebar.tsx@@ -7,10 +7,13 @@ import {import {ANY_SOURCE,type ChannelItemFilters,+ type ChannelItemGrouping,type ChannelItemModel,type ChannelItemSort,+ channelItemSortEvent,channelItemSources,DEFAULT_CHANNEL_ITEM_FILTERS,+ DEFAULT_CHANNEL_ITEM_GROUPING,DEFAULT_CHANNEL_ITEM_SORT,filterChannelItems,groupChannelItems,@@ -35,6 +38,7 @@ import {TabsTrigger,} from "@posthog/quill";import { LOOPS_FLAG } from "@posthog/shared";+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import type { Task } from "@posthog/shared/domain-types";import { ChannelBackRow } from "@posthog/ui/features/canvas/components/ChannelBackRow";import { ChannelFilterMenu } from "@posthog/ui/features/canvas/components/ChannelFilterMenu";@@ -54,6 +58,7 @@ import { SHORTCUTS } from "@posthog/ui/features/command/keyboard-shortcuts";import { useCommandCenterStore } from "@posthog/ui/features/command-center/commandCenterStore";import { placeTaskInCommandCenter } from "@posthog/ui/features/command-center/placeTaskInCommandCenter";import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";+import { EditListItemAppearanceDialog } from "@posthog/ui/features/sidebar/components/EditListItemAppearanceDialog";import { SidebarKbdHint } from "@posthog/ui/features/sidebar/components/items/SidebarKbdHint";import { MarqueeOverlay } from "@posthog/ui/features/sidebar/components/MarqueeOverlay";import { SidebarBulkActionBar } from "@posthog/ui/features/sidebar/components/SidebarBulkActionBar";@@ -66,6 +71,7 @@ import { useMarqueeSelection } from "@posthog/ui/features/sidebar/useMarqueeSeleimport { usePinDrag } from "@posthog/ui/features/sidebar/usePinDrag";import { useSidebarBulkActions } from "@posthog/ui/features/sidebar/useSidebarBulkActions";import { useRenameTask } from "@posthog/ui/features/tasks/useTaskMutations";+import { track } from "@posthog/ui/shell/analytics";import { logger } from "@posthog/ui/shell/logger";import { useNavigate, useRouterState } from "@tanstack/react-router";import { motion, useReducedMotion } from "framer-motion";@@ -101,6 +107,9 @@ function RecentSectionHeader({onClearFilters,sort,onSortChange,+ grouping,+ onGroupingChange,+ onEditAppearance,sources,showCreatedBy,showRunFilters,@@ -120,6 +129,9 @@ function RecentSectionHeader({onClearFilters: () => void;sort: ChannelItemSort;onSortChange: (sort: ChannelItemSort) => void;+ grouping: ChannelItemGrouping;+ onGroupingChange: (grouping: ChannelItemGrouping) => void;+ onEditAppearance: () => void;sources: readonly string[];/** False in #me, where every session is yours and the filter says nothing. */showCreatedBy: boolean;@@ -171,6 +183,9 @@ function RecentSectionHeader({onClearFilters={onClearFilters}sort={sort}onSortChange={onSortChange}+ grouping={grouping}+ onGroupingChange={onGroupingChange}+ onEditAppearance={onEditAppearance}sources={sources}showCreatedBy={showCreatedBy}showRunFilters={showRunFilters}@@ -311,6 +326,23 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {DEFAULT_CHANNEL_ITEM_FILTERS,);const [sort, setSort] = useState<ChannelItemSort>(DEFAULT_CHANNEL_ITEM_SORT);+ const [rawGrouping, setGrouping] = useState<ChannelItemGrouping>(+ DEFAULT_CHANNEL_ITEM_GROUPING,+ );+ // Canvases carry no repository, so grouping by one would file the whole tab+ // under a single heading. Neutralised as well as hidden, the way the run+ // filters above are.+ const grouping = tab === "canvas" ? "date" : rawGrouping;+ const [appearanceOpen, setAppearanceOpen] = useState(false);+ const changeGrouping = (next: ChannelItemGrouping) => {+ if (next === grouping) return;+ setGrouping(next);+ track(ANALYTICS_EVENTS.TASK_LIST_GROUPING_CHANGED, {+ group_by: next,+ sort_by: channelItemSortEvent(sort),+ surface: "space",+ });+ };// 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@@ -386,8 +418,8 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {// midnight even when the list itself hasn't changed for hours.const dayStart = useLocalDayStart();const sections = useMemo(- () => groupChannelItems(recentItems, sort, new Date(dayStart)),- [recentItems, sort, dayStart],+ () => groupChannelItems(recentItems, sort, new Date(dayStart), grouping),+ [recentItems, sort, dayStart, grouping],);const pinnedSection = sections.find(@@ -721,6 +753,9 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {onClearFilters={() => setFilters(DEFAULT_CHANNEL_ITEM_FILTERS)}sort={sort}onSortChange={setSort}+ grouping={grouping}+ onGroupingChange={changeGrouping}+ onEditAppearance={() => setAppearanceOpen(true)}sources={sources}showCreatedBy={!isPersonalChannel}showRunFilters={tab === "task"}@@ -805,6 +840,13 @@ export function ChannelSidebar({ channelId }: { channelId: string }) {y={pinDrag.previewY}/>) : null}+ {/* The list owns the dialog, as it owns every other piece of this+ surface's state; the menu only asks for it to open. */}+ <EditListItemAppearanceDialog+ surface="space"+ open={appearanceOpen}+ onOpenChange={setAppearanceOpen}+ /></div>);}diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItemFacts.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItemFacts.tsnew file mode 100644index 000000000000..c83f9fa4a936--- /dev/null+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItemFacts.ts@@ -0,0 +1,51 @@+import type { ChannelItemModel } from "@posthog/core/canvas/channelItems";+import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";+import { metadataFromValues } from "@posthog/ui/features/sidebar/components/ListItemMetadata";+import {+ activityValue,+ type ListItemMetadataField,+ type ListItemMetadataValue,+} from "@posthog/ui/features/sidebar/listItemAppearance";+import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";+import type { ReactNode } from "react";++/**+ * What a space list can say about a session, beyond its name. Read off the item+ * rather than resolved here: `buildChannelItems` already did it, and a second+ * resolution is how a row and its section header end up disagreeing about which+ * repository a session belongs to.+ */+export type ChannelItemFacts = Partial<+ Record<ListItemMetadataField, ListItemMetadataValue | string>+>;++/**+ * Who made it. A session carries its creator as a user (`authorName` is only+ * ever set for a canvas), so reading the name alone showed no creator on any+ * session row.+ */+export function channelItemAuthor(item: ChannelItemModel): string | null {+ if (item.authorUser) return userDisplayName(item.authorUser);+ return item.authorName;+}++export function channelItemFacts(item: ChannelItemModel): ChannelItemFacts {+ return {+ repository: item.repository?.label,+ branch: item.branch ?? undefined,+ creator: channelItemAuthor(item) ?? undefined,+ activity: activityValue(item.ts),+ };+}++/**+ * The second row under a session's name, in the order the appearance dialog+ * stored.+ */+export function useChannelItemMetadata(+ item: ChannelItemModel,+): ReactNode | undefined {+ const fields = useSidebarStore((state) => state.listItemMetadataFields);+ if (fields.length === 0) return undefined;+ return metadataFromValues(channelItemFacts(item), fields);+}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.tsxindex 4bb55c1a53c6..4d832a4449ff 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@@ -129,6 +129,8 @@ function taskItem(id: string): ChannelItemModel {authorName: null,authorUuid: null,templateId: null,+ repository: null,+ branch: null,task: null,};}diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsxindex ff5c9a5f9dd0..5bdfe415a478 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelItems.tsx@@ -3,9 +3,9 @@ import {type ChannelItemModel,type ChannelItemOwner,type ChannelSessionFacts,+ type ChannelWorkspaceFacts,} from "@posthog/core/canvas/channelItems";import { formatBulkResult } from "@posthog/core/sidebar/selection";-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";@@ -85,14 +85,21 @@ export function useChannelItems(channelId: string): {needsInputTaskIds.add(taskId);}}- const workspaceModeByTaskId = new Map<string, WorkspaceMode>();+ const workspaceByTaskId = new Map<string, ChannelWorkspaceFacts>();for (const [taskId, workspace] of Object.entries(workspaces ?? {})) {- if (workspace.mode) workspaceModeByTaskId.set(taskId, workspace.mode);+ workspaceByTaskId.set(taskId, {+ mode: workspace.mode,+ folderPath: workspace.folderPath,+ isScratch: workspace.isScratch,+ // The linked branch wins: a worktree's own branch is where the work is+ // only until it is linked to the branch the PR is on.+ branch: workspace.linkedBranch ?? workspace.branchName ?? undefined,+ });}return {needsInputTaskIds,viewedTimestamps: timestamps,- workspaceModeByTaskId,+ workspaceByTaskId,};}, [sessions, timestamps, workspaces]);diff --git a/products/desktop/packages/ui/src/features/sidebar/components/EditListItemAppearanceDialog.stories.tsx b/products/desktop/packages/ui/src/features/sidebar/components/EditListItemAppearanceDialog.stories.tsxnew file mode 100644index 000000000000..0952dca3c233--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/components/EditListItemAppearanceDialog.stories.tsx@@ -0,0 +1,30 @@+import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";+import type { Meta, StoryObj } from "@storybook/react-vite";+import { fn } from "storybook/test";+import { EditListItemAppearanceDialog } from "./EditListItemAppearanceDialog";++const meta = {+ title: "Sidebar/Edit list item appearance dialog",+ component: EditListItemAppearanceDialog,+ parameters: {+ layout: "centered",+ },+ decorators: [+ (Story) => {+ useSidebarStore.setState({+ listItemMetadataFields: ["repository", "branch"],+ });+ return <Story />;+ },+ ],+ args: {+ surface: "sidebar",+ open: true,+ onOpenChange: fn(),+ },+} satisfies Meta<typeof EditListItemAppearanceDialog>;++export default meta;+type Story = StoryObj<typeof meta>;++export const Default: Story = {};diff --git a/products/desktop/packages/ui/src/features/sidebar/components/EditListItemAppearanceDialog.test.tsx b/products/desktop/packages/ui/src/features/sidebar/components/EditListItemAppearanceDialog.test.tsxnew file mode 100644index 000000000000..d31dcf7b7b78--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/components/EditListItemAppearanceDialog.test.tsx@@ -0,0 +1,164 @@+import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";+import { act, render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it, vi } from "vitest";++type CapturedDragEvent = {+ operation: { source?: { id?: string }; target?: { id?: string } };+ canceled?: boolean;+};++const { track, dndCapture } = vi.hoisted(() => ({+ track: vi.fn(),+ dndCapture: {} as {+ onDragStart?: (event: CapturedDragEvent) => void;+ onDragOver?: (event: CapturedDragEvent) => void;+ onDragEnd?: (event: CapturedDragEvent) => void;+ },+}));++vi.mock("@posthog/ui/shell/analytics", () => ({ track }));+vi.mock("@dnd-kit/react", () => ({+ DragDropProvider: ({+ onDragStart,+ onDragOver,+ onDragEnd,+ children,+ }: {+ onDragStart?: (event: CapturedDragEvent) => void;+ onDragOver?: (event: CapturedDragEvent) => void;+ onDragEnd?: (event: CapturedDragEvent) => void;+ children?: React.ReactNode;+ }) => {+ dndCapture.onDragStart = onDragStart;+ dndCapture.onDragOver = onDragOver;+ dndCapture.onDragEnd = onDragEnd;+ return <>{children}</>;+ },+}));+vi.mock("@dnd-kit/react/sortable", () => ({+ useSortable: () => ({+ ref: () => {},+ handleRef: () => {},+ isDragging: false,+ }),+}));++import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";+import { EditListItemAppearanceDialog } from "./EditListItemAppearanceDialog";++function renderDialog(onOpenChange = vi.fn()) {+ render(+ <EditListItemAppearanceDialog+ surface="sidebar"+ open+ onOpenChange={onOpenChange}+ />,+ );+ return { onOpenChange };+}++describe("EditListItemAppearanceDialog", () => {+ beforeEach(() => {+ track.mockReset();+ useSidebarStore.setState({ listItemMetadataFields: ["repository"] });+ });++ it("previews selected metadata and saves added fields", async () => {+ const user = userEvent.setup();+ const { onOpenChange } = renderDialog();++ expect(screen.getByText("posthog/code")).toBeInTheDocument();++ await user.click(screen.getByRole("checkbox", { name: "Branch" }));+ expect(screen.getByText("posthog/session-list")).toBeInTheDocument();++ await user.click(screen.getByText("Save"));++ expect(useSidebarStore.getState().listItemMetadataFields).toEqual([+ "repository",+ "branch",+ ]);+ expect(track).toHaveBeenCalledWith(+ ANALYTICS_EVENTS.TASK_LIST_APPEARANCE_CHANGED,+ {+ secondary_fields: ["repository", "branch"],+ secondary_field_count: 2,+ surface: "sidebar",+ },+ );+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });++ it("does not persist draft changes when canceled", async () => {+ const user = userEvent.setup();+ const { onOpenChange } = renderDialog();++ await user.click(screen.getByRole("checkbox", { name: "Creator" }));+ await user.click(screen.getByText("Cancel"));++ expect(useSidebarStore.getState().listItemMetadataFields).toEqual([+ "repository",+ ]);+ expect(track).not.toHaveBeenCalled();+ expect(onOpenChange.mock.calls[0]?.[0]).toBe(false);+ });++ it("saves selected fields in their dragged order", async () => {+ const user = userEvent.setup();+ useSidebarStore.setState({+ listItemMetadataFields: ["repository", "branch"],+ });+ renderDialog();++ act(() => {+ dndCapture.onDragStart?.({+ operation: { source: { id: "branch" } },+ });+ dndCapture.onDragOver?.({+ operation: {+ source: { id: "branch" },+ target: { id: "repository" },+ },+ });+ });++ await user.click(screen.getByText("Save"));++ expect(useSidebarStore.getState().listItemMetadataFields).toEqual([+ "branch",+ "repository",+ ]);+ });++ it("restores the pre-drag order when a drag is canceled", async () => {+ const user = userEvent.setup();+ useSidebarStore.setState({+ listItemMetadataFields: ["repository", "branch"],+ });+ renderDialog();++ act(() => {+ dndCapture.onDragStart?.({+ operation: { source: { id: "branch" } },+ });+ dndCapture.onDragOver?.({+ operation: {+ source: { id: "branch" },+ target: { id: "repository" },+ },+ });+ dndCapture.onDragEnd?.({+ operation: { source: { id: "branch" } },+ canceled: true,+ });+ });++ await user.click(screen.getByText("Save"));++ expect(useSidebarStore.getState().listItemMetadataFields).toEqual([+ "repository",+ "branch",+ ]);+ });+});diff --git a/products/desktop/packages/ui/src/features/sidebar/components/EditListItemAppearanceDialog.tsx b/products/desktop/packages/ui/src/features/sidebar/components/EditListItemAppearanceDialog.tsxnew file mode 100644index 000000000000..4f56b5581dbf--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/components/EditListItemAppearanceDialog.tsx@@ -0,0 +1,279 @@+import { type DragDropEvents, DragDropProvider } from "@dnd-kit/react";+import type { TaskData } from "@posthog/core/sidebar/sidebarData.types";+import {+ Button,+ Dialog,+ DialogBody,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Text,+} from "@posthog/quill";+import {+ ANALYTICS_EVENTS,+ type TaskListAppearanceChangedProperties,+} from "@posthog/shared/analytics-events";+import { TaskStatusDot } from "@posthog/ui/features/sidebar/components/items/TaskStatusDot";+import { taskDot } from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";+import { taskMetadata } from "@posthog/ui/features/sidebar/components/ListItemMetadata";+import { SidebarItem } from "@posthog/ui/features/sidebar/components/SidebarItem";+import {+ LIST_ITEM_METADATA_FIELDS,+ type ListItemMetadataField,+ moveListItemMetadataField,+} from "@posthog/ui/features/sidebar/listItemAppearance";+import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";+import { track } from "@posthog/ui/shell/analytics";+import { useEffect, useRef, useState } from "react";+import { SortableListItemMetadataField } from "./SortableListItemMetadataField";++interface PreviewTask+ extends Pick<+ TaskData,+ "repository" | "branchName" | "linkedBranch" | "lastActivityAt"+ > {+ id: string;+ title: string;+ creatorName: string;+}++/** Ages that read as a list someone is actually working in. */+const PREVIEW_AGES_MS = [2 * 3_600_000, 3 * 86_400_000, 3 * 7 * 86_400_000];++/** The preview rows, dated against now rather than against module load. */+function datedPreview(): PreviewTask[] {+ return PREVIEW_TASKS.map((task, index) => ({+ ...task,+ lastActivityAt: Date.now() - PREVIEW_AGES_MS[index],+ }));+}++const PREVIEW_TASKS: Omit<PreviewTask, "lastActivityAt">[] = [+ {+ id: "preview-review",+ title: "Address feedback on session list",+ repository: {+ fullPath: "posthog/code",+ name: "code",+ organization: "posthog",+ },+ branchName: "posthog/session-list",+ linkedBranch: "posthog/session-list",+ creatorName: "Ada Lovelace",+ },+ {+ id: "preview-replay",+ title: "Fix recording loading state",+ repository: {+ fullPath: "posthog/posthog",+ name: "posthog",+ organization: "posthog",+ },+ branchName: "fix/replay-loading",+ linkedBranch: "fix/replay-loading",+ creatorName: "Grace Hopper",+ },+ {+ id: "preview-docs",+ title: "Update SDK installation docs",+ repository: {+ fullPath: "posthog/posthog-js",+ name: "posthog-js",+ organization: "posthog",+ },+ branchName: "docs/sdk-installation",+ linkedBranch: null,+ creatorName: "Katherine Johnson",+ },+];++function orderedFieldList(+ selectedFields: readonly ListItemMetadataField[],+): ListItemMetadataField[] {+ const selected = new Set(selectedFields);+ return [+ ...selectedFields,+ ...LIST_ITEM_METADATA_FIELDS.filter((field) => !selected.has(field)),+ ];+}++export function EditListItemAppearanceDialog({+ surface,+ open,+ onOpenChange,+}: {+ /** Which list it was opened from. The setting itself is shared by both. */+ surface: TaskListAppearanceChangedProperties["surface"];+ open: boolean;+ onOpenChange: (open: boolean) => void;+}) {+ // Dated when the dialog opens, so the preview's ages are the ages the list+ // is showing rather than whenever this module loaded.+ const storedFields = useSidebarStore((state) => state.listItemMetadataFields);+ const setStoredFields = useSidebarStore(+ (state) => state.setListItemMetadataFields,+ );+ const [fieldOrder, setFieldOrder] = useState<ListItemMetadataField[]>(() =>+ orderedFieldList(storedFields),+ );+ const [selectedFields, setSelectedFields] = useState<+ Set<ListItemMetadataField>+ >(() => new Set(storedFields));+ const lastMove = useRef<string | null>(null);+ // The order when the drag began. dragover reorders in place, so a canceled+ // drag (Escape, pointercancel) would otherwise leave the half-dragged order+ // for Save to store; this puts it back.+ const orderBeforeDrag = useRef<ListItemMetadataField[] | null>(null);++ useEffect(() => {+ if (!open) return;+ setFieldOrder(orderedFieldList(storedFields));+ setSelectedFields(new Set(storedFields));+ lastMove.current = null;+ }, [open, storedFields]);++ const handleDragStart: DragDropEvents["dragstart"] = () => {+ lastMove.current = null;+ orderBeforeDrag.current = fieldOrder;+ };++ const handleDragOver: DragDropEvents["dragover"] = (event) => {+ const sourceId = event.operation.source?.id;+ const targetId = event.operation.target?.id;+ if (!sourceId || !targetId || sourceId === targetId) return;+ const moveKey = `${String(sourceId)}->${String(targetId)}`;+ if (lastMove.current === moveKey) return;+ lastMove.current = moveKey;+ setFieldOrder((current) =>+ moveListItemMetadataField(current, String(sourceId), String(targetId)),+ );+ };++ const handleDragEnd: DragDropEvents["dragend"] = (event) => {+ const before = orderBeforeDrag.current;+ orderBeforeDrag.current = null;+ if (event.canceled && before) setFieldOrder(before);+ };++ const toggleField = (field: ListItemMetadataField, checked: boolean) => {+ setSelectedFields((current) => {+ const next = new Set(current);+ if (checked) next.add(field);+ else next.delete(field);+ return next;+ });+ };++ const visibleFields = fieldOrder.filter((field) => selectedFields.has(field));+ // Dated per render, so the ages are the ages the list is showing rather than+ // whenever this module loaded. Three objects from three constants.+ const previewTasks = datedPreview();++ const handleSave = () => {+ const changed =+ visibleFields.length !== storedFields.length ||+ visibleFields.some((field, index) => field !== storedFields[index]);+ if (changed) {+ setStoredFields(visibleFields);+ track(ANALYTICS_EVENTS.TASK_LIST_APPEARANCE_CHANGED, {+ secondary_fields: visibleFields,+ secondary_field_count: visibleFields.length,+ surface,+ });+ }+ onOpenChange(false);+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent showCloseButton={false} className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>Edit list item appearance</DialogTitle>+ <DialogDescription>+ Add context under each session name to find related work faster.+ </DialogDescription>+ </DialogHeader>++ <DialogBody viewportClassName="flex flex-col gap-5">+ <section aria-labelledby="list-item-preview-heading">+ <Text+ id="list-item-preview-heading"+ size="sm"+ weight="medium"+ className="mb-2 block"+ >+ Preview+ </Text>+ {/* Not `disabled` rows: that dims them, and the preview has to+ carry the list's real colours to be worth looking at. Nothing+ inside answers a pointer instead. */}+ <div className="pointer-events-none h-[132px] rounded-(--radius-3) border border-border bg-(--gray-2) p-2">+ {previewTasks.map((task) => (+ <SidebarItem+ key={task.id}+ depth={0}+ // The same leading mark a settled session carries in the+ // list, so the preview reads as the list it stands for.+ icon={<TaskStatusDot dot={taskDot({})} />}+ label={task.title}+ subtitle={taskMetadata(task, task.creatorName, visibleFields)}+ tabIndex={-1}+ />+ ))}+ </div>+ </section>++ <section aria-labelledby="second-row-heading">+ <Text id="second-row-heading" size="sm" weight="medium">+ Second row+ </Text>+ <Text size="xs" variant="muted" className="mt-0.5 mb-3 block">+ Choose the details to show. Drag them into the order you want.+ Leave all unchecked for a single-row list.+ </Text>+ <DragDropProvider+ onDragStart={handleDragStart}+ onDragOver={handleDragOver}+ onDragEnd={handleDragEnd}+ >+ <div className="flex flex-col gap-2">+ {fieldOrder.map((field, index) => (+ <SortableListItemMetadataField+ key={field}+ field={field}+ index={index}+ checked={selectedFields.has(field)}+ onCheckedChange={(checked) => toggleField(field, checked)}+ />+ ))}+ </div>+ </DragDropProvider>+ </section>+ </DialogBody>++ <DialogFooter>+ <DialogClose+ render={+ <Button+ variant="outline"+ data-attr="list-item-appearance-cancel"+ />+ }+ >+ Cancel+ </DialogClose>+ <Button+ variant="primary"+ data-attr="list-item-appearance-save"+ onClick={handleSave}+ >+ Save+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/ListItemMetadata.tsx b/products/desktop/packages/ui/src/features/sidebar/components/ListItemMetadata.tsxnew file mode 100644index 000000000000..33f39eae0fea--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/components/ListItemMetadata.tsx@@ -0,0 +1,52 @@+import type { TaskData } from "@posthog/core/sidebar/sidebarData.types";+import {+ type ListItemMetadataField,+ type ListItemMetadataSegment,+ listItemMetadataSegments,+ taskMetadataSegments,+} from "@posthog/ui/features/sidebar/listItemAppearance";+import { Fragment, type ReactNode } from "react";++/**+ * The second row under a session's name, or nothing where the reader chose no+ * fields. Returns the node rather than exporting a component, because a row's+ * height turns on whether it has a second row: a component always hands+ * `SidebarItem` something truthy, and every row grows a blank line.+ *+ * The parts are spans rather than one joined string so a segment can carry what+ * its short form hides — the exact moment behind "2h ago". A native `title`+ * rather than a tooltip component: a list draws dozens of these, and the+ * browser's own costs nothing.+ */+export function listItemMetadata(+ segments: readonly ListItemMetadataSegment[],+): ReactNode | undefined {+ if (segments.length === 0) return undefined;+ return segments.map((segment, index) => (+ // The separator sits outside the titled span: it belongs to neither+ // segment, and inside one it would split the segment's own text.+ <Fragment key={segment.field}>+ {index > 0 ? " · " : null}+ <span title={segment.title}>{segment.text}</span>+ </Fragment>+ ));+}++/** The Code sidebar's rows, which hold a `TaskData`. */+export function taskMetadata(+ task: Pick<+ TaskData,+ "repository" | "branchName" | "linkedBranch" | "lastActivityAt"+ >,+ creatorName: string | undefined,+ fields: readonly ListItemMetadataField[],+): ReactNode | undefined {+ return listItemMetadata(taskMetadataSegments(task, creatorName, fields));+}++/** A surface that resolved the values itself, like a space's session list. */+export function metadataFromValues(+ ...args: Parameters<typeof listItemMetadataSegments>+): ReactNode | undefined {+ return listItemMetadata(listItemMetadataSegments(...args));+}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarItem.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarItem.tsxindex 07fb87786463..bf64950dc912 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarItem.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarItem.tsx@@ -77,6 +77,10 @@ export function SidebarItem({className={cn("group flex w-full cursor-default text-left text-[13px] leading-snug transition-colors","disabled:opacity-100",+ // A second row outgrows the button's fixed height, and the overflow+ // lands on the row below it. The padding stands in for the height the+ // row gives up.+ subtitle && "h-auto py-1",// The open row keeps its neutral background on its own, and takes the// accent only once it is part of a selection, a shade above the rows// picked around it.@@ -127,7 +131,7 @@ export function SidebarItem({) : null}</span>{subtitle ? (- <span className="truncate text-gray-10 group-data-active:text-gray-11">+ <span className="truncate text-muted-foreground/70 text-xxs group-data-active:text-muted-foreground">{subtitle}</span>) : null}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsxindex 7bc4a836fa87..9b0d4dcf884f 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/SidebarMenu.tsx@@ -8,7 +8,7 @@ import {import { isTaskActivelyRunning } from "@posthog/core/sidebar/taskRunning";import { resolveBulkTaskContextMenuIntent } from "@posthog/core/tasks/contextMenuActions";import { useHostTRPCClient } from "@posthog/host-router/react";-import type { Task } from "@posthog/shared/types";+import type { Task, UserBasic } from "@posthog/shared/types";import {archiveTasksImperative,useArchiveCacheKeys,@@ -53,6 +53,15 @@ import { TaskListView } from "./TaskListView";const log = logger.scope("sidebar-menu");+function creatorName(createdBy: UserBasic | null | undefined): string | null {+ if (!createdBy) return null;+ const name = [createdBy.first_name, createdBy.last_name]+ .filter(Boolean)+ .join(" ")+ .trim();+ return name || createdBy.email || null;+}+function SidebarMenuComponent() {const hostClient = useHostTRPCClient();const archiveCacheKeys = useArchiveCacheKeys();@@ -87,6 +96,14 @@ function SidebarMenuComponent() {() => 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);@@ -543,6 +560,7 @@ function SidebarMenuComponent() {onTaskEditSubmit={handleTaskEditSubmit}onTaskEditCancel={handleTaskEditCancel}onGroupContextMenu={handleGroupContextMenu}+ creatorNameByTaskId={creatorNameByTaskId}hasMore={sidebarData.hasMore}/>)}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/SortableListItemMetadataField.tsx b/products/desktop/packages/ui/src/features/sidebar/components/SortableListItemMetadataField.tsxnew file mode 100644index 000000000000..7a8f797c30ee--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/components/SortableListItemMetadataField.tsx@@ -0,0 +1,81 @@+import { useSortable } from "@dnd-kit/react/sortable";+import {+ Clock,+ DotsSixVertical,+ GitBranch,+ GitFork,+ User,+} from "@phosphor-icons/react";+import { Checkbox, cn, Label } from "@posthog/quill";+import {+ LIST_ITEM_METADATA_LABELS,+ type ListItemMetadataField,+} from "@posthog/ui/features/sidebar/listItemAppearance";+import type { ComponentType, RefCallback } from "react";++const FIELD_ICONS: Record<+ ListItemMetadataField,+ ComponentType<{ size?: number | string }>+> = {+ repository: GitFork,+ branch: GitBranch,+ creator: User,+ activity: Clock,+};++export function SortableListItemMetadataField({+ field,+ index,+ checked,+ onCheckedChange,+}: {+ field: ListItemMetadataField;+ index: number;+ checked: boolean;+ onCheckedChange: (checked: boolean) => void;+}) {+ const { ref, handleRef, isDragging } = useSortable({+ id: field,+ index,+ group: "list-item-metadata",+ transition: { duration: 200, easing: "ease" },+ });+ const Icon = FIELD_ICONS[field];+ const checkboxId = `list-item-metadata-${field}`;++ return (+ <div+ ref={ref}+ className={cn(+ "rounded-(--radius-2) border border-border bg-(--gray-1) px-2.5 py-2",+ isDragging && "opacity-50",+ )}+ >+ <div className="flex items-center gap-2">+ <button+ ref={handleRef as RefCallback<HTMLButtonElement>}+ type="button"+ title={`Drag ${LIST_ITEM_METADATA_LABELS[field]} to reorder`}+ aria-label={`Drag ${LIST_ITEM_METADATA_LABELS[field]} to reorder`}+ data-attr={`list-item-metadata-drag-${field}`}+ className="shrink-0 cursor-grab text-gray-9 hover:text-gray-11"+ >+ <DotsSixVertical size={14} />+ </button>+ <Label+ htmlFor={checkboxId}+ className="flex flex-1 cursor-pointer items-center gap-2"+ >+ <Checkbox+ id={checkboxId}+ checked={checked}+ data-attr={`list-item-metadata-${field}`}+ onCheckedChange={(value) => onCheckedChange(value === true)}+ />+ <Icon size={15} />+ {LIST_ITEM_METADATA_LABELS[field]}+ </Label>+ </div>+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.stories.tsx b/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.stories.tsxindex 605346b93748..7ab289bf5dff 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.stories.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.stories.tsx@@ -80,6 +80,7 @@ const meta = {useSidebarStore.setState({organizeMode: "chronological",sortMode: "updated",+ listItemMetadataFields: [],});return (<div className="h-[460px] w-72 overflow-hidden rounded-lg border border-gray-6 bg-gray-1 p-2">@@ -102,6 +103,7 @@ const meta = {onTaskTogglePin: fn(),onTaskEditSubmit: fn(),onTaskEditCancel: fn(),+ creatorNameByTaskId: new Map(),hasMore: false,},} satisfies Meta<typeof TaskListView>;diff --git a/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.tsx b/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.tsxindex b25c6967a925..e795ea01985d 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/TaskListView.tsx@@ -18,6 +18,7 @@ import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";import { DragBatchLabel } from "@posthog/ui/features/sidebar/components/DragBatchLabel";import { DraggableFolder } from "@posthog/ui/features/sidebar/components/DraggableFolder";import { GroupWorktreesSection } from "@posthog/ui/features/sidebar/components/GroupWorktreesSection";+import { taskMetadata } from "@posthog/ui/features/sidebar/components/ListItemMetadata";import { SidebarSection } from "@posthog/ui/features/sidebar/components/SidebarSection";import { TaskRow } from "@posthog/ui/features/sidebar/components/TaskRow";import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";@@ -65,6 +66,7 @@ interface TaskListViewProps {) => void;onTaskEditCancel: () => void;onGroupContextMenu?: (groupId: string, e: React.MouseEvent) => void;+ creatorNameByTaskId: ReadonlyMap<string, string>;hasMore: boolean;}@@ -88,6 +90,7 @@ export function TaskListView({onTaskEditSubmit,onTaskEditCancel,onGroupContextMenu,+ creatorNameByTaskId,hasMore,}: TaskListViewProps) {const selectedIdSet = useMemo(@@ -97,6 +100,9 @@ export function TaskListView({const hasMultiSelection = selectedTaskIds.length > 1;const organizeMode = useSidebarStore((state) => state.organizeMode);const sortMode = useSidebarStore((state) => state.sortMode);+ const listItemMetadataFields = useSidebarStore(+ (state) => state.listItemMetadataFields,+ );const collapsedSections = useSidebarStore((state) => state.collapsedSections);const toggleSection = useSidebarStore((state) => state.toggleSection);const loadMoreHistory = useSidebarStore((state) => state.loadMoreHistory);@@ -216,6 +222,11 @@ export function TaskListView({onDragStart={(event) => pinDrag.onItemDragStart(task, event)}onDragEnd={pinDrag.onItemDragEnd}timestamp={task[timestampKey]}+ subtitle={taskMetadata(+ task,+ creatorNameByTaskId.get(task.id),+ listItemMetadataFields,+ )}depth={depth}/></motion.div>@@ -478,6 +489,11 @@ export function TaskListView({onEditSubmit={() => undefined}onEditCancel={() => undefined}timestamp={dragState.items[0][timestampKey]}+ subtitle={taskMetadata(+ dragState.items[0],+ creatorNameByTaskId.get(dragState.items[0].id),+ listItemMetadataFields,+ )}withPrStatus={false}/>)}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/TaskRow.tsx b/products/desktop/packages/ui/src/features/sidebar/components/TaskRow.tsxindex fb595c38d649..15c9a25245d1 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/TaskRow.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/TaskRow.tsx@@ -20,6 +20,7 @@ interface TaskRowProps {onDragStart?: (event: React.DragEvent) => void;onDragEnd?: (event: React.DragEvent) => void;timestamp: number;+ subtitle?: React.ReactNode;depth?: number;/*** Whether to resolve the PR's state — a query per row into the host, where it@@ -47,6 +48,7 @@ export function TaskRow({onDragStart,onDragEnd,timestamp,+ subtitle,depth = 0,withPrStatus = true,}: TaskRowProps) {@@ -70,6 +72,7 @@ export function TaskRow({depth={depth}taskId={task.id}label={task.title}+ subtitle={subtitle}isActive={isActive}isSelected={isSelected}isArchiving={isArchiving}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/TasksHeader.test.tsx b/products/desktop/packages/ui/src/features/sidebar/components/TasksHeader.test.tsxindex 700c9d495cf8..53ac46a2fe49 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/TasksHeader.test.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/TasksHeader.test.tsx@@ -37,7 +37,11 @@ describe("TasksHeader", () => {beforeEach(() => {vi.clearAllMocks();featureFlagEnabled.value = true;- useSidebarStore.setState({ channelsEnabled: false });+ useSidebarStore.setState({+ channelsEnabled: false,+ organizeMode: "by-project",+ sortMode: "updated",+ });});it("switches modes from the panel title and changes the available actions", async () => {@@ -75,6 +79,31 @@ describe("TasksHeader", () => {});});+ it("groups the task list by repository or date", async () => {+ const user = userEvent.setup();+ render(+ <Theme>+ <TasksHeader />+ </Theme>,+ );++ await user.click(screen.getByLabelText("Filter tasks"));++ expect(await screen.findByText("Group by")).toBeInTheDocument();+ expect(screen.getByText("Repository")).toHaveAttribute(+ "aria-checked",+ "true",+ );++ await user.click(screen.getByText("Date"));++ expect(useSidebarStore.getState().organizeMode).toBe("chronological");+ expect(track).toHaveBeenCalledWith(+ ANALYTICS_EVENTS.TASK_LIST_GROUPING_CHANGED,+ { group_by: "date", sort_by: "updated", surface: "sidebar" },+ );+ });+it("hides the mode selector when Channels is unavailable", () => {featureFlagEnabled.value = false;diff --git a/products/desktop/packages/ui/src/features/sidebar/components/TasksHeader.tsx b/products/desktop/packages/ui/src/features/sidebar/components/TasksHeader.tsxindex 90158ca854c8..9368136c48bf 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/TasksHeader.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/TasksHeader.tsx@@ -14,6 +14,7 @@ import {DropdownMenu,DropdownMenuCheckboxItem,DropdownMenuContent,+ DropdownMenuItem,DropdownMenuRadioGroup,DropdownMenuRadioItem,DropdownMenuSeparator,@@ -28,6 +29,7 @@ import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import { useMeQuery } from "@posthog/ui/features/auth/useMeQuery";import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";import { useFolders } from "@posthog/ui/features/folders/useFolders";+import { EditListItemAppearanceDialog } from "@posthog/ui/features/sidebar/components/EditListItemAppearanceDialog";import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";import { useHoldSidebarPeek } from "@posthog/ui/features/sidebar/useHoldSidebarPeek";import { Tooltip } from "@posthog/ui/primitives/Tooltip";@@ -108,111 +110,140 @@ function TaskFilterMenu() {const toggleTaskType = useSidebarStore((state) => state.toggleTaskType);const { data: currentUser } = useMeQuery();const isStaff = currentUser?.is_staff === true;+ const [appearanceDialogOpen, setAppearanceDialogOpen] = useState(false);const handleOpenChange = useHoldSidebarPeek();+ const handleOrganizeModeChange = (value: string) => {+ const nextMode = value as typeof organizeMode;+ if (nextMode === organizeMode) return;+ setOrganizeMode(nextMode);+ track(ANALYTICS_EVENTS.TASK_LIST_GROUPING_CHANGED, {+ group_by: nextMode === "by-project" ? "repository" : "date",+ sort_by: sortMode,+ surface: "sidebar",+ });+ };return (- <DropdownMenu onOpenChange={handleOpenChange}>- <DropdownMenuTrigger- render={- <Button type="button" aria-label="Filter tasks" size="icon-sm">- <FunnelSimpleIcon size={14} />- </Button>- }- />- <DropdownMenuContent- align="start"- side="bottom"- sideOffset={6}- className="min-w-fit"- >- <MenuLabel>Organize</MenuLabel>- <DropdownMenuRadioGroup- value={organizeMode}- onValueChange={(value) =>- setOrganizeMode(value as typeof organizeMode)+ <>+ <DropdownMenu onOpenChange={handleOpenChange}>+ <DropdownMenuTrigger+ render={+ <Button type="button" aria-label="Filter tasks" size="icon-sm">+ <FunnelSimpleIcon size={14} />+ </Button>}+ />+ <DropdownMenuContent+ align="start"+ side="bottom"+ sideOffset={6}+ className="min-w-fit">- <DropdownMenuRadioItem value="by-project">- By project- </DropdownMenuRadioItem>- <DropdownMenuRadioItem value="chronological">- Chronological list- </DropdownMenuRadioItem>- </DropdownMenuRadioGroup>+ <MenuLabel>Group by</MenuLabel>+ <DropdownMenuRadioGroup+ value={organizeMode}+ onValueChange={handleOrganizeModeChange}+ >+ <DropdownMenuRadioItem value="by-project">+ Repository+ </DropdownMenuRadioItem>+ <DropdownMenuRadioItem value="chronological">+ Date+ </DropdownMenuRadioItem>+ </DropdownMenuRadioGroup>- <DropdownMenuSeparator />+ <DropdownMenuSeparator />- <MenuLabel>Sort by</MenuLabel>- <DropdownMenuRadioGroup- value={sortMode}- onValueChange={(value) => setSortMode(value as typeof sortMode)}- >- <DropdownMenuRadioItem value="created">Created</DropdownMenuRadioItem>- <DropdownMenuRadioItem value="updated">Updated</DropdownMenuRadioItem>- </DropdownMenuRadioGroup>+ <MenuLabel>Sort by</MenuLabel>+ <DropdownMenuRadioGroup+ value={sortMode}+ onValueChange={(value) => setSortMode(value as typeof sortMode)}+ >+ <DropdownMenuRadioItem value="created">+ Created+ </DropdownMenuRadioItem>+ <DropdownMenuRadioItem value="updated">+ Updated+ </DropdownMenuRadioItem>+ </DropdownMenuRadioGroup>- {import.meta.env.DEV && (- <>- <DropdownMenuSeparator />+ {import.meta.env.DEV && (+ <>+ <DropdownMenuSeparator />- <MenuLabel>Show</MenuLabel>- <DropdownMenuRadioGroup- value={showAllUsers ? "all" : "mine"}- onValueChange={(value) => setShowAllUsers(value === "all")}- >- <DropdownMenuRadioItem value="mine">- My tasks- </DropdownMenuRadioItem>- <DropdownMenuRadioItem value="all">- All tasks- </DropdownMenuRadioItem>- </DropdownMenuRadioGroup>- </>- )}+ <MenuLabel>Show</MenuLabel>+ <DropdownMenuRadioGroup+ value={showAllUsers ? "all" : "mine"}+ onValueChange={(value) => setShowAllUsers(value === "all")}+ >+ <DropdownMenuRadioItem value="mine">+ My tasks+ </DropdownMenuRadioItem>+ <DropdownMenuRadioItem value="all">+ All tasks+ </DropdownMenuRadioItem>+ </DropdownMenuRadioGroup>+ </>+ )}- {isStaff && (- <>- <DropdownMenuSeparator />+ {isStaff && (+ <>+ <DropdownMenuSeparator />- <MenuLabel>Task visibility</MenuLabel>- <DropdownMenuRadioGroup- value={showInternal ? "internal" : "external"}- onValueChange={(value) => setShowInternal(value === "internal")}- >- <DropdownMenuRadioItem value="external">- External- </DropdownMenuRadioItem>- <DropdownMenuRadioItem value="internal">- Internal- </DropdownMenuRadioItem>- </DropdownMenuRadioGroup>- </>- )}+ <MenuLabel>Task visibility</MenuLabel>+ <DropdownMenuRadioGroup+ value={showInternal ? "internal" : "external"}+ onValueChange={(value) => setShowInternal(value === "internal")}+ >+ <DropdownMenuRadioItem value="external">+ External+ </DropdownMenuRadioItem>+ <DropdownMenuRadioItem value="internal">+ Internal+ </DropdownMenuRadioItem>+ </DropdownMenuRadioGroup>+ </>+ )}- <DropdownMenuSeparator />+ <DropdownMenuSeparator />- <DropdownMenuSub>- <DropdownMenuSubTrigger>Environment</DropdownMenuSubTrigger>- <DropdownMenuSubContent side="right" sideOffset={4}>- {ALL_WORKSPACE_MODES.map((mode) => {- const { label, icon: Icon } = ENVIRONMENT_META[mode];- return (- <DropdownMenuCheckboxItem- key={mode}- checked={taskTypeFilter.includes(mode)}- closeOnClick={false}- onCheckedChange={() => toggleTaskType(mode)}- >- <Icon size={14} />- {label}- </DropdownMenuCheckboxItem>- );- })}- </DropdownMenuSubContent>- </DropdownMenuSub>- </DropdownMenuContent>- </DropdownMenu>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>Environment</DropdownMenuSubTrigger>+ <DropdownMenuSubContent side="right" sideOffset={4}>+ {ALL_WORKSPACE_MODES.map((mode) => {+ const { label, icon: Icon } = ENVIRONMENT_META[mode];+ return (+ <DropdownMenuCheckboxItem+ key={mode}+ checked={taskTypeFilter.includes(mode)}+ closeOnClick={false}+ onCheckedChange={() => toggleTaskType(mode)}+ >+ <Icon size={14} />+ {label}+ </DropdownMenuCheckboxItem>+ );+ })}+ </DropdownMenuSubContent>+ </DropdownMenuSub>++ <DropdownMenuSeparator />++ <DropdownMenuItem+ data-attr="edit-list-item-appearance"+ onClick={() => setAppearanceDialogOpen(true)}+ >+ Edit list item appearance…+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <EditListItemAppearanceDialog+ surface="sidebar"+ open={appearanceDialogOpen}+ onOpenChange={setAppearanceDialogOpen}+ />+ </>);}diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/TaskItem.tsx b/products/desktop/packages/ui/src/features/sidebar/components/items/TaskItem.tsxindex f350df1d6463..e78c3e075457 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/items/TaskItem.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/TaskItem.tsx@@ -36,6 +36,7 @@ interface TaskItemProps {depth?: number;taskId: string;label: string;+ subtitle?: React.ReactNode;isActive: boolean;isSelected?: boolean;/** Archive request in flight: show a spinner and suppress hover actions. */@@ -112,6 +113,7 @@ export function TaskItem({depth = 0,taskId,label,+ subtitle,isActive,isSelected = false,isArchiving = false,@@ -222,6 +224,7 @@ export function TaskItem({depth={depth}icon={icon}label={label}+ subtitle={subtitle}isActive={isActive}isSelected={isSelected}// Lets a drag-selection find the row and the session it stands for.diff --git a/products/desktop/packages/ui/src/features/sidebar/listItemAppearance.test.ts b/products/desktop/packages/ui/src/features/sidebar/listItemAppearance.test.tsnew file mode 100644index 000000000000..eb1a92dc3b52--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/listItemAppearance.test.ts@@ -0,0 +1,119 @@+import type { TaskData } from "@posthog/core/sidebar/sidebarData.types";+import { describe, expect, it } from "vitest";+import {+ type ListItemMetadataField,+ moveListItemMetadataField,+ sanitizeListItemMetadataFields,+ taskMetadataSegments,+} from "./listItemAppearance";++const task: Pick<+ TaskData,+ "repository" | "branchName" | "linkedBranch" | "lastActivityAt"+> = {+ repository: {+ fullPath: "posthog/code",+ name: "code",+ organization: "posthog",+ },+ branchName: "current-branch",+ linkedBranch: "linked-branch",+ lastActivityAt: 0,+};++describe("list item appearance", () => {+ it.each<{+ label: string;+ taskValue: typeof task;+ creatorName: string | undefined;+ fields: ListItemMetadataField[];+ expected: string[];+ }>([+ {+ label: "selected metadata in its configured order",+ taskValue: task,+ creatorName: "Ada Lovelace",+ fields: ["branch", "repository", "creator"],+ expected: ["linked-branch", "posthog/code", "Ada Lovelace"],+ },+ {+ label: "no second row when selected metadata is unavailable",+ taskValue: task,+ creatorName: undefined,+ fields: ["creator"],+ expected: [],+ },+ {+ label: "current branch when no linked branch exists",+ taskValue: { ...task, linkedBranch: null },+ creatorName: undefined,+ fields: ["branch"],+ expected: ["current-branch"],+ },+ {+ label: "local repository name without its absolute path",+ taskValue: {+ ...task,+ repository: { fullPath: "/Users/ada/code", name: "code" },+ },+ creatorName: undefined,+ fields: ["repository"],+ expected: ["code"],+ },+ ])("formats $label", ({ taskValue, creatorName, fields, expected }) => {+ expect(+ taskMetadataSegments(taskValue, creatorName, fields).map((s) => s.text),+ ).toEqual(expected);+ });++ // The short phrase is what a row has room for; the moment behind it is what+ // a reader needs when "3w ago" is not enough, and only the segment can carry+ // it to the tooltip.+ it("says how long ago the session moved, with the moment behind it", () => {+ const [segment] = taskMetadataSegments(+ { ...task, lastActivityAt: Date.now() - 2 * 3_600_000 },+ undefined,+ ["activity"],+ );++ expect(segment.text).toBe("2h ago");+ expect(segment.title).toBeTruthy();+ });++ it("drops the activity field for a session that never moved", () => {+ expect(+ taskMetadataSegments({ ...task, lastActivityAt: 0 }, undefined, [+ "activity",+ ]),+ ).toEqual([]);+ });++ // A row's height turns on whether it has a second row, so "nothing to show"+ // has to come back as nothing rather than as an empty row.+ it("returns no segments when nothing was chosen", () => {+ expect(taskMetadataSegments(task, "Ada Lovelace", [])).toEqual([]);+ });++ it("sanitizes persisted fields to known unique values", () => {+ expect(+ sanitizeListItemMetadataFields([+ "creator",+ "retired-field",+ 7,+ "repository",+ "creator",+ ]),+ ).toEqual(["creator", "repository"]);+ expect(sanitizeListItemMetadataFields("branch")).toEqual([]);+ });++ it("moves a field to the target position", () => {+ expect(+ moveListItemMetadataField(+ ["repository", "branch", "creator"],+ "creator",+ "repository",+ ),+ ).toEqual(["creator", "repository", "branch"]);+ });+});diff --git a/products/desktop/packages/ui/src/features/sidebar/listItemAppearance.ts b/products/desktop/packages/ui/src/features/sidebar/listItemAppearance.tsnew file mode 100644index 000000000000..162846ceada4--- /dev/null+++ b/products/desktop/packages/ui/src/features/sidebar/listItemAppearance.ts@@ -0,0 +1,124 @@+import { repositoryLabel } from "@posthog/core/sidebar/groupTasks";+import type { TaskData } from "@posthog/core/sidebar/sidebarData.types";+import { formatAbsoluteDateTime, formatRelativeAge } from "@posthog/shared";++export const LIST_ITEM_METADATA_FIELDS = [+ "repository",+ "branch",+ "creator",+ "activity",+] as const;++export type ListItemMetadataField = (typeof LIST_ITEM_METADATA_FIELDS)[number];++export const LIST_ITEM_METADATA_LABELS: Record<ListItemMetadataField, string> =+ {+ repository: "Repository",+ branch: "Branch",+ creator: "Creator",+ activity: "Last activity",+ };++/**+ * One field's value. `title` carries what the short text leaves out, which the+ * row hangs off a tooltip: "2h ago" is what a reader wants at a glance, and the+ * exact moment is what they want when the glance isn't enough.+ */+export interface ListItemMetadataValue {+ text: string;+ title?: string;+}++export interface ListItemMetadataSegment extends ListItemMetadataValue {+ field: ListItemMetadataField;+}++export function sanitizeListItemMetadataFields(+ value: unknown,+): ListItemMetadataField[] {+ if (!Array.isArray(value)) return [];++ const knownFields = new Set<string>(LIST_ITEM_METADATA_FIELDS);+ const seen = new Set<ListItemMetadataField>();+ const result: ListItemMetadataField[] = [];++ for (const field of value) {+ if (typeof field !== "string" || !knownFields.has(field)) continue;+ const typedField = field as ListItemMetadataField;+ if (seen.has(typedField)) continue;+ seen.add(typedField);+ result.push(typedField);+ }++ return result;+}++export function moveListItemMetadataField(+ fields: readonly ListItemMetadataField[],+ sourceId: string,+ targetId: string,+): ListItemMetadataField[] {+ const sourceIndex = fields.indexOf(sourceId as ListItemMetadataField);+ const targetIndex = fields.indexOf(targetId as ListItemMetadataField);+ if (sourceIndex === -1 || targetIndex === -1 || sourceIndex === targetIndex) {+ return [...fields];+ }++ const next = [...fields];+ const [source] = next.splice(sourceIndex, 1);+ next.splice(targetIndex, 0, source);+ return next;+}++/** When something last happened, as a phrase with the moment behind it. */+export function activityValue(+ timestamp: number | null | undefined,+): ListItemMetadataValue | undefined {+ if (!timestamp) return undefined;+ return {+ text: formatRelativeAge(timestamp),+ title: formatAbsoluteDateTime(timestamp),+ };+}++/**+ * The second row's parts, from values a surface has already resolved. Lists+ * that hold different session shapes (the Code sidebar's `TaskData`, a space's+ * channel item) share the order this way rather than each deciding it.+ */+export function listItemMetadataSegments(+ values: Partial<+ Record<ListItemMetadataField, ListItemMetadataValue | string | null>+ >,+ fields: readonly ListItemMetadataField[],+): ListItemMetadataSegment[] {+ const segments: ListItemMetadataSegment[] = [];+ for (const field of fields) {+ const value = values[field];+ if (!value) continue;+ const { text, title } =+ typeof value === "string" ? { text: value, title: undefined } : value;+ if (!text.trim()) continue;+ segments.push({ field, text: text.trim(), title });+ }+ return segments;+}++export function taskMetadataSegments(+ task: Pick<+ TaskData,+ "repository" | "branchName" | "linkedBranch" | "lastActivityAt"+ >,+ creatorName: string | undefined,+ fields: readonly ListItemMetadataField[],+): ListItemMetadataSegment[] {+ return listItemMetadataSegments(+ {+ repository: repositoryLabel(task.repository),+ branch: task.linkedBranch ?? task.branchName,+ creator: creatorName,+ activity: activityValue(task.lastActivityAt),+ },+ fields,+ );+}diff --git a/products/desktop/packages/ui/src/features/sidebar/sidebarStore.test.ts b/products/desktop/packages/ui/src/features/sidebar/sidebarStore.test.tsindex fd243b661709..4c90a926174b 100644--- a/products/desktop/packages/ui/src/features/sidebar/sidebarStore.test.ts+++ b/products/desktop/packages/ui/src/features/sidebar/sidebarStore.test.ts@@ -4,7 +4,11 @@ import { useSidebarStore } from "./sidebarStore";describe("sidebarStore navItemOverrides", () => {beforeEach(() => {- useSidebarStore.setState({ navItemOverrides: {}, navItemOrder: [] });+ useSidebarStore.setState({+ navItemOverrides: {},+ navItemOrder: [],+ listItemMetadataFields: [],+ });});it.each(@@ -102,6 +106,26 @@ describe("sidebarStore navItemOverrides", () => {localStorage.removeItem("sidebar-storage");});+ it("rehydration sanitizes list item metadata fields", async () => {+ localStorage.setItem(+ "sidebar-storage",+ JSON.stringify({+ state: {+ listItemMetadataFields: ["creator", "unknown", "branch", "creator"],+ },+ version: 0,+ }),+ );++ await useSidebarStore.persist.rehydrate();++ expect(useSidebarStore.getState().listItemMetadataFields).toEqual([+ "creator",+ "branch",+ ]);+ localStorage.removeItem("sidebar-storage");+ });+it("rehydration drops unknown ids and non-boolean values", 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.tsindex 2067513dd4a3..16d0d5421c6b 100644--- a/products/desktop/packages/ui/src/features/sidebar/sidebarStore.ts+++ b/products/desktop/packages/ui/src/features/sidebar/sidebarStore.ts@@ -9,6 +9,10 @@ import {sanitizeNavItemOrder,sanitizeNavItemOverrides,} from "./constants";+import {+ type ListItemMetadataField,+ sanitizeListItemMetadataFields,+} from "./listItemAppearance";interface SidebarStoreState {open: boolean;@@ -20,6 +24,7 @@ interface SidebarStoreState {historyVisibleCount: number;organizeMode: "by-project" | "chronological";sortMode: "updated" | "created";+ listItemMetadataFields: ListItemMetadataField[];showAllUsers: boolean;showInternal: boolean;taskTypeFilter: WorkspaceMode[];@@ -50,6 +55,7 @@ interface SidebarStoreActions {resetHistoryVisibleCount: () => void;setOrganizeMode: (mode: SidebarStoreState["organizeMode"]) => void;setSortMode: (mode: SidebarStoreState["sortMode"]) => void;+ setListItemMetadataFields: (fields: ListItemMetadataField[]) => void;setShowAllUsers: (showAllUsers: boolean) => void;setShowInternal: (showInternal: boolean) => void;toggleTaskType: (mode: WorkspaceMode) => void;@@ -72,6 +78,7 @@ export const useSidebarStore = create<SidebarStore>()(historyVisibleCount: 25,organizeMode: "by-project",sortMode: "updated",+ listItemMetadataFields: [],showAllUsers: false,showInternal: false,taskTypeFilter: [...ALL_WORKSPACE_MODES],@@ -126,6 +133,8 @@ export const useSidebarStore = create<SidebarStore>()(resetHistoryVisibleCount: () => set({ historyVisibleCount: 25 }),setOrganizeMode: (organizeMode) => set({ organizeMode }),setSortMode: (sortMode) => set({ sortMode }),+ setListItemMetadataFields: (listItemMetadataFields) =>+ set({ listItemMetadataFields }),setShowAllUsers: (showAllUsers) => set({ showAllUsers }),setShowInternal: (showInternal) => set({ showInternal }),toggleTaskType: (mode) =>@@ -152,6 +161,7 @@ export const useSidebarStore = create<SidebarStore>()(historyVisibleCount: state.historyVisibleCount,organizeMode: state.organizeMode,sortMode: state.sortMode,+ listItemMetadataFields: state.listItemMetadataFields,showAllUsers: state.showAllUsers,showInternal: state.showInternal,taskTypeFilter: state.taskTypeFilter,@@ -169,6 +179,7 @@ export const useSidebarStore = create<SidebarStore>()(historyVisibleCount?: number;organizeMode?: SidebarStoreState["organizeMode"];sortMode?: SidebarStoreState["sortMode"];+ listItemMetadataFields?: unknown;showAllUsers?: boolean;showInternal?: boolean;taskTypeFilter?: WorkspaceMode[];@@ -191,6 +202,9 @@ export const useSidebarStore = create<SidebarStore>()(persistedState.historyVisibleCount ?? current.historyVisibleCount,organizeMode: persistedState.organizeMode ?? current.organizeMode,sortMode: persistedState.sortMode ?? current.sortMode,+ listItemMetadataFields: sanitizeListItemMetadataFields(+ persistedState.listItemMetadataFields,+ ),showAllUsers: persistedState.showAllUsers ?? current.showAllUsers,showInternal: persistedState.showInternal ?? current.showInternal,taskTypeFilter:diff --git a/products/desktop/packages/ui/src/primitives/CopyButton.tsx b/products/desktop/packages/ui/src/primitives/CopyButton.tsxindex a4da8ac0b264..67779feb0b6a 100644--- a/products/desktop/packages/ui/src/primitives/CopyButton.tsx+++ b/products/desktop/packages/ui/src/primitives/CopyButton.tsx@@ -1,30 +1,57 @@import { CheckIcon, CopyIcon } from "@phosphor-icons/react";-import { useState } from "react";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@posthog/quill";+import { useEffect, useRef, useState } from "react";+/** How long either confirmation stays up before the button goes back. */+const COPIED_MS = 1500;++/**+ * Copy-to-clipboard button with a transient confirmation. Icon-only by default;+ * `bare` drops the border/background so it can nest inside another pill or a+ * line of text.+ *+ * `confirm` answers one question: does the button have room to say it worked? A+ * bordered button with a label swaps its glyph for a check. A 12px glyph at the+ * end of a truncated line has nowhere to put that, so the word goes above it.+ */export function CopyButton({text,label = "Copy",showLabel = false,bare = false,+ confirm = "icon",}: {text: string;label?: string;showLabel?: boolean;bare?: boolean;+ confirm?: "icon" | "tooltip";}) {const [copied, setCopied] = useState(false);+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);+ useEffect(+ () => () => (timer.current ? clearTimeout(timer.current) : undefined),+ [],+ );- async function copy(): Promise<void> {+ async function copy() {try {await navigator.clipboard.writeText(text);setCopied(true);- setTimeout(() => setCopied(false), 1500);+ if (timer.current) clearTimeout(timer.current);+ timer.current = setTimeout(() => setCopied(false), COPIED_MS);} catch {- // Clipboard access can be blocked while the text remains selectable.+ // Clipboard can be blocked (insecure context) — the text stays selectable.}}- return (+ const showCheck = copied && confirm === "icon";+ const button = (<buttontype="button"onClick={copy}@@ -35,12 +62,37 @@ export function CopyButton({: "inline-flex shrink-0 cursor-pointer items-center gap-1 rounded-(--radius-1) border border-border bg-(--color-panel-solid) px-1.5 py-0.5 text-[11px] text-gray-11 transition-colors hover:bg-(--gray-3) hover:text-gray-12"}>- {copied ? (+ {showCheck ? (<CheckIcon size={12} className="text-(--green-11)" />) : (<CopyIcon size={12} />)}- {showLabel ? (copied ? "Copied" : label) : null}+ {showLabel ? (showCheck ? "Copied" : label) : null}</button>);++ return (+ <span className="relative inline-flex">+ {/* Its own element rather than the tooltip held open. Base UI closes a+ tooltip on click, so it never showed the confirmation; holding it open+ with state instead left it stuck open on its resting label once the+ pointer had gone. */}+ {copied && confirm === "tooltip" ? (+ <output className="-translate-x-1/2 pointer-events-none absolute bottom-full left-1/2 z-10 mb-1 select-none whitespace-nowrap rounded-(--radius-2) bg-(--gray-12) px-2 py-1 text-(--gray-1) text-xs shadow-md">+ Copied!+ </output>+ ) : null}+ <TooltipProvider delay={200}>+ <Tooltip disableHoverablePopup>+ <TooltipTrigger render={button} />+ <TooltipContent+ side="top"+ className="pointer-events-none select-none"+ >+ {label}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </span>+ );}diff --git a/products/desktop/packages/ui/src/primitives/FactList.tsx b/products/desktop/packages/ui/src/primitives/FactList.tsxnew file mode 100644index 000000000000..40a38f9c1ba1--- /dev/null+++ b/products/desktop/packages/ui/src/primitives/FactList.tsx@@ -0,0 +1,22 @@+import type { ReactNode } from "react";++/**+ * A label column and a value column, so a reader scanning several of these+ * finds each fact in the same place every time. Children are label/value pairs+ * in source order.+ *+ * `max-content` on the label column: `auto` leaves a gutter the widest label+ * doesn't fill, which reads as two columns that failed to line up.+ */+export function FactList({ children }: { children: ReactNode }) {+ return (+ <div className="grid grid-cols-[max-content_minmax(0,1fr)] items-center gap-x-3 gap-y-px text-gray-12 text-xs">+ {children}+ </div>+ );+}++/** A fact's name, a step lighter than its value so the eye lands on answers. */+export function FactLabel({ children }: { children: ReactNode }) {+ return <span className="text-gray-10">{children}</span>;+}