Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(desktop): add type:canvas to command palette search (#109000)

Adam Leithb7b579cc60f6
diff --git a/products/desktop/packages/core/src/tasks/canvasQuery.test.ts b/products/desktop/packages/core/src/tasks/canvasQuery.test.ts
new file mode 100644
index 000000000000..865512a22752
--- /dev/null
+++ b/products/desktop/packages/core/src/tasks/canvasQuery.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from "vitest";
+import { type FeedQueryCanvas, planCanvasQuery } from "./canvasQuery";
+import { type FeedQueryPlanContext, parseFeedQuery } from "./feedQuery";
+
+const shy = {
+ id: 1,
+ uuid: "uuid-shy",
+ email: "[email protected]",
+ first_name: "Shy",
+ last_name: "Levi",
+};
+const moshe = {
+ id: 2,
+ uuid: "uuid-moshe",
+ email: "[email protected]",
+ first_name: "Moshe",
+ last_name: "Katz",
+};
+
+const context: FeedQueryPlanContext = {
+ members: [shy, moshe],
+ spaces: [
+ { id: "space-mobile", name: "mobile" },
+ { id: "space-web", name: "desktop app" },
+ ],
+ me: shy,
+ reportsEnabled: false,
+};
+
+describe("planCanvasQuery", () => {
+ const canvases: Record<string, FeedQueryCanvas> = {
+ shyMobile: {
+ name: "Billing overview",
+ channelId: "space-mobile",
+ createdByUuid: "uuid-shy",
+ },
+ mosheWeb: {
+ name: "Signup funnel",
+ description: "Weekly billing health",
+ channelId: "space-web",
+ createdByUuid: "uuid-moshe",
+ pinnedAt: 1,
+ },
+ unowned: { name: "Scratch", channelId: "space-mobile" },
+ };
+
+ it.each([
+ ["type:canvas", ["shyMobile", "mosheWeb", "unowned"]],
+ ["type:canvas created-by:moshe", ["mosheWeb"]],
+ ["type:canvas created-by:@me", ["shyMobile"]],
+ ["type:canvas created-by:shy created-by:moshe", ["shyMobile", "mosheWeb"]],
+ ["type:canvas -created-by:shy", ["mosheWeb", "unowned"]],
+ ["type:canvas created-by:nobody", []],
+ ['type:canvas space:"desktop app"', ["mosheWeb"]],
+ ["type:canvas -space:mobile", ["mosheWeb"]],
+ ["type:canvas space:missing", []],
+ ["type:canvas is:pinned", ["mosheWeb"]],
+ ["type:canvas -is:pinned", ["shyMobile", "unowned"]],
+ ["type:canvas billing", ["shyMobile", "mosheWeb"]],
+ ["type:canvas created-by:shy billing", ["shyMobile"]],
+ ])("%s matches %j", (query, expected) => {
+ const plan = planCanvasQuery(parseFeedQuery(query), context);
+ const matched = Object.entries(canvases)
+ .filter(([, canvas]) => plan.matches(canvas))
+ .map(([name]) => name);
+ expect(matched).toEqual(expected);
+ });
+
+ it("flags task-shaped tokens as unsupported instead of half-applying them", () => {
+ const plan = planCanvasQuery(
+ parseFeedQuery("type:canvas status:failed repo:webapp type:task"),
+ context,
+ );
+ expect(
+ plan.issues.filter((i) => i.kind === "unsupported").map((i) => i.raw),
+ ).toEqual(["type:task", "status:failed", "repo:webapp"]);
+ expect(plan.matches(canvases.shyMobile)).toBe(true);
+ });
+});
diff --git a/products/desktop/packages/core/src/tasks/canvasQuery.ts b/products/desktop/packages/core/src/tasks/canvasQuery.ts
new file mode 100644
index 000000000000..b66d20272570
--- /dev/null
+++ b/products/desktop/packages/core/src/tasks/canvasQuery.ts
@@ -0,0 +1,132 @@
+import {
+ type FeedQueryIssue,
+ type FeedQueryPlanContext,
+ type FeedQueryToken,
+ type Group,
+ groupOf,
+ MATCH_ALL,
+ memberResolver,
+ normalize,
+ type ParsedFeedQuery,
+ spaceResolver,
+} from "./feedQuery";
+
+/** The canvas fields the canvas search predicate reads. */
+export interface FeedQueryCanvas {
+ name: string;
+ description?: string;
+ channelId: string;
+ createdByUuid?: string;
+ pinnedAt?: number;
+}
+
+export interface CanvasQueryPlan {
+ matches: (canvas: FeedQueryCanvas) => boolean;
+ issues: FeedQueryIssue[];
+}
+
+/**
+ * The canvas-only plan behind `type:canvas` in the command palette. Canvases
+ * load as one list, so every filter is a client-side predicate. `created-by:`,
+ * `space:`, `is:pinned` and free text apply. Every other token is task-shaped
+ * and is reported as unsupported rather than half-applied.
+ */
+export function planCanvasQuery(
+ parsed: ParsedFeedQuery,
+ context: FeedQueryPlanContext,
+): CanvasQueryPlan {
+ const issues: FeedQueryIssue[] = [...parsed.issues];
+ const resolveMembers = memberResolver(context, issues);
+ const resolveSpace = spaceResolver(context, issues);
+ const predicates: ((canvas: FeedQueryCanvas) => boolean)[] = [];
+
+ const groups = new Map<string, Group>();
+ for (const token of parsed.tokens) {
+ const key =
+ token.key === "is" && normalize(token.value) === "pinned"
+ ? "pinned"
+ : token.key;
+ const group = groupOf(groups, key);
+ (token.negated ? group.negatives : group.positives).push(token);
+ }
+
+ // Positive values OR together and negated values exclude. A positive filter
+ // that resolves to nothing matches nothing, not every canvas, the same as an
+ // unknown teammate or space in task mode.
+ const addIdFilter = (
+ group: Group,
+ resolve: (token: FeedQueryToken) => string[],
+ idOf: (canvas: FeedQueryCanvas) => string | undefined,
+ ) => {
+ if (group.positives.length > 0) {
+ const wanted = new Set(group.positives.flatMap(resolve));
+ predicates.push((canvas) => {
+ const id = idOf(canvas);
+ return id !== undefined && wanted.has(id);
+ });
+ }
+ const excluded = new Set(group.negatives.flatMap(resolve));
+ if (excluded.size > 0) {
+ predicates.push((canvas) => {
+ const id = idOf(canvas);
+ return id === undefined || !excluded.has(id);
+ });
+ }
+ };
+
+ for (const [key, group] of groups) {
+ if (key === "created-by") {
+ addIdFilter(
+ group,
+ (token) => resolveMembers(token).map((member) => member.uuid),
+ (canvas) => canvas.createdByUuid,
+ );
+ } else if (key === "space") {
+ addIdFilter(
+ group,
+ (token) => {
+ const space = resolveSpace(token);
+ return space ? [space.id] : [];
+ },
+ (canvas) => canvas.channelId,
+ );
+ } else if (key === "pinned") {
+ if (group.positives.length > 0) {
+ predicates.push((canvas) => canvas.pinnedAt != null);
+ }
+ if (group.negatives.length > 0) {
+ predicates.push((canvas) => canvas.pinnedAt == null);
+ }
+ } else {
+ for (const token of [...group.positives, ...group.negatives]) {
+ const isScope =
+ key === "type" &&
+ !token.negated &&
+ normalize(token.value) === "canvas";
+ if (isScope) continue;
+ issues.push({
+ raw: token.raw,
+ kind: "unsupported",
+ message: `Canvas search doesn't support "${token.raw}", so it is ignored`,
+ });
+ }
+ }
+ }
+
+ const text = normalize(parsed.text);
+ if (text) {
+ predicates.push(
+ (canvas) =>
+ canvas.name.toLowerCase().includes(text) ||
+ (canvas.description ?? "").toLowerCase().includes(text),
+ );
+ }
+
+ return {
+ matches:
+ predicates.length === 0
+ ? MATCH_ALL
+ : (canvas) => predicates.every((p) => p(canvas)),
+ issues,
+ };
+}
diff --git a/products/desktop/packages/core/src/tasks/feedQuery.test.ts b/products/desktop/packages/core/src/tasks/feedQuery.test.ts
index f63a5115725d..618e21773e67 100644
--- a/products/desktop/packages/core/src/tasks/feedQuery.test.ts
+++ b/products/desktop/packages/core/src/tasks/feedQuery.test.ts
@@ -111,7 +111,7 @@ describe("feedQuery", () => {
["is:sideways", "unknown-value"],
["pr:sideways", "unknown-value"],
["ci:sideways", "unknown-value"],
- ["type:canvas", "unknown-value"],
+ ["type:sideways", "unknown-value"],
])("flags %s as %s", (query, kind) => {
const parsed = parseFeedQuery(query);
expect(parsed.issues).toHaveLength(1);
diff --git a/products/desktop/packages/core/src/tasks/feedQuery.ts b/products/desktop/packages/core/src/tasks/feedQuery.ts
index 5ba9a8956bdb..981b0fbdeb00 100644
--- a/products/desktop/packages/core/src/tasks/feedQuery.ts
+++ b/products/desktop/packages/core/src/tasks/feedQuery.ts
@@ -81,6 +81,7 @@ export const CI_VALUES = [
export const TYPE_VALUES = [
"task",
+ "canvas",
"space",
"command",
"saved",
@@ -361,7 +362,7 @@ export interface FeedQueryPlan {
matchesReport?: (report: FeedQueryReport) => boolean;
}
-function normalize(value: string): string {
+export function normalize(value: string): string {
return value.trim().toLowerCase();
}
@@ -492,12 +493,12 @@ function memberMatches(member: FeedQueryMember, value: string): boolean {
);
}
-interface Group {
+export interface Group {
positives: FeedQueryToken[];
negatives: FeedQueryToken[];
}
-function groupOf(map: Map<string, Group>, key: string): Group {
+export function groupOf(map: Map<string, Group>, key: string): Group {
let group = map.get(key);
if (!group) {
group = { positives: [], negatives: [] };
@@ -506,9 +507,48 @@ function groupOf(map: Map<string, Group>, key: string): Group {
return group;
}
-const MATCH_ALL = () => true;
+export const MATCH_ALL = () => true;
const MATCH_NONE = () => false;
+export function memberResolver(
+ context: FeedQueryPlanContext,
+ issues: FeedQueryIssue[],
+): (token: FeedQueryToken) => FeedQueryMember[] {
+ return (token) => {
+ const value = normalize(token.value);
+ if (value === "@me" || value === "me") {
+ return context.me ? [context.me] : [];
+ }
+ const matched = context.members.filter((m) => memberMatches(m, value));
+ if (matched.length === 0) {
+ issues.push({
+ raw: token.raw,
+ kind: "unknown-value",
+ message: `No teammate matches "${token.value}"`,
+ });
+ }
+ return matched;
+ };
+}
+
+export function spaceResolver(
+ context: FeedQueryPlanContext,
+ issues: FeedQueryIssue[],
+): (token: FeedQueryToken) => FeedQuerySpace | undefined {
+ return (token) => {
+ const value = normalize(token.value).replace(/^#/, "");
+ const matched = context.spaces.find((s) => normalize(s.name) === value);
+ if (!matched) {
+ issues.push({
+ raw: token.raw,
+ kind: "unknown-value",
+ message: `No space named "${token.value}"`,
+ });
+ }
+ return matched;
+ };
+}
+
/** Limit fan-out requests so one query cannot overload the task-list API. */
const MAX_PLAN_REQUESTS = 8;
@@ -535,21 +575,7 @@ export function planFeedQuery(
if (parsed.text) server.search = parsed.text;
// Resolve people before building the task-list requests.
- const resolveMembers = (token: FeedQueryToken): FeedQueryMember[] => {
- const value = normalize(token.value);
- if (value === "@me" || value === "me") {
- return context.me ? [context.me] : [];
- }
- const matched = context.members.filter((m) => memberMatches(m, value));
- if (matched.length === 0) {
- issues.push({
- raw: token.raw,
- kind: "unknown-value",
- message: `No teammate matches "${token.value}"`,
- });
- }
- return matched;
- };
+ const resolveMembers = memberResolver(context, issues);
// Equivalent names for one person must not create duplicate requests.
const uniqueMembers = (tokens: FeedQueryToken[]): FeedQueryMember[] => [
...new Map(
@@ -741,18 +767,7 @@ export function planFeedQuery(
const space = groups.get("space");
if (space) {
- const resolve = (token: FeedQueryToken): FeedQuerySpace | undefined => {
- const value = normalize(token.value).replace(/^#/, "");
- const matched = context.spaces.find((s) => normalize(s.name) === value);
- if (!matched) {
- issues.push({
- raw: token.raw,
- kind: "unknown-value",
- message: `No space named "${token.value}"`,
- });
- }
- return matched;
- };
+ const resolve = spaceResolver(context, issues);
const wanted = new Set(
space.positives.map(resolve).flatMap((s) => (s ? [s.id] : [])),
);
@@ -1061,18 +1076,8 @@ function planReportFeedQuery(
}
const first = group.positives[0];
if (first) {
- const value = normalize(first.value).replace(/^#/, "");
- const matched = context.spaces.find((s) => normalize(s.name) === value);
- if (matched) {
- reportChannelId = matched.id;
- } else {
- unresolvedSpace = true;
- issues.push({
- raw: first.raw,
- kind: "unknown-value",
- message: `No space named "${first.value}"`,
- });
- }
+ reportChannelId = spaceResolver(context, issues)(first)?.id;
+ unresolvedSpace = reportChannelId === undefined;
}
continue;
}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/feedQuerySuggestions.tsx b/products/desktop/packages/ui/src/features/canvas/components/feedQuerySuggestions.tsx
index 9e78cf86fe28..4ec5453eba5a 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/feedQuerySuggestions.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/feedQuerySuggestions.tsx
@@ -116,7 +116,7 @@ const PALETTE_KEY_SUGGESTIONS: FeedQuerySuggestion[] = [
{
insert: "type:",
label: "type:",
- hint: "task, space, command, saved",
+ hint: "task, canvas, space, command, saved",
icon: keyIcon(<SquaresFourIcon size={14} />),
},
{
@@ -129,6 +129,7 @@ const PALETTE_KEY_SUGGESTIONS: FeedQuerySuggestion[] = [
const TYPE_VALUES: FeedQuerySuggestion[] = [
{ insert: "task", label: "task", hint: "only tasks" },
+ { insert: "canvas", label: "canvas", hint: "only canvases" },
{ insert: "space", label: "space", hint: "only spaces" },
{ insert: "command", label: "command", hint: "only commands" },
{ insert: "saved", label: "saved", hint: "only saved searches" },
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useCanvasQueryResults.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useCanvasQueryResults.ts
new file mode 100644
index 000000000000..78d92ca7ae55
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useCanvasQueryResults.ts
@@ -0,0 +1,30 @@
+import type { DashboardRecord } from "@posthog/core/canvas/dashboardSchemas";
+import { planCanvasQuery } from "@posthog/core/tasks/canvasQuery";
+import { parseFeedQuery } from "@posthog/core/tasks/feedQuery";
+import { useAllCanvases } from "@posthog/ui/features/canvas/hooks/useDashboards";
+import { useFeedQueryContext } from "@posthog/ui/features/canvas/hooks/useTaskFeedResults";
+import { useMemo } from "react";
+
+/** Canvases across every visible space that match a `type:canvas` query, newest first. */
+export function useCanvasQueryResults(query: string): {
+ canvases: DashboardRecord[];
+ isLoading: boolean;
+} {
+ const normalized = query.trim();
+ const parsed = useMemo(() => parseFeedQuery(normalized), [normalized]);
+ const { context, isLoading: contextLoading } = useFeedQueryContext(parsed);
+ const { dashboards, isLoading: canvasesLoading } = useAllCanvases({
+ enabled: normalized !== "",
+ });
+
+ const canvases = useMemo(() => {
+ if (normalized === "" || !context) return [];
+ const { matches } = planCanvasQuery(parsed, context);
+ return dashboards.filter(matches).sort((a, b) => b.updatedAt - a.updatedAt);
+ }, [normalized, parsed, context, dashboards]);
+
+ return {
+ canvases,
+ isLoading: normalized !== "" && (contextLoading || canvasesLoading),
+ };
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useDashboards.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useDashboards.ts
index 9dbd2cf381fc..151a6e8bc21c 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useDashboards.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useDashboards.ts
@@ -53,13 +53,14 @@ export function useDashboards(
}
/** Every canvas across every visible space. */
-export function useAllCanvases(): {
+export function useAllCanvases(options?: { enabled?: boolean }): {
dashboards: DashboardRecord[];
isLoading: boolean;
} {
const trpc = useHostTRPC();
const { data, isLoading } = useQuery(
trpc.dashboards.listAll.queryOptions(undefined, {
+ enabled: options?.enabled ?? true,
gcTime: SPACE_QUERY_GC_TIME_MS,
meta: AUTH_SCOPED_QUERY_META,
refetchInterval: SPACE_QUERY_REFETCH_INTERVAL_MS,
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskFeedResults.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskFeedResults.ts
index 1b2a3433e8f9..2ee002a51f3f 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskFeedResults.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskFeedResults.ts
@@ -1,7 +1,9 @@
import {
type FeedQueryIssue,
type FeedQueryPlan,
+ type FeedQueryPlanContext,
type FeedQueryToken,
+ type ParsedFeedQuery,
parseFeedQuery,
planFeedQuery,
} from "@posthog/core/tasks/feedQuery";
@@ -40,16 +42,19 @@ export function taskFeedResultsQueryKey(query: string) {
return [...taskFeedResultsQueryRoot, query] as const;
}
-export function useFeedQueryPlan(query: string | undefined): {
+interface FeedQueryContextState {
canRetry: boolean;
+ context: FeedQueryPlanContext | undefined;
error: Error | null;
errorMessage: string | null;
- plan: FeedQueryPlan | undefined;
isLoading: boolean;
refetch: () => void;
-} {
- const normalized = query?.trim() ?? "";
- const parsed = useMemo(() => parseFeedQuery(normalized), [normalized]);
+}
+
+/** The teammates, spaces and viewer a query's tokens resolve against. */
+export function useFeedQueryContext(
+ parsed: ParsedFeedQuery,
+): FeedQueryContextState {
const needsMembers = parsed.tokens.some(
(token) => isPersonToken(token) && !isCurrentUserToken(token),
);
@@ -78,27 +83,20 @@ export function useFeedQueryPlan(query: string | undefined): {
(needsCurrentUser && currentUserLoading) ||
(needsSpaces && channelsLoading);
- const plan = useMemo(() => {
- if (
- normalized === "" ||
- waiting ||
- memberLookupFailed ||
- memberLookupIncomplete
- ) {
+ const context = useMemo(() => {
+ if (waiting || memberLookupFailed || memberLookupIncomplete) {
return undefined;
}
- return planFeedQuery(parsed, {
+ return {
members,
spaces: channels.map((c) => ({ id: c.id, name: c.name })),
me: me ?? null,
reportsEnabled: false,
- });
+ };
}, [
- normalized,
waiting,
memberLookupFailed,
memberLookupIncomplete,
- parsed,
members,
channels,
me,
@@ -106,6 +104,7 @@ export function useFeedQueryPlan(query: string | undefined): {
return {
canRetry: memberLookupFailed,
+ context,
error: memberLookupFailed
? membersError
: memberLookupIncomplete
@@ -116,12 +115,38 @@ export function useFeedQueryPlan(query: string | undefined): {
: memberLookupIncomplete
? "Organization member lookup is incomplete. This search cannot verify every teammate."
: null,
- isLoading: normalized !== "" && waiting,
- plan,
+ isLoading: waiting,
refetch: refetchMembers,
};
}
+export function useFeedQueryPlan(query: string | undefined): {
+ canRetry: boolean;
+ error: Error | null;
+ errorMessage: string | null;
+ plan: FeedQueryPlan | undefined;
+ isLoading: boolean;
+ refetch: () => void;
+} {
+ const normalized = query?.trim() ?? "";
+ const parsed = useMemo(() => parseFeedQuery(normalized), [normalized]);
+ const { context, isLoading, ...state } = useFeedQueryContext(parsed);
+
+ const plan = useMemo(
+ () =>
+ normalized === "" || !context
+ ? undefined
+ : planFeedQuery(parsed, context),
+ [normalized, parsed, context],
+ );
+
+ return {
+ ...state,
+ isLoading: normalized !== "" && isLoading,
+ plan,
+ };
+}
+
export function useTaskFeedResults(query: string | undefined): {
canRetry: boolean;
error: Error | null;
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.tsx
index 710bea2f896c..35bf6a657f3a 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
@@ -67,6 +67,12 @@ vi.mock("@posthog/ui/router/useAppView", () => ({
vi.mock("@posthog/ui/features/sidebar/useTaskPrStatus", () => ({
useTaskPrStatus: () => ({ prState: null, hasDiff: false, prUrl: null }),
}));
+vi.mock("@posthog/ui/features/canvas/hooks/useCanvasQueryResults", () => ({
+ useCanvasQueryResults: () => ({
+ canvases: [],
+ isLoading: false,
+ }),
+}));
vi.mock("@posthog/ui/features/canvas/hooks/useTaskFeedResults", () => ({
useTaskFeedResults: () => ({
tasks: [],
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.tsx
index 924b5c2b65e1..8ffaa6e8149a 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
@@ -85,6 +85,26 @@ vi.mock("@posthog/ui/features/canvas/hooks/useChannelTaskStatus", () => ({
useTaskStatusInput: () => null,
useChannelTaskStatus: () => null,
}));
+vi.mock("@posthog/ui/features/canvas/hooks/useCanvasQueryResults", () => ({
+ useCanvasQueryResults: (query: string | undefined) => ({
+ canvases: query
+ ? [
+ {
+ id: "canvas-1",
+ channelId: "space-1",
+ name: "Revenue overview",
+ kind: "freeform",
+ description: "",
+ templateId: "freeform",
+ createdBy: "Moshe Katz",
+ createdAt: 0,
+ updatedAt: 0,
+ },
+ ]
+ : [],
+ isLoading: false,
+ }),
+}));
vi.mock("@posthog/ui/features/canvas/hooks/useTaskFeedResults", () => ({
useTaskFeedResults: (query: string | undefined) => ({
tasks: query
@@ -324,4 +344,26 @@ describe("CommandMenu feed queries", () => {
),
).toBeTruthy();
});
+
+ it("lists canvases instead of tasks with type:canvas", async () => {
+ const user = userEvent.setup();
+ render(
+ <Theme>
+ <CommandMenu open onOpenChange={() => {}} />
+ </Theme>,
+ );
+
+ await user.type(
+ screen.getByPlaceholderText(/Search commands and tasks/),
+ "type:canvas created-by:moshe ",
+ );
+ expect(
+ await screen.findByText("Revenue overview", {}, { timeout: 2000 }),
+ ).toBeTruthy();
+ expect(screen.getByText("1 matching canvas")).toBeTruthy();
+ expect(screen.queryByText("Fix billing address validation")).toBeNull();
+ expect(screen.queryByText("Actions")).toBeNull();
+ // Saved searches are task feeds, so a canvas query offers no save shortcut.
+ expect(screen.queryByText(/save search/)).toBeNull();
+ });
});
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.tsx
index b2d014478128..e964f6d5f540 100644
--- a/products/desktop/packages/ui/src/features/command/CommandMenu.search.test.tsx
+++ b/products/desktop/packages/ui/src/features/command/CommandMenu.search.test.tsx
@@ -40,6 +40,12 @@ vi.mock("@posthog/ui/features/canvas/hooks/useChannels", () => ({
vi.mock("@posthog/ui/features/canvas/hooks/useChannelsLayout", () => ({
useChannelsLayout: () => false,
}));
+vi.mock("@posthog/ui/features/canvas/hooks/useCanvasQueryResults", () => ({
+ useCanvasQueryResults: () => ({
+ canvases: [],
+ isLoading: false,
+ }),
+}));
vi.mock("@posthog/ui/features/canvas/hooks/useTaskFeedResults", () => ({
useTaskFeedResults: () => ({
tasks: [],
diff --git a/products/desktop/packages/ui/src/features/command/CommandMenu.tsx b/products/desktop/packages/ui/src/features/command/CommandMenu.tsx
index eb50e396387d..9a3d16eb748f 100644
--- a/products/desktop/packages/ui/src/features/command/CommandMenu.tsx
+++ b/products/desktop/packages/ui/src/features/command/CommandMenu.tsx
@@ -918,6 +918,7 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {
mode,
scope,
hasFilterTokens,
+ matchNoun,
searchText,
keyChips,
matchCount,
@@ -1169,7 +1170,7 @@ export function CommandMenu({ open, onOpenChange }: CommandMenuProps) {
<div className="border-border border-b px-3 py-1.5 text-subtle-foreground text-xs tabular-nums">
{partialResults
? "Some matching tasks may not be shown."
- : matchSummary(matchCount, shownCount, hasRepairs)}
+ : matchSummary(matchCount, shownCount, hasRepairs, matchNoun)}
</div>
) : (
query !== "" && (
diff --git a/products/desktop/packages/ui/src/features/command/commandRowFacts.ts b/products/desktop/packages/ui/src/features/command/commandRowFacts.ts
index 6a49ebd9775a..c4f72377adfb 100644
--- a/products/desktop/packages/ui/src/features/command/commandRowFacts.ts
+++ b/products/desktop/packages/ui/src/features/command/commandRowFacts.ts
@@ -1,4 +1,5 @@
import { channelDisplayLabel } from "@posthog/core/canvas/channelName";
+import type { DashboardRecord } from "@posthog/core/canvas/dashboardSchemas";
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";
@@ -50,6 +51,19 @@ export function channelRowParts(channel: {
];
}
+export function canvasRowParts(
+ canvas: DashboardRecord,
+): (CommandRowMetaPart | undefined)[] {
+ return [
+ textPart(
+ canvas.createdByUser
+ ? userDisplayName(canvas.createdByUser)
+ : canvas.createdBy,
+ ),
+ activityPart(canvas.updatedAt),
+ ];
+}
+
function metadataString(
result: TaskSearchResult,
key: string,
diff --git a/products/desktop/packages/ui/src/features/command/commandRowHref.ts b/products/desktop/packages/ui/src/features/command/commandRowHref.ts
index bb5b22cc974c..d9b923ad4595 100644
--- a/products/desktop/packages/ui/src/features/command/commandRowHref.ts
+++ b/products/desktop/packages/ui/src/features/command/commandRowHref.ts
@@ -10,6 +10,10 @@ export function channelHref(channelId: string): string {
return `/spaces/${channelId}`;
}
+export function canvasHref(channelId: string, canvasId: string): string {
+ return `/spaces/${channelId}/dashboards/${canvasId}`;
+}
+
function canvasId(result: TaskSearchResult): string | undefined {
const value = result.metadata.canvas_id;
return typeof value === "string" && value ? value : undefined;
@@ -28,7 +32,7 @@ export function searchResultHref(
const canvas = canvasId(result);
if (!canvas) return undefined;
return channelId
- ? `/spaces/${channelId}/dashboards/${canvas}`
+ ? canvasHref(channelId, canvas)
: `/canvases?canvas=${canvas}`;
}
if (task) return taskHref(task, bluebirdEnabled ? channelId : undefined);
diff --git a/products/desktop/packages/ui/src/features/command/useFeedQueryCommands.tsx b/products/desktop/packages/ui/src/features/command/useFeedQueryCommands.tsx
index 0c0ad302649f..c352d68f54df 100644
--- a/products/desktop/packages/ui/src/features/command/useFeedQueryCommands.tsx
+++ b/products/desktop/packages/ui/src/features/command/useFeedQueryCommands.tsx
@@ -1,13 +1,20 @@
import { ArrowRightIcon, MagnifyingGlassIcon } from "@phosphor-icons/react";
+import { UNTITLED_CANVAS_NAME } from "@posthog/core/canvas/canvasNaming";
import { channelDisplayLabel } from "@posthog/core/canvas/channelName";
+import type { DashboardRecord } from "@posthog/core/canvas/dashboardSchemas";
import {
+ type FeedQueryToken,
feedQueryTypeScope,
+ type ParsedFeedQuery,
parseFeedQuery,
type TypeValue,
} from "@posthog/core/tasks/feedQuery";
import { singleLineTitle } from "@posthog/shared";
+import type { Task } from "@posthog/shared/domain-types";
+import { iconForTemplate } from "@posthog/ui/features/canvas/components/canvasTemplateIcon";
import { useFeedQuerySuggestions } from "@posthog/ui/features/canvas/components/feedQuerySuggestions";
import { applyFeedQuerySuggestion } from "@posthog/ui/features/canvas/components/feedQuerySuggestionUtils";
+import { useCanvasQueryResults } from "@posthog/ui/features/canvas/hooks/useCanvasQueryResults";
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";
@@ -15,12 +22,19 @@ import type {
Command,
CommandSection,
} from "@posthog/ui/features/command/commandRow";
-import { taskRowParts } from "@posthog/ui/features/command/commandRowFacts";
+import {
+ canvasRowParts,
+ taskRowParts,
+} from "@posthog/ui/features/command/commandRowFacts";
+import { canvasHref } from "@posthog/ui/features/command/commandRowHref";
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";
+import {
+ navigateToChannelDashboard,
+ navigateToFeed,
+} from "@posthog/ui/router/navigationBridge";
import { openTask } from "@posthog/ui/router/useOpenTask";
import { useMemo } from "react";
@@ -32,21 +46,30 @@ export type PaletteMode =
| "completingValue"
| "querying";
+export type MatchNoun = "task" | "canvas";
+
+const MATCH_NOUN_PLURALS: Record<MatchNoun, string> = {
+ task: "tasks",
+ canvas: "canvases",
+};
+
export function matchSummary(
matchCount: number | null,
shownCount: number,
hasRepairs = false,
+ noun: MatchNoun = "task",
): string {
+ const plural = MATCH_NOUN_PLURALS[noun];
if (matchCount == null) return "Searching…";
if (matchCount === 0) {
return hasRepairs
- ? "No tasks match this query."
- : "No tasks match this query. Remove a filter to see more tasks.";
+ ? `No ${plural} match this query.`
+ : `No ${plural} match this query. Remove a filter to see more ${plural}.`;
}
if (matchCount > shownCount) {
- return `Showing ${shownCount} of ${matchCount} matching tasks.`;
+ return `Showing ${shownCount} of ${matchCount} matching ${plural}.`;
}
- return `${matchCount} ${matchCount === 1 ? "matching task" : "matching tasks"}`;
+ return `${matchCount} matching ${matchCount === 1 ? noun : plural}`;
}
export interface FeedQueryKeyChip {
@@ -61,6 +84,7 @@ export interface FeedQueryPalette {
mode: PaletteMode;
scope: TypeValue | null;
hasFilterTokens: boolean;
+ matchNoun: MatchNoun;
matchCount: number | null;
partialResults: boolean;
shownCount: number;
@@ -68,6 +92,66 @@ export interface FeedQueryPalette {
searchText: string;
}
+function isQueryFilter(token: FeedQueryToken): boolean {
+ return token.key !== "type" && token.key !== "saved";
+}
+
+/** What a query lists: canvases for `type:canvas`, tasks for a task filter, or nothing. */
+function queryResultKind(parsed: ParsedFeedQuery): MatchNoun | null {
+ const scope = feedQueryTypeScope(parsed);
+ if (scope === "canvas") return "canvas";
+ // The planner ignores `type:` and `saved:`, so neither can activate task-query mode.
+ return scope === "task" || parsed.tokens.some(isQueryFilter) ? "task" : null;
+}
+
+function taskCommand(
+ task: Task,
+ spaceName: string | undefined,
+ keywords: string,
+): Command {
+ return {
+ id: `feed-query-task-${task.id}`,
+ label: singleLineTitle(task.title),
+ subtitle: commandRowMeta(taskRowParts(task)),
+ detail: spaceName ? channelDisplayLabel(spaceName) : undefined,
+ detailPrefix: "",
+ keywords,
+ icon: <TaskCommandIcon task={task} />,
+ action: "open-task",
+ channelId: task.channel ?? undefined,
+ onRun: () => {
+ closeSettings();
+ void openTask(
+ task,
+ task.channel ? { channelId: task.channel } : undefined,
+ );
+ },
+ };
+}
+
+function canvasCommand(
+ canvas: DashboardRecord,
+ spaceName: string | undefined,
+ keywords: string,
+): Command {
+ return {
+ id: `feed-query-canvas-${canvas.id}`,
+ label: singleLineTitle(canvas.name) || UNTITLED_CANVAS_NAME,
+ subtitle: commandRowMeta(canvasRowParts(canvas)),
+ detail: spaceName ? channelDisplayLabel(spaceName) : undefined,
+ detailPrefix: "",
+ keywords,
+ icon: iconForTemplate(canvas.templateId, { size: 12 }),
+ href: canvasHref(canvas.channelId, canvas.id),
+ action: "open-canvas",
+ channelId: canvas.channelId,
+ onRun: () => {
+ closeSettings();
+ navigateToChannelDashboard(canvas.channelId, canvas.id);
+ },
+ };
+}
+
export function useFeedQueryCommands({
query,
caret,
@@ -86,32 +170,48 @@ export function useFeedQueryCommands({
const trimmed = query.trim();
const parsed = useMemo(() => parseFeedQuery(trimmed), [trimmed]);
const scope = enabled ? feedQueryTypeScope(parsed) : null;
- // The planner ignores `type:` and `saved:`, so neither can activate task-query mode.
+ const resultKind = enabled ? queryResultKind(parsed) : null;
+ const runsQuery = resultKind !== null;
+ // Saved searches are task feeds, so only a task query has filters to save.
const hasFilterTokens =
- enabled && parsed.tokens.some((t) => t.key !== "type" && t.key !== "saved");
+ resultKind === "task" && parsed.tokens.some(isQueryFilter);
const searchText = enabled ? parsed.text : query;
const { group, context } = useFeedQuerySuggestions(query, caret, {
includeType: true,
});
- const runsQuery = hasFilterTokens || scope === "task";
const { debounced: previewQuery, isPending } = useDebouncedValue(
- enabled && runsQuery ? trimmed : "",
+ runsQuery ? trimmed : "",
FEED_QUERY_DEBOUNCE_MS,
);
- const results = useTaskFeedResults(previewQuery);
- const counting = isPending || results.isLoading;
- const feeds = useProjectTaskFeeds();
- const { channels } = useChannels();
-
const previewParsed = useMemo(
() => parseFeedQuery(previewQuery),
[previewQuery],
);
- const partialResults = runsQuery && !counting && !results.isComplete;
+ // Route on the debounced text, so each list only ever receives its own kind
+ // of query. `isPending` covers the gap while the two kinds disagree.
+ const previewKind = queryResultKind(previewParsed);
+ const results = useTaskFeedResults(
+ previewKind === "task" ? previewQuery : "",
+ );
+ const canvasResults = useCanvasQueryResults(
+ previewKind === "canvas" ? previewQuery : "",
+ );
+ const counting =
+ isPending ||
+ (previewKind === "canvas" ? canvasResults.isLoading : results.isLoading);
+ // The canvas list loads in one request, so it is never partial.
+ const resultsComplete = previewKind === "canvas" || results.isComplete;
+ const feeds = useProjectTaskFeeds();
+ const { channels } = useChannels();
+
+ const partialResults = runsQuery && !counting && !resultsComplete;
const noMatches =
- runsQuery && !counting && results.isComplete && results.tasks.length === 0;
+ resultKind === "task" &&
+ !counting &&
+ results.isComplete &&
+ results.tasks.length === 0;
const splittable =
noMatches && previewParsed.text !== "" && previewParsed.tokens.length > 0;
const filtersOnlyQuery = splittable
@@ -156,6 +256,31 @@ export function useFeedQueryCommands({
[channels],
);
+ const matchNoun = previewKind ?? resultKind ?? "task";
+ const resultRows = useMemo(() => {
+ if (!runsQuery) return [];
+ const keywords = `${query} ${searchText}`;
+ return previewKind === "canvas"
+ ? canvasResults.canvases.map((canvas) =>
+ canvasCommand(canvas, channelNames.get(canvas.channelId), keywords),
+ )
+ : results.tasks.map((task) =>
+ taskCommand(
+ task,
+ task.channel ? channelNames.get(task.channel) : undefined,
+ keywords,
+ ),
+ );
+ }, [
+ runsQuery,
+ query,
+ searchText,
+ previewKind,
+ canvasResults.canvases,
+ results.tasks,
+ channelNames,
+ ]);
+
return useMemo(() => {
if (!enabled) {
return {
@@ -164,6 +289,7 @@ export function useFeedQueryCommands({
mode,
scope: null,
hasFilterTokens: false,
+ matchNoun,
matchCount: null,
partialResults: false,
shownCount: 0,
@@ -231,32 +357,10 @@ export function useFeedQueryCommands({
}
const matchCount =
- runsQuery && !counting && results.isComplete
- ? results.tasks.length
- : null;
- const shown = runsQuery ? results.tasks.slice(0, limit) : [];
+ runsQuery && !counting && resultsComplete ? resultRows.length : null;
+ const shown = resultRows.slice(0, limit);
if (shown.length > 0) {
- const items = shown.map((task): Command => {
- const space = task.channel ? channelNames.get(task.channel) : undefined;
- return {
- id: `feed-query-task-${task.id}`,
- label: singleLineTitle(task.title),
- subtitle: commandRowMeta(taskRowParts(task)),
- detail: space ? channelDisplayLabel(space) : undefined,
- detailPrefix: "",
- keywords: `${query} ${searchText}`,
- icon: <TaskCommandIcon task={task} />,
- action: "open-task",
- channelId: task.channel ?? undefined,
- onRun: () => {
- closeSettings();
- void openTask(
- task,
- task.channel ? { channelId: task.channel } : undefined,
- );
- },
- };
- });
+ const items = [...shown];
if (matchCount != null && matchCount > shown.length) {
items.push({
id: "feed-query-show-all",
@@ -269,7 +373,10 @@ export function useFeedQueryCommands({
onRun: onShowAll,
});
}
- sections.push({ label: "Matching tasks", items });
+ sections.push({
+ label: `Matching ${MATCH_NOUN_PLURALS[matchNoun]}`,
+ items,
+ });
}
let hasRepairs = false;
@@ -319,6 +426,7 @@ export function useFeedQueryCommands({
mode,
scope,
hasFilterTokens,
+ matchNoun,
matchCount,
partialResults,
shownCount: shown.length,
@@ -335,14 +443,14 @@ export function useFeedQueryCommands({
searchText,
scope,
hasFilterTokens,
+ matchNoun,
runsQuery,
counting,
- results.isComplete,
- results.tasks,
+ resultsComplete,
+ resultRows,
partialResults,
savedHits,
limit,
- channelNames,
splittable,
previewParsed.text,
filtersOnly.tasks.length,