: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): merge command menu search into one ranked list (#96153)
Shy Alterf8498ba8ae7f
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex e7d86314ec1b..3a1d05659e59 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -71,6 +71,7 @@ import type {TaskRun,TaskRunArtefact,TaskRunArtifact,+ TaskSearchResultRun,TaskThreadMessage,UserBasic,} from "@posthog/shared/domain-types";@@ -322,12 +323,16 @@ export interface TaskListOptions {export interface TaskSearchResult {id: string;- kind: "task" | "pull_request" | "artifact" | "channel";+ kind: "task" | "pull_request" | "artifact" | "channel" | "canvas";title: string;subtitle: string;task_id: string | null;task_run_id: string | null;channel_id: string | null;+ created_by?: UserBasic | null;+ origin_product?: string | null;+ latest_run?: TaskSearchResultRun | null;+ updated_at: string;metadata: Record<string, unknown>;}diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.tsindex bfe707d1b268..9ee32cb24ed4 100644--- a/products/desktop/packages/shared/src/analytics-events.ts+++ b/products/desktop/packages/shared/src/analytics-events.ts@@ -57,6 +57,7 @@ export type CommandMenuAction =| "open-task"| "open-task-from-pull-request"| "open-artifact"+ | "open-canvas"| "open-channel"| "open-command-center"| "save-feed"diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.tsindex 9dd0175299f5..ca11bda4b803 100644--- a/products/desktop/packages/shared/src/domain-types.ts+++ b/products/desktop/packages/shared/src/domain-types.ts@@ -102,15 +102,26 @@ export interface Task {export interface TaskSearchResult {id: string;- kind: "task" | "pull_request" | "artifact" | "channel";+ kind: "task" | "pull_request" | "artifact" | "channel" | "canvas";title: string;subtitle: string;task_id: string | null;task_run_id: string | null;channel_id: string | null;+ created_by?: UserBasic | null;+ /** What created the containing task, e.g. "slack". */+ origin_product?: string | null;+ latest_run?: TaskSearchResultRun | null;+ updated_at: string;metadata: Record<string, unknown>;}+export interface TaskSearchResultRun {+ id: string;+ status: TaskRunStatus | null;+ environment: TaskRunEnvironment | null;+}+/*** A backend task channel — the single channel identity: it owns the task feed,* threads, instructions (CONTEXT.md) and filed canvases. `personal` is thediff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.tsindex 90d4978117e8..4da7c4a01237 100644--- a/products/desktop/packages/shared/src/index.ts+++ b/products/desktop/packages/shared/src/index.ts@@ -349,6 +349,7 @@ export {getLocalDayKey,getRelativeDateGroup,} from "./time";+export { singleLineTitle } from "./title-text";export {mcpToolKey,parseMcpToolName,diff --git a/products/desktop/packages/shared/src/title-text.test.ts b/products/desktop/packages/shared/src/title-text.test.tsnew file mode 100644index 000000000000..0796f048e162--- /dev/null+++ b/products/desktop/packages/shared/src/title-text.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from "vitest";+import { singleLineTitle } from "./title-text";++describe("singleLineTitle", () => {+ it.each([+ [+ "why did <https://example.com/runs/1?a=b|this run> fail?",+ "why did this run fail?",+ ],+ ["see <https://example.com/runs/1>", "see https://example.com/runs/1"],+ ["read [the report](https://example.com/r.md)", "read the report"],+ [+ 'why is it stuck? ```{\n "id": "1"\n}```',+ 'why is it stuck? { "id": "1" }',+ ],+ ["fix `useSearchRows`\n\nsecond line", "fix useSearchRows second line"],+ [" spaced out ", "spaced out"],+ ])("reads %j as one line", (raw, expected) => {+ expect(singleLineTitle(raw)).toBe(expected);+ });+});diff --git a/products/desktop/packages/shared/src/title-text.ts b/products/desktop/packages/shared/src/title-text.tsnew file mode 100644index 000000000000..59a8f23adee1--- /dev/null+++ b/products/desktop/packages/shared/src/title-text.ts@@ -0,0 +1,17 @@+const MARKDOWN_LINK = /\[([^\]]+)\]\(\s*(?:https?:\/\/)?[^)\s]*\s*\)/g;+const LABELED_LINK = /<(?:https?:\/\/[^>|\s]+)\|([^>]*)>/g;+const BARE_LINK = /<(https?:\/\/[^>\s]+)>/g;+const CODE_FENCE = /```+/g;+const BACKTICK = /`/g;+const WHITESPACE = /\s+/g;++export function singleLineTitle(title: string): string {+ return title+ .replace(MARKDOWN_LINK, "$1")+ .replace(LABELED_LINK, "$1")+ .replace(BARE_LINK, "$1")+ .replace(CODE_FENCE, " ")+ .replace(BACKTICK, "")+ .replace(WHITESPACE, " ")+ .trim();+}diff --git a/products/desktop/packages/ui/src/features/command/CommandKeyHints.tsx b/products/desktop/packages/ui/src/features/command/CommandKeyHints.tsxindex 07a90645234a..c5fc0f0d8ebe 100644--- a/products/desktop/packages/ui/src/features/command/CommandKeyHints.tsx+++ b/products/desktop/packages/ui/src/features/command/CommandKeyHints.tsx@@ -1,7 +1,15 @@import { Kbd, KbdGroup } from "@posthog/quill";+import { formatHotkeyParts } from "@posthog/ui/features/command/keyboard-shortcuts";import type { ReactNode } from "react";-export function CommandKeyHints({ children }: { children?: ReactNode }) {+export function CommandKeyHints({+ newTabHint = false,+ children,+}: {+ /** Whether the highlighted row has a place of its own to open. */+ newTabHint?: boolean;+ children?: ReactNode;+}) {return (<div className="flex items-center justify-center gap-4 border-border border-t py-1"><div className="flex items-center gap-2">@@ -17,6 +25,14 @@ export function CommandKeyHints({ children }: { children?: ReactNode }) {</KbdGroup><span className="text-xs">select</span></div>+ {newTabHint && (+ <div className="flex items-center gap-2">+ <KbdGroup>+ <Kbd>{formatHotkeyParts("mod+enter").join("")}</Kbd>+ </KbdGroup>+ <span className="text-xs">new tab</span>+ </div>+ )}<div className="flex items-center gap-2"><KbdGroup><Kbd>Esc</Kbd>diff --git a/products/desktop/packages/ui/src/features/command/CommandMenu.createChannel.test.tsx b/products/desktop/packages/ui/src/features/command/CommandMenu.createChannel.test.tsxindex 3e8e7d43f995..710bea2f896c 100644--- a/products/desktop/packages/ui/src/features/command/CommandMenu.createChannel.test.tsx+++ b/products/desktop/packages/ui/src/features/command/CommandMenu.createChannel.test.tsx@@ -2,6 +2,9 @@ import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { describe, expect, it, vi } from "vitest";+vi.mock("@posthog/ui/features/browser-tabs/useOpenBrowserTab", () => ({+ useOpenBrowserTab: () => vi.fn(),+}));vi.mock("@posthog/ui/shell/analytics", () => ({ track: vi.fn() }));vi.mock("@posthog/ui/features/auth/authClient", () => ({useOptionalAuthenticatedClient: () => null,diff --git a/products/desktop/packages/ui/src/features/command/CommandMenu.feedQuery.test.tsx b/products/desktop/packages/ui/src/features/command/CommandMenu.feedQuery.test.tsxindex 76613919ffa2..44216aaf826e 100644--- a/products/desktop/packages/ui/src/features/command/CommandMenu.feedQuery.test.tsx+++ b/products/desktop/packages/ui/src/features/command/CommandMenu.feedQuery.test.tsx@@ -7,6 +7,9 @@ let taskResultsComplete = true;// The palette pulls half the app in; everything irrelevant to the feed-query// mode is stubbed to its empty state.+vi.mock("@posthog/ui/features/browser-tabs/useOpenBrowserTab", () => ({+ useOpenBrowserTab: () => vi.fn(),+}));vi.mock("@posthog/ui/shell/analytics", () => ({ track: vi.fn() }));vi.mock("@posthog/ui/features/auth/authClient", () => ({useOptionalAuthenticatedClient: () => null,diff --git a/products/desktop/packages/ui/src/features/command/CommandMenu.search.test.tsx b/products/desktop/packages/ui/src/features/command/CommandMenu.search.test.tsxnew file mode 100644index 000000000000..b2d014478128--- /dev/null+++ b/products/desktop/packages/ui/src/features/command/CommandMenu.search.test.tsx@@ -0,0 +1,136 @@+import type { TaskSearchResult } from "@posthog/shared/domain-types";+import { Theme } from "@radix-ui/themes";+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";++vi.mock("@posthog/ui/features/browser-tabs/useOpenBrowserTab", () => ({+ useOpenBrowserTab: () => vi.fn(),+}));+vi.mock("@posthog/ui/shell/analytics", () => ({ track: vi.fn() }));+vi.mock("@posthog/ui/features/auth/authClient", () => ({+ useOptionalAuthenticatedClient: () => null,+}));+vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({+ useCurrentUser: () => ({ data: { uuid: "user-1" } }),+}));+vi.mock("@posthog/di/container", () => ({+ resolveService: () => ({}),+ resolveServiceOptional: () => null,+}));+vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({+ useFeatureFlag: () => false,+}));+vi.mock("@posthog/ui/features/archive/useArchivedTaskIds", () => ({+ useArchivedTaskIds: () => new Set(),+}));+vi.mock("@posthog/ui/features/archive/useTaskArchive", () => ({+ useTaskArchive: () => ({+ requestArchive: vi.fn(),+ isArchiving: false,+ dialog: null,+ }),+}));+vi.mock("@posthog/ui/features/workspace/useWorkspace", () => ({+ useWorkspaces: () => ({ data: [], isFetched: false }),+}));+vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({+ useChannels: () => ({ channels: [], isLoading: false }),+}));+vi.mock("@posthog/ui/features/canvas/hooks/useChannelsLayout", () => ({+ useChannelsLayout: () => false,+}));+vi.mock("@posthog/ui/features/canvas/hooks/useTaskFeedResults", () => ({+ useTaskFeedResults: () => ({+ tasks: [],+ isComplete: true,+ isLoading: false,+ issues: [],+ }),+ useFeedQueryPlan: () => ({ plan: undefined, isLoading: false }),+}));+vi.mock("@posthog/ui/features/folders/useFolders", () => ({+ useFolders: () => ({ folders: [] }),+}));+vi.mock("@posthog/ui/router/useAppView", () => ({+ useAppView: () => ({ type: "home" }),+}));+vi.mock("@posthog/ui/features/canvas/hooks/useOrgMembers", () => ({+ useOrgMembers: () => ({+ members: [],+ isLoading: false,+ isError: false,+ isComplete: true,+ }),+}));+vi.mock("@posthog/ui/features/sidebar/useTaskPrStatus", () => ({+ useTaskPrStatus: () => ({ prState: null, hasDiff: false, prUrl: null }),+}));+vi.mock("@posthog/ui/features/canvas/hooks/useTaskChannelMap", () => ({+ useTaskChannelMap: () => new Map(),+}));+vi.mock("@posthog/ui/features/command/useFileSearchContext", () => ({+ useFileSearchContext: () => ({ repoPath: null }),+}));++vi.mock("@posthog/ui/features/tasks/useTasks", () => ({+ useTasks: () => ({+ data: [{ id: "task-a", title: "Run analytics queries", channel: null }],+ }),+}));++const searchResults: TaskSearchResult[] = [+ {+ id: "doc-task",+ kind: "task",+ title: "Run analytics queries",+ subtitle: "",+ task_id: "task-a",+ task_run_id: null,+ channel_id: null,+ updated_at: "2026-09-01T10:00:00Z",+ metadata: {},+ },+ {+ id: "doc-file",+ kind: "artifact",+ title: "run-log.jsonl",+ subtitle: "Nightly import check",+ task_id: "task-b",+ task_run_id: null,+ channel_id: null,+ updated_at: "2026-09-01T09:00:00Z",+ metadata: {},+ },+];+vi.mock("@posthog/ui/features/command/useTaskSearch", () => ({+ useTaskSearch: (query: string) => ({+ data: query ? searchResults : [],+ }),+}));++import { CommandMenu } from "./CommandMenu";++describe("CommandMenu global search", () => {+ it("lists a matching task above the files, without repeating it below", async () => {+ const user = userEvent.setup();+ render(+ <Theme>+ <CommandMenu open onOpenChange={() => {}} />+ </Theme>,+ );++ await user.type(+ screen.getByPlaceholderText(/Search commands and tasks/),+ "run",+ );++ await screen.findByText("run-log.jsonl");+ const rows = Array.from(document.querySelectorAll("[role='option']")).map(+ (row) => row.textContent,+ );+ expect(rows[0]).toContain("Run analytics queries");+ expect(rows[1]).toContain("run-log.jsonl");+ expect(screen.queryByText("Tasks")).toBeNull();+ });+});diff --git a/products/desktop/packages/ui/src/features/command/CommandMenu.tsx b/products/desktop/packages/ui/src/features/command/CommandMenu.tsxindex abcea73e5b7d..ce194ee37464 100644--- a/products/desktop/packages/ui/src/features/command/CommandMenu.tsx+++ b/products/desktop/packages/ui/src/features/command/CommandMenu.tsx@@ -21,6 +21,7 @@ import {SquaresFourIcon,SunIcon,} from "@phosphor-icons/react";+import { channelDisplayLabel } from "@posthog/core/canvas/channelName";import { workspaceIdSet } from "@posthog/core/command-center/eligibility";import { resolveService } from "@posthog/di/container";import {@@ -42,13 +43,18 @@ import {Kbd,KbdGroup,} from "@posthog/quill";-import { LOOPS_FLAG, PROJECT_BLUEBIRD_FLAG } from "@posthog/shared";+import {+ LOOPS_FLAG,+ PROJECT_BLUEBIRD_FLAG,+ singleLineTitle,+} from "@posthog/shared";import {ANALYTICS_EVENTS,type CommandMenuAction,} from "@posthog/shared/analytics-events";import { useArchivedTaskIds } from "@posthog/ui/features/archive/useArchivedTaskIds";import { useTaskArchive } from "@posthog/ui/features/archive/useTaskArchive";+import { useOpenBrowserTab } from "@posthog/ui/features/browser-tabs/useOpenBrowserTab";import { channelGlyph } from "@posthog/ui/features/canvas/components/channelGlyph";import {EDITOR_TEXT_CLASS,@@ -60,6 +66,20 @@ import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsimport { getDefaultReviewMode } from "@posthog/ui/features/code-review/getDefaultReviewMode";import { useReviewNavigationStore } from "@posthog/ui/features/code-review/reviewNavigationStore";import { CommandKeyHints } from "@posthog/ui/features/command/CommandKeyHints";+import type {+ Command,+ CommandSection,+} from "@posthog/ui/features/command/commandRow";+import {+ channelRowParts,+ taskRowParts,+ taskRowRecency,+} from "@posthog/ui/features/command/commandRowFacts";+import {+ channelHref,+ taskHref,+} from "@posthog/ui/features/command/commandRowHref";+import { commandRowMeta } from "@posthog/ui/features/command/commandRowMeta";import {addRecentCommand,matchesCommandSearch,@@ -71,7 +91,10 @@ import {SHORTCUTS,} from "@posthog/ui/features/command/keyboard-shortcuts";import { PaletteFilterChips } from "@posthog/ui/features/command/PaletteFilterChips";-import { sessionSubtitle } from "@posthog/ui/features/command/sessionSubtitle";+import {+ type ResultRow,+ rankResultRows,+} from "@posthog/ui/features/command/rankResultRows";import { TaskCommandIcon } from "@posthog/ui/features/command/TaskCommandIcon";import { taskSearchDelay } from "@posthog/ui/features/command/taskSearchQuery";import {@@ -79,11 +102,7 @@ import {useFeedQueryCommands,} from "@posthog/ui/features/command/useFeedQueryCommands";import { useFileSearchContext } from "@posthog/ui/features/command/useFileSearchContext";-import {- type Command,- type CommandSection,- useSearchSections,-} from "@posthog/ui/features/command/useSearchSections";+import { useSearchRows } from "@posthog/ui/features/command/useSearchRows";import { useTaskSearch } from "@posthog/ui/features/command/useTaskSearch";import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";import { useInboxAvailable } from "@posthog/ui/features/feature-flags/useInboxAvailable";@@ -137,6 +156,13 @@ const CreateChannelModalLazy = lazy(() =>);const DEFAULT_RESULT_LIMIT = 8;++/** The palette hands the highlighted row itself, not its value. */+function highlightedCommandId(value: unknown): string | null {+ if (typeof value === "string") return value;+ const id = (value as { id?: unknown } | null)?.id;+ return typeof id === "string" ? id : null;+}const COLLAPSED_CHIP_COUNT = 5;function PaletteQueryMirror({@@ -232,6 +258,7 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {const loopsEnabled = useFeatureFlag(LOOPS_FLAG);const inboxAvailable = useInboxAvailable();const { channels } = useChannels({ enabled: bluebirdEnabled });+ const openBrowserTab = useOpenBrowserTab();const { theme, setTheme } = useThemeStore();const toggleLeftSidebar = useSidebarStore((state) => state.toggle);const view = useAppView();@@ -668,7 +695,7 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {spacesLayout,]);- const taskSections = useMemo<CommandSection[]>(() => {+ const taskRows = useMemo<ResultRow[]>(() => {const workspaceIds = workspaceIdSet(workspaces);const visibleTasks = tasks.filter((task) =>@@ -681,47 +708,39 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {const channelsById = new Map(channels.map((channel) => [channel.id, channel] as const),);- return [- {- label: "Tasks",- items: visibleTasks.map((task) => {- const channel = task.channel- ? channelsById.get(task.channel)- : undefined;- return {- id: `task-${task.id}`,- label: task.title,- // Under the spaces layout a session wears the same row everywhere:- // status dot, title, and a second line saying where it lives. The- // legacy layout keeps the trailing `#channel`.- detail: spacesLayout ? undefined : channel?.name,- subtitle: spacesLayout- ? sessionSubtitle({- space: channel?.name,- repository: task.repository,- createdAt: task.created_at,- })- : undefined,- // Include the channel name so searching it surfaces filed tasks.- keywords: channel?.name,- icon: <TaskCommandIcon task={task} />,- action: "open-task" as CommandMenuAction,- channelId: bluebirdEnabled ? channel?.id : undefined,- onRun: () => {- closeSettingsDialog();- // Bluebird: a task filed to a channel opens in the channel-- // organized view under /website, keeping the channels chrome.- // Otherwise fall back to the /code task detail.- const channelTarget =- bluebirdEnabled && channel- ? { channelId: channel.id }- : undefined;- void openTask(task, channelTarget);- },- };- }),- },- ];+ return visibleTasks.map((task) => {+ const channel = task.channel ? channelsById.get(task.channel) : undefined;+ return {+ kind: "task" as const,+ recency: taskRowRecency(task),+ command: {+ id: `task-${task.id}`,+ label: singleLineTitle(task.title),+ subtitle: commandRowMeta(taskRowParts(task)),+ detail: channel+ ? channelDisplayLabel(channel.name, channel.channelType)+ : undefined,+ detailPrefix: "",+ // Include the channel name so searching it surfaces filed tasks.+ keywords: channel?.name,+ icon: <TaskCommandIcon task={task} />,+ action: "open-task" as CommandMenuAction,+ channelId: bluebirdEnabled ? channel?.id : undefined,+ href: taskHref(task, bluebirdEnabled ? channel?.id : undefined),+ onRun: () => {+ closeSettingsDialog();+ // Bluebird: a task filed to a channel opens in the channel-+ // organized view under /website, keeping the channels chrome.+ // Otherwise fall back to the /code task detail.+ const channelTarget =+ bluebirdEnabled && channel+ ? { channelId: channel.id }+ : undefined;+ void openTask(task, channelTarget);+ },+ },+ };+ });}, [tasks,archivedTaskIds,@@ -730,45 +749,64 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {provisioningTaskIds,channels,bluebirdEnabled,- spacesLayout,closeSettingsDialog,]);- const channelSections = useMemo<CommandSection[]>(() => {- if (channels.length === 0) return [];- return [- {- label: spacesLayout ? "Spaces" : "Channels",- items: channels.map((channel) => ({+ const taskSections = useMemo<CommandSection[]>(+ () =>+ taskRows.length > 0+ ? [{ label: "Tasks", items: taskRows.map((row) => row.command) }]+ : [],+ [taskRows],+ );++ const channelRows = useMemo<ResultRow[]>(+ () =>+ channels.map((channel) => ({+ kind: "channel" as const,+ command: {id: `channel-${channel.id}`,label: channel.name,+ subtitle: commandRowMeta(channelRowParts(channel)),keywords: "space channel",icon: channelGlyph(channel.name, {personal: channel.channelType === "personal",private: channel.channelType === "private",size: 12,- space: spacesLayout,className: "text-muted-foreground",}),action: "open-channel" as CommandMenuAction,channelId: channel.id,+ href: channelHref(channel.id),onRun: () => {closeSettingsDialog();navigateToChannel(channel.id);},- })),- },- ];- }, [channels, closeSettingsDialog, spacesLayout]);+ },+ })),+ [channels, closeSettingsDialog],+ );- const searchSections = useSearchSections({+ const channelSections = useMemo<CommandSection[]>(+ () =>+ channelRows.length > 0+ ? [+ {+ label: spacesLayout ? "Spaces" : "Channels",+ items: channelRows.map((row) => row.command),+ },+ ]+ : [],+ [channelRows, spacesLayout],+ );++ const searchRows = useSearchRows({remoteQuery,searchResults,tasks,taskSections,channels,bluebirdEnabled,- spacesLayout,});const [feedModalQuery, setFeedModalQuery] = useState<string | null>(null);@@ -834,25 +872,56 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {remoteSearchAllowedRef.current = browsing && !scope;}, [mode, scope]);+ const resultSections = useMemo<CommandSection[]>(() => {+ if (!searchText.trim()) return [];+ const matches = rankResultRows(+ [...searchRows, ...taskRows, ...channelRows],+ searchText,+ ).filter((command) => matchesCommandSearch(command, searchText));+ if (matches.length === 0) return [];+ const items = matches.slice(0, resultLimit);+ const hidden = matches.length - items.length;+ if (hidden > 0) {+ items.push({+ id: "results-show-all",+ label: `Show ${hidden} more`,+ keywords: searchText,+ icon: <MagnifyingGlassIcon className="h-3 w-3 text-gray-11" />,+ action: "show-all-matches",+ keepOpen: true,+ onRun: showAllMatches,+ });+ }+ return [{ label: "", items }];+ }, [+ searchRows,+ taskRows,+ channelRows,+ searchText,+ resultLimit,+ showAllMatches,+ ]);+const baseSections = useMemo(() => {const browsing = mode === "browsing" || mode === "completingKey";+ const searching = browsing && !scope && searchText.trim().length > 0;const showCommands = browsing && (!scope || scope === "command");- const showChannels = browsing && (!scope || scope === "space");- const showPlainTasks = browsing && !scope;- const showRemoteSearch = browsing && !scope;- return prioritizeExactCommandMatches(- [- ...feedQuery.sections,- ...(showRemoteSearch ? searchSections : []),- ...(showCommands ? commandSections : []),- ...(showChannels ? channelSections : []),- ...(showPlainTasks ? taskSections : []),- ],- searchText,- );+ const showChannels =+ browsing && !searching && (!scope || scope === "space");+ const showPlainTasks = browsing && !searching && !scope;+ return [+ ...feedQuery.sections,+ ...(searching ? resultSections : []),+ ...prioritizeExactCommandMatches(+ showCommands ? commandSections : [],+ searchText,+ ),+ ...(showChannels ? channelSections : []),+ ...(showPlainTasks ? taskSections : []),+ ];}, [feedQuery.sections,- searchSections,+ resultSections,commandSections,channelSections,taskSections,@@ -895,12 +964,31 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {);const highlightedId = useRef<string | null>(null);+ // Any row with a place of its own can open in a tab, so the footer says so+ // once rather than following the highlight, which re-renders on every move.+ const anyRowOpensInTab = useMemo(+ () => allCommands.some((command) => command.href),+ [allCommands],+ );const showMatchSummary = mode === "querying" || matchCount != null;- const handleSelect = (id: string | null): void => {+ const openInNewTab = (cmd: Command): boolean => {+ if (!cmd.href) return false;+ track(ANALYTICS_EVENTS.COMMAND_MENU_ACTION, {+ action_type: cmd.action,+ channel_id: cmd.channelId,+ });+ openBrowserTab(cmd.href);+ onOpenChange(false);+ setQuery("");+ return true;+ };++ const handleSelect = (id: string | null, newTab = false): void => {if (id === null) return;const cmd = allCommands.find((c) => c.id === id);if (!cmd) return;+ if (newTab && openInNewTab(cmd)) return;track(ANALYTICS_EVENTS.COMMAND_MENU_ACTION, {action_type: cmd.action,channel_id: cmd.channelId,@@ -915,6 +1003,16 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {};const onInputKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {+ const highlighted = allCommands.find(+ (command) => command.id === highlightedId.current,+ );+ if (highlighted?.href) {+ event.preventDefault();+ openInNewTab(highlighted);+ return;+ }+ }if (event.key.toLowerCase() === "s" &&(event.metaKey || event.ctrlKey) &&@@ -955,7 +1053,7 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {autoHighlightkeepHighlightonItemHighlighted={(value) => {- highlightedId.current = typeof value === "string" ? value : null;+ highlightedId.current = highlightedCommandId(value);}}onValueChange={(val, eventDetails) => {if (typeof val !== "string") return;@@ -1026,37 +1124,48 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {<AutocompleteList className="max-h-[60vh]">{(section: CommandSection) => (<AutocompleteGroup key={section.label} items={section.items}>- <AutocompleteLabel>{section.label}</AutocompleteLabel>+ {section.label && (+ <AutocompleteLabel>{section.label}</AutocompleteLabel>+ )}<AutocompleteCollection>{(cmd: Command) => (<AutocompleteItemkey={cmd.id}value={cmd.id}- onClick={() => handleSelect(cmd.id)}- className="group flex h-auto! min-h-7 w-full items-center gap-2 py-1.5 pr-2 text-left [&>span]:w-full [&>span]:overflow-visible"+ title={cmd.label}+ onClick={(event) =>+ handleSelect(cmd.id, event.metaKey || event.ctrlKey)+ }+ className="group flex h-auto! min-h-7 w-full items-center gap-2 py-1 pr-2 text-left leading-snug [&>span]:w-full [&>span]:overflow-visible">- {cmd.icon}- <span className="wrap-break-word min-w-0 whitespace-normal">- {cmd.label}+ <span className="flex size-4 shrink-0 items-center justify-center opacity-80 group-data-highlighted:opacity-100">+ {cmd.icon}+ </span>+ <span className="flex min-w-0 flex-1 flex-col">+ <span className="flex min-h-[18px] items-center gap-2">+ <span className="min-w-0 flex-1 truncate">+ {cmd.label}+ </span>+ {cmd.detail && (+ <span className="max-w-[40%] shrink-0 truncate text-[11px] text-muted-foreground">+ {cmd.detailPrefix ?? "#"}+ {cmd.detail}+ </span>+ )}+ {cmd.shortcut && (+ <span className="flex shrink-0 items-center gap-2">+ {formatHotkeyParts(cmd.shortcut).map((part) => (+ <Kbd key={part}>{part}</Kbd>+ ))}+ </span>+ )}+ </span>{cmd.subtitle && (- <span className="block truncate text-muted-foreground text-xs">+ <span className="truncate text-muted-foreground/70 text-xxs">{cmd.subtitle}</span>)}</span>- {cmd.detail && (- <span className="shrink-0 text-muted-foreground">- · {cmd.detailPrefix ?? "#"}- {cmd.detail}- </span>- )}- {cmd.shortcut && (- <span className="ml-auto flex shrink-0 items-center gap-2 pl-2">- {formatHotkeyParts(cmd.shortcut).map((part) => (- <Kbd key={part}>{part}</Kbd>- ))}- </span>- )}</AutocompleteItem>)}</AutocompleteCollection>@@ -1064,7 +1173,7 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {)}</AutocompleteList></Autocomplete>- <CommandKeyHints>+ <CommandKeyHints newTabHint={anyRowOpensInTab}>{hasFilterTokens && (<div className="flex items-center gap-2"><KbdGroup>diff --git a/products/desktop/packages/ui/src/features/command/PaletteFilterChips.tsx b/products/desktop/packages/ui/src/features/command/PaletteFilterChips.tsxindex a1df9a0e408d..ea4cd549d4fa 100644--- a/products/desktop/packages/ui/src/features/command/PaletteFilterChips.tsx+++ b/products/desktop/packages/ui/src/features/command/PaletteFilterChips.tsx@@ -1,4 +1,4 @@-import { cn } from "@posthog/quill";+import { Button, cn } from "@posthog/quill";import type { FeedQueryKeyChip } from "@posthog/ui/features/command/useFeedQueryCommands";import { useState } from "react";@@ -18,49 +18,40 @@ export function PaletteFilterChips({return (<divclassName={cn(- "flex gap-1.5 border-border border-b px-3 py-1.5",+ "flex gap-0.5 border-border border-b px-2.5 py-1",open ? "flex-wrap items-start" : "items-center",)}>- <span className="shrink-0 select-none py-1 text-[11px] text-subtle-foreground">+ <span className="shrink-0 select-none px-1 py-0.5 text-[11px] text-subtle-foreground">Filter by</span>{visible.map((chip) => (- <button+ <Buttonkey={chip.label}- type="button"- className={cn(- "flex h-[22px] shrink-0 items-center rounded-md border border-border bg-fill-hover px-2",- "text-[11.5px]",- "hover:bg-fill-selected",- "focus-visible:-outline-offset-1 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring",- )}+ size="xs"+ className="shrink-0 gap-1.5 font-normal"onMouseDown={(e) => e.preventDefault()}onClick={chip.apply}>- <span className="flex items-baseline gap-1.5 leading-none">- <span className="font-mono text-[11px] text-primary">- {chip.label}- </span>- {open && chip.hint && (- <span className="text-subtle-foreground">{chip.hint}</span>- )}+ <span className="font-mono text-[11px] text-muted-foreground">+ {chip.label}</span>- </button>+ {open && chip.hint && (+ <span className="text-[11px] text-subtle-foreground">+ {chip.hint}+ </span>+ )}+ </Button>))}{overflow > 0 && (- <button- type="button"- className={cn(- "h-[22px] shrink-0 rounded-md px-2 text-[11.5px] text-muted-foreground leading-none",- "hover:bg-fill-hover hover:text-foreground",- "focus-visible:-outline-offset-1 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring",- )}+ <Button+ size="xs"+ className="shrink-0 font-normal text-[11px] text-subtle-foreground"onMouseDown={(e) => e.preventDefault()}onClick={() => setExpanded((value) => !value)}>{expanded ? "Show fewer" : `${overflow} more`}- </button>+ </Button>)}</div>);diff --git a/products/desktop/packages/ui/src/features/command/TaskCommandIcon.tsx b/products/desktop/packages/ui/src/features/command/TaskCommandIcon.tsxindex 302743b911ea..ccb6ffa4fad8 100644--- a/products/desktop/packages/ui/src/features/command/TaskCommandIcon.tsx+++ b/products/desktop/packages/ui/src/features/command/TaskCommandIcon.tsx@@ -3,46 +3,19 @@ import {narrowFullTask,} from "@posthog/core/sidebar/buildSidebarData";import type { Task } from "@posthog/shared/domain-types";-import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";-import { useTaskStatusInput } from "@posthog/ui/features/canvas/hooks/useChannelTaskStatus";import { TaskIcon } from "@posthog/ui/features/sidebar/components/items/TaskIcon";-import { TaskDotMark } from "@posthog/ui/features/sidebar/components/items/TaskStatusDot";-import { taskDot } from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";import { useTaskPrStatus } from "@posthog/ui/features/sidebar/useTaskPrStatus";+import { SlackMark } from "@posthog/ui/primitives/SlackMark";/*** The leading mark on a session row in the command palette.*- * Under the spaces layout it is the space tree's status dot, so a session reads- * the same wherever it is listed. The legacy layout keeps the older combined- * icon, which is what the Code sidebar still shows beside it.+ * The palette answers one query with tasks, spaces, canvases, pull requests and+ * files in the same list, so each row keeps the mark its own surface uses: the+ * sidebar's run and PR status icon, and Slack's own mark for a session a person+ * started from Slack.*/export function TaskCommandIcon({ task }: { task: Task }) {- const spacesLayout = useChannelsLayout();- return spacesLayout ? (- <SessionDot task={task} />- ) : (- <TaskRunIcon task={task} />- );-}--/**- * Dot only, no tooltip: the palette is walked with the keyboard, and a popup- * that follows the highlight down the list is in the way of reading it.- *- * No PR lookup either — that is a host round trip per row, and an empty query- * lists a screenful of sessions.- */-function SessionDot({ task }: { task: Task }) {- const status = useTaskStatusInput(task, { withPrStatus: false });- return <TaskDotMark dot={taskDot(status ?? {})} />;-}--/**- * The same shared `TaskIcon` as the sidebar, including cloud run and PR/branch- * status, deriving its inputs from the raw task and a per-task PR-status query.- */-function TaskRunIcon({ task }: { task: Task }) {const { prState, hasDiff } = useTaskPrStatus({id: task.id,cloudPrUrl: null,@@ -55,6 +28,7 @@ function TaskRunIcon({ task }: { task: Task }) {)?.slack_thread_url;const slackThreadUrl =typeof stateSlackThreadUrl === "string" ? stateSlackThreadUrl : undefined;+ if (task.origin_product === "slack") return <SlackMark size={12} />;return (<TaskIconworkspaceMode={runState.taskRunEnvironment}diff --git a/products/desktop/packages/ui/src/features/command/commandRow.ts b/products/desktop/packages/ui/src/features/command/commandRow.tsnew file mode 100644index 000000000000..e2d4065cc2bc--- /dev/null+++ b/products/desktop/packages/ui/src/features/command/commandRow.ts@@ -0,0 +1,26 @@+import type { CommandMenuAction } from "@posthog/shared/analytics-events";+import type { ReactNode } from "react";++export type Command = {+ id: string;+ label: string;+ /** Muted trailing detail shown at the row's right edge, e.g. a task's space. */+ detail?: string;+ detailPrefix?: string;+ /** Muted second line under the label: what the task list says about a row. */+ subtitle?: ReactNode;+ keywords?: string;+ icon: ReactNode;+ action: CommandMenuAction;+ /** Channel in scope for the bluebird open-channel / open-task actions. */+ channelId?: string;+ /** Hotkey string (e.g. "mod+b") shown right-aligned when present. */+ shortcut?: string;+ /** Where this row lives, for a mod-click or mod+enter that opens a new tab. */+ href?: string;+ /** Running this keeps the palette open (e.g. completing a filter token). */+ keepOpen?: boolean;+ onRun: () => void;+};++export type CommandSection = { label: string; items: Command[] };diff --git a/products/desktop/packages/ui/src/features/command/commandRowFacts.ts b/products/desktop/packages/ui/src/features/command/commandRowFacts.tsnew file mode 100644index 000000000000..6a49ebd9775a--- /dev/null+++ b/products/desktop/packages/ui/src/features/command/commandRowFacts.ts@@ -0,0 +1,104 @@+import { channelDisplayLabel } from "@posthog/core/canvas/channelName";+import type { Task, TaskSearchResult } from "@posthog/shared/domain-types";+import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";+import type { CommandRowMetaPart } from "@posthog/ui/features/command/commandRowMeta";+import { getOriginProductMeta } from "@posthog/ui/features/sidebar/components/items/TaskIcon";+import { activityValue } from "@posthog/ui/features/sidebar/listItemAppearance";++function textPart(+ text: string | null | undefined,+): CommandRowMetaPart | undefined {+ return text?.trim() ? { text } : undefined;+}++function sourcePart(+ originProduct: string | null | undefined,+): CommandRowMetaPart | undefined {+ const meta = getOriginProductMeta(originProduct ?? undefined);+ return meta ? { text: meta.label } : undefined;+}++function activityPart(+ timestamp: number | undefined,+): CommandRowMetaPart | undefined {+ const value = activityValue(timestamp);+ return value ? { text: value.text, title: value.title } : undefined;+}++export function taskRowRecency(task: Task): number {+ return Date.parse(task.last_activity_at ?? task.updated_at);+}++export function taskRowParts(task: Task): (CommandRowMetaPart | undefined)[] {+ return [+ sourcePart(task.origin_product),+ textPart(task.repository),+ textPart(task.created_by ? userDisplayName(task.created_by) : undefined),+ activityPart(taskRowRecency(task)),+ ];+}++export function channelRowParts(channel: {+ repositories: string[];+ createdBy: { first_name?: string; last_name?: string; email?: string } | null;+}): (CommandRowMetaPart | undefined)[] {+ return [+ textPart(channel.repositories[0]),+ textPart(+ channel.createdBy ? userDisplayName(channel.createdBy) : undefined,+ ),+ ];+}++function metadataString(+ result: TaskSearchResult,+ key: string,+): string | undefined {+ const value = result.metadata[key];+ return typeof value === "string" && value ? value : undefined;+}++function searchResultLocation(+ result: TaskSearchResult,+ task: Task | undefined,+): string | undefined {+ if (result.kind === "pull_request") {+ return metadataString(result, "repository") ?? result.subtitle;+ }+ if (result.kind === "artifact") return result.subtitle;+ if (result.kind !== "task") return undefined;+ return task?.repository ?? result.subtitle;+}++export function searchResultRecency(+ result: TaskSearchResult,+ task: Task | undefined,+): number | undefined {+ const changed = task ? taskRowRecency(task) : Date.parse(result.updated_at);+ return Number.isNaN(changed) ? undefined : changed;+}++export function searchResultParts(+ result: TaskSearchResult,+ task: Task | undefined,+): (CommandRowMetaPart | undefined)[] {+ const author = task?.created_by ?? result.created_by;+ const source =+ result.kind === "task"+ ? sourcePart(task?.origin_product ?? result.origin_product)+ : undefined;+ return [+ source,+ textPart(searchResultLocation(result, task)),+ textPart(author ? userDisplayName(author) : undefined),+ activityPart(searchResultRecency(result, task)),+ ];+}++export function searchResultDetail(+ result: TaskSearchResult,+ channelName: string | undefined,+): string | undefined {+ if (result.kind === "channel") return undefined;+ return channelName ? channelDisplayLabel(channelName) : undefined;+}diff --git a/products/desktop/packages/ui/src/features/command/commandRowHref.ts b/products/desktop/packages/ui/src/features/command/commandRowHref.tsnew file mode 100644index 000000000000..bb5b22cc974c--- /dev/null+++ b/products/desktop/packages/ui/src/features/command/commandRowHref.ts@@ -0,0 +1,39 @@+import type { Task, TaskSearchResult } from "@posthog/shared/domain-types";++export function taskHref(task: Task, channelId?: string): string {+ return channelId+ ? `/spaces/${channelId}/tasks/${task.id}`+ : `/tasks/${task.id}`;+}++export function channelHref(channelId: string): string {+ return `/spaces/${channelId}`;+}++function canvasId(result: TaskSearchResult): string | undefined {+ const value = result.metadata.canvas_id;+ return typeof value === "string" && value ? value : undefined;+}++/** Where a search match lives, or nothing when the row has no route of its own. */+export function searchResultHref(+ result: TaskSearchResult,+ { task, bluebirdEnabled }: { task?: Task; bluebirdEnabled: boolean },+): string | undefined {+ const channelId = result.channel_id ?? undefined;+ if (result.kind === "channel") {+ return channelId ? channelHref(channelId) : undefined;+ }+ if (result.kind === "canvas") {+ const canvas = canvasId(result);+ if (!canvas) return undefined;+ return channelId+ ? `/spaces/${channelId}/dashboards/${canvas}`+ : `/canvases?canvas=${canvas}`;+ }+ if (task) return taskHref(task, bluebirdEnabled ? channelId : undefined);+ if (!result.task_id) return undefined;+ return bluebirdEnabled && channelId+ ? `/spaces/${channelId}/tasks/${result.task_id}`+ : `/tasks/${result.task_id}`;+}diff --git a/products/desktop/packages/ui/src/features/command/commandRowMeta.tsx b/products/desktop/packages/ui/src/features/command/commandRowMeta.tsxnew file mode 100644index 000000000000..17613671257c--- /dev/null+++ b/products/desktop/packages/ui/src/features/command/commandRowMeta.tsx@@ -0,0 +1,18 @@+import { Fragment, type ReactNode } from "react";++export type CommandRowMetaPart = { text: string; title?: string };++export function commandRowMeta(+ parts: (CommandRowMetaPart | undefined)[],+): ReactNode | undefined {+ const shown = parts.filter((part): part is CommandRowMetaPart =>+ Boolean(part?.text.trim()),+ );+ if (shown.length === 0) return undefined;+ return shown.map((part, index) => (+ <Fragment key={part.text}>+ {index > 0 ? " · " : null}+ <span title={part.title}>{part.text.trim()}</span>+ </Fragment>+ ));+}diff --git a/products/desktop/packages/ui/src/features/command/commandSearch.test.ts b/products/desktop/packages/ui/src/features/command/commandSearch.test.tsindex d83973636709..f49489cb89c7 100644--- a/products/desktop/packages/ui/src/features/command/commandSearch.test.ts+++ b/products/desktop/packages/ui/src/features/command/commandSearch.test.ts@@ -1,12 +1,12 @@+import type {+ Command,+ CommandSection,+} from "@posthog/ui/features/command/commandRow";import {addRecentCommand,matchesCommandSearch,prioritizeExactCommandMatches,} from "@posthog/ui/features/command/commandSearch";-import type {- Command,- CommandSection,-} from "@posthog/ui/features/command/useSearchSections";import { describe, expect, it } from "vitest";const command = (id: string, label: string): Command => ({diff --git a/products/desktop/packages/ui/src/features/command/commandSearch.ts b/products/desktop/packages/ui/src/features/command/commandSearch.tsindex 29a73a6ae512..6896d5a5a465 100644--- a/products/desktop/packages/ui/src/features/command/commandSearch.ts+++ b/products/desktop/packages/ui/src/features/command/commandSearch.ts@@ -1,4 +1,4 @@-import type { CommandSection } from "@posthog/ui/features/command/useSearchSections";+import type { CommandSection } from "@posthog/ui/features/command/commandRow";const RECENT_COMMAND_LIMIT = 5;diff --git a/products/desktop/packages/ui/src/features/command/rankResultRows.test.ts b/products/desktop/packages/ui/src/features/command/rankResultRows.test.tsnew file mode 100644index 000000000000..56ba8127f462--- /dev/null+++ b/products/desktop/packages/ui/src/features/command/rankResultRows.test.ts@@ -0,0 +1,74 @@+import type { Command } from "@posthog/ui/features/command/commandRow";+import {+ type ResultRow,+ rankResultRows,+} from "@posthog/ui/features/command/rankResultRows";+import { describe, expect, it } from "vitest";++const row = (+ label: string,+ kind: ResultRow["kind"],+ recency?: number,+): ResultRow => ({+ kind,+ recency,+ command: {+ id: label,+ label,+ icon: null,+ action: "open-task",+ onRun: () => {},+ } satisfies Command,+});++const labels = (rows: ResultRow[], query: string): string[] =>+ rankResultRows(rows, query).map((command) => command.label);++describe("rankResultRows", () => {+ it("puts an exact title above a stronger-kind partial match", () => {+ const rows = [+ row("export the retention chart", "task"),+ row("export", "artifact"),+ ];++ expect(labels(rows, "export")).toEqual([+ "export",+ "export the retention chart",+ ]);+ });++ it("prefers a task over a file when both match a word in the title", () => {+ const rows = [+ row("export-timeout.md", "artifact"),+ row("Export reliability review", "canvas"),+ row("triage the failing export job", "task"),+ ];++ expect(labels(rows, "export")).toEqual([+ "triage the failing export job",+ "Export reliability review",+ "export-timeout.md",+ ]);+ });++ it("puts a title match above a row matched by its keywords alone", () => {+ const rows = [row("PR #4821", "pull_request"), row("export job", "task")];++ expect(labels(rows, "export")).toEqual(["export job", "PR #4821"]);+ });++ it("breaks a tie on what changed last", () => {+ const rows = [+ row("export job A", "task", 1_000),+ row("export job B", "task", 5_000),+ ];++ expect(labels(rows, "export")).toEqual(["export job B", "export job A"]);+ });++ it("keeps the incoming order when there is no query", () => {+ const rows = [row("b", "task"), row("a", "task")];++ expect(labels(rows, " ")).toEqual(["b", "a"]);+ });+});diff --git a/products/desktop/packages/ui/src/features/command/rankResultRows.ts b/products/desktop/packages/ui/src/features/command/rankResultRows.tsnew file mode 100644index 000000000000..f7a213e72063--- /dev/null+++ b/products/desktop/packages/ui/src/features/command/rankResultRows.ts@@ -0,0 +1,52 @@+import type { TaskSearchResult } from "@posthog/shared/domain-types";+import type { Command } from "@posthog/ui/features/command/commandRow";++export type ResultRow = {+ command: Command;+ kind: TaskSearchResult["kind"];+ recency?: number;+};++const KIND_WEIGHT: Record<TaskSearchResult["kind"], number> = {+ task: 0,+ channel: 0,+ canvas: 1,+ pull_request: 2,+ artifact: 2,+};++const WORD_SEPARATORS = /[\s\-_/.:#]+/;++const EXACT_TITLE = 0;+const WORD_START = 1;+const IN_TITLE = 2;+const MATCHED_ELSEWHERE = 3;++function matchTier(label: string, query: string): number {+ const title = label.trim().toLowerCase();+ if (title === query) return EXACT_TITLE;+ if (title.startsWith(query)) return WORD_START;+ if (title.split(WORD_SEPARATORS).some((word) => word.startsWith(query))) {+ return WORD_START;+ }+ return title.includes(query) ? IN_TITLE : MATCHED_ELSEWHERE;+}++export function rankResultRows(rows: ResultRow[], query: string): Command[] {+ const normalizedQuery = query.trim().toLowerCase();+ if (!normalizedQuery) return rows.map((row) => row.command);+ return rows+ .map((row, order) => ({+ row,+ order,+ tier: matchTier(row.command.label, normalizedQuery),+ }))+ .sort(+ (left, right) =>+ left.tier - right.tier ||+ KIND_WEIGHT[left.row.kind] - KIND_WEIGHT[right.row.kind] ||+ (right.row.recency ?? 0) - (left.row.recency ?? 0) ||+ left.order - right.order,+ )+ .map(({ row }) => row.command);+}diff --git a/products/desktop/packages/ui/src/features/command/searchResultIcon.tsx b/products/desktop/packages/ui/src/features/command/searchResultIcon.tsxnew file mode 100644index 000000000000..62c9a2d31fca--- /dev/null+++ b/products/desktop/packages/ui/src/features/command/searchResultIcon.tsx@@ -0,0 +1,50 @@+import { GitPullRequestIcon } from "@phosphor-icons/react";+import type { Task, TaskSearchResult } from "@posthog/shared/domain-types";+import { iconForTemplate } from "@posthog/ui/features/canvas/components/canvasTemplateIcon";+import { channelGlyph } from "@posthog/ui/features/canvas/components/channelGlyph";+import { TaskCommandIcon } from "@posthog/ui/features/command/TaskCommandIcon";+import { TaskIcon } from "@posthog/ui/features/sidebar/components/items/TaskIcon";+import { FileIcon } from "@posthog/ui/primitives/FileIcon";+import { SlackMark } from "@posthog/ui/primitives/SlackMark";+import type { ReactNode } from "react";++const ICON_SIZE = 12;++function metadataString(+ result: TaskSearchResult,+ key: string,+): string | undefined {+ const value = result.metadata[key];+ return typeof value === "string" && value ? value : undefined;+}++export function searchResultIcon(+ result: TaskSearchResult,+ { title, task }: { title: string; task?: Task },+): ReactNode {+ switch (result.kind) {+ case "channel":+ return channelGlyph(title, {+ size: ICON_SIZE,+ className: "text-muted-foreground",+ });+ case "pull_request":+ return <GitPullRequestIcon size={ICON_SIZE} className="text-gray-11" />;+ case "canvas":+ return iconForTemplate(metadataString(result, "template_id") ?? "", {+ size: ICON_SIZE,+ });+ case "artifact":+ return <FileIcon filename={title} size={ICON_SIZE} />;+ default:+ if (task) return <TaskCommandIcon task={task} />;+ if (result.origin_product === "slack") return <SlackMark size={12} />;+ return (+ <TaskIcon+ workspaceMode={result.latest_run?.environment ?? undefined}+ taskRunStatus={result.latest_run?.status ?? undefined}+ originProduct={result.origin_product ?? undefined}+ />+ );+ }+}diff --git a/products/desktop/packages/ui/src/features/command/sessionSubtitle.test.ts b/products/desktop/packages/ui/src/features/command/sessionSubtitle.test.tsdeleted file mode 100644index 15a79d773d7d..000000000000--- a/products/desktop/packages/ui/src/features/command/sessionSubtitle.test.ts+++ /dev/null@@ -1,33 +0,0 @@-import { describe, expect, it } from "vitest";-import { sessionSubtitle } from "./sessionSubtitle";--describe("sessionSubtitle", () => {- it.each([- {- name: "names the space without a hash",- input: { space: "access-control", createdAt: null },- expected: "access-control",- },- {- name: "calls the private space what a reader sees",- input: { space: "me", createdAt: null },- expected: "personal",- },- {- name: "orders repository, space, then age",- input: {- space: "access-control",- repository: "example-org/webapp",- createdAt: new Date(Date.now() - 60_000).toISOString(),- },- expected: "example-org/webapp · access-control · 1m",- },- {- name: "says nothing when there is nothing to say",- input: { space: null, repository: null, createdAt: null },- expected: undefined,- },- ])("$name", ({ input, expected }) => {- expect(sessionSubtitle(input)).toBe(expected);- });-});diff --git a/products/desktop/packages/ui/src/features/command/sessionSubtitle.ts b/products/desktop/packages/ui/src/features/command/sessionSubtitle.tsdeleted file mode 100644index ad4af8cd258e..000000000000--- a/products/desktop/packages/ui/src/features/command/sessionSubtitle.ts+++ /dev/null@@ -1,23 +0,0 @@-import { channelDisplayName } from "@posthog/core/canvas/channelName";-import { formatRelativeTimeShort } from "@posthog/shared";--/**- * The muted second line under a session's title in the command palette: where- * it lives and how long ago it started.- *- * The space carries no `#`. The spaces layout dropped that mark everywhere else- * it names a space, and a lone hash in this one list reads as a different kind- * of thing.- */-export function sessionSubtitle(input: {- space?: string | null;- repository?: string | null;- createdAt?: string | null;-}): string | undefined {- const parts = [- input.repository ?? undefined,- input.space ? channelDisplayName(input.space) : undefined,- input.createdAt ? formatRelativeTimeShort(input.createdAt) : undefined,- ].filter(Boolean);- return parts.length > 0 ? parts.join(" · ") : undefined;-}diff --git a/products/desktop/packages/ui/src/features/command/useFeedQueryCommands.tsx b/products/desktop/packages/ui/src/features/command/useFeedQueryCommands.tsxindex 54230e233c35..0c0ad302649f 100644--- a/products/desktop/packages/ui/src/features/command/useFeedQueryCommands.tsx+++ b/products/desktop/packages/ui/src/features/command/useFeedQueryCommands.tsx@@ -1,20 +1,23 @@import { ArrowRightIcon, MagnifyingGlassIcon } from "@phosphor-icons/react";+import { channelDisplayLabel } from "@posthog/core/canvas/channelName";import {feedQueryTypeScope,parseFeedQuery,type TypeValue,} from "@posthog/core/tasks/feedQuery";+import { singleLineTitle } from "@posthog/shared";import { useFeedQuerySuggestions } from "@posthog/ui/features/canvas/components/feedQuerySuggestions";import { applyFeedQuerySuggestion } from "@posthog/ui/features/canvas/components/feedQuerySuggestionUtils";import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";import { useProjectTaskFeeds } from "@posthog/ui/features/canvas/hooks/useProjectTaskFeeds";import { useTaskFeedResults } from "@posthog/ui/features/canvas/hooks/useTaskFeedResults";-import { sessionSubtitle } from "@posthog/ui/features/command/sessionSubtitle";-import { TaskCommandIcon } from "@posthog/ui/features/command/TaskCommandIcon";import type {Command,CommandSection,-} from "@posthog/ui/features/command/useSearchSections";+} from "@posthog/ui/features/command/commandRow";+import { taskRowParts } from "@posthog/ui/features/command/commandRowFacts";+import { commandRowMeta } from "@posthog/ui/features/command/commandRowMeta";+import { TaskCommandIcon } from "@posthog/ui/features/command/TaskCommandIcon";import { closeSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";import { useDebouncedValue } from "@posthog/ui/primitives/hooks/useDebouncedValue";import { navigateToFeed } from "@posthog/ui/router/navigationBridge";@@ -234,15 +237,13 @@ export function useFeedQueryCommands({const shown = runsQuery ? results.tasks.slice(0, limit) : [];if (shown.length > 0) {const items = shown.map((task): Command => {- const subtitle = sessionSubtitle({- space: task.channel ? channelNames.get(task.channel) : undefined,- repository: task.repository,- createdAt: task.created_at,- });+ const space = task.channel ? channelNames.get(task.channel) : undefined;return {id: `feed-query-task-${task.id}`,- label: task.title,- subtitle,+ label: singleLineTitle(task.title),+ subtitle: commandRowMeta(taskRowParts(task)),+ detail: space ? channelDisplayLabel(space) : undefined,+ detailPrefix: "",keywords: `${query} ${searchText}`,icon: <TaskCommandIcon task={task} />,action: "open-task",diff --git a/products/desktop/packages/ui/src/features/command/useSearchRows.test.tsx b/products/desktop/packages/ui/src/features/command/useSearchRows.test.tsxnew file mode 100644index 000000000000..e33e964ac6d8--- /dev/null+++ b/products/desktop/packages/ui/src/features/command/useSearchRows.test.tsx@@ -0,0 +1,140 @@+import type { Task, TaskSearchResult } from "@posthog/shared/domain-types";+import type { CommandSection } from "@posthog/ui/features/command/commandRow";+import { useSearchRows } from "@posthog/ui/features/command/useSearchRows";+import { renderHook } from "@testing-library/react";+import { describe, expect, it } from "vitest";++function searchResult(+ overrides: Partial<TaskSearchResult> & Pick<TaskSearchResult, "id" | "kind">,+): TaskSearchResult {+ return {+ title: overrides.id,+ subtitle: "",+ task_id: null,+ task_run_id: null,+ channel_id: null,+ updated_at: "2026-09-01T10:00:00Z",+ metadata: {},+ ...overrides,+ };+}++function taskSection(taskIds: string[]): CommandSection {+ return {+ label: "Tasks",+ items: taskIds.map((taskId) => ({+ id: `task-${taskId}`,+ label: `Local ${taskId}`,+ icon: null,+ action: "open-task" as const,+ onRun: () => undefined,+ })),+ };+}++describe("useSearchRows", () => {+ const tasks: Task[] = [];++ function render(+ searchResults: TaskSearchResult[],+ { taskIds = [], bluebirdEnabled = true } = {} as {+ taskIds?: string[];+ bluebirdEnabled?: boolean;+ },+ ) {+ return renderHook(() =>+ useSearchRows({+ remoteQuery: "run",+ searchResults,+ tasks,+ taskSections: taskIds.length > 0 ? [taskSection(taskIds)] : [],+ channels: [{ id: "channel-a", name: "growth" }],+ bluebirdEnabled,+ }),+ ).result.current;+ }++ it("leaves out a task the palette already lists from the local task rows", () => {+ const rows = render(+ [+ searchResult({ id: "a1", kind: "artifact", task_id: "task-b" }),+ searchResult({ id: "t1", kind: "task", task_id: "task-a" }),+ ],+ { taskIds: ["task-a"] },+ );++ expect(rows.map((row) => row.command.id)).toEqual(["search-a1"]);+ });++ it("opens a canvas match in the space it is filed in", () => {+ const rows = render([+ searchResult({+ id: "cv1",+ kind: "canvas",+ title: "Run rate",+ channel_id: "channel-a",+ metadata: { canvas_id: "canvas-1", template_id: "freeform" },+ }),+ ]);++ expect(rows[0].command.label).toBe("Run rate");+ expect(rows[0].command.detail).toBe("#growth");+ expect(rows[0].command.action).toBe("open-canvas");+ });++ it("hides space matches while the spaces feature is off", () => {+ const rows = render(+ [searchResult({ id: "c1", kind: "channel", channel_id: "channel-b" })],+ { bluebirdEnabled: false },+ );++ expect(rows).toEqual([]);+ });++ it("gives every row a place of its own to open in a tab", () => {+ const rows = render([+ searchResult({+ id: "t3",+ kind: "task",+ task_id: "task-d",+ channel_id: "channel-a",+ }),+ searchResult({+ id: "cv2",+ kind: "canvas",+ channel_id: "channel-a",+ metadata: { canvas_id: "canvas-2" },+ }),+ searchResult({ id: "c2", kind: "channel", channel_id: "channel-b" }),+ searchResult({ id: "pr1", kind: "pull_request", task_id: "task-e" }),+ ]);++ expect(rows.map((row) => row.command.href)).toEqual([+ "/spaces/channel-a/tasks/task-d",+ "/spaces/channel-a/dashboards/canvas-2",+ "/spaces/channel-b",+ "/tasks/task-e",+ ]);+ });++ it("leaves a row with no route of its own without an href", () => {+ const rows = render([+ searchResult({ id: "cv3", kind: "canvas", metadata: {} }),+ ]);++ expect(rows[0].command.href).toBeUndefined();+ });++ it("reads a title that arrived with a labeled link as one line", () => {+ const rows = render([+ searchResult({+ id: "t2",+ kind: "task",+ task_id: "task-c",+ title: "why did <https://example.com/runs/1|this run> fail?",+ }),+ ]);++ expect(rows[0].command.label).toBe("why did this run fail?");+ });+});diff --git a/products/desktop/packages/ui/src/features/command/useSearchRows.tsx b/products/desktop/packages/ui/src/features/command/useSearchRows.tsxnew file mode 100644index 000000000000..e351462ef115--- /dev/null+++ b/products/desktop/packages/ui/src/features/command/useSearchRows.tsx@@ -0,0 +1,155 @@+import { channelDisplayName } from "@posthog/core/canvas/channelName";+import { singleLineTitle } from "@posthog/shared";+import type { CommandMenuAction } from "@posthog/shared/analytics-events";+import type { Task, TaskSearchResult } from "@posthog/shared/domain-types";+import type { CommandSection } from "@posthog/ui/features/command/commandRow";+import {+ searchResultDetail,+ searchResultParts,+ searchResultRecency,+} from "@posthog/ui/features/command/commandRowFacts";+import { searchResultHref } from "@posthog/ui/features/command/commandRowHref";+import { commandRowMeta } from "@posthog/ui/features/command/commandRowMeta";+import type { ResultRow } from "@posthog/ui/features/command/rankResultRows";+import { searchResultIcon } from "@posthog/ui/features/command/searchResultIcon";+import { closeSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";+import {+ navigateToCanvases,+ navigateToChannel,+ navigateToChannelDashboard,+ navigateToChannelTask,+ navigateToTaskDetail,+} from "@posthog/ui/router/navigationBridge";+import { openTask } from "@posthog/ui/router/useOpenTask";+import { useMemo } from "react";++type SearchChannel = { id: string; name: string };++type UseSearchRowsOptions = {+ remoteQuery: string;+ searchResults: TaskSearchResult[];+ tasks: Task[];+ taskSections: CommandSection[];+ channels: SearchChannel[];+ bluebirdEnabled: boolean;+};++const SEARCH_ACTIONS: Record<TaskSearchResult["kind"], CommandMenuAction> = {+ task: "open-task",+ pull_request: "open-task-from-pull-request",+ artifact: "open-artifact",+ canvas: "open-canvas",+ channel: "open-channel",+};++function canvasIdOf(result: TaskSearchResult): string | undefined {+ const canvasId = result.metadata.canvas_id;+ return typeof canvasId === "string" && canvasId ? canvasId : undefined;+}++/** Remote matches as palette rows that open the match's owning task or space. */+export function useSearchRows({+ remoteQuery,+ searchResults,+ tasks,+ taskSections,+ channels,+ bluebirdEnabled,+}: UseSearchRowsOptions): ResultRow[] {+ return useMemo(() => {+ if (!remoteQuery || searchResults.length === 0) return [];++ const tasksById = new Map(tasks.map((task) => [task.id, task]));+ const visibleTaskIds = new Set(+ taskSections.flatMap((section) =>+ section.items.map((item) => item.id.replace(/^task-/, "")),+ ),+ );+ const channelNamesById = new Map(+ channels.map((channel) => [channel.id, channel.name] as const),+ );+ const rows: ResultRow[] = [];++ for (const result of searchResults) {+ if (result.kind === "channel" && !bluebirdEnabled) continue;+ if (+ (result.kind === "task" &&+ result.task_id &&+ visibleTaskIds.has(result.task_id)) ||+ (result.kind === "channel" &&+ result.channel_id &&+ channelNamesById.has(result.channel_id))+ ) {+ continue;+ }++ const task = result.task_id ? tasksById.get(result.task_id) : undefined;+ // Remote search answers with the backend's own name, so a channel row is+ // the one result that has not been through the channel list.+ const title =+ result.kind === "channel"+ ? channelDisplayName(result.title)+ : singleLineTitle(result.title);+ const channelName = result.channel_id+ ? channelNamesById.get(result.channel_id)+ : undefined;+ const canvasId = canvasIdOf(result);+ rows.push({+ kind: result.kind,+ recency: searchResultRecency(result, task),+ command: {+ id: `search-${result.id}`,+ label: title,+ subtitle: commandRowMeta(searchResultParts(result, task)),+ detail: searchResultDetail(result, channelName),+ detailPrefix: "",+ keywords: `${remoteQuery} ${result.subtitle} ${Object.values(result.metadata).join(" ")}`,+ icon: searchResultIcon(result, { title, task }),+ href: searchResultHref(result, { task, bluebirdEnabled }),+ action: SEARCH_ACTIONS[result.kind],+ channelId: bluebirdEnabled+ ? (result.channel_id ?? undefined)+ : undefined,+ onRun: () => {+ closeSettings();+ if (+ bluebirdEnabled &&+ result.kind === "channel" &&+ result.channel_id+ ) {+ navigateToChannel(result.channel_id);+ } else if (result.kind === "canvas" && canvasId) {+ if (result.channel_id) {+ navigateToChannelDashboard(result.channel_id, canvasId);+ } else {+ navigateToCanvases(canvasId);+ }+ } else if (task) {+ // PR matches intentionally open their containing task. Cmd+K is a+ // navigator for Desktop context, not an external-link launcher.+ void openTask(+ task,+ result.channel_id+ ? { channelId: result.channel_id }+ : undefined,+ );+ } else if (bluebirdEnabled && result.task_id && result.channel_id) {+ navigateToChannelTask(result.channel_id, result.task_id);+ } else if (result.task_id) {+ navigateToTaskDetail(result.task_id);+ }+ },+ },+ });+ }++ return rows;+ }, [+ remoteQuery,+ searchResults,+ tasks,+ taskSections,+ channels,+ bluebirdEnabled,+ ]);+}diff --git a/products/desktop/packages/ui/src/features/command/useSearchSections.tsx b/products/desktop/packages/ui/src/features/command/useSearchSections.tsxdeleted file mode 100644index 4ae5c899361f..000000000000--- a/products/desktop/packages/ui/src/features/command/useSearchSections.tsx+++ /dev/null@@ -1,157 +0,0 @@-import { FileTextIcon, GitDiffIcon } from "@phosphor-icons/react";-import { channelDisplayName } from "@posthog/core/canvas/channelName";-import type { CommandMenuAction } from "@posthog/shared/analytics-events";-import type { Task, TaskSearchResult } from "@posthog/shared/domain-types";-import { channelGlyph } from "@posthog/ui/features/canvas/components/channelGlyph";-import { closeSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";-import {- navigateToChannel,- navigateToChannelTask,- navigateToTaskDetail,-} from "@posthog/ui/router/navigationBridge";-import { openTask } from "@posthog/ui/router/useOpenTask";-import { type ReactNode, useMemo } from "react";--export type Command = {- id: string;- label: string;- /** Muted trailing detail shown after a middot, e.g. a task's channel. */- detail?: string;- detailPrefix?: string;- /** Muted second line under the label, where a trailing `detail` would be the- * part a long label truncates away. */- subtitle?: string;- keywords?: string;- icon: ReactNode;- action: CommandMenuAction;- /** Channel in scope for the bluebird open-channel / open-task actions. */- channelId?: string;- /** Hotkey string (e.g. "mod+b") shown right-aligned when present. */- shortcut?: string;- /** Running this keeps the palette open (e.g. completing a filter token). */- keepOpen?: boolean;- onRun: () => void;-};--export type CommandSection = { label: string; items: Command[] };--type SearchChannel = { id: string; name: string };--type UseSearchSectionsOptions = {- remoteQuery: string;- searchResults: TaskSearchResult[];- tasks: Task[];- taskSections: CommandSection[];- channels: SearchChannel[];- bluebirdEnabled: boolean;- spacesLayout: boolean;-};--/** Convert remote matches into commands that open the match's owning task or space. */-export function useSearchSections({- remoteQuery,- searchResults,- tasks,- taskSections,- channels,- bluebirdEnabled,- spacesLayout,-}: UseSearchSectionsOptions): CommandSection[] {- return useMemo(() => {- if (!remoteQuery || searchResults.length === 0) return [];-- const tasksById = new Map(tasks.map((task) => [task.id, task]));- const visibleTaskIds = new Set(- taskSections.flatMap((section) =>- section.items.map((item) => item.id.replace(/^task-/, "")),- ),- );- const channelIds = new Set(channels.map((channel) => channel.id));- const items: Command[] = [];-- for (const result of searchResults) {- if (result.kind === "channel" && !bluebirdEnabled) continue;- if (- (result.kind === "task" &&- result.task_id &&- visibleTaskIds.has(result.task_id)) ||- (result.kind === "channel" &&- result.channel_id &&- channelIds.has(result.channel_id))- ) {- continue;- }-- const task = result.task_id ? tasksById.get(result.task_id) : undefined;- // Remote search answers with the backend's own name, so a channel row is- // the one result that has not been through the channel list.- const title =- result.kind === "channel"- ? channelDisplayName(result.title)- : result.title;- items.push({- id: `search-${result.id}`,- label: title,- // Under the spaces layout a session's context goes on a second line, so- // a long title truncates its own text rather than eating the context.- detail: spacesLayout ? undefined : result.subtitle || undefined,- subtitle: spacesLayout ? result.subtitle || undefined : undefined,- detailPrefix: "",- keywords: `${remoteQuery} ${result.subtitle} ${Object.values(result.metadata).join(" ")}`,- icon:- result.kind === "pull_request" ? (- <GitDiffIcon size={12} className="text-muted-foreground" />- ) : result.kind === "channel" ? (- channelGlyph(title, {- size: 12,- space: spacesLayout,- className: "text-muted-foreground",- })- ) : (- <FileTextIcon size={12} className="text-muted-foreground" />- ),- action: (result.kind === "channel"- ? "open-channel"- : result.kind === "pull_request"- ? "open-task-from-pull-request"- : result.kind === "artifact"- ? "open-artifact"- : "open-task") as CommandMenuAction,- channelId: bluebirdEnabled- ? (result.channel_id ?? undefined)- : undefined,- onRun: () => {- closeSettings();- if (- bluebirdEnabled &&- result.kind === "channel" &&- result.channel_id- ) {- navigateToChannel(result.channel_id);- } else if (task) {- // PR matches intentionally open their containing task. Cmd+K is a- // navigator for Desktop context, not an external-link launcher.- void openTask(- task,- result.channel_id ? { channelId: result.channel_id } : undefined,- );- } else if (bluebirdEnabled && result.task_id && result.channel_id) {- navigateToChannelTask(result.channel_id, result.task_id);- } else if (result.task_id) {- navigateToTaskDetail(result.task_id);- }- },- });- }-- return items.length > 0 ? [{ label: "Search results", items }] : [];- }, [- remoteQuery,- searchResults,- tasks,- taskSections,- channels,- bluebirdEnabled,- spacesLayout,- ]);-}